Skip to content

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

JavaScript

Replace the component kit review with a plan and asset review (#858)

Paul Bakaus4bdd459898f1
diff --git a/Cargo.lock b/Cargo.lock
index c6f92cd29..d97e331c2 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -525,7 +525,7 @@ dependencies = [
[[package]]
name = "impeccable"
-version = "0.1.6"
+version = "0.1.7"
dependencies = [
"base64",
"impeccable-browser",
@@ -545,7 +545,7 @@ dependencies = [
[[package]]
name = "impeccable-browser"
-version = "0.1.6"
+version = "0.1.7"
dependencies = [
"base64",
"impeccable-core",
@@ -560,7 +560,7 @@ dependencies = [
[[package]]
name = "impeccable-bundle"
-version = "0.1.6"
+version = "0.1.7"
dependencies = [
"base64",
"impeccable-core",
@@ -569,14 +569,14 @@ dependencies = [
[[package]]
name = "impeccable-common"
-version = "0.1.6"
+version = "0.1.7"
dependencies = [
"libc",
]
[[package]]
name = "impeccable-comp"
-version = "0.1.6"
+version = "0.1.7"
dependencies = [
"image",
"once_cell",
@@ -588,10 +588,11 @@ dependencies = [
[[package]]
name = "impeccable-comp-verbs"
-version = "0.1.6"
+version = "0.1.7"
dependencies = [
"impeccable-common",
"impeccable-comp",
+ "impeccable-context",
"once_cell",
"regex",
"serde",
@@ -602,7 +603,7 @@ dependencies = [
[[package]]
name = "impeccable-context"
-version = "0.1.6"
+version = "0.1.7"
dependencies = [
"flate2",
"impeccable-common",
@@ -622,7 +623,7 @@ dependencies = [
[[package]]
name = "impeccable-core"
-version = "0.1.6"
+version = "0.1.7"
dependencies = [
"impeccable-core",
"impeccable-foundation",
@@ -634,7 +635,7 @@ dependencies = [
[[package]]
name = "impeccable-detect"
-version = "0.1.6"
+version = "0.1.7"
dependencies = [
"impeccable-common",
"impeccable-core",
@@ -646,7 +647,7 @@ dependencies = [
[[package]]
name = "impeccable-foundation"
-version = "0.1.6"
+version = "0.1.7"
dependencies = [
"cssparser",
"once_cell",
@@ -659,7 +660,7 @@ dependencies = [
[[package]]
name = "impeccable-hook"
-version = "0.1.6"
+version = "0.1.7"
dependencies = [
"impeccable-common",
"impeccable-comp-verbs",
@@ -674,7 +675,7 @@ dependencies = [
[[package]]
name = "impeccable-html"
-version = "0.1.6"
+version = "0.1.7"
dependencies = [
"cssparser",
"ego-tree",
@@ -695,7 +696,7 @@ dependencies = [
[[package]]
name = "impeccable-live"
-version = "0.1.6"
+version = "0.1.7"
dependencies = [
"getrandom 0.2.17",
"impeccable-common",
@@ -713,7 +714,7 @@ dependencies = [
[[package]]
name = "impeccable-skills"
-version = "0.1.6"
+version = "0.1.7"
dependencies = [
"impeccable-common",
"impeccable-context",
@@ -732,7 +733,7 @@ dependencies = [
[[package]]
name = "impeccable-wasm"
-version = "0.1.6"
+version = "0.1.7"
dependencies = [
"impeccable-core",
"impeccable-detect",
@@ -1763,7 +1764,7 @@ checksum = "3ad82d2a33cdc9674dc7465672f271e096168fcdbe0f799d9e6db8c5892679dc"
[[package]]
name = "xtask"
-version = "0.1.6"
+version = "0.1.7"
dependencies = [
"impeccable-bundle",
]
diff --git a/Cargo.toml b/Cargo.toml
index e61da5e5e..c1ca9af3f 100644
--- a/Cargo.toml
+++ b/Cargo.toml
@@ -6,7 +6,7 @@ resolver = "2"
members = ["crates/*"]
[workspace.package]
-version = "0.1.6"
+version = "0.1.7"
edition = "2021"
license = "Apache-2.0"
publish = false
diff --git a/ENGINE_VERSION b/ENGINE_VERSION
index c946ee616..11808190d 100644
--- a/ENGINE_VERSION
+++ b/ENGINE_VERSION
@@ -1 +1 @@
-0.1.6
+0.1.7
diff --git a/bun.lock b/bun.lock
index 85b8eb509..560c83cb2 100644
--- a/bun.lock
+++ b/bun.lock
@@ -19,11 +19,11 @@
"zod": "^4.3.6",
},
"optionalDependencies": {
- "@impeccable/cli-darwin-arm64": "0.1.6",
- "@impeccable/cli-darwin-x64": "0.1.6",
- "@impeccable/cli-linux-arm64": "0.1.6",
- "@impeccable/cli-linux-x64": "0.1.6",
- "@impeccable/cli-windows-x64": "0.1.6",
+ "@impeccable/cli-darwin-arm64": "0.1.7",
+ "@impeccable/cli-darwin-x64": "0.1.7",
+ "@impeccable/cli-linux-arm64": "0.1.7",
+ "@impeccable/cli-linux-x64": "0.1.7",
+ "@impeccable/cli-windows-x64": "0.1.7",
},
},
},
@@ -72,15 +72,15 @@
"@hono/node-server": ["@hono/[email protected]", "", { "peerDependencies": { "hono": "^4" } }, "sha512-GwtvgtXxnWsucXvbQXkRgqksiH2Qed37H9xHZocE5sA3N8O8O8/8FA3uclQXxXVzc9XBZuEOMK7+r02FmSpHtw=="],
- "@impeccable/cli-darwin-arm64": ["@impeccable/[email protected]", "", { "os": "darwin", "cpu": "arm64", "bin": { "impeccable-darwin-arm64": "bin/impeccable" } }, "sha512-c81xi7ZBrdBHS1U5t6WwPyWc6F7fgYuKrRs4DtMIUFVo6SomyG6nynCX2BjWjzhKlQIIH70eUHCKTphDboeMXw=="],
+ "@impeccable/cli-darwin-arm64": ["@impeccable/[email protected]", "", { "os": "darwin", "cpu": "arm64", "bin": { "impeccable-darwin-arm64": "bin/impeccable" } }, "sha512-G8uMNqAfMiGx+4YwemH6GV1zY2PpV38LamdeVCzdvTLOOnbphPg44uEJtiP97wgPYkAsFRAo+rKyf/GaA2XZjg=="],
- "@impeccable/cli-darwin-x64": ["@impeccable/[email protected]", "", { "os": "darwin", "cpu": "x64", "bin": { "impeccable-darwin-x64": "bin/impeccable" } }, "sha512-6gMbB5P5cC60BjV8UXxGm1jCDtUp0GlJEVjqFxrJ4rMAGxUzLbZHv5xAiOurkhJW1BJYJjU0RPiRgBIYQ+2eNQ=="],
+ "@impeccable/cli-darwin-x64": ["@impeccable/[email protected]", "", { "os": "darwin", "cpu": "x64", "bin": { "impeccable-darwin-x64": "bin/impeccable" } }, "sha512-7GHedadRYKCsBVGXCSqHQJPvjY3tQiLZbVjnr7+wysRxfzKEHr7h2B/5EMR0rujCiriC0EDgJPch8X4SYKuAXQ=="],
- "@impeccable/cli-linux-arm64": ["@impeccable/[email protected]", "", { "os": "linux", "cpu": "arm64", "bin": { "impeccable-linux-arm64": "bin/impeccable" } }, "sha512-J2oqQpD/8jrPO2z58Li9ECA7hxHzROP8dy96N+qjWeMAMgp9owbSf86vkgNbxCZdU+oVOZdFgnlkhdx7yGsrTA=="],
+ "@impeccable/cli-linux-arm64": ["@impeccable/[email protected]", "", { "os": "linux", "cpu": "arm64", "bin": { "impeccable-linux-arm64": "bin/impeccable" } }, "sha512-ewfiXtVU727xTtgUbGjQKknCDhMnWH3DPyYkt+gBbdRJ59UP2uiP1IwWXZuo+IMFhKhmOlUHNY37EDptZ9t/rA=="],
- "@impeccable/cli-linux-x64": ["@impeccable/[email protected]", "", { "os": "linux", "cpu": "x64", "bin": { "impeccable-linux-x64": "bin/impeccable" } }, "sha512-HgPswOYNC8X8f8c638qaZVYqDvyxBVhOjg8aH9Ya1plSe9ynd7FIEk2sbHTpzSj0gnygQzMnXIQMXao7waDjAQ=="],
+ "@impeccable/cli-linux-x64": ["@impeccable/[email protected]", "", { "os": "linux", "cpu": "x64", "bin": { "impeccable-linux-x64": "bin/impeccable" } }, "sha512-VcF9y/RcWIQOOBx5WybgRfwLzydL7ou8eZOiuaAraQqR3YITP8BSGxj4qr7I0zoy4Nli8iV2lbYxFmrJ6eDerw=="],
- "@impeccable/cli-windows-x64": ["@impeccable/[email protected]", "", { "os": "win32", "cpu": "x64", "bin": { "impeccable-windows-x64": "bin/impeccable.exe" } }, "sha512-BvM7KcJS4BMtQlVc/OgAoNAfnKO56vx2ar2GlG6+esJZWbYBVummvA8SCWWDya/S2dKIvosvMPa3PUgj0mzK8w=="],
+ "@impeccable/cli-windows-x64": ["@impeccable/[email protected]", "", { "os": "win32", "cpu": "x64", "bin": { "impeccable-windows-x64": "bin/impeccable.exe" } }, "sha512-07Zipg5byFSGLnvjowmNrjYAlRhAYu5SsDqaDRDlqB+uleuUzcVxguHdcparYdfk/Oe0X9JOhatNgniH6l+XeQ=="],
"@jridgewell/gen-mapping": ["@jridgewell/[email protected]", "", { "dependencies": { "@jridgewell/sourcemap-codec": "^1.5.0", "@jridgewell/trace-mapping": "^0.3.24" } }, "sha512-2kkt/7niJ6MgEPxF0bYdQ6etZaA+fQvDcLKckhy1yIQOzaoKjBBjSj63/aLVjYE3qhRt5dvM+uUyfCg6UKCBbA=="],
diff --git a/crates/cli/src/reviewed_entry.rs b/crates/cli/src/reviewed_entry.rs
index da9ffe747..c99bf8375 100644
--- a/crates/cli/src/reviewed_entry.rs
+++ b/crates/cli/src/reviewed_entry.rs
@@ -1,4 +1,7 @@
-//! A human-approved assembled capture is evidence for text styling, never a
+//! A human-approved assembled capture is bound by what it looks like, not by the
+//! bytes that drew it: build-phase compares it with the current capture, so later
+//! shared-CSS edits keep it while the first viewport still matches. It is evidence
+//! for the first viewport's scores, never a
//! replacement for native integrity, missing-region, or overall fidelity gates.
use crate::entry_capture::CdpEntryRenderer;
use impeccable_comp_verbs::asset_capture::capture_sha256;
@@ -43,11 +46,7 @@ fn file(root: &Path, path: &str) -> Result<Vec<u8>, String> {
}
/// Read only private native session state. The host selects the session; neither
/// a model-written receipt nor a saved build-phase report is an authority.
-fn reference(
- session: &Path,
- r: &EntryRequest,
- evidence: &EntryEvidence,
-) -> Result<ApprovedReference, String> {
+fn reference(session: &Path, r: &EntryRequest) -> Result<ApprovedReference, String> {
let root = r.root.canonicalize().map_err(|e| e.to_string())?;
if session
.canonicalize()
@@ -91,14 +90,15 @@ fn reference(
let sources = state["sources"]
.as_object()
.ok_or("missing review sources")?;
- for (path, hash) in sources {
- if hash.as_str() != Some(&capture_sha256(&file(&root, path)?)) {
- return Err(format!("reviewed source changed: {path}"));
- }
- }
if !sources.contains_key(&r.artifact) || !sources.contains_key(&r.reference) {
return Err("review must bind entry and original comp".into());
}
+ // Only the reference is bound by bytes: the comp the user judged against must be
+ // the comp the gates measure. Page sources may change; build-phase holds the
+ // approval to the pixels of the current first viewport instead.
+ if sources[&r.reference].as_str() != Some(&capture_sha256(&file(&root, &r.reference)?)) {
+ return Err(format!("reviewed comp changed: {}", r.reference));
+ }
let comp_url = packet["comp"]["url"]
.as_str()
.ok_or("missing reviewed comp")?;
@@ -111,40 +111,6 @@ fn reference(
{
return Err("reviewed reference differs".into());
}
- // A newly added served file must not borrow an earlier approval.
- for input in evidence.report["manifest"]["files"]
- .as_array()
- .ok_or("missing current native inputs")?
- {
- let path = input["path"].as_str().ok_or("invalid input")?;
- let raster = matches!(
- Path::new(path).extension().and_then(|s| s.to_str()),
- Some("png" | "jpg" | "jpeg" | "webp" | "avif" | "gif")
- );
- if input["served"] == true
- && !raster
- && sources.get(input["path"].as_str().ok_or("invalid input")?) != Some(&input["sha256"])
- {
- return Err("native inputs differ from reviewed inputs".into());
- }
- }
- // Available but unused raster variants are not dependencies. Every raster
- // actually observed at the captured breakpoint must belong to the approval.
- for frame in &evidence.frames {
- for region in &frame.regions {
- for binding in region.receipt["resourceBindings"]
- .as_array()
- .ok_or("missing observed raster bindings")?
- {
- if !sources
- .values()
- .any(|h| h == &binding["responseSha256"] && h.is_string())
- {
- return Err("unreviewed raster contributes to current page".into());
- }
- }
- }
- }
let hash = capture["screenshotSha256"]
.as_str()
.filter(|h| h.len() == 64 && h.bytes().all(|c| c.is_ascii_hexdigit()))
@@ -164,7 +130,7 @@ fn reference(
}
Ok(ApprovedReference {
png,
- proof: json!({"schema":"human-assembled-reference-v1","requestId":packet["id"],"packetRevision":packet["revision"],"sha256":hash,"scope":"Text styling accepted in a source-bound assembled-page review; all other gates retained"}),
+ proof: json!({"schema":"human-assembled-reference-v1","requestId":packet["id"],"packetRevision":packet["revision"],"sha256":hash,"scope":"First viewport accepted in an assembled-page review; valid while the current capture matches this screenshot; material gates retained"}),
})
}
impl EntryRenderer for ReviewedEntryRenderer {
@@ -173,7 +139,7 @@ impl EntryRenderer for ReviewedEntryRenderer {
let candidate = self
.session
.as_ref()
- .map(|s| reference(s, r, source.evidence()));
+ .map(|s| reference(s, r));
let mut report = source.evidence().report.clone();
if let Some(Err(reason)) = &candidate {
report["humanTextReview"] = json!({"status":"not-current","reason":reason});
@@ -225,11 +191,7 @@ impl CapturedEntry for ReviewedEntry {
fn verify_current(&self) -> Result<(), String> {
self.source.verify_current()?;
if let Some(a) = &self.approved {
- let current = reference(
- self.session.as_ref().unwrap(),
- &self.request,
- self.source.evidence(),
- )?;
+ let current = reference(self.session.as_ref().unwrap(), &self.request)?;
if current.png != a.png || current.proof != a.proof {
return Err("human review changed during capture".into());
}
@@ -255,7 +217,7 @@ impl ReviewedEntryRenderer {
mod tests {
use super::*;
#[test]
- fn approval_is_bound_to_reviewed_sources_and_the_native_capture() {
+ fn approval_is_bound_to_the_reviewed_screenshot_and_comp_not_page_bytes() {
let dir = std::env::temp_dir().join(format!("review-reference-{}", std::process::id()));
let root = dir.join("project");
let session = dir.join("session");
@@ -281,12 +243,8 @@ mod tests {
reference: "comp.png".into(),
stage: impeccable_comp_verbs::entry_capture::EntryStage::Responsive,
};
- let evidence = EntryEvidence {
- report: json!({"manifest":{"files":[{"path":"index.html","sha256":page,"served":true}]}}),
- frames: vec![],
- };
assert_eq!(
- reference(&session, &request, &evidence).unwrap().png,
+ reference(&session, &request).unwrap().png,
b"png"
);
for (pointer, value) in [
@@ -304,25 +262,21 @@ mod tests {
*broken.pointer_mut(pointer).unwrap() = value;
save(&broken);
assert!(
- reference(&session, &request, &evidence).is_err(),
+ reference(&session, &request).is_err(),
"{pointer}"
);
}
save(&state);
+ // Page edits keep the approval: build-phase compares pixels, not bytes.
fs::write(root.join("index.html"), b"changed").unwrap();
- assert!(reference(&session, &request, &evidence).is_err());
- fs::write(root.join("index.html"), b"page").unwrap();
- let mut added = EntryEvidence {
- report: evidence.report.clone(),
- frames: vec![],
- };
- added.report["manifest"]["files"]
- .as_array_mut()
- .unwrap()
- .push(json!({"path":"late.css","sha256":"new","served":true}));
- assert!(reference(&session, &request, &added).is_err());
+ fs::write(root.join("late.css"), b"new").unwrap();
+ assert_eq!(reference(&session, &request).unwrap().png, b"png");
+ // A different comp does not.
+ fs::write(root.join("comp.png"), b"other comp").unwrap();
+ assert!(reference(&session, &request).is_err());
+ fs::write(root.join("comp.png"), b"comp").unwrap();
fs::write(session.join("blobs").join(&png), b"replaced").unwrap();
- assert!(reference(&session, &request, &evidence).is_err());
+ assert!(reference(&session, &request).is_err());
let _ = fs::remove_dir_all(dir);
}
}
diff --git a/crates/comp-verbs/Cargo.toml b/crates/comp-verbs/Cargo.toml
index 9b87ca634..8bc548fa3 100644
--- a/crates/comp-verbs/Cargo.toml
+++ b/crates/comp-verbs/Cargo.toml
@@ -6,8 +6,9 @@ license.workspace = true
publish.workspace = true
# The comp-fidelity verb orchestrators (build-phase / comp-diff / comp-spec /
-# font-match), ported from the skill's JS scripts. OPEN and free of the closed
-# `core` crate: it wires only the pure `comp` foundation plus `common` (Io).
+# font-match), ported from the skill's JS scripts. It wires the pure `comp`
+# foundation plus `common` (Io), and `context` for one thing: build-phase reads
+# the human plan and asset review (docs/PLAN-REVIEW.md) before page work.
# The one piece it cannot do alone — font-match's headless browser rendering of
# font specimens — is injected as a `FontRenderer` trait the CLI implements over
# `crates/browser`, so the browser (and its `core` dependency) stays out of here.
@@ -15,6 +16,8 @@ publish.workspace = true
[dependencies]
impeccable-comp = { workspace = true }
impeccable-common = { workspace = true }
+# The plates -> hero gate reads the human plan review (component_review::plan::gate).
+impeccable-context = { workspace = true }
serde = { workspace = true }
serde_json = { workspace = true, features = ["preserve_order", "float_roundtrip"] }
regex = { workspace = true }
diff --git a/crates/comp-verbs/src/build_phase.rs b/crates/comp-verbs/src/build_phase.rs
index 3c7216d2d..fdc2660b8 100644
--- a/crates/comp-verbs/src/build_phase.rs
+++ b/crates/comp-verbs/src/build_phase.rs
@@ -1481,6 +1481,13 @@ fn gate_hero(
}
};
let native_path = native.as_ref().map(|n| n.path("hero"));
+ // The renderer hands over an approval only while its reviewed sources are
+ // unchanged; the pixels must also still be the ones the user saw, region by region.
+ let human = native.as_ref().and_then(|n| n.capture.approved_reference().map(|a| (n, a))).and_then(|(n, a)| {
+ let spec = load_spec(&abs(io, SPEC_PATH));
+ hero_diff_labeled(io, &n.path("human-approved"), &n.path("hero"), spec.as_ref(), &format!("{out_dir}/human-reviewed"), "human-reviewed").ok()
+ .map(|(comparison, _)| json!({"proof": a.proof, "comparison": comparison}))
+ });
let mut gate = gate_hero_inner(
io,
state,
@@ -1489,6 +1496,7 @@ fn gate_hero(
out_dir,
artifact,
organic_scan,
+ human.as_ref(),
);
if let Some(native) = &native {
finish_native_capture(io, out_dir, &mut gate, native);
@@ -1614,8 +1622,37 @@ fn clear_comparison_artifacts(out_dir: &Path) -> Result<(), String> {
if errors.is_empty() { Ok(()) } else { Err(format!("cannot clear comparison artifacts: {}", errors.join("; "))) }
}
+/// Whether the current capture is the first viewport the user accepted: the
+/// approved screenshot compared with it scores at least 95% with no region
+/// missing or contradicted. A stale approval (a different capture) fails this.
+fn human_accepted_viewport(human: Option<&Value>) -> bool {
+ let Some(c) = human.map(|h| &h["comparison"]) else { return false; };
+ c["overall"].as_f64().is_some_and(|o| o >= 0.95)
+ && c["regions"].as_array().is_some_and(|rs| rs.iter().all(|r| !matches!(r["verdict"].as_str(), Some("missing" | "contradicted"))))
+}
+
+/// When the user accepted a first viewport that the current capture no longer
+/// matches: the reason that replaces the raw score.
+fn lapsed_viewport(human: Option<&Value>, frame: &str) -> Option<String> {
+ let c = &human?["comparison"];
+ if human_accepted_viewport(human) { return None; }
+ let changed: Vec<&str> = c["regions"].as_array().into_iter().flatten()
+ .filter(|r| matches!(r["verdict"].as_str(), Some("missing" | "contradicted"))).filter_map(|r| r["id"].as_str()).collect();
+ Some(format!("the {frame} no longer matches the first viewport the user accepted ({}% against the approved screenshot{}), so that acceptance no longer covers the scores. Restore what the user accepted; until then the readings apply.",
+ pct0(c["overall"].as_f64().unwrap_or(0.)), if changed.is_empty() { String::new() } else { format!("; changed: {}", changed.join(", ")) }))
+}
+
+/// Code regions (text, control, chrome) an accepted first-viewport review
+/// covers: the current capture still renders them as the approved one did.
+fn human_accepted_regions(human: Option<&Value>, regions: &[Value]) -> std::collections::HashSet<String> {
+ let reviewed = human.and_then(|h| h["comparison"]["regions"].as_array()).cloned().unwrap_or_default();
+ regions.iter().filter(|r| matches!(r["kind"].as_str(), Some("text" | "control" | "chrome")))
+ .filter(|r| reviewed.iter().any(|v| v["id"] == r["id"] && matches!(v["verdict"].as_str(), Some("match" | "drift")) && rscore(v, "structure") >= 0.75))
+ .filter_map(|r| r["id"].as_str().map(String::from)).collect()
+}
+
#[allow(clippy::too_many_arguments)]
-fn gate_hero_inner(io: &Io, state: &mut Value, build_path: &str, min: f64, out_dir: &str, artifact: Option<&str>, organic_scan: OrganicScan) -> Gate {
+fn gate_hero_inner(io: &Io, state: &mut Value, build_path: &str, min: f64, out_dir: &str, artifact: Option<&str>, organic_scan: OrganicScan, human: Option<&Value>) -> Gate {
let s = self_cmd(io);
if !abs(io, build_path).exists() {
let bp = state.get("breakpoint").and_then(Value::as_str).map(String::from).unwrap_or_else(|| "comp size".into());
@@ -1668,6 +1705,18 @@ fn gate_hero_inner(io: &Io, state: &mut Value, build_path: &str, min: f64, out_d
let mut reasons: Vec<String> = Vec::new();
let mut advisories: Vec<String> = Vec::new();
let mut region_reasons = Map::new();
+ // Material vetoes (missing or unreferenced plates, SVG illustrations, organic
+ // clips, plate readings, invented ink, the overall bar) never pass through here.
+ let accepted = human_accepted_regions(human, &regions);
+ let mut waived: Vec<String> = Vec::new();
+ // Material vetoes, recorded as they are raised: an accepted first viewport never waives these.
+ let mut material: Vec<String> = Vec::new();
+ let mut waive = |id: &str, message: &str, advisories: &mut Vec<String>| -> bool {
+ if !accepted.contains(id) { return false; }
+ advisories.push(format!("(advisory, accepted in the first-viewport review) {message}"));
+ if !waived.iter().any(|w| w == id) { waived.push(id.to_string()); }
+ true
+ };
let overall = report.get("overall").and_then(Value::as_f64).unwrap_or(0.0);
let sc = |k: &str| report.pointer(&format!("/scores/{k}")).and_then(Value::as_f64).unwrap_or(0.0);
// capture-frame check
@@ -1685,6 +1734,7 @@ fn gate_hero_inner(io: &Io, state: &mut Value, build_path: &str, min: f64, out_d
"hero capture is {}x{}; the comp is {}x{}. Capture the first viewport at the comp's own dimensions (viewport {}x{}, not full page) into {build_path}.",
bw as i64, bh as i64, cw as i64, ch as i64, cw as i64, ch as i64
));
+ material.push(reasons.last().unwrap().clone());
}
}
let above_bar = overall >= min;
@@ -1800,6 +1850,7 @@ fn gate_hero_inner(io: &Io, state: &mut Value, build_path: &str, min: f64, out_d
"region {id} is missing (detail {}%, structure {}%): the comp shows material the build does not",
pct0(rscore(r, "detail")), pct0(rscore(r, "structure"))
));
+ material.push(reasons.last().unwrap().clone());
}
}
}
@@ -1827,21 +1878,23 @@ fn gate_hero_inner(io: &Io, state: &mut Value, build_path: &str, min: f64, out_d
} else {
format!("the plate here does not read as the comp region; regenerate it with the crop as reference ({s} generate-image --ref <crop.png> --prompt-file <prompt.txt> --out <plate.png> for {id}) and place it at its box")
};
- push_region_blocker(&mut reasons, &mut region_reasons, id, format!(
+ let message = format!(
"region {id} ({kind}) is contradicted (structure {}%, detail added {}%): {tail}",
pct0(rscore(r, "structure")), pct0(rscore(r, "detailAdded"))
- ));
+ );
+ if !waive(id, &message, &mut advisories) { push_region_blocker(&mut reasons, &mut region_reasons, id, message); }
}
for r in &regions {
if r.get("kind").and_then(Value::as_str) != Some("control") || r.get("verdict").and_then(Value::as_str) != Some("drift") || rscore(r, "overall") >= 0.65 {
continue;
}
let id = r.get("id").and_then(Value::as_str).unwrap_or("");
- push_region_blocker(&mut reasons, &mut region_reasons, id, format!(
+ let message = format!(
"control {id} drifts to {}% (structure {}%, color {}%): open {} and compare its lettering and visible shape separately; use the measured readings and preserve the region's control classification",
pct0(rscore(r, "overall")), pct0(rscore(r, "structure")), pct0(rscore(r, "color")),
format!("{out_dir}/regions/{id}.png")
- ));
+ );
+ if !waive(id, &message, &mut advisories) { push_region_blocker(&mut reasons, &mut region_reasons, id, message); }
}
// control ink boxes
for r in &regions {
@@ -1876,12 +1929,14 @@ fn gate_hero_inner(io: &Io, state: &mut Value, build_path: &str, min: f64, out_d
);
if above_bar {
advisories.push(format!("(advisory, above the {}% bar) {msg}", pct0(min)));
- } else {
+ } else if !waive(r["id"].as_str().unwrap_or(""), &msg, &mut advisories) {
push_region_blocker(&mut reasons, &mut region_reasons, r.get("id").and_then(Value::as_str).unwrap_or(""), msg);
}
}
}
- let other_contradicted: Vec<&Value> = contradicted.iter().filter(|r| !direction_contradicted.iter().any(|d| d.get("id") == r.get("id"))).collect();
+ let other_contradicted: Vec<&Value> = contradicted.iter().filter(|r| !direction_contradicted.iter().any(|d| d.get("id") == r.get("id")))
+ .filter(|r| { let id = r["id"].as_str().unwrap_or(""); !waive(id, &format!("region {id} ({}) is contradicted (structure {}%)", r["kind"].as_str().unwrap_or(""), pct0(rscore(r, "structure"))), &mut advisories) })
+ .collect();
let allow = 1usize.max(regions.len() / 3);
if other_contradicted.len() > allow {
let message = format!(
@@ -1903,15 +1958,18 @@ fn gate_hero_inner(io: &Io, state: &mut Value, build_path: &str, min: f64, out_d
let id = o.get("id").and_then(Value::as_str).unwrap_or("");
let snip = o.get("snippet").and_then(Value::as_str).unwrap_or("");
push_region_blocker(&mut reasons, &mut region_reasons, id, format!("artifact draws an organic clip-path ({snip}) inside raster region {id}'s box; that region ships as its plate, never as a polygon"));
+ material.push(reasons.last().unwrap().clone());
}
let svgs = std::fs::read_to_string(abs(io, af)).map(|h| svg_illustrations(&h)).unwrap_or_default();
for v in svgs.iter().take(6) {
let label = v.get("label").and_then(Value::as_str).filter(|s| !s.is_empty()).map(|l| format!(" ({l})")).unwrap_or_default();
let snip = v.get("snippet").and_then(Value::as_str).unwrap_or("");
reasons.push(format!("artifact draws an illustration in inline SVG{label}: {snip}. Drawings, diagrams, notation, and leader lines are plates or belong to the plate they annotate; only icon-sized SVG (under 64px, a few paths) is code"));
+ material.push(reasons.last().unwrap().clone());
}
if svgs.len() > 6 {
reasons.push(format!("...and {} more inline SVG illustrations", svgs.len() - 6));
+ material.push(reasons.last().unwrap().clone());
}
}
}
@@ -1997,6 +2055,12 @@ fn gate_hero_inner(io: &Io, state: &mut Value, build_path: &str, min: f64, out_d
}
} else {
for f in &kept {
+ let ids = reading_ids.get(f).cloned().unwrap_or_default();
+ if !ids.is_empty() && ids.iter().all(|id| accepted.contains(id)) {
+ for id in &ids { waive(id, f, &mut advisories); }
+ advisories.dedup();
+ continue;
+ }
push_reading_blocker(&mut reasons, &mut region_reasons, &reading_ids, f);
}
}
@@ -2005,6 +2069,7 @@ fn gate_hero_inner(io: &Io, state: &mut Value, build_path: &str, min: f64, out_d
}
for f in &readings.plates {
push_reading_blocker(&mut reasons, &mut region_reasons, &reading_ids, f);
+ material.push(f.clone());
}
let cells = readings.invented.get("cells").and_then(Value::as_array).cloned().unwrap_or_default();
let fraction = readings.invented.get("fraction").and_then(Value::as_f64).unwrap_or(0.0);
@@ -2017,12 +2082,39 @@ fn gate_hero_inner(io: &Io, state: &mut Value, build_path: &str, min: f64, out_d
"the build carries ink in {} grid cells where the comp is calm ({shown}{more}); nothing exists on the page that the comp does not show (a kicker, an extra nav item, a divider, a second row of controls); remove it or name it in a stated decision after the hero passes",
labels.len()
));
+ material.push(reasons.last().unwrap().clone());
}
}
// worst regions
let worst_sorted = repair_regions(&regions, &region_reasons);
let worst_top: Vec<&Value> = worst_sorted.iter().take(3).collect();
let region_dir = format!("{out_dir}/regions");
+ // The user accepted this first viewport (the approved screenshot is the current
+ // capture): the numeric fight is over. Every non-material reason becomes an advisory.
+ let viewport_accepted = human_accepted_viewport(human);
+ if viewport_accepted {
+ let (kept, numeric): (Vec<String>, Vec<String>) = reasons.into_iter().partition(|r| material.contains(r));
+ reasons = kept;
+ for rows in region_reasons.values_mut() {
+ if let Some(a) = rows.as_array_mut() { a.retain(|m| m.as_str().is_some_and(|m| material.iter().any(|x| x == m))); }
+ }
+ region_reasons.retain(|_, v| v.as_array().is_some_and(|a| !a.is_empty()));
+ if !numeric.is_empty() {
+ advisories.insert(0, format!("The user accepted this first viewport in the review; {} numeric reading{} below {} advisories, not blockers.", numeric.len(), if numeric.len() == 1 { "" } else { "s" }, if numeric.len() == 1 { "is" } else { "are" }));
+ }
+ advisories.extend(numeric.into_iter().map(|m| format!("(advisory, first viewport accepted) {m}")));
+ } else if let Some(lapse) = lapsed_viewport(human, "hero capture") {
+ // Say why the acceptance does not hold instead of arguing the raw score.
+ match reasons.iter().position(|r| r.starts_with("hero overall")) {
+ Some(i) => { advisories.push(format!("(measured) {}", reasons[i])); reasons[i] = lapse; }
+ None if reasons.iter().any(|r| !material.contains(r)) => reasons.insert(0, lapse),
+ None => {}
+ }
+ }
+ if let Some(h) = human {
+ report["humanHeroReview"] = json!({"proof": h["proof"], "comparison": h["comparison"], "acceptedRegions": waived, "viewportAccepted": viewport_accepted,
+ "scope": if viewport_accepted { "first viewport accepted: overall bar, palette and every numeric reading are advisories; material vetoes retained" } else { "contradicted readings on text, control and chrome regions; material vetoes retained" }});
+ }
let mut g = Gate::blank();
g.ok = reasons.is_empty();
g.reasons = reasons;
@@ -2125,7 +2217,7 @@ fn apply_gate_evidence(report: &mut Value, measured: &mut CompareResult, regions
}
/// JS: heroLoopVerdict(state, gate, artifactPath).
-fn hero_loop_verdict(state: &mut Value, gate: &Gate, artifact_path: &str, io: &Io) -> Option<String> {
+fn hero_loop_verdict(state: &mut Value, gate: &Gate, artifact_path: &str, io: &Io, viewport_accepted: bool) -> Option<String> {
let hero = state.pointer_mut("/phases/hero")?.as_object_mut()?;
let mut history: Vec<Value> = hero.get("history").and_then(Value::as_array).cloned().unwrap_or_default();
let entry = json!({
@@ -2145,10 +2237,17 @@ fn hero_loop_verdict(state: &mut Value, gate: &Gate, artifact_path: &str, io: &I
}
let last3 = &history[history.len() - 3..];
let current = json!(gate.reasons);
- let stuck = !gate.ok && !gate.reasons.is_empty()
- && last3.iter().all(|h| h.get("blockingReasons") == Some(&current));
- if stuck {
- return Some("The same hero gate checks remain unresolved after three attempts. The blocking reasons below still apply.".into());
+ let failed = !gate.ok && !gate.reasons.is_empty()
+ && last3.iter().all(|h| h["blockingReasons"].as_array().is_some_and(|a| !a.is_empty()));
+ if failed {
+ let lead = if last3.iter().all(|h| h.get("blockingReasons") == Some(&current)) {
+ "The same hero gate checks remain unresolved after three attempts."
+ } else { "The hero gate has failed three attempts in a row." };
+ if viewport_accepted {
+ // The review is closed once accepted: asking for another would loop.
+ return Some(format!("{lead} The user already accepted a first viewport, and that review is closed. Restore what they accepted: while the capture matches the approved screenshot, the overall bar, the palette check and every numeric reading are advisories. Until then the readings below apply; a missing or unreferenced plate, an SVG illustration, an organic clip, a clipped plate, invented ink and failed rendered presence block either way."));
+ }
+ return Some(format!("{lead} Stop iterating and present the first-viewport review (the assembled hero, stage hero, in component-review.md) so the user judges the page in context. An accepted review of this capture turns the overall bar, the palette check and every numeric reading into advisories; a missing or unreferenced plate, an SVG illustration, a clipped plate and invented ink still block. The blocking reasons below still apply."));
}
None
}
@@ -2246,7 +2345,17 @@ fn gate_responsive_inner(io: &Io, state: &mut Value, min: f64, out_dir: &str, na
let mut region_reasons = Map::new();
let overall = report.get("overall").and_then(Value::as_f64).unwrap_or(0.0);
let mut reasons = Vec::new();
- if overall < min {
+ // The same first viewport the user accepted, still rendered at desktop width: its
+ // score and contradictions are not re-litigated here; missing regions still block.
+ let viewport_accepted = accepted_text.as_ref().is_some_and(|(comparison, _)| human_accepted_viewport(Some(&json!({"comparison": comparison}))));
+ let mut advisories: Vec<String> = Vec::new();
+ if viewport_accepted { report["humanTextReview"]["viewportAccepted"] = json!(true); }
+ if overall < min && viewport_accepted {
+ advisories.push(format!("(advisory, first viewport accepted) the desktop capture scores {}% against the comp, under {}%", pct0(overall), pct0(min)));
+ } else if let Some(lapse) = (overall < min).then(|| accepted_text.as_ref().and_then(|(comparison, _)| lapsed_viewport(Some(&json!({"comparison": comparison})), "desktop capture"))).flatten() {
+ advisories.push(format!("(measured) the desktop capture scores {}% against the comp, under {}%", pct0(overall), pct0(min)));
+ reasons.push(lapse);
+ } else if overall < min {
let bp = state.get("breakpoint").and_then(Value::as_str).map(String::from).unwrap_or_else(|| "the comp size".into());
reasons.push(format!(
"the desktop capture ({}; the top {} rows scaled to the comp's width are compared, a full-page capture is fine) scores {}% against the comp, under {}%: the first viewport does not survive a common desktop width. The hero passed at {bp}; the layout must hold from ~1280 up, not only at the comp's exact width (grid columns in fr / minmax, not fixed px that overflow and wrap).",
@@ -2261,6 +2370,10 @@ fn gate_responsive_inner(io: &Io, state: &mut Value, min: f64, out_dir: &str, na
}
for r in &contradicted_direction {
let accepted = r["kind"]=="text" && accepted_text.as_ref().is_some_and(|(comparison,_)| comparison["regions"].as_array().is_some_and(|reviewed| reviewed.iter().any(|region|region["id"]==r["id"] && matches!(region["verdict"].as_str(),Some("match"|"drift")) && rscore(region,"structure")>=0.75)));
+ if viewport_accepted && !accepted {
+ advisories.push(format!("(advisory, first viewport accepted) at desktop width, region {} ({}) is contradicted (structure {}%)", r["id"].as_str().unwrap_or(""), r["kind"].as_str().unwrap_or(""), pct0(rscore(r, "structure"))));
+ continue;
+ }
if accepted {
report["humanTextReview"]["acceptedTextRegions"].as_array_mut().map(|v|v.push(r["id"].clone())).unwrap_or_else(||{report["humanTextReview"]["acceptedTextRegions"]=json!([r["id"].clone()]);});
continue;
@@ -2277,6 +2390,7 @@ fn gate_responsive_inner(io: &Io, state: &mut Value, min: f64, out_dir: &str, na
g.score = Some(overall);
g.side_by_side = report.pointer("/files/sideBySide").and_then(Value::as_str).map(String::from);
g.region_reasons = region_reasons;
+ g.advisories = advisories;
publish_gate_evidence(io, out_dir, &mut report, &mut measured, &regions, &mut g, "responsive");
g
}
@@ -2319,6 +2433,42 @@ fn run_gate(io: &Io, state: &mut Value, phase: &str, opts: &GateOpts, organic_sc
}
}
+/// Page work waits for the human plan and asset review (docs/PLAN-REVIEW.md) of the
+/// current spec. A hosted review lives in the host's store: the host names its trusted
+/// session directories, and the gate fails closed without them.
+fn plan_review_refusal(io: &Io) -> Option<String> {
+ let s = self_cmd(io);
+ if let Some(tool) = io.env("IMPECCABLE_COMPONENT_REVIEW_TOOL") {
+ let Some(named) = io.env("IMPECCABLE_COMPONENT_REVIEW_SESSIONS") else {
+ // A harness defect, not something the agent can repair: say so rather than invite it to set the variable.
+ return Some(format!("The plan and asset review runs in the host ({tool}), but this host does not name its review sessions, so no acceptance can be verified. This is a harness configuration problem: stop and report it; do not set environment variables to work around it."));
+ };
+ let sessions: Vec<PathBuf> = std::env::split_paths(named).filter(|p| !p.as_os_str().is_empty()).collect();
+ if sessions.is_empty() {
+ return Some(format!("The plan and asset review is not accepted for this build. Call {tool} with manifest_path .impeccable/review/components.json (after `{s} component-review plan`) and wait for the user's decisions; page work waits until then."));
+ }
+ return impeccable_context::component_review::plan::gate_hosted(&sessions, &io.cwd, &s, tool).err();
+ }
+ let Some(home) = io.home() else { return Some("the plan and asset review store needs a home directory".into()) };
+ impeccable_context::component_review::plan::gate(&home.join(".impeccable/component-reviews"), &io.cwd, &s).err()
+}
+
+/// The plan review as the hero phase sees it. A plates advance forced with a quoted
+/// user downgrade waived the review along with the plate readings, so it stays waived.
+fn hero_plan_review_refusal(io: &Io, state: &Value) -> Option<String> {
+ if state.pointer("/phases/plates/forced").is_some_and(|f| !f.is_null()) { return None; }
+ plan_review_refusal(io)
+}
+
+/// Whether the user accepted an assembled first viewport for this build, in the local
+/// review store or in the sessions a host names.
+fn first_viewport_accepted(io: &Io) -> bool {
+ let sessions: Vec<PathBuf> = io.env("IMPECCABLE_COMPONENT_REVIEW_SESSIONS")
+ .map(|named| std::env::split_paths(named).filter(|p| !p.as_os_str().is_empty()).collect()).unwrap_or_default();
+ let store = io.home().map(|h| h.join(".impeccable/component-reviews"));
+ impeccable_context::component_review::plan::first_viewport_accepted(store.as_deref(), &sessions, &io.cwd)
+}
+
/// JS: forceAllowed(reason).
fn force_allowed(reason: Option<&str>) -> bool {
use once_cell::sync::Lazy;
@@ -2377,7 +2527,14 @@ fn advance(io: &Io, state: &mut Value, force: bool, reason: Option<&str>, opts:
if let Some(p) = state.pointer_mut(&format!("/phases/{phase}")).and_then(|p| p.as_object_mut()) {
p.insert("gate".into(), gate.record_json(&now()));
}
- if phase == "plates" { save_plate_receipts(state, &gate); }
+ if phase == "plates" {
+ save_plate_receipts(state, &gate);
+ if let Some(why) = plan_review_refusal(io) { gate.ok = false; gate.reasons.push(why); }
+ } else if phase == "hero" {
+ // The same spec-change gate `record hero` applies: a reclassified region after
+ // the plates closed reopens the plan review before the hero can close.
+ if let Some(why) = hero_plan_review_refusal(io, state) { gate.ok = false; gate.reasons.push(why); }
+ }
if !gate.ok && force && !force_allowed(reason) {
if let Some(p) = state.pointer_mut(&format!("/phases/{phase}")).and_then(|p| p.as_object_mut()) {
p.insert("status".into(), json!("open"));
@@ -2391,7 +2548,7 @@ fn advance(io: &Io, state: &mut Value, force: bool, reason: Option<&str>, opts:
}
if phase == "hero" && gate.score.is_some() {
let artifact = opts.artifact.clone().or_else(|| state.get("artifact").and_then(Value::as_str).map(String::from)).unwrap_or_else(|| "index.html".into());
- if let Some(stuck) = hero_loop_verdict(state, &gate, &artifact, io) {
+ if let Some(stuck) = hero_loop_verdict(state, &gate, &artifact, io, first_viewport_accepted(io)) {
if !gate.ok {
let mut r = vec![stuck];
r.extend(gate.reasons.clone());
@@ -2464,7 +2621,7 @@ fn next_instruction(io: &Io, state: &Value) -> String {
"Measure the comp: {s} comp-spec --comp {comp} --grid, open {}, write regions.json (every illustration, photo, texture as its own plate region; every text block its own text region), run {s} comp-spec --comp {comp} --regions regions.json. Then measure the type: {s} font-match --measure <id> for each text region (cap height, width class, weight class) and {s} font-match --rank <lead text region> --text \"<its first words>\" to choose the headline face by metrics (the USE line is the CSS; with no browser it records the catalog's nearest face, which is the choice; do not install one, and do not write a chosen face into the spec by hand). Then {s} build-phase advance.",
format!("{BUILD_DIR}/comp-grid.png")
),
- "plates" => format!("Produce every plate in the spec ({s} comp-spec --print lists them). For each illustration, photo, or figure, run {s} comp-spec --crop <id> --out <crop.png> and save {s} comp-spec --plate-prompt <id> to a prompt file. For an isolated figure or object on the page ground, add --background transparent to that plate-prompt command. Prefer the harness image tool with the crop as reference and that prompt; request native transparent PNG for cutouts. With the API fallback, run {s} generate-image --ref <crop.png> --prompt-file <prompt.txt> --out <plate.png> --size <WxH> --quality high; add --background transparent for cutouts. Create the output directory first and choose a supported size matching the region's aspect at least 1.5x its pixel size. generate-image embeds the prompt; after a harness generation run {s} embed-prompt <plate.png> --prompt-file <prompt.txt>. Preserve white paint, fine edges, and interior holes; verify alpha and inspect the cutout on light and dark grounds. Do not chroma-key native transparent output. Keep photos and textures opaque. Place cutouts with a plain <img> over the page's own ground; inspect glass and other translucent material carefully. Textures (paper, cloth, grain): crop a clean patch from {s} comp-spec --crop <id> --raw and mirror-tile it to the plate size; generate only when no clean patch exists. The gate scores a texture against its whole region box, so draw its region around clean ground. Keep candidate crops in separate files. Test each with {s} build-phase check-plate <id> --candidate <png> --json; this does not replace the selected asset or advance state. Inspect the candidate before explicitly selecting it at the spec plate path. Then {s} build-phase advance scores all selected plates against their comp regions. A pass does not replace visual inspection of placement, scale, and alpha. Write no page code before this passes."),
+ "plates" => format!("Produce every plate in the spec ({s} comp-spec --print lists them). For each illustration, photo, or figure, run {s} comp-spec --crop <id> --out <crop.png> and save {s} comp-spec --plate-prompt <id> to a prompt file. For an isolated figure or object on the page ground, add --background transparent to that plate-prompt command. Prefer the harness image tool with the crop as reference and that prompt; request native transparent PNG for cutouts. With the API fallback, run {s} generate-image --ref <crop.png> --prompt-file <prompt.txt> --out <plate.png> --size <WxH> --quality high; add --background transparent for cutouts. Create the output directory first and choose a supported size matching the region's aspect at least 1.5x its pixel size. generate-image embeds the prompt; after a harness generation run {s} embed-prompt <plate.png> --prompt-file <prompt.txt>. Preserve white paint, fine edges, and interior holes; verify alpha and inspect the cutout on light and dark grounds. Do not chroma-key native transparent output. Keep photos and textures opaque. Place cutouts with a plain <img> over the page's own ground; inspect glass and other translucent material carefully. Textures (paper, cloth, grain): crop a clean patch from {s} comp-spec --crop <id> --raw and mirror-tile it to the plate size; generate only when no clean patch exists. The gate scores a texture against its whole region box, so draw its region around clean ground. Keep candidate crops in separate files. Test each with {s} build-phase check-plate <id> --candidate <png> --json; this does not replace the selected asset or advance state. Inspect the candidate before explicitly selecting it at the spec plate path. Then {s} build-phase advance scores all selected plates against their comp regions. A pass does not replace visual inspection of placement, scale, and alpha. Score the plates before the review opens: once advance reports nothing but the pending review, run {s} component-review plan, then {s} component-review capture --manifest .impeccable/review/components.json and {s} component-review serve --session <session>, and wait for the user: advance also waits until they accept this plan and asset review for the current spec. A plate replaced after they accept needs a new round. Write no page code before this passes."),
"hero" => format!(
"Run {s} build-phase scaffold first: it writes the measured layout as CSS custom properties (.impeccable/build/scaffold/layout.css, --r-<id>-x/y/w/h in % of the comp, plus cap height, font-size, family, and weight where measured) and a reference page with every region at its box. Bind those numbers to your own markup (an element per region, its box from the properties); the reference is a check, not the page, and overlapping boxes are overlapping boxes. Build only the first viewport at {}. Copy the comp's words verbatim in this phase (headline, labels, table cells, footer): the user approved that comp with those words, and rewriting is a later, stated decision, never a silent one here. Set every text region's font-size from its measured cap height and its face from the ranking. Plates first: place every plate at its spec box ({s} comp-spec --print lists boxes as percentages of the viewport) with object-fit: cover before writing a line of text or a control, capture into {HERO_REPRO}, and run {s} build-phase record hero (not advance) once so you see the plate regions read as match before text exists; then lay the semantic layer (text, controls, rules) over the plates from the spec's palette and boxes, capture, advance. When it fails, open the region crops it lists first, in order, then fix; do not build past the hero until it passes.",
bp.unwrap_or("the comp size")
@@ -2977,6 +3134,10 @@ pub fn run_with_renderer(argv: &[String],io: &mut Io,organic_scan: OrganicScan,r
io.err("build-phase: record hero --build <png>\n");
return 1;
}
+ if let Some(why) = hero_plan_review_refusal(io, &state) {
+ io.err(&format!("build-phase: record hero refused. {why}\n"));
+ return 1;
+ }
let build_path = arg(argv, "build").unwrap_or(HERO_REPRO).to_string();
let min = arg(argv, "min").map(|m| util::parse_f64(m, HERO_MIN)).unwrap_or(HERO_MIN);
let gate = gate_hero(io, &mut state, &build_path, min, ".impeccable/review/diff/hero", None, organic_scan, renderer);
diff --git a/crates/comp-verbs/src/build_phase/integrity_tests.rs b/crates/comp-verbs/src/build_phase/integrity_tests.rs
index ce6a492ce..91d2e96ff 100644
--- a/crates/comp-verbs/src/build_phase/integrity_tests.rs
+++ b/crates/comp-verbs/src/build_phase/integrity_tests.rs
@@ -111,7 +111,7 @@ fn stall_feedback_does_not_rebuild_a_nonblocking_plate() {
gate.score = Some(0.7524);
gate.worst_ids = vec!["accepted-fox".into()];
for _ in 0..3 {
- if let Some(message) = hero_loop_verdict(&mut state, &gate, "missing.html", &io) {
+ if let Some(message) = hero_loop_verdict(&mut state, &gate, "missing.html", &io, false) {
assert!(!message.contains("accepted-fox"), "{message}");
assert!(!message.contains("generate-image"), "{message}");
}
@@ -886,3 +886,258 @@ fn quoted_plate_force_holds_for_the_same_bytes_but_not_a_changed_plate() {
assert!(failure.reasons.iter().any(|r| r.contains("comp crop")), "{:?}", failure.reasons);
assert!(state["plates"]["art"]["forced"].is_null());
}
+
+#[test]
+fn page_work_waits_for_the_plan_and_asset_review_of_the_current_spec() {
+ let ws = Workspace::new();
+ let home = ws.path.join("home");
+ std::fs::create_dir_all(&home).unwrap();
+ let project = ws.path.join("project");
+ let write = |file: &str, bytes: &[u8]| { let p = project.join(file); std::fs::create_dir_all(p.parent().unwrap()).unwrap(); std::fs::write(p, bytes).unwrap(); };
+ write("comp.png", b"comp");
+ write("art.png", b"plate");
+ write(SPEC_PATH, br#"{"comp":"comp.png","compSize":{"width":64,"height":64},"regions":[{"id":"art","kind":"plate","medium":"raster","plate":"art.png","note":"Figure","box":{"x":0,"y":0,"w":1,"h":1}}]}"#);
+ let io_with = |extra: &[(&str, &str)]| {
+ let mut env: std::collections::HashMap<String, String> = [("HOME".to_string(), home.to_string_lossy().into_owned())].into();
+ env.extend(extra.iter().map(|(k, v)| (k.to_string(), v.to_string())));
+ Io::captured("", project.clone(), env)
+ };
+ let (io, _) = io_with(&[]);
+ let why = plan_review_refusal(&io).expect("no review exists yet");
+ assert!(why.contains("not accepted") && why.contains("impeccable component-review plan"), "{why}");
+ // advance from plates carries the refusal with the plate readings.
+ let mut state = json!({"phase":"plates","comp":"comp.png","phases":{"plates":{"attempts":0},"hero":{}}});
+ let opts = GateOpts { build_path: None, min: None, artifact: None };
+ let result = advance(&io, &mut state, false, None, &opts, &no_organic_scan, None);
+ assert!(!result.ok && result.reasons.iter().any(|r| r.contains("plan and asset review")), "{:?}", result.reasons);
+ assert_eq!(state["phase"], "plates");
+ // record hero refuses before measuring anything.
+ write(".impeccable/build/state.json", br#"{"phase":"hero","startedAt":"s","phases":{"hero":{}}}"#);
+ let (mut io, captured) = io_with(&[]);
+ assert_eq!(run(&["record", "hero"].map(String::from), &mut io, &no_organic_scan), 1);
+ let err = String::from_utf8(captured.stderr.borrow().clone()).unwrap();
+ assert!(err.contains("record hero refused") && err.contains("component-review capture --manifest .impeccable/review/components.json"), "{err}");
+ // advance from hero applies the same check, so a spec change after the plates closed cannot slip past it.
+ let mut state = json!({"phase":"hero","comp":"comp.png","phases":{"plates":{"status":"closed"},"hero":{"attempts":0}}});
+ let result = advance(&io, &mut state, false, None, &opts, &no_organic_scan, None);
+ assert!(!result.ok && result.reasons.iter().any(|r| r.contains("plan and asset review")), "{:?}", result.reasons);
+ // A plates advance forced with a quoted downgrade waived the review; the hero phase honours that.
+ let mut forced = json!({"phase":"hero","comp":"comp.png","phases":{"plates":{"status":"closed","forced":{"reason":"quoted"}},"hero":{"attempts":0}}});
+ assert!(hero_plan_review_refusal(&io, &forced).is_none());
+ let result = advance(&io, &mut forced, false, None, &opts, &no_organic_scan, None);
+ assert!(!result.reasons.iter().any(|r| r.contains("plan and asset review")), "{:?}", result.reasons);
+ // A hosted session fails closed: no named sessions, or sessions without an accepted review.
+ let (hosted, _) = io_with(&[("IMPECCABLE_COMPONENT_REVIEW_TOOL", "component_review")]);
+ let why = plan_review_refusal(&hosted).unwrap();
+ assert!(why.contains("harness configuration problem") && why.contains("do not set environment variables"), "{why}");
+ let (hosted, _) = io_with(&[("IMPECCABLE_COMPONENT_REVIEW_TOOL", "component_review"), ("IMPECCABLE_COMPONENT_REVIEW_SESSIONS", "")]);
+ let why = plan_review_refusal(&hosted).unwrap();
+ assert!(why.contains("is not accepted for this build") && why.contains("Call component_review") && !why.contains("IMPECCABLE_COMPONENT_REVIEW_SESSIONS"), "{why}");
+ let (hosted, _) = io_with(&[("IMPECCABLE_COMPONENT_REVIEW_TOOL", "component_review"), ("IMPECCABLE_COMPONENT_REVIEW_PENDING", "0")]);
+ assert!(plan_review_refusal(&hosted).is_some(), "the retired pending flag opens nothing");
+ let empty = ws.path.join("host-session");
+ std::fs::create_dir_all(&empty).unwrap();
+ let (hosted, _) = io_with(&[("IMPECCABLE_COMPONENT_REVIEW_TOOL", "component_review"), ("IMPECCABLE_COMPONENT_REVIEW_SESSIONS", empty.to_str().unwrap())]);
+ assert!(plan_review_refusal(&hosted).is_some());
+ // A spec with nothing to decide has no review to wait for.
+ write(SPEC_PATH, br#"{"comp":"comp.png","regions":[{"id":"copy","kind":"text","note":"Body","box":{"x":0,"y":0,"w":1,"h":1}}]}"#);
+ assert!(plan_review_refusal(&io_with(&[]).0).is_none());
+}
+
+struct ReviewedCapture(crate::entry_capture::EntryEvidence, Option<crate::entry_capture::ApprovedReference>);
+impl CapturedEntry for ReviewedCapture {
+ fn approved_reference(&self) -> Option<&crate::entry_capture::ApprovedReference> { self.1.as_ref() }
+ fn evidence(&self) -> &crate::entry_capture::EntryEvidence { &self.0 }
+ 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>> }
+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] },
+ self.approved.clone().map(|png| crate::entry_capture::ApprovedReference { png, proof: json!({"schema": "test-review"}) }))))
+ }
+}
+
+/// A comp with a striped headline and a dark plate; `restyled` turns the headline's stripes
+/// (a contradicted text reading), `plate_shown` decides whether the plate renders.
+fn reviewed_hero(restyled: bool, plate_shown: bool) -> Image {
+ let mut img = r::create_image(200, 120, [230, 220, 200, 255]);
+ if plate_shown {
+ r::fill_rect(&mut img, 18., 18., 44., 44., [40., 40., 40., 255.]);
+ for y in (20..60).step_by(4) { r::fill_rect(&mut img, 20., y as f64, 40., 2., [200., 120., 60., 255.]); }
+ }
+ r::fill_rect(&mut img, 120., 84., 60., 24., [20., 50., 80., 255.]);
+ if restyled {
+ for x in (122..178).step_by(3) { r::fill_rect(&mut img, x as f64, 86., 1., 20., [240., 240., 240., 255.]); }
+ } else {
+ for y in (86..106).step_by(3) { r::fill_rect(&mut img, 124., y as f64, 52., 1., [240., 240., 240., 255.]); }
+ }
+ img
+}
+
+fn run_reviewed_hero(capture: &Image, approved: Option<&Image>, html: &str) -> (Gate, Value) {
+ run_reviewed_hero_min(capture, approved, html, HERO_MIN)
+}
+
+fn run_reviewed_hero_min(capture: &Image, approved: Option<&Image>, html: &str, min: f64) -> (Gate, Value) {
+ let ws = Workspace::new();
+ let comp = reviewed_hero(false, true);
+ let png = |i: &Image| png_io::encode_png(i, &[]).unwrap();
+ ws.write("comp.png", &png(&comp));
+ ws.write("art.png", &png(&r::crop(&comp, 10., 10., 60., 60.)));
+ ws.write("index.html", html.as_bytes());
+ let art = json!({"id":"art","kind":"plate","medium":"raster","plate":"art.png","note":"dark printed square",
+ "box":{"x":0.05,"y":0.0833,"w":0.3,"h":0.5},"px":{"x":10,"y":10,"w":60,"h":60}});
+ let spec = json!({"comp":"comp.png","regions":[art.clone(), {"id":"headline","kind":"text","medium":"semantic","note":"striped headline lettering",
+ "type":{},"box":{"x":0.6,"y":0.7,"w":0.3,"h":0.2},"px":{"x":120,"y":84,"w":60,"h":24}}]});
+ ws.write(SPEC_PATH, util::json_pretty(&spec).as_bytes());
+ let io = ws.io();
+ let receipt = json!({"status":"ok","score":0.9,"file":"art.png","assetHash":sha256_file(&io,"art.png"),"compHash":sha256_file(&io,"comp.png"),"regionHash":sha256_bytes(util::json_pretty(&art).as_bytes()),"referenceHash":plate_reference_hash(&spec)});
+ let mut state = json!({"comp":"comp.png","capturePolicy":"native-html-v1","plates":{"art":receipt},"phases":{"hero":{}}});
+ let renderer = ReviewedRenderer { hero: png(capture), approved: approved.map(png) };
+ 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)
+}
+
+const REVIEWED_PAGE: &str = "<main><img src=\"art.png\"><h1>Headline</h1></main>";
+
+#[test]
+fn accepted_first_viewport_review_turns_a_contradicted_text_region_into_an_advisory() {
+ let current = reviewed_hero(true, true);
+ let contradicted = |g: &Gate| g.reasons.iter().any(|r| r.contains("headline (text) is contradicted"));
+ let (unreviewed, _) = run_reviewed_hero(&current, None, REVIEWED_PAGE);
+ assert!(contradicted(&unreviewed), "{:?}", unreviewed.reasons);
+ let (reviewed, report) = run_reviewed_hero(&current, Some(&current), REVIEWED_PAGE);
+ assert!(!contradicted(&reviewed), "{:?}", reviewed.reasons);
+ assert!(reviewed.advisories.iter().any(|a| a.contains("accepted in the first-viewport review") && a.contains("headline")), "{:?}", reviewed.advisories);
+ assert_eq!(report["humanHeroReview"]["acceptedRegions"], json!(["headline"]));
+ assert_eq!(report["humanHeroReview"]["proof"]["schema"], "test-review");
+}
+
+#[test]
+fn stale_first_viewport_approval_waives_nothing() {
+ // The user approved a different rendering of the headline than the one captured now.
+ let (gate, report) = run_reviewed_hero(&reviewed_hero(true, true), Some(&reviewed_hero(false, true)), REVIEWED_PAGE);
+ assert!(!gate.ok);
+ assert!(gate.reasons.iter().any(|r| r.contains("headline (text) is contradicted")), "{:?}", gate.reasons);
+ assert!(!gate.advisories.iter().any(|a| a.contains("first-viewport review")), "{:?}", gate.advisories);
+ assert_eq!(report["humanHeroReview"]["acceptedRegions"], json!([]));
+}
+
+#[test]
+fn accepted_first_viewport_review_keeps_material_vetoes() {
+ // An inline SVG drawing blocks even though the user approved exactly this capture.
+ let current = reviewed_hero(true, true);
+ let svg = format!("{REVIEWED_PAGE}<svg width=\"400\" height=\"300\" viewBox=\"0 0 400 300\">{}</svg>",
+ (0..12).map(|i| format!("<path d=\"M{i} 0 C {} 40 80 {} 120 {i} S 200 90 240 {}\"/>", i * 7, i * 9, i * 11)).collect::<String>());
+ let (gate, _) = run_reviewed_hero(&current, Some(&current), &svg);
+ assert!(!gate.ok);
+ assert!(gate.reasons.iter().any(|r| r.contains("inline SVG")), "{:?}", gate.reasons);
+ assert!(!gate.reasons.iter().any(|r| r.contains("headline (text) is contradicted")), "{:?}", gate.reasons);
+ // A plate that does not render stays missing, approved or not.
+ let blank = reviewed_hero(true, false);
+ let (gate, report) = run_reviewed_hero(&blank, Some(&blank), REVIEWED_PAGE);
+ assert!(!gate.ok, "{report}");
+ assert!(gate.reasons.iter().any(|r| r.contains("region art is missing")), "{:?}", gate.reasons);
+ // And an unreferenced plate refuses before any comparison.
+ let (gate, _) = run_reviewed_hero(&current, Some(&current), "<main><h1>Headline</h1></main>");
+ assert!(gate.reasons.iter().any(|r| r.contains("is not referenced")), "{:?}", gate.reasons);
+}
+
+#[test]
+fn third_failed_hero_attempt_sends_the_agent_to_the_first_viewport_review() {
+ let ws = Workspace::new();
+ let io = ws.io();
+ let mut state = json!({"phases":{"hero":{}}});
+ let mut gate = Gate::fail(vec!["hero overall 61% < 80%".into()]);
+ gate.score = Some(0.61);
+ assert!(hero_loop_verdict(&mut state, &gate, "index.html", &io, false).is_none());
+ gate.reasons = vec!["region headline (text) is contradicted".into()];
+ assert!(hero_loop_verdict(&mut state, &gate, "index.html", &io, false).is_none());
+ let third = hero_loop_verdict(&mut state, &gate, "index.html", &io, false).unwrap();
+ assert!(third.starts_with("The hero gate has failed three attempts in a row. Stop iterating and present the first-viewport review"), "{third}");
+ assert!(hero_loop_verdict(&mut state, &gate, "index.html", &io, false).unwrap().starts_with("The same hero gate checks remain unresolved"));
+ let mut passed = Gate::fail(vec![]);
+ passed.ok = true;
+ passed.score = Some(0.9);
+ assert!(hero_loop_verdict(&mut state, &passed, "index.html", &io, false).is_none());
+}
+
+#[test]
+fn third_failed_hero_attempt_after_acceptance_asks_to_restore_not_to_review_again() {
+ // The review store hands back the accepted session, so asking for a new review would loop.
+ let ws = Workspace::new();
+ let io = ws.io();
+ let mut state = json!({"phases":{"hero":{}}});
+ let mut gate = Gate::fail(vec!["the hero capture no longer matches the first viewport the user accepted".into()]);
+ gate.score = Some(0.61);
+ for _ in 0..2 { assert!(hero_loop_verdict(&mut state, &gate, "index.html", &io, true).is_none()); }
+ let third = hero_loop_verdict(&mut state, &gate, "index.html", &io, true).unwrap();
+ assert!(third.contains("already accepted a first viewport") && third.contains("Restore what they accepted"), "{third}");
+ assert!(!third.contains("present the first-viewport review"), "{third}");
+}
+
+#[test]
+fn accepted_first_viewport_turns_the_overall_bar_into_an_advisory() {
+ // A tiled ground can never land on the comp's repeats: the bar fails on a correct page.
+ let current = reviewed_hero(true, true);
+ let bar = |g: &Gate| g.reasons.iter().any(|r| r.starts_with("hero overall"));
+ let (unreviewed, _) = run_reviewed_hero_min(&current, None, REVIEWED_PAGE, 0.999);
+ assert!(bar(&unreviewed), "{:?}", unreviewed.reasons);
+ let (accepted, report) = run_reviewed_hero_min(&current, Some(&current), REVIEWED_PAGE, 0.999);
+ assert!(accepted.ok, "{:?}", accepted.reasons);
+ assert!(accepted.advisories[0].starts_with("The user accepted this first viewport in the review"), "{:?}", accepted.advisories);
+ assert!(accepted.advisories.iter().any(|a| a.starts_with("(advisory, first viewport accepted) hero overall")), "{:?}", accepted.advisories);
+ assert_eq!(report["humanHeroReview"]["viewportAccepted"], true);
+ // A stale approval (another rendering) closes nothing.
+ let (stale, report) = run_reviewed_hero_min(&current, Some(&reviewed_hero(false, true)), REVIEWED_PAGE, 0.999);
+ assert!(!stale.ok && !bar(&stale), "{:?}", stale.reasons);
+ assert!(stale.reasons[0].starts_with("the hero capture no longer matches the first viewport the user accepted") && stale.reasons[0].contains("changed: headline") && stale.reasons[0].ends_with("Restore what the user accepted; until then the readings apply.") && !stale.reasons[0].contains("review"), "{:?}", stale.reasons);
+ assert!(stale.advisories.iter().any(|a| a.starts_with("(measured) hero overall")), "the raw score is kept as a measurement: {:?}", stale.advisories);
+ assert_eq!(report["humanHeroReview"]["viewportAccepted"], false);
+ // The material veto still blocks under an accepted, below-bar viewport.
+ let blank = reviewed_hero(true, false);
+ let (missing, _) = run_reviewed_hero_min(&blank, Some(&blank), REVIEWED_PAGE, 0.999);
+ assert!(!missing.ok);
+ assert_eq!(missing.reasons.iter().filter(|r| !r.contains("region art is missing")).count(), 0, "only the material veto blocks: {:?}", missing.reasons);
+}
+
+struct DesktopRenderer { desktop: Vec<u8>, approved: Option<Vec<u8>> }
+impl EntryRenderer for DesktopRenderer {
+ fn capture_entry(&self, _: &EntryRequest) -> Result<Box<dyn CapturedEntry>, String> {
+ let frame = |name: &str| crate::entry_capture::FrameEvidence { name: name.into(), png: self.desktop.clone(), regions: vec![] };
+ Ok(Box::new(ReviewedCapture(crate::entry_capture::EntryEvidence { report: json!({}), frames: vec![frame("desktop"), frame("mobile")] },
+ self.approved.clone().map(|png| crate::entry_capture::ApprovedReference { png, proof: json!({"schema": "test-review"}) }))))
+ }
+}
+
+#[test]
+fn responsive_does_not_relitigate_an_accepted_first_viewport_score() {
+ let ws = Workspace::new();
+ let comp = reviewed_hero(false, false);
+ let png = |i: &Image| png_io::encode_png(i, &[]).unwrap();
+ ws.write("comp.png", &png(&comp));
+ ws.write("index.html", b"<main><h1>Headline</h1></main>");
+ ws.write(SPEC_PATH, util::json_pretty(&json!({"comp":"comp.png","regions":[{"id":"headline","kind":"control","medium":"semantic","note":"striped headline lettering",
+ "box":{"x":0.6,"y":0.7,"w":0.3,"h":0.2},"px":{"x":120,"y":84,"w":60,"h":24}}]})).as_bytes());
+ let current = reviewed_hero(true, false);
+ let run = |approved: Option<&Image>| {
+ let mut state = json!({"comp":"comp.png","capturePolicy":"native-html-v1","phases":{}});
+ gate_responsive(&ws.io(), &mut state, 0.999, "diff", Some(&DesktopRenderer { desktop: png(&current), approved: approved.map(png) }))
+ };
+ let unreviewed = run(None);
+ assert!(!unreviewed.ok && unreviewed.reasons.iter().any(|r| r.contains("scores")), "{:?}", unreviewed.reasons);
+ // Accepted, then shared CSS changed without changing the first viewport: the renderer
+ // still hands over the approval and the pixels still match, so the waiver holds.
+ let accepted = run(Some(&current));
+ assert!(accepted.ok, "{:?}", accepted.reasons);
+ assert!(accepted.advisories.iter().any(|a| a.starts_with("(advisory, first viewport accepted) the desktop capture scores")), "{:?}", accepted.advisories);
+ // A later edit that changes the first viewport: the acceptance lapses and the gate says so.
+ let lapsed = run(Some(&comp));
+ assert!(!lapsed.ok);
+ 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);
+}
diff --git a/crates/comp-verbs/src/comp_spec.rs b/crates/comp-verbs/src/comp_spec.rs
index a99a740e9..942b4d7a6 100644
--- a/crates/comp-verbs/src/comp_spec.rs
+++ b/crates/comp-verbs/src/comp_spec.rs
@@ -37,6 +37,29 @@ static PAINTED_NOTE: Lazy<Regex> = Lazy::new(|| {
Regex::new(r"(?i)\b(diagram|drawing|drawn|illustration|illustrations|illustrated|figure|schematic|exploded|photo|photos|photograph\w*|picture|painting|painted|render|rendered|rendering|artwork|engraving|etching|linework|line art|texture|textured|textures|grain|fabric|halftone|watercolou?r|sketch|sketched|blueprint|geometry|leader lines?|callout lines?|thumbnail|silhouette|product shot|hero image|3d)\b").unwrap()
});
+/// A raster note that names a frame (surround, window, shutters, doorway,
+/// arch...) and then an opening onto content behind it (a view, "showing",
+/// "looking out", an interior, "photograph of"). Order matters: in "photograph
+/// of a window" or "coast seen through a carriage window" the frame is the
+/// content, and a bare "framed portrait" gives no sign the frame is separate.
+static FRAME_WORD: Lazy<Regex> = Lazy::new(|| Regex::new(r"(?i)\b(surround(?:s|ed)?|frame[ds]?|framing|windows?|doorway|doors?|arch(?:es)?|archway|shutter(?:s|ed)?|cartouche|portal|niche|alcove|mirror|porthole|casement|proscenium)\b").unwrap());
+static OPENING: Lazy<Regex> = Lazy::new(|| Regex::new(r"(?i)\b(views?|viewing|vista|showing|shows|reveal(?:s|ing)?|looking (?:out|through|into|onto|over)|looks? (?:out|onto|into)|inside|interior|through|beyond|opening (?:onto|to|on)|opens? (?:onto|to|on)|glimpse|(?:photo(?:graph)?|scene|picture|image) of)\b").unwrap());
+static MOVING: Lazy<Regex> = Lazy::new(|| Regex::new(r"(?i)\b(shutters?|doors?|gates?|curtains?|blinds?)\b").unwrap());
+
+/// The reviewer-facing observation when a raster note bakes a frame around the content it opens onto.
+pub fn baked_composite(note: &str) -> Option<String> {
+ static BLEED: Lazy<Regex> = Lazy::new(|| Regex::new(r"(?i)full-?(?:frame|bleed)|frame[- ]filling").unwrap());
+ // A note that leads with the content ("photograph through window: ...") describes the
+ // view; a window or doors later in it are its subject matter, not a frame around it.
+ static CONTENT_LEAD: Lazy<Regex> = Lazy::new(|| Regex::new(r"(?i)^\W*(?:(?:a|an|the)\s+)?(?:[\w-]+\s+){0,2}?(?:photo(?:graph)?s?|views?|scenes?|pictures?|images?)\b").unwrap());
+ if CONTENT_LEAD.is_match(note.split([':', ',', ';']).next().unwrap_or("")) { return None; }
+ let note = BLEED.replace_all(note, "");
+ let frame = FRAME_WORD.find(&note)?;
+ OPENING.find_at(&note, frame.end())?;
+ let moving = MOVING.find(&note).map(|m| format!(" or move the {} on their own", m.as_str().to_lowercase())).unwrap_or_else(|| " on its own".into());
+ Some(format!("Frame and view are one image here, so the page can't swap the view{moving}."))
+}
+
/// JS: gridToBox(span). Err(message) mirrors the thrown Error.
pub fn grid_to_box(span: &str) -> Result<(f64, f64, f64, f64), String> {
static RE: Lazy<Regex> = Lazy::new(|| Regex::new(r"(?i)^([A-J])([0-9]):([A-J])([0-9])$").unwrap());
@@ -400,6 +423,162 @@ fn uncovered_ink_cells(comp: &Image, regions: &[Value]) -> Vec<String> {
cells
}
+/// Painted-pixel reading of a code region's comp crop: how many colours sit
+/// off the line between its two main tones (ground and ink, with every
+/// antialiased mix between them), and the share of continuous-tone pixels in
+/// its busy 8x8 blocks. Type and flat controls stay near their two tones;
+/// photographs, rendered figures and material surfaces do not.
+#[derive(Clone, Copy, Debug, PartialEq)]
+pub struct PaintedPixels { pub colours: usize, pub soft: f64 }
+/// A window reads painted when any clause holds: (colours, soft) at least
+/// (18, 0.44) or (28, 0.38), or 60 colours alone. Calibrated on 556 regions of
+/// 12 eval comps plus 24 replayed runs: no text or control region that shows
+/// only type reads painted, while every photograph and about half the plates do
+/// (the misses are small single-ink sprigs that look like type).
+pub const PAINTED_CLAUSES: [(usize, f64); 3] = [(18, 0.44), (28, 0.38), (60, 0.)];
+
+fn seg_dist(p: [f64; 3], a: [f64; 3], b: [f64; 3]) -> f64 {
+ let ab = [b[0] - a[0], b[1] - a[1], b[2] - a[2]];
+ let l2 = ab.iter().map(|v| v * v).sum::<f64>();
+ let t = if l2 == 0. { 0. } else { ((0..3).map(|k| (p[k] - a[k]) * ab[k]).sum::<f64>() / l2).clamp(0., 1.) };
+ (0..3).map(|k| (a[k] + t * ab[k] - p[k]).powi(2)).sum::<f64>().sqrt()
+}
+
+/// Side of the square window the painted reading is taken over, in comp
+/// pixels. A fixed window keeps the reading independent of how much calm
+/// ground a box also holds: a painted patch reads the same in a tight box and
+/// in a generous one.
+pub const PAINTED_WINDOW: usize = 64;
+
+/// The strongest reading over `PAINTED_WINDOW` windows (half-window stride; a
+/// crop smaller than a window is one window). None when no window keeps half
+/// its pixels and 64 samples (`skip` marks crop pixels another raster region owns).
+pub fn painted_pixels(img: &Image, skip: &dyn Fn(usize, usize) -> bool) -> Option<PaintedPixels> {
+ painted_pixels_window(img, skip, PAINTED_WINDOW)
+}
+
+pub fn painted_pixels_window(img: &Image, skip: &dyn Fn(usize, usize) -> bool, win: usize) -> Option<PaintedPixels> {
+ let starts = |n: usize| -> Vec<usize> { let w = win.min(n) & !1; if w == 0 { return vec![]; }
+ let mut v: Vec<usize> = (0..=(n - w)).step_by((w / 2).max(2) & !1).collect(); if *v.last().unwrap() != (n - w) & !1 { v.push((n - w) & !1); } v };
+ let (ww, wh) = (win.min(img.width) & !1, win.min(img.height) & !1);
+ let score = painted_score;
+ let mut best: Option<PaintedPixels> = None;
+ for &y in &starts(img.height) { for &x in &starts(img.width) {
+ let Some(p) = painted_window(img, skip, x, y, ww, wh) else { continue; };
+ if best.as_ref().map_or(true, |b| score(&p) > score(b)) { best = Some(p); }
+ }}
+ best
+}
+
+fn painted_window(img: &Image, skip: &dyn Fn(usize, usize) -> bool, x0: usize, y0: usize, w: usize, h: usize) -> Option<PaintedPixels> {
+ let d = &img.data;
+ let px = |x: usize, y: usize| { let i = (y * img.width + x) * 4; [d[i] as f64, d[i + 1] as f64, d[i + 2] as f64] };
+ let key = |p: [f64; 3]| ((p[0] as u32 >> 4) << 8) | ((p[1] as u32 >> 4) << 4) | (p[2] as u32 >> 4);
+ // 2x box average: comp grain and paper noise average out, painted tone does not.
+ let mut samples: Vec<[f64; 3]> = Vec::new();
+ for y in (y0..y0 + h).step_by(2) { for x in (x0..x0 + w).step_by(2) {
+ let cells = [(x, y), (x + 1, y), (x, y + 1), (x + 1, y + 1)];
+ if cells.iter().any(|&(cx, cy)| skip(cx, cy)) { continue; }
+ let s = cells.iter().fold([0.; 3], |a, &(cx, cy)| { let p = px(cx, cy); [a[0] + p[0], a[1] + p[1], a[2] + p[2]] });
+ samples.push([(s[0] / 4.).floor(), (s[1] / 4.).floor(), (s[2] / 4.).floor()]);
+ }}
+ if samples.len() < 64 || samples.len() * 8 < w * h { return None; }
+ let mut bins: std::collections::BTreeMap<u32, (usize, [f64; 3])> = Default::default();
+ for &p in &samples { let e = bins.entry(key(p)).or_insert((0, [0.; 3])); e.0 += 1; for k in 0..3 { e.1[k] += p[k]; } }
+ let mut ranked: Vec<(usize, [f64; 3])> = bins.values().map(|&(n, s)| (n, [s[0] / n as f64, s[1] / n as f64, s[2] / n as f64])).collect();
+ ranked.sort_by(|a, b| b.0.cmp(&a.0));
+ let ground = ranked[0].1;
+ let ink = ranked.iter().map(|r| r.1).find(|c| seg_dist(*c, ground, ground) > 48.).unwrap_or(ground);
+ let mut off: std::collections::HashMap<u32, usize> = Default::default();
+ for &p in &samples { if seg_dist(p, ground, ink) > 24. { *off.entry(key(p)).or_default() += 1; } }
+ let min = (samples.len() as f64 * 0.002).max(2.);
+ let colours = off.values().filter(|&&n| n as f64 >= min).count();
+ let (mut mid, mut busy) = (0usize, 0usize);
+ for by in (y0..y0 + h.saturating_sub(7)).step_by(8) { for bx in (x0..x0 + w.saturating_sub(7)).step_by(8) {
+ let cells: Vec<(usize, usize)> = (0..64).map(|k| (bx + k % 8, by + k / 8)).collect();
+ if cells.iter().any(|&(x, y)| skip(x, y)) { continue; }
+ let l: Vec<f64> = cells.iter().map(|&(x, y)| { let p = px(x, y); 0.299 * p[0] + 0.587 * p[1] + 0.114 * p[2] }).collect();
+ let (lo, hi) = l.iter().fold((f64::MAX, f64::MIN), |(a, b), &v| (a.min(v), b.max(v)));
+ if hi - lo < 24. { continue; }
+ busy += 64;
+ mid += l.iter().filter(|&&v| (v - lo) / (hi - lo) > 0.25 && (v - lo) / (hi - lo) < 0.75).count();
+ }}
+ Some(PaintedPixels { colours, soft: if busy == 0 { 0. } else { mid as f64 / busy as f64 } })
+}
+
+/// How far the reading gets toward its nearest clause; 1 or more reads painted.
+fn painted_score(p: &PaintedPixels) -> f64 {
+ PAINTED_CLAUSES.iter().map(|&(c, s)| (p.colours as f64 / c as f64).min(if s > 0. { p.soft / s } else { f64::MAX })).fold(0., f64::max)
+}
+
+pub fn reads_painted(p: &PaintedPixels) -> bool {
+ PAINTED_CLAUSES.iter().any(|&(c, s)| p.colours >= c && p.soft >= s)
+}
+
+/// What a code region's own pixels hold once raster regions and smaller
+/// regions inside it are set aside. `flat`: under 2% of them leave the main
+/// tone (a bare ground). `rules`: the box is at most 6px on its short side, or
+/// its ink is straight hairlines, at least 80% of ink pixels on a horizontal or
+/// vertical run of 12px or more that is at most 6px thick. Neither needs a
+/// human decision; emblems, marks and icons are neither.
+#[derive(Clone, Copy, Debug, PartialEq)]
+pub struct Surface { pub flat: bool, pub rules: bool }
+
+pub fn surface_of(img: &Image, skip: &dyn Fn(usize, usize) -> bool) -> Surface {
+ let (w, h, d) = (img.width, img.height, &img.data);
+ let px = |x: usize, y: usize| { let i = (y * w + x) * 4; [d[i] as f64, d[i + 1] as f64, d[i + 2] as f64] };
+ let key = |p: [f64; 3]| ((p[0] as u32 >> 4) << 8) | ((p[1] as u32 >> 4) << 4) | (p[2] as u32 >> 4);
+ let mut bins: std::collections::HashMap<u32, (usize, [f64; 3])> = Default::default();
+ let mut kept = 0usize;
+ for y in 0..h { for x in 0..w { if skip(x, y) { continue; } kept += 1;
+ let p = px(x, y); let e = bins.entry(key(p)).or_insert((0, [0.; 3])); e.0 += 1; for k in 0..3 { e.1[k] += p[k]; } } }
+ let thin_box = w.min(h) <= 6;
+ let Some(&(n, sum)) = bins.values().max_by_key(|v| v.0) else { return Surface { flat: true, rules: thin_box }; };
+ let ground = sum.map(|v| v / n as f64);
+ let ink: Vec<bool> = (0..w * h).map(|i| !skip(i % w, i / w) && seg_dist(px(i % w, i / w), ground, ground) > 32.).collect();
+ let count = ink.iter().filter(|&&v| v).count();
+ // Length of the ink run through each pixel, per axis (index = y * w + x).
+ let runs = |horizontal: bool| -> Vec<usize> {
+ let (outer, inner) = if horizontal { (h, w) } else { (w, h) };
+ let at = |o: usize, i: usize| if horizontal { o * w + i } else { i * w + o };
+ let mut out = vec![0; w * h];
+ for o in 0..outer { let mut i = 0; while i < inner {
+ if !ink[at(o, i)] { i += 1; continue; }
+ let start = i; while i < inner && ink[at(o, i)] { i += 1; }
+ for k in start..i { out[at(o, k)] = i - start; }
+ }}
+ out
+ };
+ let (hr, vr) = (runs(true), runs(false));
+ let straight = (0..w * h).filter(|&i| ink[i] && ((hr[i] >= 12 && vr[i] <= 6) || (vr[i] >= 12 && hr[i] <= 6))).count();
+ Surface { flat: (count as f64) < 0.02 * kept as f64, rules: thin_box || (count > 0 && straight as f64 >= 0.8 * count as f64) }
+}
+
+/// Per code region: `surface` (above) and, when its crop reads painted, a
+/// `painted-pixels` flag. The flag is never a refusal; it sends the region to
+/// the human plan review. Pixels inside raster regions belong to their plates;
+/// containers are judged on what shows between their raster children.
+fn code_region_readings(comp: &Image, regions: &mut [Value]) {
+ let pxbox = |r: &Value| ["x", "y", "w", "h"].map(|k| r["px"][k].as_i64().unwrap_or(0));
+ let boxes: Vec<(String, bool, [i64; 4])> = regions.iter().filter(|r| r["kind"] != "band")
+ .map(|r| (r["id"].as_str().unwrap_or("").to_string(), r["kind"].as_str().is_some_and(is_raster_kind), pxbox(r))).collect();
+ let inside = |b: &[i64; 4], gx: i64, gy: i64| gx >= b[0] && gx < b[0] + b[2] && gy >= b[1] && gy < b[1] + b[3];
+ for region in regions.iter_mut() {
+ if !matches!(region["kind"].as_str(), Some("text" | "control" | "chrome")) { continue; }
+ let [x, y, w, h] = pxbox(region);
+ let crop = r::crop(comp, x as f64, y as f64, w as f64, h as f64);
+ let raster = |cx: usize, cy: usize| boxes.iter().any(|(_, r, b)| *r && inside(b, x + cx as i64, y + cy as i64));
+ // Smaller regions inside this one (its text, its controls) are theirs to judge.
+ let owned = |cx: usize, cy: usize| boxes.iter().any(|(id, r, b)| (*r || (b[2] * b[3] < w * h && region["id"] != id.as_str())) && inside(b, x + cx as i64, y + cy as i64));
+ let sf = surface_of(&crop, &owned);
+ region["surface"] = json!({"flat": sf.flat, "rules": sf.rules});
+ let Some(p) = painted_pixels(&crop, &raster).filter(reads_painted) else { continue; };
+ region["flags"] = json!([{"id": "painted-pixels", "message": format!(
+ "Looks painted: {} colours beyond its two main tones and soft shading across {}% of it. Drawn in code, this becomes a flat copy.",
+ p.colours, round(p.soft * 100.) as i64)}]);
+ }
+}
+
fn box_json(b: (f64, f64, f64, f64)) -> Value {
json!({ "x": r4(b.0), "y": r4(b.1), "w": r4(b.2), "h": r4(b.3) })
}
@@ -585,6 +764,25 @@ pub fn measure_regions(comp: &Image, regions_input: &Value, comp_path: &str) ->
obj.insert("text".into(), raw.get("text").filter(|v| !v.is_null()).cloned().unwrap_or(Value::Null));
regions.push(Value::Object(obj));
}
+ code_region_readings(comp, &mut regions);
+ // A frame plate with its own opening already decomposes whatever it covers.
+ static OPEN_FRAME: Lazy<Regex> = Lazy::new(|| Regex::new(r"(?i)\b(transparent|open|cut-?out|empty)\s+(opening|centre|center|aperture|window)\b|\bcut-?out\b").unwrap());
+ let pxb = |r: &Value| ["x", "y", "w", "h"].map(|k| r["px"][k].as_f64().unwrap_or(0.));
+ let frames: Vec<(Value, [f64; 4])> = regions.iter()
+ .filter(|r| r["kind"] == "plate" && r["note"].as_str().is_some_and(|n| FRAME_WORD.is_match(n) && OPEN_FRAME.is_match(n)))
+ .map(|r| (r["id"].clone(), pxb(r))).collect();
+ for region in regions.iter_mut().filter(|r| r["kind"].as_str().is_some_and(is_raster_kind)) {
+ let b = pxb(region);
+ let framed = frames.iter().any(|(id, f)| *id != region["id"] && {
+ let ix = (b[0] + b[2]).min(f[0] + f[2]) - b[0].max(f[0]);
+ let iy = (b[1] + b[3]).min(f[1] + f[3]) - b[1].max(f[1]);
+ ix > 0. && iy > 0. && ix * iy >= 0.5 * b[2] * b[3]
+ });
+ if framed { continue; }
+ if let Some(message) = region["note"].as_str().and_then(baked_composite) {
+ region["flags"] = json!([{"id": "baked-composite", "message": message}]);
+ }
+ }
let uncovered = uncovered_ink_cells(comp, &regions);
if uncovered.len() > 3 && !truthy(regions_input.get("allowUncovered")) {
return Err(format!(
@@ -846,6 +1044,16 @@ pub fn print_spec(spec: &Value) -> String {
note.map(|n| format!(" # {n}")).unwrap_or_default()
));
}
+ for r in &regions {
+ for f in r["flags"].as_array().into_iter().flatten() {
+ let advice = match f["id"].as_str() {
+ Some("painted-pixels") => " If it shows an illustration, photograph or texture, make it a plate, image or texture region; the plan review asks the user either way.",
+ Some("baked-composite") => " Split it: a frame plate with a transparent opening, the view as its own image region beneath it, and moving parts (shutters, doors) as their own plates; the page composites the overlapping regions.",
+ _ => "",
+ };
+ lines.push(format!("FLAG {} {}: {}{advice}", r["id"].as_str().unwrap_or(""), f["id"].as_str().unwrap_or(""), f["message"].as_str().unwrap_or("")));
+ }
+ }
let plates: Vec<&Value> = regions.iter().filter(|r| r.get("medium").and_then(Value::as_str) == Some("raster")).collect();
let plate_ids = plates.iter().filter_map(|r| r.get("id").and_then(Value::as_str)).collect::<Vec<_>>().join(", ");
lines.push(format!("PLATES {} to produce: {}", plates.len(), if plate_ids.is_empty() { "none".to_string() } else { plate_ids }));
@@ -1266,4 +1474,172 @@ mod reference_tests {
assert!(!reference.fully_excluded());
assert!(reference.issue("art").is_none());
}
+
+ /// Deterministic noise so the synthetic crops carry comp-like grain.
+ fn grain(seed: &mut u64) -> f64 { *seed = seed.wrapping_mul(6364136223846793005).wrapping_add(1442695040888963407); ((*seed >> 33) % 13) as f64 - 6. }
+
+ fn text_like(ground: [f64; 3], ink: [f64; 3]) -> Image {
+ let mut img = r::create_image(240, 80, [0, 0, 0, 255]);
+ let mut seed = 7;
+ for y in 0..80 { for x in 0..240 {
+ // Glyph-ish strokes with a one-pixel antialiased ramp on each side.
+ let t = match (x % 9, (y / 20) % 2 == 0 && y % 20 > 4 && y % 20 < 16) { (3 | 4, true) => 1., (2 | 5, true) => 0.5, _ => 0. };
+ let i = (y * 240 + x) * 4;
+ for k in 0..3 { img.data[i + k] = (ground[k] + (ink[k] - ground[k]) * t + grain(&mut seed)).clamp(0., 255.) as u8; }
+ }}
+ img
+ }
+
+ #[test]
+ fn flat_type_on_grained_ground_does_not_read_painted() {
+ for (ground, ink) in [([236., 229., 214.], [40., 36., 30.]), ([34., 38., 44.], [235., 235., 230.]), ([226., 160., 60.], [30., 70., 45.])] {
+ let p = painted_pixels(&text_like(ground, ink), &|_, _| false).unwrap();
+ assert!(!reads_painted(&p), "{p:?}");
+ }
+ }
+
+ #[test]
+ fn continuous_tone_crop_reads_painted_and_is_flagged_on_a_code_region() {
+ // A shaded, multi-hue surface: what a photograph or rendered figure looks like.
+ let mut comp = r::create_image(240, 160, [0, 0, 0, 255]);
+ let mut seed = 11;
+ for y in 0..160 { for x in 0..240 {
+ let (fx, fy) = (x as f64 / 240., y as f64 / 160.);
+ let i = (y * 240 + x) * 4;
+ let rgb = [60. + 180. * fx * (1. - 0.5 * fy), 40. + 150. * (fy * 3.1).sin().abs(), 50. + 170. * ((fx + fy) * 2.3).cos().abs()];
+ for k in 0..3 { comp.data[i + k] = (rgb[k] + grain(&mut seed)).clamp(0., 255.) as u8; }
+ }}
+ let p = painted_pixels(&comp, &|_, _| false).unwrap();
+ assert!(reads_painted(&p), "{p:?}");
+ let input = json!({"allowUncovered": true, "regions": [
+ {"id": "figure", "kind": "chrome", "note": "decorative panel", "container": true, "pixelBox": {"x": 0, "y": 0, "w": 120, "h": 160}},
+ {"id": "art", "kind": "plate", "note": "the same surface as art", "pixelBox": {"x": 120, "y": 0, "w": 120, "h": 160}}]});
+ let spec = measure_regions(&comp, &input, "comp.png").unwrap();
+ assert_eq!(spec["regions"][0]["flags"][0]["id"], "painted-pixels");
+ assert!(spec["regions"][1].get("flags").is_none(), "raster regions are never flagged");
+ assert!(print_spec(&spec).contains("FLAG figure painted-pixels: Looks painted: ") && print_spec(&spec).contains("make it a plate, image or texture region"));
+ assert!(!spec["regions"][0]["flags"][0]["message"].as_str().unwrap().contains("make it"), "the stored message is an observation for the reviewer");
+ // A code region wholly covered by a raster region has no pixels of its own to judge.
+ let covered = json!({"allowUncovered": true, "regions": [
+ {"id": "caption", "kind": "text", "note": "caption over the art", "pixelBox": {"x": 20, "y": 20, "w": 80, "h": 60}},
+ {"id": "art", "kind": "image", "note": "full photograph", "pixelBox": {"x": 0, "y": 0, "w": 240, "h": 160}}]});
+ assert!(measure_regions(&comp, &covered, "comp.png").unwrap()["regions"][0].get("flags").is_none());
+ }
+
+ fn paint(comp: &mut Image, x0: usize, y0: usize, w: usize, h: usize, seed: &mut u64) {
+ for y in y0..y0 + h { for x in x0..x0 + w {
+ let (fx, fy) = ((x - x0) as f64 / w as f64, (y - y0) as f64 / h as f64);
+ let i = (y * comp.width + x) * 4;
+ let rgb = [60. + 180. * fx * (1. - 0.5 * fy), 40. + 150. * (fy * 3.1).sin().abs(), 50. + 170. * ((fx + fy) * 2.3).cos().abs()];
+ for k in 0..3 { comp.data[i + k] = (rgb[k] + grain(seed)).clamp(0., 255.) as u8; }
+ }}
+ }
+
+ #[test]
+ fn a_painted_patch_reads_the_same_in_a_tight_box_and_a_generous_one() {
+ // Type on paper with a painted sprig at the left, like foliage over a nav bar.
+ let mut comp = text_like([236., 229., 214.], [40., 36., 30.]);
+ let mut wide = r::create_image(640, 80, [0, 0, 0, 255]);
+ for y in 0..80 { for x in 0..640 { let (i, j) = ((y * 640 + x) * 4, (y * 240 + x % 240) * 4); wide.data[i..i + 4].copy_from_slice(&comp.data[j..j + 4]); } }
+ let mut seed = 5;
+ paint(&mut wide, 0, 8, 72, 64, &mut seed);
+ comp = wide;
+ let readings: Vec<PaintedPixels> = [120, 240, 400, 640].iter().map(|&w| painted_pixels(&r::crop(&comp, 0., 0., w as f64, 80.), &|_, _| false).unwrap()).collect();
+ assert!(readings.iter().all(reads_painted), "{readings:?}");
+ assert!(readings.windows(2).all(|p| p[0] == p[1]), "the strongest window is the same window: {readings:?}");
+ assert!(!reads_painted(&painted_pixels(&r::crop(&comp, 120., 0., 520., 80.), &|_, _| false).unwrap()), "type alone stays code");
+ }
+
+ #[test]
+ fn containers_flag_on_unmapped_painted_material_between_their_raster_children() {
+ let mut comp = r::create_image(480, 200, [236, 229, 214, 255]);
+ let mut seed = 9;
+ paint(&mut comp, 20, 20, 140, 160, &mut seed);
+ paint(&mut comp, 300, 20, 140, 160, &mut seed);
+ let map = |mapped_both: bool| {
+ let mut regions = vec![json!({"id": "grid", "kind": "control", "container": true, "note": "grid of room cards", "pixelBox": {"x": 0, "y": 0, "w": 480, "h": 200}}),
+ json!({"id": "photo-a", "kind": "image", "note": "room photograph", "pixelBox": {"x": 20, "y": 20, "w": 140, "h": 160}})];
+ if mapped_both { regions.push(json!({"id": "photo-b", "kind": "image", "note": "room photograph", "pixelBox": {"x": 300, "y": 20, "w": 140, "h": 160}})); }
+ measure_regions(&comp, &json!({"allowUncovered": true, "regions": regions}), "comp.png").unwrap()
+ };
+ assert_eq!(map(false)["regions"][0]["flags"][0]["id"], "painted-pixels", "the second photograph is in no raster region");
+ assert!(map(true)["regions"][0].get("flags").is_none(), "every painted pixel belongs to a plate");
+ }
+
+ #[test]
+ fn surface_separates_grounds_and_rules_from_marks() {
+ let ground = [30, 50, 80, 255];
+ let mut comp = r::create_image(800, 240, ground);
+ r::fill_rect(&mut comp, 10., 10., 300., 2., [200., 170., 90., 255.]); // a hairline rule
+ r::fill_rect(&mut comp, 40., 40., 120., 14., [240., 240., 240., 255.]); // a text child on the ground
+ for a in 0..360 { // a ring mark with a dot: curves, not rules
+ let t = a as f64 * std::f64::consts::PI / 180.;
+ r::fill_rect(&mut comp, (340. + 20. * t.cos()).round(), (80. + 20. * t.sin()).round(), 2., 2., [200., 170., 90., 255.]);
+ }
+ r::fill_rect(&mut comp, 337., 77., 6., 6., [200., 170., 90., 255.]);
+ let input = json!({"allowUncovered": true, "regions": [
+ {"id": "rule", "kind": "chrome", "note": "brass hairline rule", "pixelBox": {"x": 5, "y": 4, "w": 310, "h": 14}},
+ {"id": "panel", "kind": "chrome", "note": "blue panel ground", "pixelBox": {"x": 20, "y": 30, "w": 280, "h": 80}},
+ {"id": "label", "kind": "text", "note": "white label text", "pixelBox": {"x": 38, "y": 38, "w": 124, "h": 18}},
+ {"id": "mark", "kind": "chrome", "note": "brass ring mark", "pixelBox": {"x": 312, "y": 52, "w": 56, "h": 56}},
+ {"id": "tick", "kind": "chrome", "note": "short tick", "pixelBox": {"x": 320, "y": 10, "w": 40, "h": 5}}]});
+ let spec = measure_regions(&comp, &input, "comp.png").unwrap();
+ let surface = |i: usize| (spec["regions"][i]["surface"]["flat"] == true, spec["regions"][i]["surface"]["rules"] == true);
+ assert_eq!(surface(0), (false, true), "a hairline rule");
+ assert_eq!(surface(1), (true, false), "the panel's own pixels are bare ground once its label is set aside");
+ assert_eq!(surface(3), (false, false), "a mark is neither");
+ assert_eq!(surface(4).1, true, "a box under 6px is a rule");
+ }
+
+ #[test]
+ fn a_frame_note_that_opens_onto_content_is_a_baked_composite() {
+ // The live hotel run: frame, shutters and room photograph baked into one plate.
+ let hotel = baked_composite("painted stone window surround with keystone, green louvred shutters open, view inside of a whitewashed bedroom with linen bed and a balcony window to the sea").unwrap();
+ assert_eq!(hotel, "Frame and view are one image here, so the page can't swap the view or move the shutters on their own.");
+ assert!(baked_composite("small painted window with rose surround and open green shutters showing a bright hotel bedroom interior").is_some());
+ assert_eq!(baked_composite("arched stone niche framing a photograph of the owner").unwrap(), "Frame and view are one image here, so the page can't swap the view on its own.");
+ // The frame is the content, the frame comes after the view, or nothing opens onto content.
+ for note in ["a photograph of a window with blue shutters", "large sunlit coast photograph seen through a dark train carriage window",
+ "Room 4 Il Limone sea window photo", "framed portrait photo", "Full-frame deep blue Ligurian sea and sky",
+ "painted pale stone cartouche plaque with scalloped arched top, empty centre", "small dark green painted wooden shutter panel with louvre slats"] {
+ assert!(baked_composite(note).is_none(), "{note}");
+ }
+ }
+
+ #[test]
+ fn baked_composites_are_flagged_on_raster_regions_only() {
+ let comp = r::create_image(200, 100, [236, 229, 214, 255]);
+ let note = "painted window surround with open shutters, view of the sea";
+ let input = json!({"allowUncovered": true, "regions": [
+ {"id": "window", "kind": "plate", "note": note, "pixelBox": {"x": 0, "y": 0, "w": 80, "h": 100}},
+ {"id": "caption", "kind": "text", "note": "caption beside the window view of the sea", "codeDrawn": true, "pixelBox": {"x": 100, "y": 10, "w": 60, "h": 20}}]});
+ let spec = measure_regions(&comp, &input, "comp.png").unwrap();
+ assert_eq!(spec["regions"][0]["flags"], json!([{"id": "baked-composite", "message": "Frame and view are one image here, so the page can't swap the view or move the shutters on their own."}]));
+ assert!(spec["regions"][1].get("flags").is_none());
+ assert!(print_spec(&spec).contains("FLAG window baked-composite: Frame and view are one image here") && print_spec(&spec).contains("a frame plate with a transparent opening"));
+ }
+
+ #[test]
+ fn decomposed_views_are_not_baked_composites() {
+ let views = ["photograph through window: whitewashed guest room, blue-striped bed, balcony doors open to the sea",
+ "photograph through window: pergola terrace with a laid table and the sea beyond",
+ "view through the window of a tiled kitchen with copper pans and a door open onto the garden"];
+ for note in views { assert!(baked_composite(note).is_none(), "content-led note: {note}"); }
+ for note in ["painted stone window surround with keystone, green louvred shutters open, view inside of a whitewashed bedroom with linen bed and a balcony window to the sea",
+ "painted stone window surround with keystone, green louvred shutters open, view of a pergola terrace with a laid table, lantern and the sea",
+ "painted stone window surround with keystone, green louvred shutters open, view down a Ligurian cliff to the blue sea"] {
+ assert!(baked_composite(note).is_some(), "{note}");
+ }
+ // The same composite note under its own frame plate is already split; alone it is not.
+ let comp = r::create_image(400, 300, [236, 229, 214, 255]);
+ let baked = "painted stone window surround with keystone, green louvred shutters open, view inside of a whitewashed bedroom";
+ let map = |framed: bool| {
+ let mut regions = vec![json!({"id": "view-room", "kind": "image", "note": baked, "pixelBox": {"x": 40, "y": 40, "w": 120, "h": 200}})];
+ if framed { regions.push(json!({"id": "frame-3", "kind": "plate", "note": "painted grey stone window surround with pediment and sill, transparent opening", "pixelBox": {"x": 20, "y": 20, "w": 160, "h": 260}})); }
+ measure_regions(&comp, &json!({"allowUncovered": true, "regions": regions}), "comp.png").unwrap()
+ };
+ assert_eq!(map(false)["regions"][0]["flags"][0]["id"], "baked-composite");
+ let split = map(true);
+ assert!(split["regions"][0].get("flags").is_none() && split["regions"][1].get("flags").is_none(), "{split}");
+ }
}
diff --git a/crates/comp-verbs/src/map_inspection.html b/crates/comp-verbs/src/map_inspection.html
index 8b324332e..d2e93038c 100644
--- a/crates/comp-verbs/src/map_inspection.html
+++ b/crates/comp-verbs/src/map_inspection.html
@@ -5,102 +5,54 @@
<meta name="viewport" content="width=device-width,initial-scale=1">
<title>Region map · Impeccable</title>
<style>
- :root {
- color-scheme: light;
- --paper: #f6f7f5;
- --panel: #fff;
- --ink: #202623;
- --muted: #5b655f;
- --line: #d2d9d4;
- --accent: #00685f;
- --danger: #a6361d;
- --warning: #7a4d09;
- font: 14px/1.45 'Avenir Next', system-ui, sans-serif;
- color: var(--ink);
- background: var(--paper);
- }
+ /* Fonts ship beside this page (fonts/), declared with their variable weight ranges. */
+ @font-face { font-family: "Albert Sans"; src: url(fonts/albertsans.ttf); font-weight: 100 900; }
+ @font-face { font-family: "Alumni Sans"; src: url(fonts/alumnisans.ttf); font-weight: 100 900; }
+ @font-face { font-family: "JetBrains Mono"; src: url(fonts/jetbrainsmono.ttf); font-weight: 100 800; }
+/*__KS_KIT__*/
+ :root { font: 400 14px/1.5 var(--ks-font); color: var(--ks-text); background: var(--ks-paper); }
+ button, a { font: inherit; }
* { box-sizing: border-box; }
[hidden] { display: none !important; }
body { margin: 0; }
button, select, a { font: inherit; }
- button, select {
- color: inherit;
- background: var(--panel);
- border: 1px solid var(--line);
- border-radius: 4px;
- padding: 7px 11px;
- cursor: pointer;
- }
- button:hover { background: #eaf1ed; }
- button[aria-pressed=true] { background: var(--accent); border-color: var(--accent); color: white; }
- button:disabled { opacity: .45; cursor: default; }
- a { color: var(--accent); text-underline-offset: 3px; }
- :is(button, select, a, summary):focus-visible { outline: 2px solid var(--accent); outline-offset: 3px; }
- ::selection { background: #c3e3d9; }
+ :is(button, select, a, summary):focus-visible { outline: 2px solid var(--ks-focus-ring); outline-offset: 3px; }
+ ::selection { background: oklch(82% 0.07 188); }
header {
- height: 68px;
+ min-height: 72px;
display: flex;
- align-items: center;
+ align-items: baseline;
gap: 20px;
- padding: 12px 24px;
- background: var(--panel);
- box-shadow: 0 2px 8px #17261b12;
- position: relative;
- z-index: 2;
+ padding: 18px 28px 14px;
+ border-bottom: 1px solid var(--ks-rule);
}
- h1 { font-size: 20px; line-height: 1.3; margin: 0; }
- header p { margin: 0; color: var(--muted); font-size: 13px; }
- header a { margin-left: auto; font-size: 12px; }
- #sheets { display: flex; align-items: center; flex-wrap: wrap; gap: 12px; margin-bottom: 18px; font-size: 12px; }
+ h1 { font: 300 34px/1.04 var(--ks-font-display); font-variation-settings: 'wght' 300; color: var(--ks-ink); margin: 0; }
+ header p { margin: 0; color: var(--ks-text-muted); font-size: var(--ks-type-ui-size); }
+ header a { margin-left: auto; font-size: var(--ks-type-ui-size); }
+ #sheets { display: flex; align-items: center; flex-wrap: wrap; gap: 14px; margin-bottom: 22px; font-size: var(--ks-type-ui-size); }
#sheets:empty { display: none; }
- .layout { display: grid; grid-template-columns: 220px minmax(0, 1fr); height: calc(100dvh - 68px); }
- nav { background: var(--panel); border-right: 1px solid var(--line); overflow: auto; padding: 14px 12px; }
- .filters { display: flex; gap: 4px; margin-bottom: 14px; }
- .filters button { flex: 1; font-size: 12px; padding: 7px 3px; }
- .region {
- display: flex;
- align-items: center;
- gap: 9px;
- text-align: left;
- width: 100%;
- margin-bottom: 4px;
- border-color: transparent;
- background: none;
- padding: 10px 8px;
- overflow-wrap: anywhere;
- }
- .region[aria-current=true] { background: #e4eeea; border-color: #8dbbb0; }
- .region .dot { flex: 0 0 7px; height: 7px; background: var(--line); border-radius: 50%; }
- .region.error .dot { background: var(--danger); }
- .region.masked .dot { background: var(--warning); }
- .region .name { flex: 1; }
- .region .status { font-size: 11px; white-space: nowrap; color: var(--warning); font-variant-numeric: tabular-nums; }
- .region.error .status { color: var(--danger); }
- #related { display: flex; flex-wrap: wrap; align-items: center; gap: 6px; margin-top: 10px; font-size: 12px; color: var(--muted); }
+ .layout { display: grid; grid-template-columns: 232px minmax(0, 1fr); height: calc(100dvh - 72px); }
+ nav { border-right: 1px solid var(--ks-rule); overflow: auto; padding: 18px 14px; }
+ #related { display: flex; flex-wrap: wrap; align-items: center; gap: 6px; margin-top: 12px; font-size: var(--ks-type-label-size); color: var(--ks-text-muted); }
#related:empty { display: none; }
- #related button { padding: 4px 8px; font-size: 12px; }
- main { min-width: 0; overflow: auto; padding: 24px; }
- .heading { display: flex; justify-content: space-between; align-items: start; gap: 20px; margin-bottom: 20px; }
- h2 { font-size: 24px; line-height: 1.2; margin: 0 0 8px; font-weight: 600; }
+ main { min-width: 0; overflow: auto; padding: 26px 28px; }
+ .heading { display: flex; justify-content: space-between; align-items: start; gap: 20px; margin-bottom: 22px; }
+ h2 { font-size: 1.5rem; line-height: 1.2; margin: 0 0 8px; font-weight: 500; color: var(--ks-ink); }
#explanation { margin: 0; max-width: 65ch; }
- #explanation.error { color: var(--danger); }
+ #explanation.error { color: var(--ks-vermilion); }
#next { white-space: nowrap; }
- .inspection { display: grid; grid-template-columns: minmax(0, 1fr) minmax(0, 1fr); gap: 24px; align-items: start; }
+ .inspection { display: grid; grid-template-columns: minmax(0, 1fr) minmax(0, 1fr); gap: 28px; align-items: start; }
.section-title { display: flex; align-items: center; justify-content: space-between; min-height: 36px; gap: 12px; margin-bottom: 12px; }
- h3 { font-size: 14px; margin: 0; font-weight: 600; }
- .section-title button, .section-title select { font-size: 12px; padding: 5px 8px; }
- .context {
- height: clamp(280px, 48vh, 580px);
- background: #e9ede8;
- box-shadow: 0 4px 14px #17261b12;
- }
+ h3 { font: 400 var(--ks-type-eyebrow-size)/1.3 var(--ks-mono); letter-spacing: var(--ks-type-eyebrow-track); text-transform: uppercase; color: var(--ks-text-muted); margin: 0; }
+ .section-title label { font-size: var(--ks-type-label-size); color: var(--ks-text-muted); }
+ .context { height: clamp(280px, 48vh, 580px); box-shadow: 0 0 0 1px var(--ks-rule); }
.context svg { display: block; width: 100%; height: 100%; }
- .pair { display: grid; grid-template-columns: minmax(0, 1fr) minmax(0, 1fr); gap: 12px; }
+ .pair { display: grid; grid-template-columns: minmax(0, 1fr) minmax(0, 1fr); gap: 16px; }
figure { margin: 0; min-width: 0; }
- figcaption { font-size: 12px; color: var(--muted); margin-bottom: 8px; }
+ figcaption { font-size: var(--ks-type-label-size); color: var(--ks-text-muted); margin-bottom: 8px; }
.crop {
height: clamp(220px, 35vh, 440px);
- background: #e9ede8;
+ box-shadow: 0 0 0 1px var(--ks-rule);
display: grid;
place-items: center;
overflow: auto;
@@ -108,36 +60,50 @@
.crop svg { display: block; width: 100%; height: 100%; }
.crop.zoom { display: block; }
.crop.zoom svg { max-width: none; max-height: none; margin: auto; }
- .legend { display: flex; flex-wrap: wrap; gap: 14px; margin: 12px 0; color: var(--muted); font-size: 12px; }
- .key { display: inline-flex; align-items: center; gap: 6px; }
- .swatch { width: 12px; height: 12px; border: 2px solid var(--accent); }
- .swatch.covering { border-color: var(--danger); }
- #impact { font-size: 13px; margin: 14px 0; max-width: 55ch; }
- .details { margin-top: 28px; border-top: 1px solid var(--line); padding-top: 16px; }
+ .legend { display: flex; flex-wrap: wrap; gap: 16px; margin: 12px 0; color: var(--ks-text-muted); font-size: var(--ks-type-label-size); }
+ .key { display: inline-flex; align-items: center; gap: 7px; }
+ .swatch { width: 12px; height: 12px; border: 2px solid var(--ks-patina-deep); }
+ .swatch.covering { border: 2px dashed var(--ks-vermilion); }
+ #impact { font-size: var(--ks-type-ui-size); margin: 14px 0; max-width: 55ch; }
+ .details { margin-top: 32px; border-top: 1px solid var(--ks-rule); padding-top: 16px; }
details { margin: 0 0 16px; }
- summary { cursor: pointer; font-size: 13px; color: var(--muted); }
- details p { font-size: 12px; margin: 8px 0; overflow-wrap: anywhere; }
- .issue { padding: 9px 0; font-size: 12px; border-bottom: 1px solid var(--line); }
- .issue b { display: block; font-weight: 600; }
- .issue.error b { color: var(--danger); }
- .empty { color: var(--muted); font-size: 13px; }
+ summary { cursor: pointer; font-size: var(--ks-type-ui-size); color: var(--ks-text-muted); }
+ summary:hover { color: var(--ks-ink); }
+ details p { font-size: var(--ks-type-label-size); margin: 8px 0; overflow-wrap: anywhere; }
+ .issue { padding: 10px 0; font-size: var(--ks-type-label-size); border-bottom: 1px solid var(--ks-rule); }
+ .issue b { display: block; font-weight: 600; color: var(--ks-ink); }
+ .issue.error b { color: var(--ks-vermilion); }
+ .empty { color: var(--ks-text-muted); font-size: var(--ks-type-ui-size); }
@media(max-width: 1000px) {
- .layout { grid-template-columns: 190px minmax(0, 1fr); }
+ .layout { grid-template-columns: 196px minmax(0, 1fr); }
.inspection { grid-template-columns: 1fr; }
.context { height: 360px; }
.crop { height: 280px; }
}
@media(max-width: 600px) {
- header { height: auto; padding: 14px; flex-wrap: wrap; gap: 6px 16px; }
- h1 { font-size: 18px; }
- header p { font-size: 12px; }
+ header { min-height: 0; padding: 16px; flex-wrap: wrap; gap: 6px 16px; }
+ h1 { font-size: 28px; }
+ header p { font-size: var(--ks-type-label-size); }
.layout { display: block; height: auto; }
- nav { height: 190px; border-bottom: 1px solid var(--line); }
- main { padding: 18px; }
+ nav { height: 190px; border-right: 0; border-bottom: 1px solid var(--ks-rule); }
+ main { padding: 18px 16px; }
.heading { flex-wrap: wrap; }
.context { height: 300px; }
.crop { height: 220px; }
}
+ .strip-row { margin-bottom: 18px; }
+ .strip-row .ks-instrument-strip { width: 100%; }
+ .strip-row .ks-instrument-key { flex: 1; justify-content: center; }
+ nav.docs-kinpaku .skills-sidebar-list a { display: flex; align-items: baseline; gap: 10px; overflow-wrap: anywhere; }
+ nav.docs-kinpaku .skills-sidebar-list a .name { flex: 1; }
+ .status { font: 500 var(--ks-type-label-size)/1 var(--ks-mono); white-space: nowrap; color: var(--ks-text); font-variant-numeric: tabular-nums; font-weight: 500; }
+ .is-error .status { color: var(--ks-vermilion); }
+ .text-action { border: 0; background: none; padding: 0 2px; color: var(--ks-link-on-paper); font: inherit; text-decoration: underline; text-decoration-color: var(--ks-link-on-paper-line); text-underline-offset: 3px; cursor: pointer; }
+ .text-action:hover { text-decoration-color: var(--ks-link-on-paper-line-hover); }
+ a { color: var(--ks-link-on-paper); text-decoration-color: var(--ks-link-on-paper-line); text-underline-offset: 3px; }
+ a:hover { text-decoration-color: var(--ks-link-on-paper-line-hover); }
+ #related .text-action { font-size: var(--ks-type-label-size); }
+ .zoom-strip .ks-instrument-key { padding: 0 12px 0 10px; }
</style>
</head>
<body>
@@ -147,22 +113,22 @@
<a href="report.json" target="_blank" rel="noopener">Technical report</a>
</header>
<div class="layout">
- <nav aria-label="Regions">
- <div class="filters">
- <button id="problems" aria-pressed="true">Inspect</button>
- <button id="all" aria-pressed="false">All regions</button>
- </div>
- <div id="list"></div>
+ <nav class="docs-kinpaku" aria-label="Regions">
+ <div class="strip-row"><div class="ks-instrument-strip is-paper" role="group" aria-label="Which regions to list">
+ <button type="button" class="ks-instrument-key" id="problems" aria-pressed="true">Inspect</button>
+ <button type="button" class="ks-instrument-key" id="all" aria-pressed="false">All regions</button>
+ </div></div>
+ <ul class="skills-sidebar-list" id="list"></ul>
</nav>
<main>
<div class="heading">
<div><h2 id="title">Check the region map</h2><p id="explanation"></p><div id="related"></div></div>
- <button id="next">Next check →</button>
+ <button type="button" class="ks-button ks-button-secondary" id="next">Next check</button>
</div>
<div id="sheets" aria-label="Comparison sheets"></div>
<div id="inspection" class="inspection">
<section>
- <div class="section-title"><h3>In the comp</h3><button id="context-toggle" aria-pressed="false">Show whole comp</button></div>
+ <div class="section-title"><h3>In the comp</h3><button type="button" class="ks-switch" id="context-toggle" aria-pressed="false"><span class="ks-switch-track" aria-hidden="true"><span class="ks-switch-knob"></span></span><span class="ks-switch-label">Whole comp</span></button></div>
<div class="context"><svg id="context" role="img" aria-label="Selected asset and overlapping boxes in the original comp"></svg></div>
<div class="legend">
<span class="key"><span class="swatch"></span><span id="asset-key">This asset</span></span>
@@ -170,7 +136,7 @@
</div>
</section>
<section>
- <div class="section-title"><h3>What gets compared</h3><label>Zoom <select id="zoom"><option value="fit">Fit</option><option value="1">100%</option><option value="2">200%</option><option value="4">400%</option></select></label></div>
+ <div class="section-title"><h3>What gets compared</h3><div class="ks-instrument-strip is-paper zoom-strip" id="zoom" role="group" aria-label="Zoom"><button type="button" class="ks-instrument-key" data-zoom="fit" aria-pressed="true">Fit</button><button type="button" class="ks-instrument-key" data-zoom="1" aria-pressed="false">100%</button><button type="button" class="ks-instrument-key" data-zoom="2" aria-pressed="false">200%</button><button type="button" class="ks-instrument-key" data-zoom="4" aria-pressed="false">400%</button></div></div>
<div class="pair">
<figure><figcaption>Original crop</figcaption><div class="crop" id="original"></div></figure>
<figure><figcaption id="ignored-label">Pixels ignored by the checker</figcaption><div class="crop" id="ignored"></div></figure>
@@ -201,6 +167,7 @@
let selected = null;
let filter = problemRegions.length ? 'problems' : 'all';
let wholeComp = false;
+ let zoomValue = 'fit';
function name(region) {
return region.id.replace(/-plate$/, /photo/i.test(region.note || '') ? ' photo' : ' artwork').replace(/-/g, ' ').replace(/^./, c => c.toUpperCase());
@@ -222,21 +189,23 @@
$('all').textContent = `All (${data.regions.length})`;
for (const key of ['problems', 'all']) $(key).setAttribute('aria-pressed', String(filter === key));
for (const r of filter === 'problems' ? problemRegions : data.regions) {
- const button = element('button', '', `region ${errors(r.id).length ? 'error' : r.reference?.excludedPixels ? 'masked' : ''}`);
- button.setAttribute('aria-label', name(r));
- button.setAttribute('aria-current', String(selected?.id === r.id));
- button.append(element('span', '', 'dot'), element('span', name(r), 'name'));
+ const li = document.createElement('li');
+ const link = element('a', '', errors(r.id).length ? 'is-error' : r.reference?.excludedPixels ? 'is-masked' : '');
+ link.href = `#region=${encodeURIComponent(r.id)}`;
+ if (selected?.id === r.id) link.setAttribute('aria-current', 'page');
+ link.append(element('span', name(r), 'name'));
if (errors(r.id).length || r.reference?.excludedPixels) {
const label = errors(r.id).length ? 'Error' : `${percent(r.reference)}%`;
const badge = element('span', label, 'status');
- badge.title = errors(r.id).length ? 'Map error' : `${label} excluded — inspect foreground bounds`;
- button.setAttribute('aria-description', badge.title);
- button.append(badge);
+ badge.title = errors(r.id).length ? 'Map error' : `${label} excluded. Inspect the foreground bounds.`;
+ link.setAttribute('aria-description', badge.title);
+ link.append(badge);
}
- button.onclick = () => select(r);
- $('list').append(button);
+ link.onclick = event => { event.preventDefault(); select(r); };
+ li.append(link);
+ $('list').append(li);
}
- if (!$('list').children.length) $('list').append(element('p', 'No drawable regions have errors or masked pixels. Crop accuracy still needs visual inspection; rejected entries are in Other map findings.', 'empty'));
+ if (!$('list').children.length) $('list').append(element('li', 'No drawable regions have errors or masked pixels. Crop accuracy still needs visual inspection; rejected entries are in Other map findings.', 'empty'));
}
function renderContext() {
if (!selected) return;
@@ -255,12 +224,11 @@
svg.setAttribute('viewBox', wholeComp ? `0 0 ${data.compSize.width} ${data.compSize.height}` : `${x} ${y} ${w} ${h}`);
svg.append(svgElement('image', { href: 'comp.png', width: data.compSize.width, height: data.compSize.height }));
for (const r of covering) {
- svg.append(svgElement('rect', { x: r.px.x, y: r.px.y, width: r.px.w, height: r.px.h, fill: '#a6361d12', stroke: '#a6361d', 'stroke-width': 2, 'stroke-dasharray': '6 3', 'vector-effect': 'non-scaling-stroke' }));
+ svg.append(svgElement('rect', { x: r.px.x, y: r.px.y, width: r.px.w, height: r.px.h, fill: 'oklch(52% 0.16 35 / 0.07)', stroke: 'oklch(52% 0.16 35)', 'stroke-width': 2, 'stroke-dasharray': '6 3', 'vector-effect': 'non-scaling-stroke' }));
}
- svg.append(svgElement('rect', { x: selected.px.x, y: selected.px.y, width: selected.px.w, height: selected.px.h, fill: 'none', stroke: '#00685f', 'stroke-width': 3, 'vector-effect': 'non-scaling-stroke' }));
+ svg.append(svgElement('rect', { x: selected.px.x, y: selected.px.y, width: selected.px.w, height: selected.px.h, fill: 'none', stroke: 'oklch(45% 0.10 190)', 'stroke-width': 3, 'vector-effect': 'non-scaling-stroke' }));
$('covering-key').hidden = covering.length === 0;
$('covering-key').lastChild.textContent = selected.reference ? ' Overlapping foreground' : ' Affected artwork';
- $('context-toggle').textContent = wholeComp ? 'Show nearby context' : 'Show whole comp';
$('context-toggle').setAttribute('aria-pressed', String(wholeComp));
}
function renderCrop(target, ignored) {
@@ -270,15 +238,15 @@
if (ignored && selected.reference) {
const defs = svgElement('defs', {});
const pattern = svgElement('pattern', { id: 'excluded', width: 8, height: 8, patternUnits: 'userSpaceOnUse' });
- pattern.append(svgElement('rect', { width: 8, height: 8, fill: '#a6361d20' }));
- pattern.append(svgElement('path', { d: 'M-2 2L2-2M0 8L8 0M6 10L10 6', stroke: '#a6361d', 'stroke-width': 1.2 }));
+ pattern.append(svgElement('rect', { width: 8, height: 8, fill: 'oklch(52% 0.16 35 / 0.12)' }));
+ pattern.append(svgElement('path', { d: 'M-2 2L2-2M0 8L8 0M6 10L10 6', stroke: 'oklch(52% 0.16 35)', 'stroke-width': 1.2 }));
defs.append(pattern); svg.append(defs);
for (const mask of selected.reference.regions) {
const p = mask.cropPx;
svg.append(svgElement('rect', { x: p.x, y: p.y, width: p.w, height: p.h, fill: 'url(#excluded)' }));
}
}
- const zoom = $('zoom').value;
+ const zoom = zoomValue;
target.className = `crop ${zoom === 'fit' ? '' : 'zoom'}`;
if (zoom !== 'fit') {
svg.style.width = `${selected.px.w * Number(zoom)}px`;
@@ -299,7 +267,7 @@
$('explanation').textContent = `The “${covering}” box hides this entire asset from the checker.`;
$('impact').textContent = 'Every hatched pixel is ignored. Nothing remains to compare, even if the generated asset is perfect. The covering box needs correcting.';
} else if (ref?.excludedPixels) {
- $('explanation').textContent = `${percentage}% excluded — check the foreground bounds.`;
+ $('explanation').textContent = `${percentage}% excluded. Check the foreground bounds.`;
$('impact').textContent = 'Hatching should cover foreground text or controls only. If it covers artwork in the gaps, split the foreground into tighter boxes. Keep every text element.';
} else if (affected.length) {
$('explanation').textContent = `This box excludes pixels from ${affected.length} ${affected.length === 1 ? 'asset' : 'assets'}.`;
@@ -313,7 +281,7 @@
if (related.length) {
$('related').append(element('span', ref ? 'Excluding boxes:' : 'Inspect affected assets:'));
for (const other of related) {
- const button = element('button', name(other));
+ const button = element('button', name(other), 'text-action');
button.onclick = () => select(other);
$('related').append(button);
}
@@ -331,14 +299,18 @@
$('details').append(element('p', 'Reference only. These images cannot ship as page assets. Inspection does not change build state or approvals.'));
$('next').hidden = problemRegions.length < 2;
const queueIndex = problemRegions.findIndex(p => p.id === r.id);
- $('next').textContent = queueIndex >= 0 ? `Next check (${queueIndex + 1}/${problemRegions.length}) →` : 'Next check →';
+ $('next').textContent = queueIndex >= 0 ? `Next check (${queueIndex + 1}/${problemRegions.length})` : 'Next check';
history.replaceState(null, '', `#region=${encodeURIComponent(r.id)}`);
renderList(); renderContext(); renderCrop($('original'), false); renderCrop($('ignored'), true);
}
for (const key of ['all', 'problems']) $(key).onclick = () => { filter = key; renderList(); };
$('next').onclick = () => select(problemRegions[(problemRegions.findIndex(r => r.id === selected.id) + 1) % problemRegions.length]);
$('context-toggle').onclick = () => { wholeComp = !wholeComp; renderContext(); };
- $('zoom').onchange = () => { if (selected) { renderCrop($('original'), false); renderCrop($('ignored'), true); } };
+ for (const key of document.querySelectorAll('[data-zoom]')) key.onclick = () => {
+ zoomValue = key.dataset.zoom;
+ for (const other of document.querySelectorAll('[data-zoom]')) other.setAttribute('aria-pressed', String(other === key));
+ if (selected) { renderCrop($('original'), false); renderCrop($('ignored'), true); }
+ };
$('summary').textContent = `${data.inputRegionCount} regions · ${data.issues.filter(i => i.severity === 'error').length} errors · ${partialMasks.length} partial masks to inspect`;
for (const [index, sheet] of (data.comparisonSheets || []).entries()) {
const link = element('a', `Comparison sheet ${index + 1}`);
@@ -356,5 +328,6 @@
if (data.regions.length) select(data.regions.find(r => r.id === requestedRegion) || problemRegions[0] || data.regions[0]);
else { $('inspection').hidden = true; $('next').hidden = true; $('diagnostics').open = true; renderList(); }
</script>
+ <script>/*__KS_STRIP__*/</script>
</body>
</html>
diff --git a/crates/comp-verbs/src/map_inspection.rs b/crates/comp-verbs/src/map_inspection.rs
index 289a9167c..8e2cd102e 100644
--- a/crates/comp-verbs/src/map_inspection.rs
+++ b/crates/comp-verbs/src/map_inspection.rs
@@ -405,9 +405,33 @@ fn write_report_contents(dir: &Path, comp: &Image, report: &mut Value) -> Result
.replace('&', "\\u0026")
.replace('<', "\\u003c")
.replace('>', "\\u003e");
+ // The page is standalone: the design-system kit (vendored from impeccable-site, the source of
+ // truth) is inlined, and the three licensed fonts ship beside it.
+ let kit = [
+ include_str!("../../../ui/component-review/vendor/kinpaku-tokens.css"),
+ include_str!("../../../ui/component-review/vendor/kinpaku-kit.css"),
+ include_str!("../../../ui/component-review/vendor/docs-rail.css"),
+ ]
+ .join("\n");
+ let strip = include_str!("../../../ui/component-review/vendor/instrument-strip.js").replace("export function", "function");
+ let fonts = dir.join("fonts");
+ std::fs::create_dir(&fonts).map_err(|e| e.to_string())?;
+ for (name, bytes) in [
+ ("albertsans.ttf", &include_bytes!("../../../ui/component-review/fonts/albertsans.ttf")[..]),
+ ("alumnisans.ttf", &include_bytes!("../../../ui/component-review/fonts/alumnisans.ttf")[..]),
+ ("jetbrainsmono.ttf", &include_bytes!("../../../ui/component-review/fonts/jetbrainsmono.ttf")[..]),
+ ("albertsans-OFL.txt", include_bytes!("../../../ui/component-review/fonts/albertsans-OFL.txt")),
+ ("alumnisans-OFL.txt", include_bytes!("../../../ui/component-review/fonts/alumnisans-OFL.txt")),
+ ("jetbrainsmono-OFL.txt", include_bytes!("../../../ui/component-review/fonts/jetbrainsmono-OFL.txt")),
+ ] {
+ std::fs::write(fonts.join(name), bytes).map_err(|e| e.to_string())?;
+ }
std::fs::write(
dir.join("index.html"),
- include_str!("map_inspection.html").replace("__REPORT_JSON__", &safe),
+ include_str!("map_inspection.html")
+ .replace("/*__KS_KIT__*/", &kit)
+ .replace("/*__KS_STRIP__*/", &strip)
+ .replace("__REPORT_JSON__", &safe),
)
.map_err(|e| e.to_string())
}
diff --git a/crates/context/assets/component-review.js b/crates/context/assets/component-review.js
index 91c12403a..12d102b23 100644
--- a/crates/context/assets/component-review.js
+++ b/crates/context/assets/component-review.js
@@ -1,148 +1,1131 @@
-(()=>{function Wi(a,o){let x=o?.changes[a],e=o?.feedback?.[a],n=e?.decision??(o?.submitted?o.draft.decisions[a]:void 0),p=x?.kind==="unchanged"&&(x.carried??(o?.submitted&&n?.action==="approve"))===!0;return{change:x,prior:n,feedbackRound:e?.round??o?.packet.round,carried:p,label:x?.kind==="added"?"New component":x?.kind==="changed"?"Review again":p?"Approval kept":n?.action==="revise"?"Changes still requested":"Awaiting review"}}function O(a,o,x){let e=o.decisions[a.id],n=e?.revision===a.revision?e:void 0,p=Wi(a.id,x);if(n?.action==="approve")return{kind:"approved",label:p.carried?"Approval kept":"Approved",priority:3};if(n?.action==="revise")return{kind:"feedback",label:"Feedback ready",priority:2};return{kind:"pending",label:p.change?.kind==="changed"?"Review again":p.change?.kind==="added"?"New · review needed":"Not reviewed",priority:p.change?.kind==="changed"||p.change?.kind==="added"?0:1}}function Qo(a){return{packetRevision:a.revision,decisions:{},missing:[],inventoryConfirmed:!1}}function or(a){return Object.values(a).every(Number.isFinite)&&a.x>=0&&a.y>=0&&a.w>0&&a.h>0&&a.x+a.w<=1.00001&&a.y+a.h<=1.00001}function ki(a,o){let x=a.components.map((g)=>o.decisions[g.id]?.revision===g.revision?o.decisions[g.id]:void 0),e=x.filter((g)=>g?.action==="approve").length,n=x.filter((g)=>g?.action==="revise").length,p=x.length-e-n,y=n>0||o.missing.length>0;return{approved:e,revisions:n,pending:p,hasFeedback:y,canSubmit:o.packetRevision===a.revision&&o.missing.every((g)=>g.name.trim()&&or(g.box))&&(y||!p&&o.inventoryConfirmed)}}function Yo(a,o){let x={...o.decisions};for(let e of a.components)if(!x[e.id]||x[e.id].revision!==e.revision)x[e.id]={revision:e.revision,action:"approve",feedback:"",split:!1};return{...o,decisions:x}}function _o(a,o){if(!ki(a,o).canSubmit)throw Error("Review is incomplete or stale");return{schemaVersion:1,requestId:a.id,...structuredClone(o)}}function zi(a){let o=a.preview.kind==="page"||a.preview.sourceKind==="page",x=a.preview.sourceKind==="page";return{code:o,captured:x,label:o?a.medium.match(/html|css|svg/i)?a.medium:"HTML / CSS / SVG":"Raster",caption:o?x?a.preview.isolation?"Component only":"Region capture":"Live component":"Produced asset",fileLabel:x?"Open captured preview":"Open source image"}}function Xo(a,o,x){let e=a.components.findIndex((n)=>n.id===x);for(let n=1;n<=a.components.length;n++){let p=a.components[(e+n)%a.components.length];if(O(p,o).kind==="pending")return p.id}}function Gi(a,o){if(!o.reviewGroup||!zi(o).code)return[o];return a.components.filter((x)=>x.reviewGroup===o.reviewGroup&&zi(x).code)}function Ji(a,o,x,e,n=[]){let p=e?Gi(a,x):[x];if(p.length===1)return[x];return p.filter((y)=>O(y,o).kind==="pending"&&(y.id===x.id||!n.includes(y.id)))}function Eo(a,o,x){let e=new Set;return a.components.flatMap((n)=>{if(e.has(n.id))return[];let p=Gi(a,n);p.forEach((s)=>e.add(s.id));let y=p.filter((s)=>O(s,o,x).kind==="pending"),g=p.filter((s)=>O(s,o,x).kind==="feedback"),v=y[0]??g[0]??n,Z=y.length?"pending":g.length?"feedback":"approved";return[{id:n.id,members:p,representative:v,pending:y.length,kind:Z,label:p.length>1?n.reviewGroup.replace(/[-_]+/g," ").replace(/^./,(s)=>s.toUpperCase()):n.name,box:{x:Math.min(...p.map((s)=>s.box.x)),y:Math.min(...p.map((s)=>s.box.y)),w:Math.max(...p.map((s)=>s.box.x+s.box.w))-Math.min(...p.map((s)=>s.box.x)),h:Math.max(...p.map((s)=>s.box.y+s.box.h))-Math.min(...p.map((s)=>s.box.y))},stateLabel:y.length?p.length>1?`${y.length} to review`:O(v,o,x).label:g.length?p.length>1?`${g.length} ${g.length===1?"needs":"need"} work`:"Feedback ready":"Approved"}]})}function Ti(a,o){let x=new Set(o.preview.isolation?.excludedComponents??[]),e=o.box,n=a.components.filter((p)=>{if(p.id===o.id)return!1;if(x.has(p.id))return!0;let y=p.box,g=Math.min(e.x+e.w,y.x+y.w)-Math.max(e.x,y.x),v=Math.min(e.y+e.h,y.y+y.h)-Math.max(e.y,y.y);return y.w*y.h<e.w*e.h&&g*a.comp.width>1&&v*a.comp.height>1});return{description:o.note.trim(),related:n,excluded:n.filter((p)=>x.has(p.id))}}function eo(a,o,x,e,n){let p=n==="fit"?Math.min(1,x/a,e/o):n;return{scale:p,width:a*p,height:o*p}}function no(a,o,x,e){if(x<=0||e<=x)return 0;return Math.max(0,Math.min(1,((a-o)/x-0.08)/0.84))*(e-x)}var No=`
+(()=>{function wi(e,n){let o=n?.changes[e],a=n?.feedback?.[e],t=a?.decision??(n?.submitted?n.draft.decisions[e]:void 0),p=o?.kind==="unchanged"&&(o.carried??(n?.submitted&&t?.action==="approve"))===!0;return{change:o,prior:t,feedbackRound:a?.round??n?.packet.round,carried:p,label:o?.kind==="added"?"New component":o?.kind==="changed"?"Review again":p?"Approval kept":t?.action==="revise"?"Changes still requested":"Awaiting review"}}function bn(e,n,o){let a=n.decisions[e.id],t=a?.revision===e.revision?a:void 0,p=wi(e.id,o);if(t?.action==="approve")return{kind:"approved",label:p.carried?"Approval kept":"Approved",priority:3};if(t?.action==="revise")return{kind:"feedback",label:"Feedback ready",priority:2};return{kind:"pending",label:p.change?.kind==="changed"?"Review again":p.change?.kind==="added"?"New · review needed":"Not reviewed",priority:p.change?.kind==="changed"||p.change?.kind==="added"?0:1}}function fe(e){return{packetRevision:e.revision,decisions:{},missing:[],inventoryConfirmed:!1}}function Wi(e){return Object.values(e).every(Number.isFinite)&&e.x>=0&&e.y>=0&&e.w>0&&e.h>0&&e.x+e.w<=1.00001&&e.y+e.h<=1.00001}function Cn(e,n){let o=e.components.map((g)=>n.decisions[g.id]?.revision===g.revision?n.decisions[g.id]:void 0),a=o.filter((g)=>g?.action==="approve").length,t=o.filter((g)=>g?.action==="revise").length,p=o.length-a-t,y=t>0||n.missing.length>0;return{approved:a,revisions:t,pending:p,hasFeedback:y,canSubmit:n.packetRevision===e.revision&&n.missing.every((g)=>g.name.trim()&&Wi(g.box))&&(y||!p&&n.inventoryConfirmed)}}function we(e,n){let o={...n.decisions};for(let a of e.components)if(!o[a.id]||o[a.id].revision!==a.revision)o[a.id]={revision:a.revision,action:"approve",feedback:"",split:!1};return{...n,decisions:o}}function me(e,n){if(!Cn(e,n).canSubmit)throw Error("Review is incomplete or stale");return{schemaVersion:1,requestId:e.id,...structuredClone(n)}}function Fn(e){let n=e.preview.kind==="page"||e.preview.sourceKind==="page",o=e.preview.sourceKind==="page";return{code:n,captured:o,label:n?e.medium.match(/html|css|svg/i)?e.medium:"HTML / CSS / SVG":"Raster",caption:n?o?e.preview.isolation?"Component only":"Region capture":"Live component":"Produced asset",fileLabel:o?"Open captured preview":"Open source image"}}function ye(e,n,o){let a=e.components.findIndex((t)=>t.id===o);for(let t=1;t<=e.components.length;t++){let p=e.components[(a+t)%e.components.length];if(bn(p,n).kind==="pending")return p.id}}function mi(e,n){if(!n.reviewGroup||!Fn(n).code)return[n];return e.components.filter((o)=>o.reviewGroup===n.reviewGroup&&Fn(o).code)}function pi(e,n,o,a,t=[]){let p=a?mi(e,o):[o];if(p.length===1)return[o];return p.filter((y)=>bn(y,n).kind==="pending"&&(y.id===o.id||!t.includes(y.id)))}function ze(e,n,o){let a=new Set;return e.components.flatMap((t)=>{if(a.has(t.id))return[];let p=mi(e,t);p.forEach((v)=>a.add(v.id));let y=p.filter((v)=>bn(v,n,o).kind==="pending"),g=p.filter((v)=>bn(v,n,o).kind==="feedback"),b=y[0]??g[0]??t,z=y.length?"pending":g.length?"feedback":"approved";return[{id:t.id,members:p,representative:b,pending:y.length,kind:z,label:p.length>1?t.reviewGroup.replace(/[-_]+/g," ").replace(/^./,(v)=>v.toUpperCase()):t.name,box:{x:Math.min(...p.map((v)=>v.box.x)),y:Math.min(...p.map((v)=>v.box.y)),w:Math.max(...p.map((v)=>v.box.x+v.box.w))-Math.min(...p.map((v)=>v.box.x)),h:Math.max(...p.map((v)=>v.box.y+v.box.h))-Math.min(...p.map((v)=>v.box.y))},stateLabel:y.length?p.length>1?`${y.length} to review`:bn(b,n,o).label:g.length?p.length>1?`${g.length} ${g.length===1?"needs":"need"} work`:"Feedback ready":"Approved"}]})}function yi(e,n){let o=new Set(n.preview.isolation?.excludedComponents??[]),a=n.box,t=e.components.filter((p)=>{if(p.id===n.id)return!1;if(o.has(p.id))return!0;let y=p.box,g=Math.min(a.x+a.w,y.x+y.w)-Math.max(a.x,y.x),b=Math.min(a.y+a.h,y.y+y.h)-Math.max(a.y,y.y);return y.w*y.h<a.w*a.h&&g*e.comp.width>1&&b*e.comp.height>1});return{description:n.note.trim(),related:t,excluded:t.filter((p)=>o.has(p.id))}}function Ii(e,n,o,a,t){let p=t==="fit"?Math.min(1,o/e,a/n):t;return{scale:p,width:e*p,height:n*p}}function Oi(e,n,o,a){if(o<=0||a<=o)return 0;return Math.max(0,Math.min(1,((e-n)/o-0.08)/0.84))*(a-o)}var je=`
:host{height:var(--component-review-height,100dvh);min-height:0;overflow:hidden}
-.review{height:100%;max-width:none;min-height:0;padding:0;display:flex;flex-direction:column;overflow:hidden;background:var(--color-bg,#fafafa)}
+.review{height:100%;max-width:none;min-height:0;padding:0;display:flex;flex-direction:column;overflow:hidden;background:var(--color-bg,var(--ks-paper))}
.review>header{flex-shrink:0;padding:16px 24px;margin:0;border-bottom:1px solid var(--line);gap:16px}.review>header>div{min-width:0}.review h1{font-size:30px;line-height:1}.review>header p{font-size:12px;margin-top:6px;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}.review .badge{font-size:11px}
.review>.preview-note{flex-shrink:0;margin:0;padding:8px 24px;font-size:11px}.review>.round-summary{flex-shrink:0;margin:0;padding:8px 24px;border-top:0;gap:6px 16px;max-height:120px;overflow:auto}.round-summary p{font-size:12px;gap:6px 14px}.round-summary button{font-size:12px;min-height:32px;padding:5px 10px}
-.review>.workbench{flex:1;min-height:0;align-items:stretch;padding:20px 24px;gap:32px;overflow:hidden;grid-template-columns:minmax(0,1.12fr) minmax(0,1fr)}.reference{display:flex;flex-direction:column;min-height:0;width:100%;max-width:none;margin:0}.reference>.section-head{flex-shrink:0;margin-bottom:10px}.map-space{flex:1;min-height:0;display:flex;align-items:center;justify-content:center;background:#eeefec;border:1px solid var(--line);overflow:hidden}.map{flex-shrink:0;max-width:100%;max-height:100%}.map-legend{flex-shrink:0;margin-top:9px;gap:6px 14px}.map-caption{flex-shrink:0;min-height:0;padding-top:6px;font-size:10px}.map-caption button{display:inline-block;margin:0 0 0 8px;min-height:28px;padding:3px 7px}
-.workbench>.inspector{height:100%;min-height:0;padding:0;border:0}.inspector>.section-head{margin-bottom:10px;min-height:32px}.section-head h2{font-size:16px}.inspection-content{padding-bottom:8px}.review-form{max-height:55%;overflow-y:auto;scrollbar-width:thin;scrollbar-gutter:stable}.material{min-height:28px}.material strong{font-size:13px}.compare-toolbar{margin-bottom:12px}.previous-feedback{padding:10px 12px}.repair-context{margin-bottom:12px}.preview-round{margin-bottom:10px}.decision-title p{font-size:11px}.decisions>button{min-height:40px;font-size:13px}.decision-title strong{font-size:13px}.view-controls{margin-top:8px}.component-details{height:auto;max-height:80px}
-.review>.inventory-section{height:236px;flex-shrink:0;display:flex;flex-direction:column;min-height:0;margin:0;padding:10px 24px 8px;border-top:1px solid var(--line);background:var(--color-panel,#f5f5f2);overflow:hidden}.inventory-section>.section-head{margin:0 0 8px;min-height:36px;flex-shrink:0;gap:10px}.inventory-section h2{font-size:14px}.inventory{flex:1;min-height:0;align-items:stretch;margin:0;padding:3px 3px 7px;overflow-x:auto;overflow-y:hidden}.inventory.all{overflow:auto;align-items:start;grid-auto-rows:160px}.inventory .item{flex:0 0 136px;padding:8px;gap:3px;grid-template-rows:auto auto minmax(24px,1fr) auto;min-height:0}.inventory .item-thumb{height:46px;margin-bottom:3px}.inventory .thumb-crop{max-height:46px}.inventory .item-number{font-size:11px;min-height:16px;padding:0}.inventory .item strong{font-size:12px;min-height:26px;line-height:1.2;display:-webkit-box;-webkit-line-clamp:2;-webkit-box-orient:vertical;overflow:hidden}.inventory .state{font-size:11px;padding-top:4px}.tray-actions{display:flex;gap:6px;align-items:center}.tray-actions button{white-space:nowrap;font-size:11px;min-height:32px}.tray-actions #toggle-tray{display:flex;align-items:center;gap:6px}.tray-actions svg{width:14px;height:14px;stroke:currentColor;fill:none;stroke-width:1.5;stroke-linecap:round;stroke-linejoin:round}.review>.inventory-section.tray-expanded{height:min(42dvh,390px)}.review>.inventory-section.tray-collapsed{height:56px;padding-block:10px}.tray-collapsed .inventory{display:none}.tray-collapsed>.section-head{margin-bottom:0}
-.review>footer{flex-shrink:0;margin:0;padding:12px 24px;gap:16px;border-top:1px solid var(--line);background:var(--paper);align-items:center}.review>footer>div:first-child{display:flex;align-items:center;gap:14px;min-width:0}.review>footer .check{margin:0;max-width:240px;font-size:11px}.review>footer #approve-rest{min-height:36px;font-size:12px;max-width:210px;padding:7px 10px}.review>footer .submit-area{gap:12px}.review>footer .submit-area p{font-size:11px;max-width:24ch}.review>footer .primary{min-height:40px;font-size:13px}.mobile-panes{display:none}
+.review>.workbench{flex:1;min-height:0;align-items:stretch;padding:20px 24px;gap:32px;overflow:hidden;grid-template-columns:minmax(0,1.12fr) minmax(0,1fr)}.reference{display:flex;flex-direction:column;min-height:0;width:100%;max-width:none;margin:0}.reference>.section-head{flex-shrink:0;margin-bottom:10px}.map-space{flex:1;min-height:0;display:flex;align-items:center;justify-content:center;background:var(--ks-paper-deep);border:1px solid var(--line);overflow:hidden}.map{flex-shrink:0;max-width:100%;max-height:100%}.map-legend{flex-shrink:0;margin-top:9px;gap:6px 14px}.map-caption{flex-shrink:0;min-height:0;padding-top:6px;font-size:10px}.map-caption button{display:inline-block;margin:0 0 0 8px;min-height:28px;padding:3px 7px}
+.workbench>.inspector{height:100%;min-height:0;padding:0;border:0}.inspector>.section-head{margin-bottom:10px;min-height:32px}.section-head h2{font-size:16px}.inspection-content{padding-bottom:8px}.review-form{max-height:55%;overflow-y:auto;scrollbar-width:thin;scrollbar-gutter:stable}.material{min-height:28px}.material strong{font-size:13px}.compare-toolbar{margin-bottom:12px}.previous-feedback{padding:10px 12px}.repair-context{margin-bottom:12px}.preview-round{margin-bottom:10px}.decision-title p{font-size:11px}.decision-title strong{font-size:13px}.view-controls{margin-top:8px}.component-details{height:auto;max-height:80px}
+.review>.inventory-section{height:236px;flex-shrink:0;display:flex;flex-direction:column;min-height:0;margin:0;padding:10px 24px 8px;border-top:1px solid var(--line);background:var(--color-panel,var(--ks-paper));overflow:hidden}.inventory-section>.section-head{margin:0 0 8px;min-height:36px;flex-shrink:0;gap:10px}.inventory-section h2{font-size:14px}.inventory{flex:1;min-height:0;align-items:stretch;margin:0;padding:3px 3px 7px;overflow-x:auto;overflow-y:hidden}.inventory.all{overflow:auto;align-items:start;grid-auto-rows:160px}.inventory .item{flex:0 0 136px;padding:8px;gap:3px;grid-template-rows:auto auto minmax(24px,1fr) auto;min-height:0}.inventory .item-thumb{height:46px;margin-bottom:3px}.inventory .thumb-crop{max-height:46px}.inventory .item-number{font-size:11px;min-height:16px;padding:0}.inventory .item strong{font-size:12px;min-height:26px;line-height:1.2;display:-webkit-box;-webkit-line-clamp:2;-webkit-box-orient:vertical;overflow:hidden}.inventory .state{font-size:11px;padding-top:4px}.tray-actions{display:flex;gap:6px;align-items:center}.tray-actions button{white-space:nowrap;font-size:11px;min-height:32px}.tray-actions svg{width:14px;height:14px;stroke:currentColor;fill:none;stroke-width:1.5;stroke-linecap:round;stroke-linejoin:round}.review>.inventory-section.tray-expanded{height:min(42dvh,390px)}.review>.inventory-section.tray-collapsed{height:56px;padding-block:10px}.tray-collapsed .inventory{display:none}.tray-collapsed>.section-head{margin-bottom:0}
+.review>footer{flex-shrink:0;margin:0;padding:12px 24px;gap:16px;border-top:1px solid var(--line);background:var(--paper);align-items:center}.review>footer>div:first-child{display:flex;align-items:center;gap:14px;min-width:0}.review>footer .check{margin:0;max-width:240px;font-size:11px}.review>footer .submit-area{gap:12px}.review>footer .submit-area p{font-size:11px;max-width:24ch}.mobile-panes{display:none}
/* Depth describes the shell: recessed work area, raised inspector, anchored docks. */
-.review{--workspace:#e3e6e2;--canvas:#d5dad5;--dock:#f6f7f4;--surface:#fff;background:var(--workspace)}
-.review>header{position:relative;z-index:8;background:var(--surface);border-bottom-color:#d5d9d3}
-.review>.round-summary,.review>.preview-note{position:relative;z-index:7;background:var(--dock);box-shadow:0 3px 6px #202b2510;border-bottom-color:#c8cfc7}
+.review{--workspace:var(--ks-paper);--canvas:var(--ks-paper-deep);--dock:var(--ks-paper);--surface:var(--ks-paper-raised);background:var(--workspace)}
+.review>header{position:relative;z-index:8;background:var(--surface);border-bottom-color:var(--ks-rule)}
+.review>.round-summary,.review>.preview-note{position:relative;z-index:7;background:var(--dock);box-shadow:0 3px 6px oklch(13% 0 0 / 0.06);border-bottom-color:var(--ks-rule)}
.review>.workbench{background:var(--workspace)}
-.map-space{background:var(--canvas);border-color:#bdc6bd;box-shadow:inset 0 2px 7px #263d2a12;border-radius:5px}
-.map{box-shadow:0 3px 10px #182a242b}
-.workbench>.inspector{background:var(--surface);border-radius:6px;box-shadow:0 2px 4px #24332812,0 8px 24px #24332818;scrollbar-gutter:auto;isolation:isolate}
-.inspector>.section-head{position:relative;z-index:2;margin:0;padding:12px 16px;background:var(--surface);border-bottom:1px solid #dce0da}
-.inspection-content{padding:14px 12px 14px 16px;background:#fafbf9}
-.inspector>.review-form{position:relative;z-index:2;padding:12px 12px 12px 16px;background:var(--surface);border-top:1px solid #cdd4ca}
-.inspector[data-scroll-above=true]>.section-head{box-shadow:0 6px 8px -4px #24332838}
-.inspector[data-scroll-below=true]>.review-form{box-shadow:0 -6px 8px -4px #24332838}
-.inspection-content,.review-form,.inventory{scrollbar-width:auto;scrollbar-color:#8d9c91 #e3e8e1;overscroll-behavior:contain}
+.map-space{background:var(--canvas);border-color:var(--ks-rule);box-shadow:inset 0 2px 7px oklch(13% 0 0 / 0.07);border-radius:5px}
+.map{box-shadow:0 3px 10px oklch(13% 0 0 / 0.17)}
+.workbench>.inspector{background:var(--surface);border-radius:6px;box-shadow:0 2px 4px oklch(13% 0 0 / 0.07),0 8px 24px oklch(13% 0 0 / 0.09);scrollbar-gutter:auto;isolation:isolate}
+.inspector>.section-head{position:relative;z-index:2;margin:0;padding:12px 16px;background:var(--surface);border-bottom:1px solid var(--ks-rule)}
+.inspection-content{padding:14px 12px 14px 16px;background:var(--ks-paper)}
+.inspector>.review-form{position:relative;z-index:2;padding:12px 12px 12px 16px;background:var(--surface);border-top:1px solid var(--ks-rule)}
+.inspector[data-scroll-above=true]>.section-head{box-shadow:0 6px 8px -4px oklch(13% 0 0 / 0.22)}
+.inspector[data-scroll-below=true]>.review-form{box-shadow:0 -6px 8px -4px oklch(13% 0 0 / 0.22)}
+.inspection-content,.review-form,.inventory{scrollbar-width:auto;scrollbar-color:var(--ks-gray-2) var(--ks-paper-deep);overscroll-behavior:contain}
.inspection-content::-webkit-scrollbar,.review-form::-webkit-scrollbar,.inventory::-webkit-scrollbar{width:10px;height:10px}
-.inspection-content::-webkit-scrollbar-track,.review-form::-webkit-scrollbar-track,.inventory::-webkit-scrollbar-track{background:#e3e8e1;border-radius:6px}
-.inspection-content::-webkit-scrollbar-thumb,.review-form::-webkit-scrollbar-thumb,.inventory::-webkit-scrollbar-thumb{background:#8d9c91;border:2px solid #e3e8e1;border-radius:6px}
-.review>.inventory-section{position:relative;z-index:8;background:var(--dock);border-top-color:#b9c3b8;box-shadow:0 -3px 5px #2433280c,0 -10px 24px #24332814}
-.inventory-section>.section-head{border-bottom:1px solid #d9dfd5;padding-bottom:8px;margin-bottom:8px}
+.inspection-content::-webkit-scrollbar-track,.review-form::-webkit-scrollbar-track,.inventory::-webkit-scrollbar-track{background:var(--ks-paper-deep);border-radius:6px}
+.inspection-content::-webkit-scrollbar-thumb,.review-form::-webkit-scrollbar-thumb,.inventory::-webkit-scrollbar-thumb{background:var(--ks-gray-2);border:2px solid var(--ks-paper-deep);border-radius:6px}
+.review>.inventory-section{position:relative;z-index:8;background:var(--dock);border-top-color:var(--ks-rule);box-shadow:0 -3px 5px oklch(13% 0 0 / 0.05),0 -10px 24px oklch(13% 0 0 / 0.08)}
+.inventory-section>.section-head{border-bottom:1px solid var(--ks-rule);padding-bottom:8px;margin-bottom:8px}
.tray-collapsed>.section-head{border:0;padding-bottom:0;margin-bottom:0}
.inventory{background:transparent;border-radius:0;padding:3px 3px 7px}
-.inventory .item{background:#fafbf8}
-.inventory .item.active{background:#fff}
-.review>footer{position:relative;z-index:9;background:var(--surface);border-top-color:#ccd4c7;box-shadow:0 -2px 5px #2433280b}
-.mobile-panes{position:relative;z-index:7;box-shadow:0 3px 6px #202b2510}
+.inventory .item{background:var(--ks-paper)}
+.inventory .item.active{background:var(--ks-paper-raised)}
+.review>footer{position:relative;z-index:9;background:var(--surface);border-top-color:var(--ks-rule);box-shadow:0 -2px 5px oklch(13% 0 0 / 0.04)}
+.mobile-panes{position:relative;z-index:7;box-shadow:0 3px 6px oklch(13% 0 0 / 0.06)}
/* Utility actions share a compact icon language; decisions retain explicit labels. */
.utility-icon{width:18px;height:18px;fill:none;stroke:currentColor;stroke-width:1.6;stroke-linecap:round;stroke-linejoin:round;flex-shrink:0}
-:is(.review,.comparison-panel) .icon-button{display:inline-flex;align-items:center;justify-content:center;flex-shrink:0;width:36px;height:36px;min-height:36px;padding:7px;text-decoration:none;border:1px solid transparent;border-radius:4px;background:transparent;color:var(--muted)}
-:is(.review,.comparison-panel) .icon-button:hover{background:#e5ebe4;border-color:#b9c8bd;color:var(--teal)}
-:is(.review,.comparison-panel) .icon-button[aria-pressed=true]{background:#e5eee8;color:var(--teal)}
-:is(.review,.comparison-panel) .icon-button:focus-visible{outline:2px solid var(--teal);outline-offset:2px}
-.review .label-icon{display:inline-flex;align-items:center;justify-content:center;gap:7px}
.review .tray-actions .utility-icon{width:18px;height:18px;stroke-width:1.6}
.material{align-items:center;margin-bottom:10px}
.compare-toolbar{margin-bottom:10px}
-.view-controls{min-height:0}.view-controls>.background-options{margin-left:auto;gap:2px}.view-controls .swatch-button{display:flex;align-items:center;justify-content:center;min-width:32px;height:32px;padding:5px}
-.background-swatch{display:block;width:20px;height:20px;border:1px solid #9ba99d;border-radius:2px;pointer-events:none}.background-swatch.checker{background-size:8px 8px}.page-swatch{background:var(--comp-background,#eee)}
+.view-controls{min-height:0}.view-controls>.background-options{margin-left:auto;gap:2px}.page-swatch{background:var(--comp-background,var(--ks-paper-deep))}
.review>footer .submit-area p{max-width:25ch}
-@media(max-width:1100px) and (min-width:801px){.review>header{padding:12px 20px}.review>.workbench{padding:16px 20px;gap:24px}.review>.round-summary{padding-inline:20px}.round-summary p{max-width:calc(100% - 52px)}.round-summary p>span{font-size:11px}.inventory-section>.section-head h2{max-width:none;white-space:nowrap}.review>footer>div:first-child{gap:8px}.review>footer .submit-area p{max-width:19ch}.inventory-filters button{padding-inline:8px}}
+@media(max-width:1100px) and (min-width:801px){.review>header{padding:12px 20px}.review>.workbench{padding:16px 20px;gap:24px}.review>.round-summary{padding-inline:20px}.round-summary p{max-width:calc(100% - 52px)}.round-summary p>span{font-size:11px}.inventory-section>.section-head h2{max-width:none;white-space:nowrap}.review>footer>div:first-child{gap:8px}.review>footer .submit-area p{max-width:19ch}}
@media(max-width:800px){
.review>header{padding:12px 14px;align-items:center}.review h1{font-size:25px}.review>header p{max-width:68vw;font-size:11px}.review .badge{display:none}.review>.preview-note{padding:6px 14px}.review>.round-summary{padding:6px 14px;max-height:76px;gap:4px 8px}.round-summary p{max-width:calc(100% - 44px);gap:4px 10px;font-size:11px}.round-summary p>span{font-size:10px}.round-summary button{font-size:11px}
- .mobile-panes{display:flex;flex-shrink:0;gap:4px;padding:7px 14px;border-bottom:1px solid var(--line);background:var(--paper)}.mobile-panes button{flex:1;font-size:12px;min-height:32px;padding:5px;border-color:transparent;background:transparent}.mobile-panes button[aria-pressed=true]{background:#e8efec;color:var(--teal);box-shadow:none;border-color:#bdd0c8}
- .review>.workbench{display:block;padding:12px 14px;min-height:0;overflow:hidden}.workbench[data-mobile-pane=component]>.reference,.workbench[data-mobile-pane=comp]>.inspector{display:none}.reference{height:100%;max-width:none}.connector{display:none}.inspector{height:100%;border:0}.map-legend{gap:6px 12px;font-size:10px}.map-caption{font-size:9px}.reference .section-head button{min-height:30px;padding:4px 8px}.reference .section-head h2{font-size:14px}.inspector>.section-head{min-height:26px;margin-bottom:0;padding:9px 12px}.inspection-content{padding:10px 8px 10px 12px}.inspector>.review-form{padding:8px 8px 8px 12px}.number{width:23px;height:23px;font-size:11px}.section-head h2{font-size:14px}.review-form{padding-top:8px}.decision-title strong{font-size:12px}.decision-title p{font-size:10px}.decisions>button{min-height:36px}.review-form .feedback-field{font-size:12px}.review-form .feedback-field textarea{min-height:60px}.compare{max-width:none}
- .review>.inventory-section{height:160px;padding:6px 14px}.inventory-section>.section-head{flex-direction:row;flex-wrap:nowrap;align-items:center;gap:6px;min-height:34px;margin-bottom:4px}.inventory-section h2{display:none}.inventory-filters{flex:1;width:auto;min-width:0;padding:2px}.inventory-filters button{padding:4px 6px;font-size:10px;min-height:28px}.inventory-filters b{margin-left:3px}.tray-actions #show-all{display:none}.tray-actions #toggle-tray{padding:6px;min-width:32px;min-height:32px}.tray-actions #toggle-tray span{display:none}.tray-actions svg{width:16px;height:16px}.review>.inventory-section.tray-collapsed{height:46px;padding:6px 14px}.review>.inventory-section.tray-expanded{height:160px}.inventory .item{flex-basis:130px;grid-template-rows:auto 1fr auto;padding:6px}.inventory .item-thumb{display:none}.inventory.all{display:flex;overflow-x:auto;overflow-y:hidden}.inventory .item strong{font-size:11px;min-height:22px}.inventory .state{font-size:10px}.inventory .item-number{font-size:10px;min-height:14px}.inventory-empty{padding:8px 0;font-size:12px}
- .review>footer{padding:8px 14px calc(8px + env(safe-area-inset-bottom));gap:8px;flex-direction:column;align-items:stretch}.review>footer>div:first-child{gap:10px;justify-content:space-between}.review>footer #approve-rest{font-size:10px;min-height:32px;max-width:47%;padding:5px 8px}.review>footer .check{font-size:10px;max-width:48%;gap:4px}.review>footer .check input{width:14px;height:14px}.review>footer .submit-area{justify-content:space-between;gap:10px}.review>footer .submit-area p{font-size:10px;max-width:22ch}.review>footer .primary{min-height:34px;font-size:12px;padding:6px 10px}
+ .mobile-panes{display:flex;flex-shrink:0;gap:4px;padding:7px 14px;border-bottom:1px solid var(--line);background:var(--paper)}
+ .review>.workbench{display:block;padding:12px 14px;min-height:0;overflow:hidden}.workbench[data-mobile-pane=component]>.reference,.workbench[data-mobile-pane=comp]>.inspector{display:none}.reference{height:100%;max-width:none}.connector{display:none}.inspector{height:100%;border:0}.map-legend{gap:6px 12px;font-size:10px}.map-caption{font-size:9px}.reference .section-head button{min-height:30px;padding:4px 8px}.reference .section-head h2{font-size:14px}.inspector>.section-head{min-height:26px;margin-bottom:0;padding:9px 12px}.inspection-content{padding:10px 8px 10px 12px}.inspector>.review-form{padding:8px 8px 8px 12px}.number{width:23px;height:23px;font-size:11px}.section-head h2{font-size:14px}.review-form{padding-top:8px}.decision-title strong{font-size:12px}.decision-title p{font-size:10px}.review-form .feedback-field{font-size:12px}.review-form .feedback-field textarea{min-height:60px}.compare{max-width:none}
+ .review>.inventory-section{height:160px;padding:6px 14px}.inventory-section>.section-head{flex-direction:row;flex-wrap:nowrap;align-items:center;gap:6px;min-height:34px;margin-bottom:4px}.inventory-section h2{display:none}.tray-actions svg{width:16px;height:16px}.review>.inventory-section.tray-collapsed{height:46px;padding:6px 14px}.review>.inventory-section.tray-expanded{height:160px}.inventory .item{flex-basis:130px;grid-template-rows:auto 1fr auto;padding:6px}.inventory .item-thumb{display:none}.inventory.all{display:flex;overflow-x:auto;overflow-y:hidden}.inventory .item strong{font-size:11px;min-height:22px}.inventory .state{font-size:10px}.inventory .item-number{font-size:10px;min-height:14px}.inventory-empty{padding:8px 0;font-size:12px}
+ .review>footer{padding:8px 14px calc(8px + env(safe-area-inset-bottom));gap:8px;flex-direction:column;align-items:stretch}.review>footer>div:first-child{gap:10px;justify-content:space-between}.review>footer .check{font-size:10px;max-width:48%;gap:4px}.review>footer .check input{width:14px;height:14px}.review>footer .submit-area{justify-content:space-between;gap:10px}.review>footer .submit-area p{font-size:10px;max-width:22ch}
}
-`;var Zo=`
+`;var Me=`/* VENDORED from impeccable-site/site/styles/kinpaku-tokens.css (the source of truth).
+ Do not edit here: change the site, then run node scripts/sync-kinpaku-kit.mjs. */
+/*
+ * impeccable.style tokens (page-global, single source of truth)
+ *
+ * One theme. The page is neutral paper, the type is ink, and the brand gold
+ * appears as a mark, a line, or an indicator on a dark control surface. It
+ * never carries text and it never fills a large area on paper.
+ *
+ * Three families of surface:
+ * paper the page and everything that sits flat on it
+ * gray chips, inactive fills, sunk wells
+ * instrument dark control surfaces: sliders, tab strips, segmented
+ * controls, terminals. This is where gold and patina signal.
+ *
+ * New pages read these via var(--ks-*) rather than hand-typing oklch values.
+ * Pages may override a token locally when there is a documented reason.
+ * When in doubt, do not override; match.
+ */
+
+:root {
+ color-scheme: light;
+
+ /* ============================================================
+ Brand anchors. Kinpaku gold is the mark and the signal. Verdigris
+ patina carries state, links, and selection wherever color has to
+ be read as text, because gold cannot pass contrast on paper.
+ ============================================================ */
+
+ /* Kinpaku gold. Fills on instruments, the mark, hairlines, and the label
+ of the active key on a dark instrument. Never text on paper. */
+ --ks-kinpaku: oklch(84% 0.19 80.46); /* mark, indicators, gold fills on instruments */
+ --ks-kinpaku-vivid: oklch(87% 0.20 85); /* lit hover on a gold fill */
+ --ks-kinpaku-pale: oklch(86% 0.07 84); /* pale tint; rarely needed on paper */
+ --ks-kinpaku-rich: oklch(77% 0.13 82); /* hairline gold on paper, active rule */
+ --ks-kinpaku-deep: oklch(61% 0.085 78); /* gold border against paper */
+ --ks-on-gold: oklch(14% 0.018 95); /* foreground on a gold fill */
+ --ks-gold-line: var(--ks-kinpaku-rich); /* the one-pixel gold rule */
+
+ /* Verdigris patina. State, links, selection. */
+ --ks-patina: oklch(70% 0.12 188); /* indicator on instruments, focus */
+ --ks-patina-pale: oklch(82% 0.07 188); /* soft fill behind a selected row */
+ --ks-patina-deep: oklch(45% 0.10 190); /* text-safe patina, including selected gray surfaces */
+ --ks-patina-ink: oklch(41% 0.11 190); /* hover on patina text */
+
+ /* Semantic foregrounds. Labels, eyebrows and category names are muted
+ ink; color is not how this site labels things. Patina is reserved for
+ state: selected, live, passed. */
+ --ks-gold-ink: var(--ks-text-muted);
+ --ks-accent-ink: var(--ks-text-muted);
+ --ks-state-ink: var(--ks-patina-deep);
+ --ks-focus-ring: var(--ks-patina-deep); /* paper; dark controls override locally */
+ --ks-kinpaku-ink: var(--ks-text-muted); /* legacy alias, same rule */
+
+ /* Links on paper are ink with a quiet underline; the underline turns
+ gold on hover, which is the brand as a line. */
+ --ks-link-on-paper: var(--ks-ink);
+ --ks-link-on-paper-hover: var(--ks-ink);
+ --ks-link-on-paper-line: oklch(13% 0 0 / 0.28);
+ --ks-link-on-paper-line-hover: var(--ks-kinpaku);
+ --ks-nav-active: var(--ks-ink);
+
+ /* Warning. Failures and warnings only. */
+ --ks-vermilion: oklch(52% 0.16 35);
+
+ /* ============================================================
+ Paper. The page ground is a hair below white so a raised card can
+ read as raised. Neutral, no warm cast: gold on cream is gold on gold.
+ ============================================================ */
+ --ks-paper: oklch(97.8% 0 0); /* page ground */
+ --ks-paper-raised: oklch(99.5% 0 0); /* cards, panels, inputs */
+ --ks-paper-deep: oklch(95% 0 0); /* sunk wells, code blocks, footer */
+ --ks-gray: oklch(92% 0 0); /* chips, inactive fills */
+ --ks-gray-2: oklch(88% 0 0); /* one step down from gray */
+
+ /* ============================================================
+ Instrument. Dark control surfaces on the paper, like a device on a
+ desk. The only place the site goes dark, and the only place gold is
+ read as a signal rather than a mark.
+ ============================================================ */
+ --ks-instrument: oklch(24% 0 0); /* face */
+ --ks-instrument-deep: oklch(17% 0 0); /* track, well */
+ --ks-instrument-raised: oklch(31% 0 0); /* key cap, thumb */
+ --ks-instrument-text: oklch(93% 0 0);
+ --ks-instrument-muted: oklch(68% 0 0);
+ --ks-instrument-rule: oklch(100% 0 0 / 0.12);
+ --ks-instrument-edge: oklch(100% 0 0 / 0.3);
+
+ /* ============================================================
+ Ink. Neutral. Body copy is --ks-text; headlines and <strong> are
+ --ks-ink. Muted is for labels and captions, faint for meta.
+ ============================================================ */
+ --ks-ink: oklch(13% 0 0); /* headlines, <strong>, active nav */
+ --ks-text: oklch(22% 0 0); /* body */
+ --ks-text-muted: oklch(46% 0 0); /* captions, meta, eyebrows */
+ --ks-text-faint: oklch(51% 0 0); /* subdued meta, readable on paper and gray */
+ --ks-text-mute-deep: oklch(66% 0 0); /* disabled */
+
+ /* ============================================================
+ Rules. A divider is faint. The boundary of a control is not:
+ WCAG 1.4.11 asks 3:1 of anything that tells you where a control is.
+ Use --ks-rule to divide, --ks-edge to bound something you can operate.
+ ============================================================ */
+ --ks-rule: oklch(13% 0 0 / 0.08);
+ --ks-edge: oklch(13% 0 0 / 0.45);
+
+ /* ============================================================
+ Control scales. Three radii, three heights, two lifts.
+ ============================================================ */
+ --ks-radius-sm: 3px;
+ --ks-radius-md: 8px;
+ --ks-radius-pill: 999px;
+
+ --ks-control-sm: 26px;
+ --ks-control-md: 32px;
+ --ks-control-lg: 44px;
+
+ /* Section cadence. Every top-level section on a page takes this vertical
+ padding, so the seams between sections are one rhythm. */
+ --ks-section-pad: clamp(72px, 8vw, 120px);
+
+ /* Layered, so they read as one soft light from above rather than a
+ single blurred rectangle: a contact edge, a short throw, a long one. */
+ --ks-lift-1: 0 1px 1px oklch(13% 0 0 / 0.05), 0 2px 3px oklch(13% 0 0 / 0.04), 0 6px 12px oklch(13% 0 0 / 0.05);
+ --ks-lift-2: 0 1px 1px oklch(13% 0 0 / 0.04), 0 3px 5px oklch(13% 0 0 / 0.05), 0 12px 20px oklch(13% 0 0 / 0.06), 0 32px 48px oklch(13% 0 0 / 0.07);
+
+ /* Instrument depth. A raised key sits a pixel off its dark strip, and the
+ lit indicator throws a short gold glow. These are the only shadows that
+ read against a dark surface. */
+ --ks-key-lift: 0 1px 2px oklch(0% 0 0 / 0.4);
+
+ /* Light hardware. A paper key is a raised cap: a white highlight along
+ its top edge, a hard 1px shadow under it, a soft one behind. The track
+ it sits in is recessed. Gold is the lit indicator. */
+ --ks-cap-lift: inset 0 1px 0 oklch(100% 0 0 / 0.9), 0 1px 0 oklch(13% 0 0 / 0.14), 0 2px 3px oklch(13% 0 0 / 0.08);
+ --ks-cap-press: inset 0 1px 2px oklch(13% 0 0 / 0.14);
+ --ks-track-recess: inset 0 1px 3px oklch(13% 0 0 / 0.16), inset 0 -1px 0 oklch(100% 0 0 / 0.7);
+ --ks-led: 0 0 0 1px oklch(13% 0 0 / 0.12), 0 0 4px oklch(84% 0.19 80 / 0.6);
+ --ks-indicator-glow: 0 0 0 1px oklch(0% 0 0 / 0.3), 0 0 4px oklch(84% 0.19 80 / 0.65);
+
+ /* ============================================================
+ Code. Inline code is a gray chip. Blocks and CLI commands are a sunk
+ paper well with a hairline. A command that is itself a link reads as
+ a link.
+ ============================================================ */
+ --ks-code-fg: var(--ks-ink);
+ --ks-code-bg: var(--ks-gray);
+ --ks-code-radius: 3px;
+ --ks-code-pad: 0.2em 0.45em;
+ --ks-code-block-fg: var(--ks-text);
+ --ks-code-block-bg: var(--ks-paper-deep);
+ --ks-code-block-border: var(--ks-rule);
+ --ks-code-block-radius: 3px;
+ --ks-code-cmd: var(--ks-link-on-paper);
+
+ /* ============================================================
+ Typography. One family for everything that is read: Albert Sans, a
+ quiet geometric humanist, at normal weights. The wordmark keeps
+ Alumni Sans because it is part of the logo lockup, and that is the
+ only place it appears.
+ ============================================================ */
+ --ks-font: "Albert Sans", "Avenir Next", "Helvetica Neue", Arial, system-ui, sans-serif;
+ --ks-font-display: var(--ks-font-wordmark); /* Alumni Sans: the brand's own display voice, at a weight that holds on paper */
+ --ks-font-wordmark: "Alumni Sans", "Albert Sans", Arial, sans-serif;
+ --ks-mono: "JetBrains Mono", ui-monospace, "SFMono-Regular", Menlo, Consolas, monospace;
+
+ /* Display: page h1. */
+ --ks-type-display-size: clamp(3.2rem, 6.2vw, 5.6rem);
+ --ks-type-display-weight: 200;
+ --ks-type-display-line: 1.0;
+ --ks-type-display-track: 0;
+
+ /* Headline: section h2. */
+ --ks-type-headline-size: clamp(2.4rem, 3.6vw, 3.4rem);
+ --ks-type-headline-weight: 300;
+ --ks-type-headline-line: 1.04;
+ --ks-type-headline-track: 0;
+
+ /* Title: card and panel headings (h3). */
+ --ks-type-title-size: 1.0625rem;
+ --ks-type-title-weight: 600;
+ --ks-type-title-line: 1.35;
+
+ /* Body. */
+ --ks-type-body-size: 1rem;
+ --ks-type-body-line: 1.65;
+
+ /* Eyebrow: small mono labels above titles. */
+ --ks-type-eyebrow-size: 0.6875rem;
+ --ks-type-eyebrow-track: 0.14em;
+
+ /* Wordmark: IMPECCABLE in the header. */
+ --ks-type-wordmark-size: 1.25rem;
+ --ks-type-wordmark-track: 0.18em;
+
+ /* Mono: code, terminal, audit lines. */
+ --ks-type-mono-size: 0.6875rem;
+ --ks-type-mono-track: 0.12em;
+
+ /* Dense UI ramp. Micro is the floor for anything functional. */
+ --ks-type-micro-size: 0.6875rem; /* 11px */
+ --ks-type-label-size: 0.75rem; /* 12px */
+ --ks-type-ui-size: 0.8125rem; /* 13px */
+ --ks-type-ui-lead: 0.9375rem; /* 15px */
+
+ /* Reading ramp between body and headline. Small is secondary body copy
+ and captions that are read, not scanned; lead and subhead are the
+ intro paragraph and the card-level heading; title-lg is a bento tile
+ or panel heading that is larger than a card title but not a section. */
+ --ks-type-small-size: 0.875rem; /* 14px */
+ --ks-type-lead-size: 1.125rem; /* 18px */
+ --ks-type-subhead-size: 1.25rem; /* 20px */
+ --ks-type-title-lg-size: 1.5rem; /* 24px */
+
+ /* ============================================================
+ Motion. Quick is a state change, settle is something arriving.
+ ============================================================ */
+ --ks-ease: cubic-bezier(0.2, 0.8, 0.2, 1);
+ --ks-quick: 120ms;
+ --ks-settle: 200ms;
+}
+`,Te=`/* VENDORED from impeccable-site/site/styles/kinpaku-kit.css (buttons, tabs, select, icon button, instrument strip, grain, switch, paper strip, thumb) (the source of truth).
+ Do not edit here: change the site, then run node scripts/sync-kinpaku-kit.mjs. */
+/* ============================================================
+ Buttons: primary, secondary, ghost, disabled
+
+ The primary action is ink on paper. Gold does not fill a button on this
+ site: a gold slab on paper is the hotel-lobby read. The brand is present
+ on the primary as the gold arrow, not as the fill.
+
+ Variants chain on .ks-button so specificity (0,2,0) wins over generic page
+ anchor resets like \`.kinpaku-system-page a { color: inherit }\` (0,1,1).
+ Use class="ks-button ks-button-primary", both classes required.
+ ============================================================ */
+
+.ks-button {
+ position: relative;
+ min-height: var(--ks-control-lg);
+ display: inline-flex;
+ align-items: center;
+ justify-content: center;
+ gap: 12px;
+ padding: 0 22px;
+ border-radius: var(--ks-radius-sm);
+ font-family: var(--ks-font);
+ font-size: 0.9375rem;
+ font-weight: 500;
+ line-height: 1;
+ letter-spacing: -0.005em;
+ text-decoration: none;
+ border: 1px solid transparent;
+ cursor: pointer;
+ transition: background-color var(--ks-quick) var(--ks-ease), border-color var(--ks-quick) var(--ks-ease), color var(--ks-quick) var(--ks-ease);
+}
+
+.ks-button .ks-button-arrow {
+ width: 16px;
+ height: 8px;
+ display: inline-block;
+ flex: none;
+}
+
+.ks-button-arrow svg { width: 100%; height: 100%; display: block; overflow: visible; }
+
+/* The arrow says where the button goes. On a button whose target is further
+ down the page (an in-page anchor, or .is-down on the arrow) it curves and
+ points downward on hover, and straightens again on leave. The rest shape
+ is set here too, as the same command list, so the two interpolate. */
+.ks-button-arrow path {
+ d: path("M0 4C5 4 9 4 14 4M10 0L14 4L10 8");
+ transition: d 420ms var(--ks-ease);
+}
+
+.ks-button[href^="#"]:hover .ks-button-arrow path,
+.ks-button:hover .ks-button-arrow.is-down path {
+ d: path("M0 4C7 4 11 4 11 11M7 7L11 11L15 7");
+}
+
+@media (prefers-reduced-motion: reduce) {
+ .ks-button-arrow path { transition: none; }
+}
+
+.ks-button.ks-button-primary {
+ color: var(--ks-paper-raised);
+ background: var(--ks-ink);
+ border-color: var(--ks-ink);
+}
+
+.ks-button.ks-button-primary .ks-button-arrow {
+ color: var(--ks-kinpaku);
+}
+
+.ks-button.ks-button-primary:hover {
+ color: var(--ks-paper-raised);
+ background: var(--ks-text);
+ border-color: var(--ks-text);
+}
+
+.ks-button.ks-button-primary:active {
+ background: oklch(8% 0 0);
+ border-color: oklch(8% 0 0);
+}
+
+.ks-button.ks-button-secondary {
+ color: var(--ks-ink);
+ background: var(--ks-paper-raised);
+ border-color: var(--ks-edge);
+}
+
+.ks-button.ks-button-secondary:hover {
+ color: var(--ks-ink);
+ border-color: var(--ks-ink);
+}
+
+.ks-button.ks-button-secondary:active {
+ background: var(--ks-gray);
+}
+
+.ks-button.ks-button-ghost {
+ color: var(--ks-ink);
+ background: transparent;
+ border-color: transparent;
+ padding: 0 12px;
+}
+
+.ks-button.ks-button-ghost:hover {
+ color: var(--ks-accent-ink);
+}
+
+.ks-button[disabled],
+.ks-button.ks-button-disabled {
+ color: var(--ks-text-mute-deep);
+ background: transparent;
+ border-color: var(--ks-rule);
+ cursor: not-allowed;
+ transform: none !important;
+}
+
+.ks-button:focus-visible {
+ outline: 2px solid var(--ks-focus-ring);
+ outline-offset: 3px;
+}
+
+.ks-button-row {
+ display: flex;
+ flex-wrap: wrap;
+ align-items: center;
+ gap: 18px;
+}
+
+/* ============================================================
+ Tabs
+ ============================================================ */
+
+.ks-tabs { max-width: 460px; }
+
+.ks-tab-list { display: flex; border-bottom: 1px solid var(--ks-rule); }
+
+.ks-tab-list button {
+ flex: 1;
+ min-height: 42px;
+ border: 0;
+ border-bottom: 2px solid transparent;
+ background: transparent;
+ color: var(--ks-text-muted);
+ cursor: pointer;
+ font-size: 0.92rem;
+ transition: color 180ms var(--ks-ease), border-color 180ms var(--ks-ease);
+}
+
+.ks-tab-list button:hover { color: var(--ks-ink); }
+
+.ks-tab-list button[aria-selected="true"] {
+ color: var(--ks-accent-ink);
+ border-bottom-color: var(--ks-kinpaku);
+}
+
+.ks-tab-panel {
+ padding: 22px 4px 0;
+ color: var(--ks-ink);
+ font-size: 0.92rem;
+ line-height: 1.6;
+}
+
+/* ============================================================
+ Form controls — input, toggle, checkbox, select
+ ============================================================ */
+
+.ks-form-sample {
+ display: grid;
+ gap: 22px;
+ max-width: 360px;
+}
+
+.ks-form-sample label {
+ display: grid;
+ gap: 8px;
+ color: var(--ks-text-muted);
+ font-size: 0.82rem;
+ letter-spacing: 0.04em;
+}
+
+.ks-form-sample input[type="search"],
+.ks-form-sample input[type="text"] {
+ min-height: 46px;
+ padding: 0 14px;
+ border: 1px solid var(--ks-rule);
+ border-radius: var(--ks-radius-sm);
+ background: var(--ks-paper-raised);
+ color: var(--ks-ink);
+ font-size: 0.92rem;
+}
+
+.ks-form-sample input[type="search"]:focus,
+.ks-form-sample input[type="text"]:focus {
+ outline: none;
+ border-color: var(--ks-patina);
+}
+
+.ks-toggle {
+ display: flex !important;
+ align-items: center;
+ gap: 12px !important;
+}
+
+.ks-toggle input {
+ appearance: none;
+ width: 44px;
+ height: 24px;
+ border-radius: 999px;
+ border: 1px solid var(--ks-rule);
+ background: var(--ks-gray);
+ position: relative;
+ cursor: pointer;
+ flex: none;
+}
+
+.ks-toggle input::before {
+ content: "";
+ position: absolute;
+ width: 16px;
+ height: 16px;
+ left: 3px;
+ top: 3px;
+ border-radius: 999px;
+ background: var(--ks-text-muted);
+ transition: transform 220ms var(--ks-ease), background 220ms var(--ks-ease);
+}
+
+.ks-toggle input:checked {
+ border-color: var(--ks-patina);
+ background: oklch(48% 0.08 188 / 0.2);
+}
+
+.ks-toggle input:checked::before {
+ transform: translateX(20px);
+ background: var(--ks-patina);
+}
+
+.ks-toggle span { color: var(--ks-ink); font-size: 0.92rem; }
+
+.ks-checkbox {
+ display: flex;
+ align-items: center;
+ gap: 10px;
+ color: var(--ks-ink);
+ font-size: 0.92rem;
+ cursor: pointer;
+}
+
+.ks-checkbox input {
+ appearance: none;
+ width: 18px;
+ height: 18px;
+ border: 1px solid var(--ks-rule);
+ border-radius: var(--ks-radius-sm);
+ background: var(--ks-paper-raised);
+ position: relative;
+ cursor: pointer;
+ flex: none;
+}
+
+.ks-checkbox input:checked {
+ border-color: var(--ks-ink);
+ background: var(--ks-ink);
+}
+
+.ks-checkbox input:checked::after {
+ content: "";
+ position: absolute;
+ left: 5px;
+ top: 2px;
+ width: 5px;
+ height: 9px;
+ border: solid var(--ks-paper-raised);
+ border-width: 0 1.5px 1.5px 0;
+ transform: rotate(45deg);
+}
+
+.ks-select {
+ appearance: none;
+ min-height: 46px;
+ padding: 0 38px 0 14px;
+ border: 1px solid var(--ks-rule);
+ border-radius: var(--ks-radius-sm);
+ background-color: var(--ks-paper-raised);
+ background-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 10 6' fill='none' stroke='%23222222' stroke-width='1.2'%3E%3Cpath d='M1 1l4 4 4-4'/%3E%3C/svg%3E");
+ background-repeat: no-repeat;
+ background-position: right 14px center;
+ background-size: 10px 6px;
+ color: var(--ks-ink);
+ font-size: 0.92rem;
+ cursor: pointer;
+}
+
+/* ============================================================
+ Icon button + tooltip
+ ============================================================ */
+
+.ks-icon-button {
+ width: 32px;
+ height: 32px;
+ display: grid;
+ place-items: center;
+ border: 1px solid var(--ks-rule);
+ border-radius: 999px;
+ background: transparent;
+ color: var(--ks-accent-ink);
+ cursor: pointer;
+}
+
+.ks-tooltip {
+ position: absolute;
+ bottom: calc(100% - 18px);
+ left: 50%;
+ transform: translateX(-50%);
+ width: 200px;
+ padding: 10px 12px;
+ border: 1px solid var(--ks-rule);
+ background: var(--ks-paper-deep);
+ color: var(--ks-ink);
+ font-size: 0.8rem;
+ line-height: 1.4;
+ border-radius: var(--ks-radius-sm);
+ opacity: 0;
+ pointer-events: none;
+ transition: opacity 160ms var(--ks-ease);
+}
+
+.ks-icon-button:focus-visible + .ks-tooltip {
+ opacity: 1;
+}
+
+/* ============================================================
+ Instrument strip: the site's one dark control.
+
+ A row of keys on a dark strip, sitting on the paper like a device on a
+ desk. The active key is raised and carries a gold indicator. Use for tab
+ strips, view switches and command pickers: anything the reader operates.
+ Never for decoration, and never for a link list.
+
+ Markup: <div class="ks-instrument-strip" role="tablist">
+ <button class="ks-instrument-key is-active">One</button>
+ <button class="ks-instrument-key">Two</button>
+ </div>
+ ============================================================ */
+.ks-instrument-strip {
+ display: inline-flex;
+ align-items: center;
+ gap: 2px;
+ padding: 3px;
+ background: var(--ks-instrument);
+ border: 1px solid var(--ks-instrument-deep);
+ border-radius: var(--ks-radius-pill);
+ box-shadow: inset 0 1px 0 var(--ks-instrument-rule), var(--ks-lift-1);
+}
+
+.ks-instrument-key {
+ display: inline-flex;
+ align-items: center;
+ gap: 8px;
+ min-height: var(--ks-control-md);
+ padding: 0 14px 0 12px;
+ color: var(--ks-instrument-muted);
+ background: transparent;
+ border: 0;
+ border-radius: var(--ks-radius-pill);
+ font-family: var(--ks-mono);
+ font-size: var(--ks-type-label-size);
+ letter-spacing: 0.02em;
+ text-transform: none;
+ line-height: 1;
+ white-space: nowrap;
+ cursor: pointer;
+ transition: color var(--ks-quick) var(--ks-ease), background-color var(--ks-quick) var(--ks-ease);
+}
+
+.ks-instrument-key::before {
+ content: "";
+ width: 6px;
+ height: 6px;
+ flex: none;
+ border-radius: 50%;
+ background: var(--ks-instrument-raised);
+ box-shadow: inset 0 0 0 1px var(--ks-instrument-rule);
+ transition: background-color var(--ks-quick) var(--ks-ease), box-shadow var(--ks-quick) var(--ks-ease);
+}
+
+.ks-instrument-key:hover,
+.ks-instrument-key:focus-visible {
+ color: var(--ks-instrument-text);
+}
+
+.ks-instrument-key:focus-visible {
+ outline: 2px solid var(--ks-focus-ring);
+ outline-offset: 2px;
+}
+
+.ks-instrument-key.is-active,
+.ks-instrument-key[aria-selected="true"] {
+ color: var(--ks-instrument-text);
+ background: var(--ks-instrument-raised);
+ box-shadow: inset 0 1px 0 var(--ks-instrument-edge), var(--ks-key-lift);
+}
+
+.ks-instrument-key.is-active::before,
+.ks-instrument-key[aria-selected="true"]::before {
+ background: var(--ks-kinpaku);
+ box-shadow: var(--ks-indicator-glow);
+}
+
+/* ============================================================
+ Grain.
+
+ Grain is part of a material, not a layer over the page. The page ground
+ (the paper) carries it, and so do the moulded surfaces: the recessed
+ track and raised caps of a paper strip, the dark instruments, code
+ blocks. Anything that sits on top of those (a card, a demo, an image,
+ type) is clean. One 160px tile of monochrome noise from an SVG filter,
+ held under 6% on paper and a little higher on dark, where it is what
+ makes a strip read as a part instead of a black rectangle.
+ ============================================================ */
+:root {
+ --ks-grain: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='160' height='160'%3E%3Cfilter id='n' x='0' y='0'%3E%3CfeTurbulence type='fractalNoise' baseFrequency='0.9' numOctaves='2' stitchTiles='stitch'/%3E%3CfeColorMatrix type='saturate' values='0'/%3E%3C/filter%3E%3Crect width='100%25' height='100%25' filter='url(%23n)'/%3E%3C/svg%3E");
+}
+
+/* The paper. Fixed behind the page's content, above the canvas colour. */
+body {
+ position: relative;
+ isolation: isolate;
+}
+
+body::before {
+ content: "";
+ position: fixed;
+ inset: 0;
+ z-index: -1;
+ pointer-events: none;
+ opacity: 0.055;
+ mix-blend-mode: multiply;
+ background-image: var(--ks-grain);
+ background-size: 160px 160px;
+}
+
+/* Moulded surfaces. The pseudo sits under the surface's own children. */
+.ks-grain,
+.ks-instrument-strip {
+ position: relative;
+}
+
+.ks-grain::before,
+.ks-instrument-strip::before {
+ content: "";
+ position: absolute;
+ inset: 0;
+ z-index: 0;
+ border-radius: inherit;
+ pointer-events: none;
+ opacity: 0.16;
+ mix-blend-mode: screen;
+ will-change: opacity;
+ background-image: var(--ks-grain);
+ background-size: 160px 160px;
+}
+
+.ks-instrument-strip.is-paper::before {
+ opacity: 0.05;
+ mix-blend-mode: normal;
+}
+
+/* The strip is its own stacking context: grain at 0, the cap at 1, the
+ labels at 2, whatever the page around it does. */
+.ks-instrument-strip {
+ isolation: isolate;
+}
+
+
+.ks-instrument-strip > :not(.ks-thumb) {
+ position: relative;
+ z-index: 2;
+}
+
+/* ============================================================
+ Switch: a physical slide switch for one on/off state.
+
+ A recessed track, a raised knob that slides from left (off) to right
+ (on), and a lit dot on the knob when on. Markup:
+ <button class="ks-switch" type="button" aria-pressed="true">
+ <span class="ks-switch-track" aria-hidden="true"><span class="ks-switch-knob"></span></span>
+ <span class="ks-switch-label">Detector on</span>
+ </button>
+ ============================================================ */
+.ks-switch {
+ display: inline-flex;
+ align-items: center;
+ gap: 10px;
+ padding: 0;
+ border: 0;
+ background: transparent;
+ color: var(--ks-text-muted);
+ font-family: var(--ks-font);
+ font-size: var(--ks-type-ui-size);
+ font-weight: 500;
+ cursor: pointer;
+}
+
+.ks-switch[aria-pressed="true"] {
+ color: var(--ks-ink);
+}
+
+.ks-switch-track {
+ position: relative;
+ width: 44px;
+ height: 24px;
+ border-radius: var(--ks-radius-pill);
+ background: var(--ks-gray-2);
+ box-shadow: var(--ks-track-recess);
+ transition: background-color var(--ks-quick) var(--ks-ease);
+}
+
+.ks-switch-knob {
+ position: absolute;
+ top: 3px;
+ left: 3px;
+ width: 18px;
+ height: 18px;
+ border-radius: 50%;
+ background: var(--ks-paper-raised);
+ box-shadow: var(--ks-cap-lift);
+ transition: transform 220ms cubic-bezier(0.3, 0.7, 0.2, 1);
+}
+
+.ks-switch-knob::after {
+ content: "";
+ position: absolute;
+ top: 50%;
+ left: 50%;
+ width: 6px;
+ height: 6px;
+ border-radius: 50%;
+ transform: translate(-50%, -50%);
+ background: var(--ks-gray-2);
+ box-shadow: inset 0 1px 1px oklch(13% 0 0 / 0.18);
+ transition: background-color var(--ks-quick) var(--ks-ease), box-shadow var(--ks-quick) var(--ks-ease);
+}
+
+.ks-switch[aria-pressed="true"] .ks-switch-knob {
+ transform: translateX(20px);
+}
+
+.ks-switch[aria-pressed="true"] .ks-switch-knob::after {
+ background: var(--ks-patina);
+ box-shadow: var(--ks-led);
+}
+
+.ks-switch:active .ks-switch-knob {
+ box-shadow: var(--ks-cap-press);
+}
+
+.ks-switch:focus-visible {
+ outline: none;
+}
+
+.ks-switch:focus-visible .ks-switch-track {
+ outline: 2px solid var(--ks-kinpaku);
+ outline-offset: 2px;
+}
+
+/* ============================================================
+ Tag: the brand's label.
+
+ The detector flags bad design with a small gold tag carrying dark mono
+ text. That tag is the one device a visitor already associates with
+ Impeccable, so it is also how the site labels things: section numerals,
+ a card's state, a release's status. Small, mono, ink on gold. It is the
+ only gold fill allowed on paper, and it never grows past a label.
+ ============================================================ */
+.ks-tag {
+ display: inline-flex;
+ align-items: center;
+ gap: 6px;
+ min-height: 22px;
+ padding: 0 7px;
+ color: var(--ks-ink);
+ background: var(--ks-kinpaku);
+ border-radius: var(--ks-radius-sm);
+ font-family: var(--ks-mono);
+ font-size: var(--ks-type-eyebrow-size);
+ font-weight: 600;
+ letter-spacing: 0.02em;
+ line-height: normal;
+ text-transform: uppercase;
+ white-space: nowrap;
+ vertical-align: middle;
+}
+
+/* A quiet tag for a secondary label sitting next to a gold one. */
+.ks-tag.is-quiet {
+ color: var(--ks-text-muted);
+ background: var(--ks-gray);
+}
+
+/* Paper variant. A page control (a view switch, a tab row) sits on paper
+ and keeps the gold dot, so it does not compete with the primary action
+ the way a dark strip does. The dark strip is for product chrome: the
+ live picker, lab toolbars, terminals. */
+
+.ks-instrument-strip.is-paper {
+ background: var(--ks-gray);
+ border-color: transparent;
+ box-shadow: var(--ks-track-recess);
+}
+
+.ks-instrument-strip.is-paper .ks-instrument-key {
+ color: var(--ks-text-muted);
+ transition: color var(--ks-quick) var(--ks-ease), background-color var(--ks-quick) var(--ks-ease), box-shadow var(--ks-quick) var(--ks-ease), transform var(--ks-quick) var(--ks-ease);
+}
+
+.ks-instrument-strip.is-paper .ks-instrument-key::before {
+ background: var(--ks-gray-2);
+ box-shadow: inset 0 1px 1px oklch(13% 0 0 / 0.18);
+}
+
+.ks-instrument-strip.is-paper .ks-instrument-key:hover,
+.ks-instrument-strip.is-paper .ks-instrument-key:focus-visible {
+ color: var(--ks-ink);
+}
+
+.ks-instrument-strip.is-paper .ks-instrument-key:active {
+ box-shadow: var(--ks-cap-press);
+ transform: translateY(1px);
+}
+
+/* The raised cap. Light from above: a white edge on top, a hard shadow
+ underneath, so it stands a millimetre proud of the track. */
+.ks-instrument-strip.is-paper .ks-instrument-key.is-active,
+.ks-instrument-strip.is-paper .ks-instrument-key[aria-selected="true"],
+.ks-instrument-strip.is-paper .ks-instrument-key[aria-pressed="true"] {
+ color: var(--ks-ink);
+ background: var(--ks-paper-raised);
+ box-shadow: var(--ks-cap-lift);
+}
+
+.ks-instrument-strip.is-paper .ks-instrument-key.is-active::before,
+.ks-instrument-strip.is-paper .ks-instrument-key[aria-selected="true"]::before,
+.ks-instrument-strip.is-paper .ks-instrument-key[aria-pressed="true"]::before {
+ background: var(--ks-patina);
+ box-shadow: 0 0 0 1px oklch(13% 0 0 / 0.12), 0 0 4px color-mix(in oklch, var(--ks-patina) 60%, transparent);
+}
+
+.ks-instrument-strip.is-paper .ks-instrument-key:focus-visible {
+ outline: 2px solid var(--ks-focus-ring);
+ outline-offset: 1px;
+}
+
+/* ============================================================
+ Instrument strip thumb (real element, positioned by
+ instrument-strip.js). Last in the file on purpose: these override the
+ key's own cap, and they must come after every key rule above.
+ ============================================================ */
+.ks-thumb {
+ position: absolute;
+ top: 3px;
+ bottom: 3px;
+ left: 0;
+ width: 0;
+ border-radius: var(--ks-radius-pill);
+ background: var(--ks-instrument-raised);
+ box-shadow: inset 0 1px 0 var(--ks-instrument-edge), var(--ks-key-lift);
+ transition: transform 360ms cubic-bezier(0.22, 1, 0.3, 1);
+ pointer-events: none;
+ z-index: 1;
+}
+
+.ks-instrument-strip.is-paper .ks-thumb {
+ background: var(--ks-paper-raised);
+ box-shadow: var(--ks-cap-lift);
+}
+
+.ks-instrument-strip.has-thumb .ks-instrument-key,
+.ks-instrument-strip.has-thumb .ks-instrument-key.is-active,
+.ks-instrument-strip.has-thumb .ks-instrument-key[aria-selected="true"],
+.ks-instrument-strip.has-thumb .ks-instrument-key[aria-pressed="true"],
+.ks-instrument-strip.is-paper.has-thumb .ks-instrument-key.is-active,
+.ks-instrument-strip.is-paper.has-thumb .ks-instrument-key[aria-selected="true"],
+.ks-instrument-strip.is-paper.has-thumb .ks-instrument-key[aria-pressed="true"] {
+ background: transparent;
+ box-shadow: none;
+ transform: none;
+ transition: color 120ms var(--ks-ease);
+}
+
+.ks-instrument-strip.has-thumb .ks-instrument-key::before {
+ transition: background-color 120ms var(--ks-ease), box-shadow 120ms var(--ks-ease);
+}
+
+/* Dark instruments need the light state color for keyboard focus. */
+.ks-instrument-strip:not(.is-paper),
+.live-demo-gbar,
+.live-demo-ctx,
+.worlds-rating {
+ --ks-focus-ring: var(--ks-patina);
+}
+
+/* Touch gets the kit's large target, without enlarging the desktop controls
+ or their labels. Pointer capability also covers tablets with a keyboard. */
+@media (any-pointer: coarse) {
+ .ks-instrument-strip .ks-instrument-key,
+ .ks-segmented button {
+ min-height: var(--ks-control-lg);
+ min-width: var(--ks-control-lg);
+ }
+
+ .site-header-menu {
+ width: var(--ks-control-lg);
+ height: var(--ks-control-lg);
+ }
+
+ .kinpaku-chrome .site-header-brand,
+ .kinpaku-chrome .site-header-github {
+ min-height: var(--ks-control-lg);
+ }
+
+ .kinpaku-chrome .site-header-nav a {
+ min-height: var(--ks-control-lg);
+ min-width: var(--ks-control-lg);
+ padding-block: 10px;
+ }
+}
+`,qe=`/* VENDORED from impeccable-site/site/styles/docs-kinpaku.css (the command rail list: the site's selected-row pattern) (the source of truth).
+ Do not edit here: change the site, then run node scripts/sync-kinpaku-kit.mjs. */
+/* Group headings are ink and bold, so they read as headings over their
+ links rather than as meta beside them; the links are muted and a step
+ smaller, ink on hover and on the current page. */
+.docs-kinpaku .skills-sidebar-category {
+ display: block;
+ font-family: var(--ks-font);
+ font-size: 0.8125rem;
+ font-weight: 650;
+ letter-spacing: 0.01em;
+ text-transform: none;
+ color: var(--ks-ink);
+ margin-bottom: 6px;
+ padding: 0 0 0 14px;
+}
+
+.docs-kinpaku .skills-sidebar-list {
+ list-style: none;
+ padding: 0;
+ margin: 0;
+}
+
+.docs-kinpaku .skills-sidebar-list li {
+ margin: 0;
+}
+
+.docs-kinpaku .skills-sidebar-list a {
+ display: block;
+ padding: 4px 0 4px 12px;
+ border-left: 2px solid transparent;
+ font-family: var(--ks-font);
+ font-size: 0.875rem;
+ font-weight: 400;
+ line-height: 1.5;
+ color: var(--ks-text-muted);
+ text-decoration: none;
+ transition: color 160ms var(--ks-ease),
+ border-color 160ms var(--ks-ease);
+}
+
+.docs-kinpaku .skills-sidebar-list a:hover {
+ color: var(--ks-ink);
+}
+
+.docs-kinpaku .skills-sidebar-list a[aria-current="page"] {
+ color: var(--ks-ink);
+ font-weight: 600;
+ border-left-color: var(--ks-gold-line);
+}
+`;var Ve=(e)=>e.replace(/^:root\s*\{/gm,":root, :host {"),zi=Ve(Me)+`
+`+Ve(Te)+`
+`+qe,Bn='<span class="ks-button-arrow" aria-hidden="true"><svg viewBox="0 0 16 8" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="square"><path d="M0 4h14M10 0l4 4-4 4"/></svg></span>';var Ee=`
.review-peers{display:grid;gap:8px;padding:8px 0 12px;font-size:12px}
.review-peers strong span{font-weight:400}.review-peers>div{display:flex;flex-wrap:wrap;gap:4px}
.review-peers button{min-width:28px;min-height:28px;padding:3px;border:1px solid var(--line);border-radius:4px;background:var(--paper);color:inherit}
-.review-peers button[aria-pressed="true"]{background:var(--teal);color:white}
+.review-peers button[aria-pressed="true"]{background:var(--teal);color:var(--ks-paper-raised)}
.review-peers label{display:flex;align-items:center;gap:6px}
-:host{display:block;color:var(--color-text,#292929);font:14px/1.45 var(--font-sans,Arial,sans-serif);--line:var(--color-border,#ddd);--paper:var(--color-panel,#fff);--muted:var(--color-muted,#666);--teal:var(--color-patina,#28625e);--warn:var(--color-warn,#8a5b30);--selection:#43897f}
-*{box-sizing:border-box}h1,h2,p,figure{margin:0}button,input,textarea{font:inherit}button{cursor:pointer;border:1px solid var(--line);border-radius:4px;background:var(--paper);color:inherit;padding:8px 12px;min-height:36px}button:hover{border-color:var(--teal);color:var(--teal)}button:disabled{cursor:default;opacity:.45}button:focus-visible,input:focus-visible,textarea:focus-visible{outline:2px solid var(--teal);outline-offset:3px}button[aria-pressed=true]{box-shadow:inset 0 0 0 1px var(--teal)}input[type=checkbox]{accent-color:var(--teal);width:16px;height:16px;flex-shrink:0}textarea,input:not([type=checkbox]){width:100%;background:var(--paper);color:inherit;border:1px solid #999;border-radius:4px;padding:9px 10px}textarea{resize:vertical;min-height:80px}::selection{background:#c7ddd8}a{color:var(--teal)}
+:host{display:block;color:var(--ks-text);font:14px/1.45 var(--ks-font);--line:var(--ks-rule);--paper:var(--ks-paper-raised);--muted:var(--ks-text-muted);--teal:var(--ks-patina-deep);--warn:var(--ks-vermilion);--selection:var(--ks-patina)}
+*{box-sizing:border-box}h1,h2,p,figure{margin:0}button,input,textarea{font:inherit}button{cursor:pointer;border:1px solid var(--line);border-radius:4px;background:var(--paper);color:inherit;padding:8px 12px;min-height:36px}button:hover{border-color:var(--teal);color:var(--teal)}button:disabled{cursor:default;opacity:.45}button:focus-visible,input:focus-visible,textarea:focus-visible{outline:2px solid var(--teal);outline-offset:3px}button[aria-pressed=true]{box-shadow:inset 0 0 0 1px var(--teal)}input[type=checkbox]{accent-color:var(--teal);width:16px;height:16px;flex-shrink:0}textarea,input:not([type=checkbox]){width:100%;background:var(--paper);color:inherit;border:1px solid var(--ks-edge);border-radius:4px;padding:9px 10px}textarea{resize:vertical;min-height:80px}::selection{background:var(--ks-patina-pale)}a{color:var(--teal)}
.review{max-width:1600px;margin:auto;padding:24px 28px 0}header{display:flex;align-items:center;justify-content:space-between;gap:20px;margin-bottom:16px}h1{font:400 40px/1.05 var(--font-display,Arial,sans-serif);letter-spacing:-.02em}header p{margin-top:8px;font-size:15px}header p span,.medium{color:var(--muted)}.badge{border:1px solid var(--line);padding:5px 10px;font-size:12px;white-space:nowrap}.preview-note{color:var(--muted);font-size:12px;border-bottom:1px solid var(--line);padding-bottom:16px;margin-bottom:24px}
.connector{position:absolute;inset:0;width:100%;height:100%;pointer-events:none;z-index:5;overflow:visible}.connector path{fill:none;stroke:var(--selection);stroke-width:2}.workbench{align-items:start;display:grid;grid-template-columns:minmax(0,1.18fr) minmax(0,1fr);gap:40px;position:relative}.section-head{display:flex;align-items:center;justify-content:space-between;gap:12px;margin-bottom:14px;min-height:36px}.section-head h2{font-size:17px;font-weight:500;line-height:1.2}.section-head>span,.section-head h2>span:not(.number){font-size:12px;color:var(--muted)}.section-head button{font-size:12px}.number{display:inline-flex;align-items:center;justify-content:center;width:27px;height:27px;border:1px solid var(--teal);color:var(--teal);margin-right:7px;font:12px var(--font-mono,monospace)}
-.map{position:relative;background:#eaeaea;isolation:isolate}.comp{width:100%;height:100%;display:block;user-select:none}.map.marking{touch-action:none;cursor:crosshair}.map.marking .pin{pointer-events:none;opacity:.25}.pin{position:absolute;transform:translate(-50%,-50%);padding:0;min-height:25px;width:25px;height:25px;border-radius:50%;border:1px solid #fff;background:#fff;color:#292929;font:11px var(--font-mono,monospace);box-shadow:0 1px 4px #0006;z-index:2}.pin.selected{background:var(--teal);color:#fff;border-color:var(--teal);box-shadow:none;outline:none;z-index:3}.pin:focus-visible{outline:2px solid white;outline-offset:3px}.region,.draw-box{position:absolute;pointer-events:none;outline:2px solid var(--selection);z-index:1}.draw-box{background:#28625e33;z-index:4}.map-caption{font-size:12px;color:var(--muted);padding-top:12px;min-height:40px}.map-caption button{display:block;margin-top:10px}.compare{display:grid;grid-template-columns:1fr 1fr;gap:12px}.compare figure{min-width:0}.compare figcaption{height:24px;min-height:0;font-size:12px;margin-bottom:9px}.compare figcaption span{display:block;color:var(--muted);font-size:11px}.crop-stage{position:relative;overflow:hidden;background:var(--comp-background,#eee);min-width:0}.crop-image{position:absolute;max-width:none;height:auto}.asset{display:block;width:100%;height:100%;object-fit:contain}.crop-stage iframe{position:absolute;max-width:none;border:0;transform-origin:top left;pointer-events:none}.overlay-image{opacity:.5;pointer-events:none}.component-note{font-size:12px;line-height:1.5;color:var(--muted);margin:6px 0 0}.decisions{display:flex;gap:10px;padding:10px 0;background:var(--paper);position:sticky;bottom:0;z-index:6}.decisions>button{flex:1;min-height:48px;font-weight:600;font-size:15px;border-color:var(--teal)}.decision-approve{background:var(--teal);color:white}.decision-approve:hover{background:#224e4b;color:white}.decision-revise{color:var(--teal);background:var(--paper)}.decisions>.quiet{flex:0;border:0;background:transparent;font-size:12px}.decisions .approved{color:var(--teal);background:#e9f0ed;border-color:var(--teal)}.decisions .revise{color:var(--warn);background:#f7f0e6;border-color:var(--warn)}.feedback-field{display:block;margin-top:16px;font-size:13px}.feedback-field>span{float:right;color:var(--muted);font-size:12px}.feedback-field textarea,.feedback-field input{display:block;margin-top:7px}.check{display:flex;align-items:center;gap:7px;font-size:12px;line-height:1.5;margin-top:12px}.coordinates{display:grid;grid-template-columns:repeat(4,1fr);gap:8px;margin:16px 0}.coordinates label{font-size:12px}.coordinates input{margin-top:5px}
-.inventory-section{margin-top:28px;border-top:1px solid var(--line);padding-top:16px}.inventory-section .section-head{margin-bottom:10px}.inventory{display:flex;gap:8px;overflow-x:auto;padding:3px 3px 14px;scrollbar-color:#a6bcb8 #eee;scrollbar-width:thin}.item{position:relative;flex:0 0 134px;display:grid;grid-template-columns:20px 1fr;column-gap:8px;row-gap:3px;padding:10px;text-align:left;background:transparent}.item strong{grid-column:2;font-size:12px;font-weight:500;white-space:nowrap;overflow:hidden;text-overflow:ellipsis}.item.active{background:var(--paper);border-color:var(--teal)}.thumb-crop{position:relative;display:block;overflow:hidden}.item-thumb{display:flex;align-items:center;justify-content:center;grid-column:1/-1;position:relative;overflow:hidden;width:100%;height:76px;background:var(--comp-background,#eee);margin-bottom:7px}.item-thumb img{width:100%;height:100%;object-fit:contain}.item-thumb img[style]{height:auto}.inventory.all{display:grid;grid-template-columns:repeat(auto-fill,minmax(128px,1fr));overflow:visible}.item-number{grid-row:2/4;font:12px var(--font-mono,monospace);color:var(--muted);padding-top:2px}.state{grid-column:2;font-size:11px;color:var(--muted)}.state.approve{color:var(--teal)}.state.revise{color:var(--warn)}footer{display:flex;justify-content:space-between;gap:24px;padding:20px 0 24px;border-top:1px solid var(--line);margin-top:8px}.submit-area{display:flex;align-items:center;gap:20px}.submit-area p{font-size:12px;color:var(--muted);max-width:28ch}.primary{min-height:46px;font-weight:600;background:var(--teal);border-color:var(--teal);color:white;white-space:nowrap}.primary:hover{color:white;background:#224e4b}.primary:disabled{opacity:.45}.inspector>p{margin:12px 0}
+.map{position:relative;background:var(--ks-paper-deep);isolation:isolate}.comp{width:100%;height:100%;display:block;user-select:none}.map.marking{touch-action:none;cursor:crosshair}.map.marking .pin{pointer-events:none;opacity:.25}.pin{position:absolute;transform:translate(-50%,-50%);padding:0;min-height:25px;width:25px;height:25px;border-radius:50%;border:1px solid var(--ks-paper-raised);background:var(--ks-paper-raised);color:var(--ks-text);font:11px var(--font-mono,monospace);box-shadow:0 1px 4px oklch(13% 0 0 / .4);z-index:2}.pin.selected{background:var(--teal);color:var(--ks-paper-raised);border-color:var(--teal);box-shadow:none;outline:none;z-index:3}.pin:focus-visible{outline:2px solid var(--ks-paper-raised);outline-offset:3px}.region,.draw-box{position:absolute;pointer-events:none;outline:2px solid var(--selection);z-index:1}.draw-box{background:oklch(45% 0.10 190 / .2);z-index:4}.map-caption{font-size:12px;color:var(--muted);padding-top:12px;min-height:40px}.map-caption button{display:block;margin-top:10px}.compare{display:grid;grid-template-columns:1fr 1fr;gap:12px}.compare figure{min-width:0}.compare figcaption{height:24px;min-height:0;font-size:12px;margin-bottom:9px}.compare figcaption span{display:block;color:var(--muted);font-size:11px}.crop-stage{position:relative;overflow:hidden;background:var(--comp-background,var(--ks-paper-deep));min-width:0}.crop-image{position:absolute;max-width:none;height:auto}.asset{display:block;width:100%;height:100%;object-fit:contain}.crop-stage iframe{position:absolute;max-width:none;border:0;transform-origin:top left;pointer-events:none}.overlay-image{opacity:.5;pointer-events:none}.component-note{font-size:12px;line-height:1.5;color:var(--muted);margin:6px 0 0}.decisions{display:flex;gap:10px;padding:10px 0;background:var(--paper);position:sticky;bottom:0;z-index:6}.feedback-field{display:block;margin-top:16px;font-size:13px}.feedback-field>span{float:right;color:var(--muted);font-size:12px}.feedback-field textarea,.feedback-field input{display:block;margin-top:7px}.check{display:flex;align-items:center;gap:7px;font-size:12px;line-height:1.5;margin-top:12px}.coordinates{display:grid;grid-template-columns:repeat(4,1fr);gap:8px;margin:16px 0}.coordinates label{font-size:12px}.coordinates input{margin-top:5px}
+.inventory-section{margin-top:28px;border-top:1px solid var(--line);padding-top:16px}.inventory-section .section-head{margin-bottom:10px}.inventory{display:flex;gap:8px;overflow-x:auto;padding:3px 3px 14px;scrollbar-color:var(--ks-gray-2) var(--ks-paper-deep);scrollbar-width:thin}.item{position:relative;flex:0 0 134px;display:grid;grid-template-columns:20px 1fr;column-gap:8px;row-gap:3px;padding:10px;text-align:left;background:transparent}.item strong{grid-column:2;font-size:12px;font-weight:500;white-space:nowrap;overflow:hidden;text-overflow:ellipsis}.item.active{background:var(--paper);border-color:var(--teal)}.thumb-crop{position:relative;display:block;overflow:hidden}.item-thumb{display:flex;align-items:center;justify-content:center;grid-column:1/-1;position:relative;overflow:hidden;width:100%;height:76px;background:var(--comp-background,var(--ks-paper-deep));margin-bottom:7px}.item-thumb img{width:100%;height:100%;object-fit:contain}.item-thumb img[style]{height:auto}.inventory.all{display:grid;grid-template-columns:repeat(auto-fill,minmax(128px,1fr));overflow:visible}.item-number{grid-row:2/4;font:12px var(--font-mono,monospace);color:var(--muted);padding-top:2px}.state{grid-column:2;font-size:11px;color:var(--muted)}.state.approve{color:var(--teal)}.state.revise{color:var(--warn)}footer{display:flex;justify-content:space-between;gap:24px;padding:20px 0 24px;border-top:1px solid var(--line);margin-top:8px}.submit-area{display:flex;align-items:center;gap:20px}.submit-area p{font-size:12px;color:var(--muted);max-width:28ch}.inspector>p{margin:12px 0}
@media(min-width:1300px){.workbench{gap:56px}.review{padding-top:32px}.component-note{max-width:62ch}}
@media(max-width:800px){.connector{display:none}.review{padding:20px 16px 0}.workbench{grid-template-columns:1fr;gap:24px}.reference{max-width:640px;margin:auto;width:100%}.inspector{border-top:1px solid var(--line);padding-top:16px}.compare{max-width:640px}.inventory-section .section-head{align-items:flex-start;flex-direction:column;gap:4px}footer{flex-direction:column}.submit-area{justify-content:space-between}.badge{font-size:11px}.section-head{gap:8px}h1{font-size:34px}header{align-items:flex-start}.section-head h2{font-size:16px}}
.inspector{height:690px;overflow-y:auto;scrollbar-gutter:stable;scrollbar-width:thin;padding:0 5px 0 1px;overflow-anchor:none}
.material{display:flex;align-items:baseline;flex-wrap:wrap;gap:5px 12px;min-height:34px;margin-bottom:6px}.material strong{font-size:14px;font-weight:600}.material span{font:11px var(--font-mono,monospace);color:var(--muted)}
-.compare-toolbar{display:flex;align-items:center;justify-content:space-between;gap:10px;margin-bottom:16px}.compare-toolbar label{font-size:12px;display:flex;align-items:center;gap:8px}select{font:inherit;color:inherit;background:var(--paper);border:1px solid #999;border-radius:4px;padding:7px 9px;min-height:36px}select:focus-visible,.pan-viewport:focus-visible{outline:2px solid var(--teal);outline-offset:2px}
-.overlay-control{display:flex;align-items:center;gap:8px;border-color:var(--teal);color:var(--teal);font-weight:500}.overlay-control[aria-pressed=true]{background:#e9f0ed}.overlay-control svg{width:18px;height:18px;fill:none;stroke:currentColor;stroke-width:1.3}
-.pan-viewport{height:248px;overflow:auto;display:flex;background:#efefef;scrollbar-width:thin;scrollbar-color:#829b98 #eee;overscroll-behavior:contain}.crop-stage{flex-shrink:0;margin:auto}.checker{background-color:#eee;background-image:conic-gradient(#c7c7c7 25%,transparent 0 50%,#c7c7c7 0 75%,transparent 0);background-size:16px 16px}
-.view-controls{display:flex;justify-content:space-between;align-items:center;flex-wrap:wrap;gap:8px;margin-top:12px;min-height:36px}.view-controls>div{display:flex;background:#eee;border:1px solid var(--line);padding:2px;border-radius:4px}.view-controls button{border:0;background:transparent;font-size:12px;min-height:30px;padding:5px 9px}.view-controls button[aria-pressed=true]{background:var(--paper);box-shadow:0 1px 2px #0002}.view-controls label{font-size:11px;display:flex;gap:6px;align-items:center}.view-controls select{font-size:11px;min-height:32px;padding:5px}.view-controls>span{font-size:12px;color:var(--muted)}.scale-note{font-size:11px;color:var(--muted);margin:10px 0 0;min-height:18px}.scale-note a{white-space:nowrap}
+.compare-toolbar{display:flex;align-items:center;justify-content:space-between;gap:10px;margin-bottom:16px}.compare-toolbar label{font-size:12px;display:flex;align-items:center;gap:8px}select{font:inherit;color:inherit;background:var(--paper);border:1px solid var(--ks-edge);border-radius:4px;padding:7px 9px;min-height:36px}select:focus-visible,.pan-viewport:focus-visible{outline:2px solid var(--teal);outline-offset:2px}
+.pan-viewport{height:248px;overflow:auto;display:flex;background:var(--ks-paper-deep);scrollbar-width:thin;scrollbar-color:var(--ks-gray-2) var(--ks-paper-deep);overscroll-behavior:contain}.crop-stage{flex-shrink:0;margin:auto}.checker{background-color:var(--ks-paper-deep);background-image:conic-gradient(var(--ks-gray-2) 25%,transparent 0 50%,var(--ks-gray-2) 0 75%,transparent 0);background-size:16px 16px}
+.view-controls{display:flex;justify-content:space-between;align-items:center;flex-wrap:wrap;gap:8px;margin-top:12px;min-height:36px}.view-controls label{font-size:11px;display:flex;gap:6px;align-items:center}.view-controls select{font-size:11px;min-height:32px;padding:5px}.view-controls>span{font-size:12px;color:var(--muted)}.scale-note{font-size:11px;color:var(--muted);margin:10px 0 0;min-height:18px}.scale-note a{white-space:nowrap}
.component-details{height:78px;overflow:auto;margin-top:12px;padding-right:4px;scrollbar-width:thin}.layering{font-size:12px;line-height:1.5}.component-details .component-note{margin-top:6px}
-#approve-rest{min-height:44px;font-weight:600;border-color:var(--teal);color:var(--teal)}
@media(max-width:800px){.inspector{height:720px}.pan-viewport{height:248px}.component-details{height:92px}.view-controls label{font-size:11px}.review header{align-items:flex-start}}
.round-summary{display:flex;flex-wrap:wrap;align-items:center;justify-content:space-between;gap:10px 20px;padding:14px 0;margin-bottom:22px;border-block:1px solid var(--line)}.round-summary p{display:flex;flex-wrap:wrap;gap:5px 18px;font-size:13px}.round-summary p>span{color:var(--muted)}.round-summary details{flex-basis:100%;font-size:12px}.round-summary details p{font-size:12px;margin-top:8px;max-width:80ch}
.repair-context{display:grid;grid-template-columns:minmax(0,1fr) auto;gap:4px 12px;margin:0 0 10px;font-size:12px}.previous-feedback{display:contents;overflow-wrap:anywhere}.previous-feedback h3{grid-column:1;grid-row:1;margin:0;font-size:11px;font-weight:500;color:var(--muted);align-self:center}.previous-feedback h3 span{font-weight:400;white-space:nowrap}.previous-feedback blockquote{grid-column:1/-1;grid-row:2;margin:0;white-space:pre-wrap;font-size:13px;line-height:1.45;max-height:5.8em;overflow:auto}.previous-feedback>p{grid-column:1/-1;margin:0;font-size:12px}.kept-approval{color:var(--teal);font-size:12px;align-self:center}
-.round-switch{display:flex;gap:1px;border:1px solid var(--line);border-radius:4px;padding:2px;background:#eee;flex-shrink:0}.round-switch button{min-height:28px;font-size:11px;padding:4px 7px;border:0;background:transparent}.round-switch button[aria-pressed=true]{background:var(--paper);color:var(--teal);box-shadow:0 1px 2px #0002}
-.changed-files{grid-column:2;grid-row:1;margin:0;color:var(--muted);font-size:11px}.changed-files summary{padding:2px 0;min-height:24px}.changed-files[open]{grid-column:1/-1;grid-row:auto}.changed-files[open] summary{font-weight:500}summary{cursor:pointer;padding:5px 0;min-height:30px}summary:focus-visible{outline:2px solid var(--teal);outline-offset:2px}.changed-files ul{padding-left:18px;margin:6px 0;overflow-wrap:anywhere;font:11px/1.6 var(--font-mono,monospace)}.description-diff{margin:6px 0 12px}.description-diff dt{font-weight:600;font-size:11px;margin-top:10px}.description-diff dd{margin:4px 0 0;white-space:pre-wrap;overflow-wrap:anywhere;color:var(--color-text,#292929)}.previous-notice{font-size:12px;color:var(--muted);margin-top:8px}.inspector .previous-notice{display:none}
-.decisions{display:grid;grid-template-columns:minmax(0,1fr) minmax(0,1fr) auto;gap:8px 10px;padding-top:12px}.decision-title{grid-column:1/-1}.decision-title strong{font-size:14px;font-weight:600;display:flex;justify-content:space-between;gap:12px}.decision-title strong span{font-size:11px;color:var(--muted);font-weight:400}.decision-title p{font-size:12px;font-weight:400;color:var(--muted);margin-top:4px}.decisions>.quiet{align-self:center;padding-inline:4px}.decisions:not(:has(.quiet)){grid-template-columns:1fr 1fr}
+.changed-files{grid-column:2;grid-row:1;margin:0;color:var(--muted);font-size:11px}.changed-files summary{padding:2px 0;min-height:24px}.changed-files[open]{grid-column:1/-1;grid-row:auto}.changed-files[open] summary{font-weight:500}summary{cursor:pointer;padding:5px 0;min-height:30px}summary:focus-visible{outline:2px solid var(--teal);outline-offset:2px}.changed-files ul{padding-left:18px;margin:6px 0;overflow-wrap:anywhere;font:11px/1.6 var(--font-mono,monospace)}.description-diff{margin:6px 0 12px}.description-diff dt{font-weight:600;font-size:11px;margin-top:10px}.description-diff dd{margin:4px 0 0;white-space:pre-wrap;overflow-wrap:anywhere;color:var(--color-text,var(--ks-text))}.previous-notice{font-size:12px;color:var(--muted);margin-top:8px}.inspector .previous-notice{display:none}
+.decisions{display:grid;grid-template-columns:minmax(0,1fr) minmax(0,1fr) auto;gap:8px 10px;padding-top:12px}.decision-title{grid-column:1/-1}.decision-title strong{font-size:14px;font-weight:600;display:flex;justify-content:space-between;gap:12px}.decision-title strong span{font-size:11px;color:var(--muted);font-weight:400}.decision-title p{font-size:12px;font-weight:400;color:var(--muted);margin-top:4px}.decisions:not(:has(.quiet)){grid-template-columns:1fr 1fr}
.inspector{display:flex;flex-direction:column;overflow:hidden;padding:0}.inspection-content{flex:1;min-height:0;overflow:auto;scrollbar-width:thin;scrollbar-gutter:stable;overscroll-behavior:contain;padding:0 5px 10px 1px}.review-form{flex-shrink:0;padding:12px 5px 0 1px;border-top:1px solid var(--line);background:var(--paper)}.review-form .decisions{position:static;padding:0 0 8px;background:transparent}.review-form .feedback{margin-top:8px}.review-form .feedback textarea{min-height:72px;max-height:120px}.review-form .check{margin:8px 0;font-size:11px}
.inspection-content:focus-visible{outline:2px solid var(--teal);outline-offset:-2px}
.inspector>.section-head{flex-shrink:0;padding:0 5px 0 1px}
-.pin{display:flex;align-items:center;justify-content:center;gap:3px;font-size:12px;font-weight:600;width:30px;height:30px;min-height:30px}.pin svg,.map-legend svg,.item-number svg{width:13px;height:13px;fill:none;stroke:currentColor;stroke-width:1.8;stroke-linecap:round;stroke-linejoin:round;flex-shrink:0}.pin.pending,.pin.pending.selected{background:#f4cd68;border-color:#f4cd68;color:#3c300f}.pin.approved,.pin.approved.selected{width:38px;min-height:24px;height:24px;background:#edf3ef;border-color:#edf3ef;color:#326258;border-radius:4px}.pin.approved:not(.selected){opacity:.55;box-shadow:none}.pin.approved:hover,.pin.approved:focus-visible{opacity:1}.pin.feedback,.pin.feedback.selected{width:38px;background:#964b2f;border-color:#fff;color:#fff;border-radius:4px}.pin.selected{outline:none;border:3px solid #fff;box-shadow:none;z-index:3}.pin:focus-visible{outline:2px solid #fff;outline-offset:3px}
-.map-legend{display:flex;flex-wrap:wrap;gap:9px 18px;margin-top:14px;font-size:11px;color:var(--muted)}.map-legend>span{display:flex;align-items:center;gap:6px}.map-legend i{display:inline-flex;align-items:center;justify-content:center;min-width:21px;height:21px;font-style:normal}.legend-pending{background:#f4cd68;color:#3c300f;border-radius:50%}.legend-feedback{background:#964b2f;color:#fff;border-radius:3px}.legend-approved{background:#edf3ef;color:#326258;border-radius:3px}.map-caption{font-size:11px}
-.inventory-section .section-head{flex-wrap:wrap}.inventory-filters{display:flex;gap:3px;padding:3px;background:#eee;border-radius:5px}.inventory-filters button{border:0;background:transparent;min-height:34px;padding:7px 10px;font-size:12px;white-space:nowrap}.inventory-filters button[aria-pressed=true]{background:var(--paper);color:var(--teal);box-shadow:0 1px 2px #0002}.inventory-filters b{margin-left:5px;font-weight:600;font-variant-numeric:tabular-nums}.item.pending{border-color:#b18a2f;background:#fffbef}.item.feedback{border-color:#964b2f;background:#fcf1eb}.item.approved{background:#f1f4f2;border-color:#ccd8d1}.item.approved .item-thumb{opacity:.65}.item.active{outline:2px solid var(--teal);outline-offset:0;box-shadow:none}.item-number{display:flex;align-items:center;gap:3px;grid-column:1/-1;grid-row:auto;min-height:20px;font-weight:600}.item strong{grid-column:1/-1;font-size:13px;white-space:normal;min-height:36px;line-height:1.35}.state{grid-column:1/-1;font-size:12px;font-weight:600;padding-top:6px;border-top:1px solid #0002}.state.pending{color:#725819}.state.feedback{color:#914429}.state.approved{color:#326258}.inventory-empty{padding:20px 0;font-size:13px;color:var(--muted)}
-@media(max-width:800px){.inventory-section .section-head{gap:10px}.inventory-filters{width:100%}.inventory-filters button{padding-inline:7px;font-size:11px;flex:1}.inventory-filters b{margin-left:3px}}
+.pin{display:flex;align-items:center;justify-content:center;gap:3px;font-size:12px;font-weight:600;width:30px;height:30px;min-height:30px}.pin svg,.map-legend svg,.item-number svg{width:13px;height:13px;fill:none;stroke:currentColor;stroke-width:1.8;stroke-linecap:round;stroke-linejoin:round;flex-shrink:0}.pin.pending,.pin.pending.selected{background:var(--ks-kinpaku);border-color:var(--ks-kinpaku);color:var(--ks-on-gold)}.pin.approved,.pin.approved.selected{width:38px;min-height:24px;height:24px;background:var(--ks-paper-raised);border-color:var(--ks-paper-raised);color:var(--ks-state-ink);border-radius:4px}.pin.approved:not(.selected){opacity:.55;box-shadow:none}.pin.approved:hover,.pin.approved:focus-visible{opacity:1}.pin.feedback,.pin.feedback.selected{width:38px;background:var(--ks-ink);border-color:var(--ks-paper-raised);color:var(--ks-paper-raised);border-radius:4px}.pin.selected{outline:none;border:3px solid var(--ks-paper-raised);box-shadow:none;z-index:3}.pin:focus-visible{outline:2px solid var(--ks-paper-raised);outline-offset:3px}
+.map-legend{display:flex;flex-wrap:wrap;gap:9px 18px;margin-top:14px;font-size:11px;color:var(--muted)}.map-legend>span{display:flex;align-items:center;gap:6px}.map-legend i{display:inline-flex;align-items:center;justify-content:center;min-width:21px;height:21px;font-style:normal}.legend-pending{background:var(--ks-kinpaku);color:var(--ks-on-gold);border-radius:50%}.legend-feedback{background:var(--ks-ink);color:var(--ks-paper-raised);border-radius:3px}.legend-approved{background:var(--ks-paper-raised);color:var(--ks-state-ink);border-radius:3px}.map-caption{font-size:11px}
+.inventory-section .section-head{flex-wrap:wrap}.item.pending{border-color:var(--ks-kinpaku-deep);background:var(--ks-paper-raised)}.item.feedback{border-color:var(--ks-ink);background:var(--ks-paper-raised)}.item.approved{background:var(--ks-paper);border-color:var(--ks-rule)}.item.approved .item-thumb{opacity:.65}.item.active{outline:2px solid var(--teal);outline-offset:0;box-shadow:none}.item-number{display:flex;align-items:center;gap:3px;grid-column:1/-1;grid-row:auto;min-height:20px;font-weight:600}.item strong{grid-column:1/-1;font-size:13px;white-space:normal;min-height:36px;line-height:1.35}.state{grid-column:1/-1;font-size:12px;font-weight:600;padding-top:6px;border-top:1px solid var(--ks-rule)}.state.pending{color:var(--ks-ink)}.state.feedback{color:var(--ks-ink)}.state.approved{color:var(--ks-state-ink)}.inventory-empty{padding:20px 0;font-size:13px;color:var(--muted)}
+@media(max-width:800px){.inventory-section .section-head{gap:10px}}
@media(prefers-reduced-motion:reduce){*{scroll-behavior:auto}}
.item-medium{margin-left:auto;font-weight:400;display:flex;align-items:center;gap:4px;font-size:10px;color:var(--muted);min-height:16px}.item-medium .utility-icon{width:14px;height:14px;flex-shrink:0}.material>.utility-icon{width:18px;height:18px;align-self:center;color:var(--teal)}
-.feedback-actions{display:flex;align-items:center;gap:10px;margin-top:12px;flex-wrap:wrap}.feedback-actions .primary{margin-left:auto;display:inline-flex;align-items:center;gap:10px}.feedback-actions svg{width:18px;height:18px;fill:none;stroke:currentColor;stroke-width:1.5}.feedback-hint,.shortcut-hint{font-size:12px;color:var(--muted)}.feedback-hint{margin-top:6px}.shortcut-hint{flex-basis:100%;text-align:right}.record-verdict{display:flex;flex-wrap:wrap;align-items:baseline;gap:5px 12px;font-size:13px}.record-verdict span{font-size:11px;color:var(--muted)}.review>.record-footer{font-size:12px;color:var(--muted);flex-wrap:wrap;gap:6px 16px}.saved-feedback{font-size:13px;white-space:pre-wrap;overflow-wrap:anywhere;margin:8px 0}.decision-notice{display:flex;align-items:center;gap:12px;font-size:12px;margin-bottom:10px}.decision-notice>span{flex:1;overflow-wrap:anywhere}.decision-notice button{color:var(--teal);flex-shrink:0}.review-summary{padding:4px 2px}.completion-mark{display:flex;align-items:center;justify-content:center;width:32px;height:32px;border-radius:50%;background:#e6efe8;color:#28625e;float:left;margin:0 10px 8px 0}.completion-mark svg{width:24px;height:24px;fill:none;stroke:currentColor;stroke-width:1.6}.completion-link{display:inline-flex;align-items:center;gap:8px;color:var(--teal);border:0;background:transparent;padding:0;font-size:12px;text-align:left}.completion-link svg{width:18px;height:18px;fill:none;stroke:currentColor;stroke-width:1.8;flex-shrink:0}.queue-complete #approve-rest{display:none}.review-summary h2{font-size:22px;line-height:32px}.review-summary p{clear:both;margin-top:8px;color:var(--muted)}.summary-decisions{margin-top:24px;display:grid}.summary-decisions button{display:grid;grid-template-columns:1fr auto;gap:6px 16px;text-align:left;border:0;border-bottom:1px solid var(--line);border-radius:0;padding:12px 0;background:transparent}.summary-decisions strong{font-size:13px;font-weight:500}.summary-decisions span{font-size:12px;color:var(--teal)}.summary-decisions small{grid-column:1/-1;font-size:12px;color:var(--muted);white-space:pre-wrap;overflow-wrap:anywhere}
-`+No+`
+.feedback-actions{display:flex;align-items:center;gap:10px;margin-top:12px;flex-wrap:wrap}.feedback-actions svg{width:18px;height:18px;fill:none;stroke:currentColor;stroke-width:1.5}.feedback-hint,.shortcut-hint{font-size:12px;color:var(--muted)}.feedback-hint{margin-top:6px}.shortcut-hint{flex-basis:100%;text-align:right}.record-verdict{display:flex;flex-wrap:wrap;align-items:baseline;gap:5px 12px;font-size:13px}.record-verdict span{font-size:11px;color:var(--muted)}.review>.record-footer{font-size:12px;color:var(--muted);flex-wrap:wrap;gap:6px 16px}.saved-feedback{font-size:13px;white-space:pre-wrap;overflow-wrap:anywhere;margin:8px 0}.decision-notice{display:flex;align-items:center;gap:12px;font-size:12px;margin-bottom:10px}.decision-notice>span{flex:1;overflow-wrap:anywhere}.decision-notice button{color:var(--teal);flex-shrink:0}.review-summary{padding:4px 2px}.completion-mark{display:flex;align-items:center;justify-content:center;width:32px;height:32px;border-radius:50%;background:var(--ks-gray);color:var(--ks-patina-deep);float:left;margin:0 10px 8px 0}.completion-mark svg{width:24px;height:24px;fill:none;stroke:currentColor;stroke-width:1.6}.completion-link{display:inline-flex;align-items:center;gap:8px;color:var(--teal);border:0;background:transparent;padding:0;font-size:12px;text-align:left}.completion-link svg{width:18px;height:18px;fill:none;stroke:currentColor;stroke-width:1.8;flex-shrink:0}.review-summary h2{font-size:22px;line-height:32px}.review-summary p{clear:both;margin-top:8px;color:var(--muted)}.summary-decisions{margin-top:24px;display:grid}.summary-decisions button{display:grid;grid-template-columns:1fr auto;gap:6px 16px;text-align:left;border:0;border-bottom:1px solid var(--line);border-radius:0;padding:12px 0;background:transparent}.summary-decisions strong{font-size:13px;font-weight:500}.summary-decisions span{font-size:12px;color:var(--teal)}.summary-decisions small{grid-column:1/-1;font-size:12px;color:var(--muted);white-space:pre-wrap;overflow-wrap:anywhere}
+`+je+`
.review-form:has(#feedback-form){max-height:75%;min-height:0;flex-shrink:1;display:flex;flex-direction:column;overflow:hidden;padding-top:8px}
#feedback-form{display:flex;flex-direction:column;flex:1;min-height:0}
/* Leave room inside the scrollport for the 2px focus ring and 3px offset. */
.feedback-fields{flex:1;min-height:0;overflow:auto;padding:6px}
.review-form:has(#feedback-form) .decision-notice{flex-shrink:0}
.review-form:has(#feedback-form) .decisions{display:none}
-.feedback-actions{flex-shrink:0;position:static;background:var(--surface,var(--paper));padding:8px 0;margin-top:8px;box-shadow:0 -5px 8px -6px #24332838}
+.feedback-actions{flex-shrink:0;position:static;background:var(--surface,var(--paper));padding:8px 0;margin-top:8px;box-shadow:0 -5px 8px -6px oklch(13% 0 0 / 0.22)}
.feedback-actions .shortcut-hint{flex-basis:auto;order:-1;margin-right:auto}
-.feedback-actions .primary{margin-left:0}
-@media(max-height:800px),(max-width:800px){.feedback-actions .shortcut-hint{display:none}.feedback-actions .primary{margin-left:auto}.review-form .feedback textarea{min-height:56px}.review-form:has(#feedback-form) .decision-notice{margin-bottom:4px}}
+@media(max-height:800px),(max-width:800px){.feedback-actions .shortcut-hint{display:none}.review-form .feedback textarea{min-height:56px}.review-form:has(#feedback-form) .decision-notice{margin-bottom:4px}}
-.comparison-panel{min-width:0;container-type:inline-size}.comparison-panel .expanded-title{display:none}.comparison-panel .compare-toolbar{justify-content:flex-start}.comparison-panel .overlay-control{margin-left:0}.comparison-panel #expand-comparison{flex-shrink:0}.pan-viewport.pannable{cursor:move}.pan-viewport img{user-select:none;-webkit-user-drag:none}
-#comparison-dialog{position:fixed;inset:16px;width:calc(100vw - 32px);height:calc(100dvh - 32px);max-width:none;max-height:none;margin:0;padding:24px;background:var(--paper);color:inherit;border:1px solid var(--line);border-radius:8px;box-shadow:0 20px 60px #14292340;overflow:hidden;transform-origin:top left}
+.comparison-panel{min-width:0;container-type:inline-size}.comparison-panel .expanded-title{display:none}.comparison-panel .compare-toolbar{justify-content:flex-start}.comparison-panel #expand-comparison{flex-shrink:0}.pan-viewport.pannable{cursor:move}.pan-viewport img{user-select:none;-webkit-user-drag:none}
+#comparison-dialog{position:fixed;inset:16px;width:calc(100vw - 32px);height:calc(100dvh - 32px);max-width:none;max-height:none;margin:0;padding:24px;background:var(--paper);color:inherit;border:1px solid var(--line);border-radius:8px;box-shadow:0 20px 60px oklch(13% 0 0 / .25);overflow:hidden;transform-origin:top left}
#comparison-dialog[open]{display:flex;flex-direction:column;gap:12px}
#comparison-dialog>.review-form{width:100%;max-width:900px;align-self:center;max-height:55%;padding:12px 4px 0}
#comparison-dialog>.review-form .decision-title{display:none}
-#comparison-dialog::backdrop{background:#172821a6}
+#comparison-dialog::backdrop{background:oklch(13% 0 0 / .6)}
#comparison-dialog .comparison-panel{flex:1;min-height:0;display:flex;flex-direction:column;gap:12px}
#comparison-dialog .expanded-title{display:block;font-size:20px;line-height:1.3;margin:0;font-weight:500}
#comparison-dialog .compare-toolbar{flex-shrink:0;margin:0}
#comparison-dialog .compare{flex:1;min-height:0;max-width:none;grid-template-columns:minmax(0,1fr) minmax(0,1fr)}
#comparison-dialog .compare figure{display:flex;flex-direction:column;min-height:0}#comparison-dialog .pan-viewport{flex:1;min-height:0}#comparison-dialog .compare figcaption{flex-shrink:0}
#comparison-dialog .view-controls{flex-shrink:0;margin:0}
-@media(max-width:600px){#comparison-dialog{inset:6px;width:calc(100vw - 12px);height:calc(100dvh - 12px);padding:14px}.comparison-panel .compare-toolbar{gap:6px}.comparison-panel .overlay-control{padding-inline:8px;font-size:12px}#comparison-dialog .compare{gap:8px}#comparison-dialog .compare figcaption{font-size:11px}}
+@media(max-width:600px){#comparison-dialog{inset:6px;width:calc(100vw - 12px);height:calc(100dvh - 12px);padding:14px}.comparison-panel .compare-toolbar{gap:6px}#comparison-dialog .compare{gap:8px}#comparison-dialog .compare figcaption{font-size:11px}}
.comparison-panel .compare-toolbar{gap:6px;padding:0;min-width:0;flex-wrap:wrap;margin-bottom:8px}
.comparison-actions{display:flex;align-items:center;gap:2px;margin-left:auto;flex-shrink:0}
-.comparison-panel .zoom-control{position:relative;display:block;flex-shrink:0}
-.zoom-control select{appearance:none;-webkit-appearance:none;width:104px;height:36px;min-height:36px;padding:6px 30px 6px 32px;font-size:12px;line-height:1.4;border-color:var(--line);background:var(--paper);cursor:pointer}
-.zoom-control>.utility-icon{position:absolute;top:50%;transform:translateY(-50%);pointer-events:none}
-.zoom-control>.utility-icon:first-child{left:10px;width:15px;height:15px;color:var(--muted)}
-.zoom-control>.utility-icon:last-child{right:10px;width:13px;height:13px;color:var(--muted)}
-.comparison-panel .overlay-control{height:36px;min-height:36px;font-size:12px;padding:6px 10px;gap:6px}
-.comparison-panel .overlay-control svg{width:18px;height:18px;stroke-width:1.6}
.comparison-actions .source-link{color:var(--muted)}
.component-details .material{min-height:0;margin:12px 0 5px;gap:5px 8px}.component-details .material strong{font-size:11px;font-weight:500;color:var(--muted)}.component-details .material>.utility-icon{width:15px;height:15px}.component-details .material span{font-size:10px}
-@container(max-width:460px){.compare-toolbar .overlay-label{display:none}.compare-toolbar .overlay-control{width:34px;padding:7px}.compare-toolbar .zoom-control select{width:86px;padding-left:27px;padding-right:24px}.compare-toolbar .zoom-control>.utility-icon:first-child{left:8px}.compare-toolbar .zoom-control>.utility-icon:last-child{right:7px}}
-@media(forced-colors:active){.zoom-control select{appearance:auto;padding:6px 8px}.zoom-control>.utility-icon{display:none}}
+@container(max-width:460px){}
+@media(forced-colors:active){}
/* A full-page checkpoint is one comparison, not a component inventory. */
.assembled-review>.workbench{grid-template-columns:minmax(0,1fr);gap:0}
.assembled-review .workbench>.inspector{display:flex}
.assembled-review .inspection-content{padding:16px 20px;scrollbar-gutter:auto}
.assembled-review .compare{max-width:none;gap:20px}
-.assembled-review .pan-viewport{background:var(--canvas);border:1px solid #bdc6bd;box-shadow:inset 0 2px 7px #263d2a12}
+.assembled-review .pan-viewport{background:var(--canvas);border:1px solid var(--ks-rule);box-shadow:inset 0 2px 7px oklch(13% 0 0 / 0.07)}
.assembled-review .inspector>.review-form{padding:12px 20px;max-height:55%}
.assembled-review .decisions{display:flex;justify-content:flex-end;gap:10px}
-.assembled-review #approve{order:2;min-width:180px}
.assembled-review .page-review-status{font-size:11px;color:var(--muted);text-align:right;line-height:1.4;overflow-wrap:anywhere}
.assembled-review .page-review-status:empty{display:none}
.assembled-review .review-form:has(#feedback-form){max-height:55%}
@@ -153,7 +1136,6 @@
.assembled-review .inspection-content{padding:10px}
.assembled-review .compare{grid-template-columns:minmax(0,1fr) minmax(0,1fr);gap:8px}
.assembled-review .inspector>.review-form{padding:10px}
- .assembled-review .decisions>button{flex:1;min-width:0}
.assembled-review .page-review-status{text-align:left}
}
@@ -169,7 +1151,7 @@
.instance-grid{display:grid;gap:0;flex:none;grid-auto-rows:max-content}
.instance-grid-labels{display:grid;grid-template-columns:1fr 1fr;gap:16px;color:var(--muted);font-size:12px;padding:8px 0}
.instance-row{display:block;height:auto;width:100%;text-align:left;padding:12px 0;border:0;border-top:1px solid var(--line);border-radius:0;background:transparent;color:inherit}
-.instance-row:hover{background:#eef3f1}
+.instance-row:hover{background:var(--ks-paper-deep)}
.instance-caption{display:flex;justify-content:space-between;align-items:baseline;gap:12px;font-size:12px;margin-bottom:8px}
.instance-caption>span{color:var(--muted);font-size:11px}
.instance-pair{display:grid;grid-template-columns:1fr 1fr;align-items:center;gap:16px}
@@ -183,56 +1165,418 @@
#comparison-dialog .group-overview>.compare-toolbar{top:0}
#comparison-dialog .group-overview>.expanded-title{padding-right:44px}
-.review-scope{font-size:12px;line-height:1.5;margin:8px 0 12px;color:var(--color-text,#292929);text-align:left;white-space:normal}
+.review-scope{font-size:12px;line-height:1.5;margin:8px 0 12px;color:var(--color-text,var(--ks-text));text-align:left;white-space:normal}
.review-scope p{margin:4px 0;overflow-wrap:anywhere}.review-scope strong{font-weight:600;margin-right:5px}
.review-scope .separate-reviews,.review-scope .scope-excluded{font-size:11px;color:var(--muted)}
.instance-row .review-scope{margin:12px 0 0}
#comparison-dialog .review-scope{flex:none}
-.reference-layer{position:absolute;box-sizing:border-box;border:1px dashed #fff;outline:1px solid #173e43;pointer-events:none;z-index:2}.reference-layer>span{position:absolute;top:0;left:0;max-width:100%;padding:1px 4px;background:#173e43;color:white;font:10px/1.4 var(--font-sans,sans-serif);white-space:nowrap;overflow:hidden;text-overflow:ellipsis;opacity:0;transition:opacity .12s}.instance-row:hover .reference-layer>span,.instance-row:focus-visible .reference-layer>span,.pan-viewport:hover .reference-layer>span,.pan-viewport:focus .reference-layer>span{opacity:1}
-`;var rr={chevronDown:'<path d="m6 9 6 6 6-6"/>',code:'<path d="m8 6-6 6 6 6m8-12 6 6-6 6m-3-15-2 18"/>',image:'<rect x="3" y="3" width="18" height="18" rx="2"/><circle cx="8" cy="8" r="1.5"/><path d="m3 17 6-6 4 4 3-3 5 5"/>',expand:'<path d="M8 3H3v5m13-5h5v5M3 16v5h5m13-5v5h-5M3 3l6 6m12-6-6 6M3 21l6-6m12 6-6-6"/>',compact:'<path d="M3 9h6V3m6 0v6h6M9 21v-6H3m12 6v-6h6M3 3l6 6m12-6-6 6M3 21l6-6m12 6-6-6"/>',hideTray:'<rect x="3" y="3" width="18" height="18" rx="2"/><path d="M3 14h18m-12 3 3 2 3-2"/>',showTray:'<rect x="3" y="3" width="18" height="18" rx="2"/><path d="M3 14h18m-12-4 3-3 3 3"/>',next:'<path d="M5 12h14m-6-6 6 6-6 6"/>',mark:'<path d="M9 4H4v5m11-5h5v5M4 15v5h5m11-5v5h-5M8 12h8m-4-4v8"/>',close:'<path d="m6 6 12 12M6 18 18 6"/>',undo:'<path d="M4 10h9a6 6 0 0 1 0 12M4 10l5-5m-5 5 5 5" transform="translate(0 -2)"/>',external:'<path d="M14 3h7v7m0-7L10 14m0-10H5a2 2 0 0 0-2 2v13a2 2 0 0 0 2 2h13a2 2 0 0 0 2-2v-5"/>',zoom:'<circle cx="10.5" cy="10.5" r="6.5"/><path d="m16 16 5 5"/>'};function T(a){return`<svg class="utility-icon" viewBox="0 0 24 24" aria-hidden="true" focusable="false">${rr[a]}</svg>`}var l=(a)=>a.replace(/[&<>"']/g,(o)=>({"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#39;"})[o]),hi=(a)=>`${a*100}%`,C=(a)=>{let o=new URL(a,location.href);if(!["http:","https:"].includes(o.protocol))throw Error("Unsupported preview URL");return l(o.href)};function Lo(a,o,x){let e=a.attachShadow({mode:"open"}),n=structuredClone(x.initialDraft??Qo(o)),p=o.stage==="hero"&&o.components.length===1&&!n.missing.length,y=()=>[...o.components].sort((f,c)=>O(f,n,x.history).priority-O(c,n,x.history).priority),g=y().find((f)=>O(f,n,x.history).kind!=="approved")?.id??o.components[0]?.id,v=ki(o,n).pending?"pending":"reviewed",Z=!1,s=!1,z=x.completed??!1,$i="",V={},k=!!x.completed||!ki(o,n).pending,P=null,ii=!0,Wo=/Mac|iPhone|iPad/.test(navigator.platform)?"⌘Enter":"Ctrl+Enter",li=!1,H=!1,ji=!1,Ui=null,di=!1,W=!0,bi=!1,Y="comp",ao=Y,ni="fit",qi="checker",A=!1,gi="isolated",Ai,po="fit",ai=null,pi=null,xi=null,Hi='<svg viewBox="0 0 16 16" aria-hidden="true"><path d="m3 8 3 3 7-7"/></svg>',Ki='<svg viewBox="0 0 16 16" aria-hidden="true"><path d="m3 11 1 2 2-1 7-7-3-3-7 7v2Z"/></svg>',xo=(f,c)=>{if(f.stage==="hero")return"";let j=Ti(f,c);if(!j.related.length)return"";let q=j.related.map((_)=>l(_.name)).join(" · ");return`<div class="review-scope" aria-label="Review scope"><p><strong>Reviewing</strong> ${l(j.description||c.name)}</p><p class="separate-reviews"><strong>Outlined · reviewed separately</strong> ${q}</p>${j.excluded.length?`<p class="scope-excluded">Hidden in this preview: ${j.excluded.map((_)=>l(_.name)).join(" · ")}</p>`:""}</div>`},Qi=(f)=>`left:${hi(f.x)};top:${hi(f.y)};width:${hi(f.w)};height:${hi(f.h)}`,to=(f,c)=>f.stage==="hero"?"":Ti(f,c).related.map((j)=>{let q=c.box,_=j.box,fi=Math.max(q.x,_.x),X=Math.max(q.y,_.y),Ii={x:(fi-q.x)/q.w,y:(X-q.y)/q.h,w:Math.max(0,Math.min(q.x+q.w,_.x+_.w)-fi)/q.w,h:Math.max(0,Math.min(q.y+q.h,_.y+_.h)-X)/q.h};return`<span class="reference-layer" style="${Qi(Ii)}" title="Reviewed separately: ${l(j.name)}" aria-label="Reviewed separately: ${l(j.name)}"><span>${l(j.name)}</span></span>`}).join("");function vi(f){e.getElementById(f)?.focus({preventScroll:!0})}function Go(f){let c=Xo(o,n,f);if(k=!c,c)g=c;Y="component",A=!1,li=!1,ni="fit",gi="isolated",ii=!0,v=k?"reviewed":"pending";let j=()=>{w(),vi(k?"review-summary":V[g]?"feedback":"approve")};if(k&&H&&Ui)Ui(j);else j()}async function lo(){if(s||z||A||Object.keys(V).length)return;s=!0,$i="",w();try{await x.onSubmit(_o(o,n)),z=!0,k=!0,Z=!1,v="reviewed"}catch(f){$i=f instanceof Error?f.message:"Could not save. Try again."}finally{s=!1,w()}}function Bi(f){if(s||z||A||ji)return;let c=o.components.find((X)=>X.id===g);if(!c||!Ji(o,n,c,ii,Object.keys(V)).length)return;let j=n.decisions[c.id],q=j?.revision===c.revision?j:void 0,_=Ji(o,n,c,ii,Object.keys(V));P={id:c.id,name:_.length>1?`${c.reviewGroup} · ${_.length} instances`:c.name,action:f,previous:Object.fromEntries(_.map((X)=>[X.id,n.decisions[X.id]?{...n.decisions[X.id]}:void 0]))};let fi=V[c.id]??q;for(let X of _)n.decisions[X.id]={revision:X.revision,action:f,feedback:f==="revise"?fi?.feedback??"":"",split:f==="revise"&&(fi?.split??!1)};if(delete V[c.id],bi)W=!0,bi=!1;if(p)n.inventoryConfirmed=f==="approve",P=null,lo();else Go(c.id)}function To(){if(s||z||A||ji)return;let f=o.components.find((q)=>q.id===g);if(!f||!Ji(o,n,f,ii,Object.keys(V)).length)return;let c=n.decisions[f.id],j=c?.revision===f.revision?c:void 0;if(V[f.id]??={feedback:j?.feedback??"",split:j?.split??!1},W&&(e.querySelector(".workbench")?.clientHeight??0)<420)bi=!0,W=!1;k=!1,w(),vi("feedback")}function ho(f){let c=`missing-${crypto.randomUUID()}`;n.missing.push({id:c,name:"Missing component",feedback:"",box:f}),n.inventoryConfirmed=!1,k=!1,g=c,Y="component",Z=!1,ai=null,pi=null,w(),e.querySelector("#missing-name")?.focus()}function w(){if(xi?.disconnect(),z||k&&!p)H=!1;let f=e.activeElement,c=f?.id,j=f?.dataset.select,q=window.scrollX,_=window.scrollY,fi=e.querySelector(".inventory")?.scrollLeft??0,X=Ai===g,Ii=Y==="component"&&(!X||ao!==Y);ao=Y;let Uo=X?e.querySelector(".inspection-content")?.scrollTop??0:0,Ao=X&&(e.querySelector(".changed-files")?.open??!1),Bo=e.querySelector(".comparison-slot")?.clientHeight??200,go=e.querySelector(".pan-viewport"),fo=Ai===g&&po===ni,Io=fo?go?.scrollLeft??0:0,Ro=fo?go?.scrollTop??0:0;Ai=g,po=ni;let m=o.components.find((i)=>i.id===g),J=n.missing.find((i)=>i.id===g),E=Eo(o,n,x.history),G=E.find((i)=>i.members.some((r)=>r.id===g)),D=!!G&&G.members.length>1&&ii,so=D?G.box:m?.box??J?.box,wo=G?E.indexOf(G)+1:E.length+n.missing.findIndex((i)=>i.id===g)+1,co=m?n.decisions[m.id]:void 0,ti=co?.revision===m?.revision?co:void 0,Yi=m?V[m.id]:void 0,si=Object.keys(V).length>0,mo=m?Gi(o,m):[],wi=m?Ji(o,n,m,ii,Object.keys(V)):[],Oo=m?!o.components.some((i)=>!wi.some((r)=>r.id===i.id)&&O(i,n).kind==="pending"):!1,Ri=P&&!z?`<div class="decision-notice"><span role="status">${l(P.name)} ${P.action==="approve"?"approved":"flagged for repair"}.</span><button id="undo-decision" class="quiet">Undo</button></div>`:"",M=ki(o,n),$=x.history,B=m?Wi(m.id,$):void 0,ci=$?.packet.components.find((i)=>i.id===m?.id),oi=A&&!!ci,d=oi?ci:m,L=oi?$.packet:o,bo=Object.values($?.changes??{}),vo=bo.filter((i)=>i.kind==="changed").length,uo=bo.filter((i)=>i.kind==="added").length,Oi=o.components.filter((i)=>O(i,n,$).kind==="approved"&&Wi(i.id,$).carried).length,Di=(i)=>{let r=O(i,n,$);return z&&r.kind==="feedback"?{...r,label:"Changes requested"}:r},Mi=E.filter((i)=>i.kind==="pending").length,Do=E.length-Mi+n.missing.length,yo=E.filter((i)=>v==="all"||i.kind==="pending"===(v==="pending")).map((i)=>i.representative),So=(i)=>E.find((r)=>r.members.some((t)=>t.id===i))?.label??i,Fo=[M.revisions+n.missing.length?`${M.revisions+n.missing.length} feedback ready`:"",Oi?`${Oi} ${Oi===1?"approval":"approvals"} kept`:"",vo?`${vo} changed`:"",uo?`${uo} added`:"",$?.removed.length?`${$.removed.length} removed`:""].filter(Boolean).join(" · "),Co=$i||(si?"Save or cancel your open feedback before sending.":z?x.preview?"Preview submitted. No run changed.":"Review submitted.":M.hasFeedback?"Ready to send for corrections.":M.pending?`${Mi} left to review`:!n.inventoryConfirmed?"Confirm the map is complete.":"Ready to continue."),ri=d?zi(d):null,Si=d?.preview.kind==="image"&&!ri?.code,Fi=Si||d?.material?.alpha==="transparent",S=!!(d?.context&&gi==="context"),zo=d&&(S?d.context?.kind!=="image":d.preview.kind==="page"),Ci=S&&d?.context?d.context.url:d?.preview.url,ko=d?Ti(L,d):null,Po=ri?.code?`${ri.label} · ${ri.captured?"captured from code":"live preview"}`:d?.material?`${d.material.alpha==="transparent"?"Transparent":d.material.alpha==="opaque"?"Opaque":"Transparency unverified"} ${d.material.format}`:"Raster · transparency unverified";e.innerHTML=`<style>${Zo}</style><section class="review ${p?"assembled-review":""}" aria-label="${p?"Assembled page review":"Component review"}" style="--comp-background:${/^#[0-9a-f]{6}$/i.test(o.comp.background??"")?o.comp.background:"#eeeeee"}">
- <header><div><h1>${z?"Review record.":p?"Review the assembled page.":"Review the components."}</h1><p>${l(o.title)} <span>· Round ${o.round}</span></p></div>${z?'<span class="badge">Submitted · read-only</span>':x.preview?'<span class="badge">Interactive preview</span>':""}</header>
- ${x.preview?'<p class="preview-note">Historical hotel artwork for testing this interface. Decisions stay in this preview; no run is changed.</p>':""}
- ${$&&!p?`<section class="round-summary" aria-label="Changes since previous round"><p><strong>${Mi} ${Mi===1?"item":"items"} to review</strong><span>${Fo}</span></p>${M.pending?`<button id="review-changes" class="icon-button" aria-label="Next to review" title="Next to review">${T("next")}</button>`:""}${$.removed.length?`<details><summary>Removed from the map</summary><p>${$.removed.map((i)=>l(i.name)).join(" · ")}. Confirm these omissions are intentional before accepting the map.</p></details>`:""}</section>`:""}
- ${!p?`<div class="mobile-panes" role="group" aria-label="Inspection view"><button id="show-comp" aria-pressed="${Y==="comp"}">Approved comp</button><button id="show-component" aria-pressed="${Y==="component"}">Component ${wo}</button></div>`:""}
- <div class="workbench" data-mobile-pane="${Y}">${!p?`<svg class="connector" aria-hidden="true"><path /></svg>
+.reference-layer{position:absolute;box-sizing:border-box;border:1px dashed var(--ks-paper-raised);outline:1px solid var(--ks-ink);pointer-events:none;z-index:2}.reference-layer>span{position:absolute;top:0;left:0;max-width:100%;padding:1px 4px;background:var(--ks-ink);color:var(--ks-paper-raised);font:10px/1.4 var(--font-sans,sans-serif);white-space:nowrap;overflow:hidden;text-overflow:ellipsis;opacity:0;transition:opacity .12s}.instance-row:hover .reference-layer>span,.instance-row:focus-visible .reference-layer>span,.pan-viewport:hover .reference-layer>span,.pan-viewport:focus .reference-layer>span{opacity:1}
+
+/* Design-system pass (tokens.ts mirrors kinpaku-tokens.css). One paper plane, hairline rules
+ instead of nested panels, ink for the primary action, patina for state, gold as a line. */
+.review,.review>.workbench,.review>.inventory-section,.review>.round-summary,.review>.preview-note,.mobile-panes{--workspace:var(--ks-paper);--canvas:var(--ks-paper-deep);--dock:var(--ks-paper);--surface:var(--ks-paper);background:var(--ks-paper)}
+.review{color:var(--ks-text)}
+.review h1{font:300 34px/1.04 var(--ks-font-display);font-variation-settings:'wght' 300;color:var(--ks-ink);letter-spacing:0}
+.review>header{background:var(--ks-paper);border-bottom:1px solid var(--ks-rule);box-shadow:none}
+.review>header p,.review>header p span{color:var(--ks-text-muted)}
+.review>.round-summary,.review>.preview-note,.mobile-panes{box-shadow:none;border-bottom:1px solid var(--ks-rule)}
+.section-head h2,.inventory-section h2{font:400 var(--ks-type-eyebrow-size)/1.3 var(--ks-mono);letter-spacing:var(--ks-type-eyebrow-track);text-transform:uppercase;color:var(--ks-text-muted)}
+.compare figcaption,.instance-grid-labels{font:400 var(--ks-type-eyebrow-size)/1.4 var(--ks-mono);letter-spacing:var(--ks-type-eyebrow-track);text-transform:uppercase;color:var(--ks-text-muted)}
+.map-space{background:transparent;border:0;box-shadow:none;border-radius:0}
+.map{box-shadow:0 0 0 1px var(--ks-rule)}
+.workbench>.inspector{background:transparent;border-radius:0;box-shadow:none;border-left:1px solid var(--ks-rule)}
+.inspector>.section-head{background:transparent;border-bottom:1px solid var(--ks-rule);box-shadow:none!important}
+.inspection-content{background:transparent}
+.inspector>.review-form{background:transparent;border-top:1px solid var(--ks-rule);box-shadow:none!important}
+.pan-viewport,.crop-stage{background:transparent}
+.pan-viewport{border:0;box-shadow:none;border-radius:0}
+.crop-stage{box-shadow:0 0 0 1px var(--ks-rule)}
+.review>.inventory-section{box-shadow:none;border-top:1px solid var(--ks-rule)}
+.inventory-section>.section-head{border-bottom:1px solid var(--ks-rule)}
+.inventory .item,.inventory .item.active{background:var(--ks-paper-raised)}
+.item.active{box-shadow:inset 0 -2px 0 var(--ks-kinpaku)}
+.review>footer{background:var(--ks-paper-raised);border-top:1px solid var(--ks-rule);box-shadow:none}
+button:focus-visible,input:focus-visible,textarea:focus-visible{outline-color:var(--ks-focus-ring)}
+textarea,input:not([type=checkbox]),select{border-color:var(--ks-edge);border-radius:var(--ks-radius-sm);background:var(--ks-paper-raised)}
+input[type=checkbox]{accent-color:var(--ks-ink)}
+.decisions{background:transparent}
+.badge{border:0;border-radius:var(--ks-radius-sm);background:var(--ks-gray);color:var(--ks-text-muted);font:600 var(--ks-type-eyebrow-size)/1 var(--ks-mono);letter-spacing:.02em;text-transform:uppercase;padding:5px 7px}
+#comparison-dialog{background:var(--ks-paper);border-color:var(--ks-rule);border-radius:var(--ks-radius-md);box-shadow:var(--ks-lift-2)}
+/* The first-viewport review: two figures on the paper, a small toolbar, two buttons. */
+.assembled-review>.workbench{padding:20px 28px 0}
+.assembled-review .workbench>.inspector{border-left:0}
+.assembled-review .inspection-content{padding:0}
+.assembled-review .compare{gap:28px}
+.assembled-review .pan-viewport{background:transparent;border:0;box-shadow:none}
+.assembled-review .inspector>.review-form{padding:14px 0 18px;margin-top:8px}
+.assembled-review .decisions{padding:0}
+.assembled-review .page-review-status{color:var(--ks-text-muted);font-size:var(--ks-type-label-size)}
+@media(max-width:800px){.assembled-review>.workbench{padding:12px 16px 0}.assembled-review .compare{gap:12px}}
+`+zi+`
+/* Local fit for the vendored kit: sizes the legacy layout expects, the link-style text action,
+ and the paper grain the site puts on its page ground (kit body::before, here on the review root). */
+.review{position:relative;isolation:isolate}
+.review::before{content:"";position:fixed;inset:0;z-index:-1;pointer-events:none;opacity:0.055;mix-blend-mode:multiply;background-image:var(--ks-grain);background-size:160px 160px}
+.decisions>.ks-button{flex:1}
+.assembled-review .decisions{display:flex;justify-content:flex-end;gap:12px}
+.assembled-review .decisions>.ks-button{flex:0 0 auto;min-width:200px}
+.assembled-review #approve{order:2}
+.ks-button[disabled] .ks-button-arrow{color:currentColor}
+.text-action{border:0;background:none;padding:0 2px;min-height:0;color:var(--ks-link-on-paper);font:inherit;font-size:var(--ks-type-label-size);text-decoration:underline;text-decoration-color:var(--ks-link-on-paper-line);text-underline-offset:3px;cursor:pointer}
+.text-action:hover{text-decoration-color:var(--ks-link-on-paper-line-hover)}
+.compare-toolbar{align-items:center;gap:16px}
+.comparison-actions{display:flex;gap:8px;margin-left:auto}
+.ks-icon-button{padding:0;min-height:0}
+.ks-icon-button .utility-icon{width:16px;height:16px}
+.mobile-panes{padding:8px 14px}
+.ks-checkbox input{margin:0}
+.review .ks-switch,.review .ks-switch[aria-pressed=true],.review .ks-instrument-key[aria-pressed=true]{box-shadow:none}
+`;var ir={chevronDown:'<path d="m6 9 6 6 6-6"/>',code:'<path d="m8 6-6 6 6 6m8-12 6 6-6 6m-3-15-2 18"/>',image:'<rect x="3" y="3" width="18" height="18" rx="2"/><circle cx="8" cy="8" r="1.5"/><path d="m3 17 6-6 4 4 3-3 5 5"/>',expand:'<path d="M8 3H3v5m13-5h5v5M3 16v5h5m13-5v5h-5M3 3l6 6m12-6-6 6M3 21l6-6m12 6-6-6"/>',compact:'<path d="M3 9h6V3m6 0v6h6M9 21v-6H3m12 6v-6h6M3 3l6 6m12-6-6 6M3 21l6-6m12 6-6-6"/>',hideTray:'<rect x="3" y="3" width="18" height="18" rx="2"/><path d="M3 14h18m-12 3 3 2 3-2"/>',showTray:'<rect x="3" y="3" width="18" height="18" rx="2"/><path d="M3 14h18m-12-4 3-3 3 3"/>',next:'<path d="M5 12h14m-6-6 6 6-6 6"/>',mark:'<path d="M9 4H4v5m11-5h5v5M4 15v5h5m11-5v5h-5M8 12h8m-4-4v8"/>',close:'<path d="m6 6 12 12M6 18 18 6"/>',undo:'<path d="M4 10h9a6 6 0 0 1 0 12M4 10l5-5m-5 5 5 5" transform="translate(0 -2)"/>',external:'<path d="M14 3h7v7m0-7L10 14m0-10H5a2 2 0 0 0-2 2v13a2 2 0 0 0 2 2h13a2 2 0 0 0 2-2v-5"/>',zoom:'<circle cx="10.5" cy="10.5" r="6.5"/><path d="m16 16 5 5"/>'};function mn(e){return`<svg class="utility-icon" viewBox="0 0 24 24" aria-hidden="true" focusable="false">${ir[e]}</svg>`}var Di=[{kind:"plate",label:"Illustration / plate",hint:"Painted or drawn artwork"},{kind:"image",label:"Photo / image",hint:"A photograph"},{kind:"texture",label:"Texture",hint:"A surface or material"}];function Mi(e){let n=e;return!!n&&n.schemaVersion===3&&n.stage==="components"}function Ri(e){return e.role==="plan"&&(!!e.flags?.length||!!e.codeDrawn)}function Fi(e){let n=(o)=>Ri(o)?0:o.role==="asset"?1:2;return e.components.map((o,a)=>({c:o,i:a})).sort((o,a)=>n(o.c)-n(a.c)||o.i-a.i).map((o)=>o.c)}function Ti(e){let n=new Set(e.components.map((o)=>o.id));return(e.codeRegions??[]).filter((o)=>!n.has(o.id))}function zn(e,n){let o=n.decisions[e.id];return o?.revision===e.revision?o:void 0}function yn(e,n){let o=zn(e,n);return o?o.action==="approve"?"approved":o.action:"pending"}function qi(e,n){return e.reclassify?.find((o)=>o.id===n)}function Ci(e){let n=[e.name,e.note,...(e.flags??[]).map((o)=>o.message)].join(" ");if(/\b(textures?|surfaces?|grain|grainy|brushed|metal(lic)?|steel|brass|copper|paper|linen|canvas|fabric|cloth|wood(en)?|stone|marble|concrete|plaster|leather|noise|pattern(ed)?|weave|patina)\b/i.test(n))return"texture";if(/\b(photo|photos|photograph|photographs|photographic|photography)\b/i.test(n)&&!/\bphotographic shading\b/i.test(n))return"image";return"plate"}function Xe(e){return`Drawn in code (${e.kind})`}function Pi(e){return e.message}function Pn(e,n){let o=e.components.map((f)=>yn(f,n)),a=o.filter((f)=>f==="approved").length,t=o.filter((f)=>f==="revise").length,p=new Set(Ti(e).map((f)=>f.id)),y=(n.reclassify??[]).filter((f)=>p.has(f.id)).length,g=o.filter((f)=>f==="reclassify").length+y,b=o.filter((f)=>f==="pending").length,z=n.missing.length,v=t+g+z>0,w=n.packetRevision===e.revision,M=n.missing.every((f)=>f.name.trim()&&Wi(f.box)),u=w&&!v&&b===0;return{total:o.length,approved:a,revise:t,reclassify:g,pending:b,missing:z,hasChanges:v,canApprove:u,mode:v?"changes":"approve",canSubmit:w&&M&&(v||u)}}function Si(e,n,o,a={}){if(a.split&&!(o==="revise"&&n.role==="asset"))throw Error("Only a generated asset can be split into layers");if(o==="revise"&&n.role!=="asset"&&!(a.feedback??"").trim())throw Error("Revising a plan item needs feedback");if(o==="reclassify"&&n.role!=="plan")throw Error("Only planned code can become an image");let t={revision:n.revision,action:o,feedback:o==="approve"?"":(a.feedback??"").trim(),split:!!a.split};if(o==="reclassify")t.kind=a.kind??Ci(n);return{...e,inventoryConfirmed:!1,decisions:{...e.decisions,[n.id]:t}}}function Je(e,n){let o={...e.decisions};return delete o[n],{...e,inventoryConfirmed:!1,decisions:o}}function ne(e,n,o){let a=(e.reclassify??[]).filter((t)=>t.id!==n);return{...e,inventoryConfirmed:!1,reclassify:o?[...a,{id:n,kind:o.kind,feedback:(o.feedback??"").trim()}]:a}}function $e(e,n){let o=Pn(e,n);if(!o.canSubmit)throw Error("Review is incomplete or stale");let a={};for(let y of e.components){let g=zn(y,n);if(g)a[y.id]=structuredClone(g)}let t=new Set(Ti(e).map((y)=>y.id)),p=(n.reclassify??[]).filter((y)=>t.has(y.id)).map((y)=>({...y}));return{schemaVersion:1,requestId:e.id,packetRevision:n.packetRevision,decisions:a,missing:structuredClone(n.missing),inventoryConfirmed:o.mode==="approve",...p.length?{reclassify:p}:{}}}function Ge(e){return{packetRevision:e.revision,decisions:{},missing:[],inventoryConfirmed:!1,reclassify:[]}}function Qe(e,n,o,a,t=0.02){let p=Math.max(0,Math.floor((a.x-t)*n)),y=Math.min(n-1,Math.ceil((a.x+a.w+t)*n)),g=Math.max(0,Math.floor((a.y-t)*o)),b=Math.min(o-1,Math.ceil((a.y+a.h+t)*o)),z=Math.floor(a.x*n),v=Math.ceil((a.x+a.w)*n),w=Math.floor(a.y*o),M=Math.ceil((a.y+a.h)*o),u=[],f=Math.max(1,Math.round(Math.max(y-p,b-g)/80));for(let Q=g;Q<=b;Q+=f)for(let Z=p;Z<=y;Z+=f){if(Z>=z&&Z<v&&Q>=w&&Q<M)continue;let dn=(Q*n+Z)*4;if(e[dn+3]<200)continue;u.push([e[dn],e[dn+1],e[dn+2]])}return u}function Ze(e){if(!e.length)return;let n=(o)=>{let a=e.map((t)=>t[o]).sort((t,p)=>t-p);return a[a.length>>1]};return"#"+[0,1,2].map((o)=>n(o).toString(16).padStart(2,"0")).join("")}function ie(e,n,o,a,t,p=4,y=24){let g=e.w*n,b=e.h*o,z=Math.min(24,Math.max(8,0.04*Math.max(g,b))),v=Math.min(n,g+z*2),w=Math.min(o,b+z*2),M=Math.min(p,a/v,t/w);if(b*M<y&&b>0)M=Math.min(p,y/b,t/w),v=Math.min(v,a/M);let u=(e.x+e.w/2)*n,f=(e.y+e.h/2)*o,Q=Math.max(0,Math.min(n-v,u-v/2)),Z=Math.max(0,Math.min(o-w,f-w/2));return{scale:M,width:v*M,height:w*M,view:{x:Q/n,y:Z/o,w:v/n,h:w/o}}}var er=["no","one","two","three","four","five","six","seven","eight","nine","ten","eleven","twelve"],ji=(e)=>er[e]??String(e),Ye=(e)=>e[0].toUpperCase()+e.slice(1);function Ue(e,n,o){let a=e.components.filter((p)=>yn(p,n)==="pending").length;if(o&&e.round>1){let p=e.components.filter((g)=>["changed","added"].includes(o.changes[g.id]?.kind??"")||o.feedback?.[g.id]).length,y=e.components.filter((g)=>yn(g,n)==="approved").length;return`The agent worked on your notes for ${ji(p)} ${p===1?"item":"items"}. ${Ye(ji(y))} ${y===1?"approval is":"approvals are"} kept.`}let t=Math.max(1,Math.round(a*15/60));return`${Ye(ji(a))} ${a===1?"thing":"things"} to check before any page code is written. About ${ji(t)} ${t===1?"minute":"minutes"}.`}var Ae="Frame, view and moving parts as separate pieces, e.g. the shutters.";function ee(e){return e.role==="asset"?e.flags??[]:[]}var re=(e)=>ee(e).some((n)=>n.id==="baked-composite"),ae=(e)=>e?.action==="revise"&&e.split===!0;function Vi(e,n){if(!n)return null;let o=n.feedback?.[e]?void 0:Object.entries(n.feedback??{}).filter(([g,b])=>b.decision.action==="revise"&&b.decision.split&&e.startsWith(`${g}-`)).sort((g,b)=>b[0].length-g[0].length)[0];if(o){let[g,b]=o;return{round:b.round,action:"split",words:(b.decision.feedback??"").trim(),splitFrom:n.packet.components.find((z)=>z.id===g)?.name??g,beforeUrl:void 0,wasCode:!1,wasKind:void 0,wasNote:""}}let a=n.feedback?.[e],t=n.packet.components.find((g)=>g.id===e),p=n.packet.codeRegions?.find((g)=>g.id===e),y=n.changes[e]?.kind;if(!a&&y!=="changed")return null;return{round:a?.round??n.packet.round,action:a?.decision.action,words:(a?.decision.feedback??"").trim(),beforeUrl:t?.role==="asset"?t.preview.url:void 0,wasCode:t?.role==="plan"||!t&&!!p,wasKind:t?.kind??p?.kind,wasNote:t?.note??p?.note??"",splitFrom:void 0}}function Ne(e,n,o,a,t,p=4,y){let g=e.length,b=Math.max(0,Math.min(o-t,(n-a*(g-1))/e.reduce((M,u)=>M+u,0))),z=Math.max(0,Math.min(n,(o-g*t-a*(g-1))/e.reduce((M,u)=>M+1/u,0)));if(y)b=Math.min(b,y.h*p),z=Math.min(z,y.w*p);let v=e.reduce((M,u)=>M+u*b*b,0),w=e.reduce((M,u)=>M+z*z/u,0);return v>=w?{direction:"row",sizes:e.map((M)=>({w:M*b,h:b}))}:{direction:"column",sizes:e.map((M)=>({w:z,h:z/M}))}}function Le(e,n,o,a,t,p){return{x:t-e*o*p,y:t-n*a*p}}function _e(e,n,o){return Fi(e).map((a)=>({id:a.id,name:a.name,state:yn(a,n),current:a.id===o}))}function Ke(e,n){let o=Pn(e,n);if(o.mode==="approve")return"Approve plan and assets";let a=e.components.filter((y)=>ae(zn(y,n))).length,t=o.revise-a;return`Send notes (${[t?`${t} ${t===1?"note":"notes"}`:"",a?`${a} to split`:"",o.reclassify?`${o.reclassify} to become ${o.reclassify===1?"an image":"images"}`:"",o.missing?`${o.missing} missing`:""].filter(Boolean).join(", ")})`}var Be=zi+`
+:host{display:block;height:var(--component-review-height,100dvh);min-height:0;overflow:hidden;color:var(--ks-text);font:400 var(--ks-type-small-size)/1.5 var(--ks-font);
+ --asset:var(--ks-patina);--plan:var(--ks-ink);--flag:var(--ks-vermilion);--missing:var(--ks-vermilion);--stage-ease:var(--ks-ease)}
+*{box-sizing:border-box}
+h1,h2,h3,p,figure,blockquote,dl,dd{margin:0}
+button,input,textarea{font:inherit;color:inherit}
+button{cursor:pointer}
+button:disabled{cursor:not-allowed}
+svg{width:16px;height:16px;flex-shrink:0;fill:none;stroke:currentColor;stroke-width:1.6;stroke-linecap:round;stroke-linejoin:round}
+:focus-visible{outline:2px solid var(--ks-focus-ring);outline-offset:3px}
+.eyebrow{font:400 var(--ks-type-eyebrow-size)/1.3 var(--ks-mono);letter-spacing:var(--ks-type-eyebrow-track);text-transform:uppercase;color:var(--ks-text-muted)}
+.muted{color:var(--ks-text-muted)}
+.cap{display:inline-flex;align-items:center;justify-content:center;min-width:20px;height:20px;padding:0 5px;margin:0 -8px 0 2px;border:1px solid currentColor;border-radius:var(--ks-radius-sm);font:500 var(--ks-type-micro-size)/1 var(--ks-mono);letter-spacing:0;opacity:.5}
+.ks-button-primary .cap{opacity:.55}
+.ks-button[disabled] .ks-button-arrow{color:currentColor}
+.text-action{border:0;background:none;padding:0 2px;min-height:0;color:var(--ks-link-on-paper);font:inherit;text-decoration:underline;text-decoration-color:var(--ks-link-on-paper-line);text-underline-offset:3px;transition:text-decoration-color var(--ks-quick) var(--ks-ease)}
+.text-action:hover:not(:disabled){text-decoration-color:var(--ks-link-on-paper-line-hover)}
+.text-action .cap{margin:0 0 0 8px;height:18px;min-width:18px}
+textarea,input{width:100%;display:block;background:var(--ks-paper-raised);color:var(--ks-ink);border:1px solid var(--ks-edge);border-radius:var(--ks-radius-sm);padding:10px 14px;line-height:1.45}
+textarea{resize:vertical;min-height:64px}
+textarea:focus,input:focus{outline:none;border-color:var(--ks-patina);box-shadow:0 0 0 1px var(--ks-patina)}
+.field{display:flex;flex-direction:column;gap:8px}
+
+.rv{height:100%;display:flex;flex-direction:column;min-height:0;background:var(--ks-paper);position:relative;isolation:isolate}
+.rv::before{content:"";position:fixed;inset:0;z-index:-1;pointer-events:none;opacity:0.055;mix-blend-mode:multiply;background-image:var(--ks-grain);background-size:160px 160px}
+
+/* Top bar: title, round, a light per item. */
+.bar{flex-shrink:0;height:56px;display:grid;grid-template-columns:1fr auto 1fr;align-items:center;gap:20px;padding:0 28px;border-bottom:1px solid var(--ks-rule)}
+.bar-title{display:flex;align-items:baseline;gap:12px;min-width:0}
+.bar-name{font-size:var(--ks-type-ui-size);font-weight:500;color:var(--ks-ink);white-space:nowrap;overflow:hidden;text-overflow:ellipsis}
+.bar-round{font:400 var(--ks-type-eyebrow-size)/1 var(--ks-mono);letter-spacing:var(--ks-type-eyebrow-track);text-transform:uppercase;color:var(--ks-text-muted);white-space:nowrap}
+.lights{display:flex;align-items:center;gap:4px}
+.light{position:relative;width:20px;height:24px;padding:0;border:0;background:transparent;display:grid;place-items:center}
+.light::before{content:"";width:8px;height:8px;border-radius:50%;background:var(--ks-gray-2);box-shadow:inset 0 1px 1px oklch(13% 0 0 / 0.18);transition:background-color 160ms var(--ks-ease),box-shadow 160ms var(--ks-ease),transform 160ms var(--ks-ease)}
+.lights.dense{gap:0}.lights.dense .light{width:14px}.lights.dense .light::before{width:7px;height:7px}
+.light.decided::before{background:var(--ks-kinpaku);box-shadow:var(--ks-led)}
+.light.current::before{transform:scale(1.35);background:var(--ks-patina);box-shadow:0 0 0 1px oklch(13% 0 0 / 0.12),0 0 4px color-mix(in oklch,var(--ks-patina) 60%,transparent)}
+.light:hover::before{transform:scale(1.25)}
+.light.current:hover::before{transform:scale(1.35)}
+.light:focus-visible{outline-offset:0;border-radius:var(--ks-radius-sm)}
+.tip{position:absolute;top:calc(100% + 6px);left:50%;transform:translate(-50%,-2px);padding:5px 8px;border:1px solid var(--ks-rule);border-radius:var(--ks-radius-sm);background:var(--ks-paper-deep);color:var(--ks-ink);font-size:var(--ks-type-label-size);white-space:nowrap;opacity:0;pointer-events:none;transition:opacity var(--ks-quick) var(--ks-ease),transform var(--ks-quick) var(--ks-ease);z-index:20}
+.tip-state{color:var(--ks-text-muted)}
+.light:hover .tip,.light:focus-visible .tip{opacity:1;transform:translate(-50%,0)}
+.lights-summary{margin-left:14px;padding:4px 2px;border:0;background:none;border-bottom:2px solid transparent;font-size:var(--ks-type-label-size);color:var(--ks-text-muted);transition:color 180ms var(--ks-ease),border-color 180ms var(--ks-ease)}
+.lights-summary:hover{color:var(--ks-ink)}
+.lights-summary.current{color:var(--ks-ink);border-bottom-color:var(--ks-kinpaku)}
+.bar-locator{display:none;justify-self:end;position:relative;width:52px;height:34px;padding:0;border:0;overflow:hidden;background:var(--ks-paper-deep);box-shadow:0 0 0 1px var(--ks-rule)}
+
+.banner{flex-shrink:0;display:flex;align-items:center;gap:14px;padding:12px 28px;border-bottom:1px solid var(--ks-rule)}
+.banner>svg{width:18px;height:18px;color:var(--ks-vermilion)}
+.banner>div{flex:1;min-width:0}
+.banner strong{display:block;color:var(--ks-ink);font-weight:500}
+.banner p{color:var(--ks-text-muted);font-size:var(--ks-type-ui-size)}
+
+.screen{flex:1;min-height:0;display:flex;flex-direction:column;overflow:hidden;position:relative}
+.view-summary .screen{overflow:auto}
+
+/* Arrivals. */
+@keyframes enter-next{from{opacity:0;transform:translateX(28px)}to{opacity:1;transform:none}}
+@keyframes enter-prev{from{opacity:0;transform:translateX(-28px)}to{opacity:1;transform:none}}
+@keyframes enter-fade{from{opacity:0}to{opacity:1}}
+.enter-next{animation:enter-next 240ms var(--stage-ease) both}
+.enter-prev{animation:enter-prev 240ms var(--stage-ease) both}
+.enter-fade{animation:enter-fade 200ms var(--stage-ease) both}
+
+/* Intro. */
+.intro{flex:1;min-height:0;display:grid;grid-template-columns:minmax(320px,440px) minmax(0,1fr);gap:56px;align-items:center;padding:40px 56px}
+.intro-copy{display:flex;flex-direction:column;align-items:flex-start;gap:18px}
+.intro h1{font:300 clamp(2.6rem,4.4vw,3.6rem)/1.02 var(--ks-font-display);font-variation-settings:'wght' 300;color:var(--ks-ink)}
+.lead{font-size:var(--ks-type-lead-size,1.125rem);line-height:1.5;color:var(--ks-text);max-width:34ch}
+.kinds-explained{display:flex;flex-direction:column;gap:12px;margin-top:6px;padding-top:18px;border-top:1px solid var(--ks-rule);width:100%}
+.kinds-explained dt{display:flex;align-items:center;gap:10px;color:var(--ks-ink);font-weight:500}
+.kinds-explained dd{margin-left:24px;color:var(--ks-text-muted);font-size:var(--ks-type-ui-size)}
+.swatch{display:inline-block;width:14px;height:10px}
+.swatch.asset{border:2px solid var(--asset)}.swatch.plan{border:1.5px dashed var(--plan)}
+.intro-copy .ks-button{margin-top:14px}
+.intro-comp{min-height:0;height:100%;display:flex;align-items:center;justify-content:center}
+
+/* The comp with regions (intro, summary, overlay). */
+.map{position:relative;overflow:hidden;background:var(--ks-paper-deep);box-shadow:0 0 0 1px var(--ks-rule)}
+.map .comp{display:block;width:100%;height:100%;user-select:none;pointer-events:none}
+.region{position:absolute;padding:0;min-height:0;border:0;border-radius:0;background:transparent;outline:2px solid transparent;outline-offset:-1px}
+.region.is-asset{outline:2px solid var(--asset);box-shadow:0 0 0 1px oklch(99.5% 0 0 / .7),inset 0 0 0 1px oklch(99.5% 0 0 / .7)}
+.region.is-plan{outline:1.5px dashed var(--plan);box-shadow:0 0 0 1px oklch(99.5% 0 0 / .6),inset 0 0 0 1px oklch(99.5% 0 0 / .6)}
+.region.flagged{outline:2px solid var(--flag);background:oklch(52% 0.16 35 / .1);box-shadow:0 0 0 1px var(--ks-paper-raised),inset 0 0 0 1px var(--ks-paper-raised)}
+.region.code:hover,.region.code:focus-visible,.region.code.selected{outline:1.5px dotted var(--ks-ink);background:oklch(99.5% 0 0 / .15);box-shadow:0 0 0 1px oklch(99.5% 0 0 / .6)}
+.region.code.reclassify{outline:2px solid var(--ks-ink);background:oklch(13% 0 0 / .06)}
+.region.missing{outline:2px dashed var(--missing);background:oklch(52% 0.16 35 / .12);box-shadow:0 0 0 1px oklch(99.5% 0 0 / .7)}
+.region.approved{opacity:.55}
+.region.revise,.region.reclassify{outline-color:var(--ks-ink);outline-style:solid}
+button.region{cursor:pointer}
+button.region:hover{opacity:1;background-color:oklch(99.5% 0 0 / .14);z-index:4}
+.map.has-selection .region.selected{z-index:5;opacity:1;outline:2px solid var(--ks-paper-raised);box-shadow:0 0 0 1.5px var(--ks-ink),0 0 0 100vmax oklch(13% 0 0 / .22)}
+.tag{position:absolute;left:-2px;bottom:calc(100% + 4px);padding:3px 7px;border-radius:var(--ks-radius-sm);background:var(--ks-ink);color:var(--ks-paper-raised);font:500 var(--ks-type-micro-size)/1.25 var(--ks-font);white-space:nowrap;pointer-events:none;opacity:0;transform:translateY(2px);transition:opacity var(--ks-quick) var(--ks-ease),transform var(--ks-quick) var(--ks-ease);z-index:6}
+.region.tag-below .tag{bottom:auto;top:calc(100% + 4px)}
+.region.tag-right .tag{left:auto;right:-2px}
+.region:hover .tag,.region:focus-visible .tag,.region.selected .tag{opacity:1;transform:none}
+.map.marking{cursor:crosshair;touch-action:none}
+.map.marking .region{pointer-events:none;opacity:.35}
+.draw-box{position:absolute;outline:2px dashed var(--missing);background:oklch(52% 0.16 35 / .15);pointer-events:none;z-index:7}
+
+/* Stage: one item. */
+.stage{flex:1;min-height:0;display:flex;flex-direction:column;align-items:center;gap:14px;padding:22px 48px 12px;position:relative}
+.stage-head{flex-shrink:0;display:flex;flex-direction:column;align-items:center;gap:8px;text-align:center;max-width:760px}
+.stage h1{font:300 clamp(2rem,3vw,2.75rem)/1.04 var(--ks-font-display);font-variation-settings:'wght' 300;color:var(--ks-ink)}
+.asked{margin-top:6px;display:flex;flex-direction:column;align-items:center;gap:6px;padding:12px 18px 0;border-top:1px solid var(--ks-rule)}
+.asked p{font-size:var(--ks-type-lead-size,1.125rem);line-height:1.45;color:var(--ks-ink);max-width:58ch}
+.figures{flex:1 1 0;min-height:0;width:100%;display:flex;justify-content:center;align-items:center;gap:28px}
+.figures[data-direction=column]{flex-direction:column;gap:14px}
+.stage.is-single{justify-content:center}
+.figures.single{flex:none;align-items:center}
+.figures.empty{color:var(--ks-text-muted)}
+.fig{display:flex;flex-direction:column;gap:10px;min-width:0}
+.fig figcaption{height:20px;display:flex;align-items:center;justify-content:space-between;gap:12px}
+.frame{position:relative;overflow:hidden;background:var(--ks-paper-deep);box-shadow:0 0 0 1px var(--ks-rule)}
+.pic{position:absolute;inset:0;display:block;overflow:hidden}
+.pic.crop img{position:absolute;max-width:none;height:auto;user-select:none}
+.pic.gen img{display:block;width:100%;height:100%;object-fit:contain;user-select:none}
+.frame .flip{visibility:hidden}
+.frame.flipped .flip{visibility:visible}
+.frame.flipped .gen:not(.before){visibility:hidden}
+.focus-box{position:absolute;outline:2px solid var(--ks-paper-raised);box-shadow:0 0 0 1.5px var(--ks-ink),0 0 0 100vmax oklch(13% 0 0 / .35);pointer-events:none}
+.figures.looking .frame{cursor:none}
+.lens{position:absolute;top:0;left:0;width:156px;height:156px;border-radius:50%;overflow:hidden;pointer-events:none;opacity:0;z-index:3;background:var(--ks-paper-deep);box-shadow:0 0 0 2px var(--ks-paper-raised),0 0 0 3px oklch(13% 0 0 / .35),var(--ks-lift-2);transition:opacity var(--ks-quick) var(--ks-ease)}
+.figures.looking .lens{opacity:1}
+.lens-inner{position:absolute;top:0;left:0;transform-origin:0 0}
+.lens-inner .focus-box{box-shadow:0 0 0 1.5px var(--ks-ink)}
+.backdrop-switch{font-size:var(--ks-type-label-size)}
+.backdrop-switch .ks-switch-track{transform:scale(.8);transform-origin:right center;margin-right:-6px}
+.stage-foot{flex-shrink:0;display:flex;flex-direction:column;align-items:center;gap:6px;text-align:center;max-width:720px;min-height:22px}
+.sentence{font-size:var(--ks-type-ui-lead);color:var(--ks-ink)}
+.sentence.muted{color:var(--ks-text-muted);font-size:var(--ks-type-small-size)}
+.sentence strong{font-weight:600}
+.sentence s{color:var(--ks-text-muted);text-decoration-color:var(--ks-text-muted);margin-right:4px}
+.flag{display:flex;align-items:baseline;gap:8px;text-align:left;font-size:var(--ks-type-ui-size);color:var(--ks-vermilion);max-width:64ch}
+.flag::before{content:"";flex-shrink:0;width:6px;height:6px;border-radius:50%;background:var(--ks-vermilion);transform:translateY(-1px)}
+.undo-line{color:var(--ks-text-muted);animation:toast-in 240ms var(--ks-ease)}.undo-line .text-action{margin-left:6px}.undo-line .text-action .cap{margin-left:6px}.hint{font-size:var(--ks-type-label-size);color:var(--ks-text-faint);transition:opacity 400ms var(--ks-ease)}
+.hint .cap{margin:0 2px;height:18px}
+.hint.gone,.undo-line.gone{opacity:0;pointer-events:none}
+.locator{position:absolute;left:28px;bottom:14px;display:flex;flex-direction:column;align-items:flex-start;gap:6px;padding:0;border:0;background:none;color:var(--ks-text-muted)}
+.locator-map{position:relative;display:block;width:128px;overflow:hidden;box-shadow:0 0 0 1px var(--ks-rule);transition:box-shadow var(--ks-quick) var(--ks-ease)}
+.locator-map img{display:block;width:100%;height:100%}
+.locator-box{position:absolute;outline:1.5px solid var(--ks-paper-raised);box-shadow:0 0 0 1px var(--ks-ink),0 0 0 100vmax oklch(13% 0 0 / .3)}
+.locator:hover .locator-map{box-shadow:0 0 0 1px var(--ks-edge),var(--ks-lift-1)}
+.locator-label{font:400 var(--ks-type-eyebrow-size)/1 var(--ks-mono);letter-spacing:var(--ks-type-eyebrow-track);text-transform:uppercase;display:inline-flex;align-items:center}
+.locator-label .cap{margin:0 0 0 8px;height:18px;min-width:18px}
+.locator:hover{color:var(--ks-ink)}
+
+/* Decision bar. */
+.decide-bar{flex-shrink:0;display:flex;flex-direction:column;align-items:center;gap:10px;padding:16px 28px 22px;border-top:1px solid var(--ks-rule);background:var(--ks-paper)}
+.decisions{display:flex;justify-content:center;gap:12px}
+.decisions .ks-button{min-width:210px}
+.decisions .ks-button-ghost{min-width:0}
+.current-decision{display:inline-flex;align-items:center;gap:8px;font-size:var(--ks-type-ui-size);color:var(--ks-text-muted);max-width:720px}
+.current-decision svg{color:var(--ks-state-ink)}
+.current-decision span{color:var(--ks-ink)}
+.record{font-size:var(--ks-type-ui-lead);color:var(--ks-ink)}
+.decide-bar.form{align-items:stretch;width:100%}
+.decide-bar.form>*{width:100%;max-width:720px;margin:0 auto}
+.form-row{display:flex;align-items:center;gap:14px}
+.form-actions{display:flex;justify-content:flex-end;gap:8px}
+.form-actions.start{justify-content:flex-start}
+
+/* Toast. */
+@keyframes toast-in{from{opacity:0;transform:translateY(8px)}to{opacity:1;transform:none}}
+
+
+
+.view-summary
+
+/* Summary. */
+.summary{width:100%;max-width:1240px;margin:0 auto;padding:36px 48px 0;display:flex;flex-direction:column;gap:36px}
+.summary-head{display:flex;flex-direction:column;gap:10px}
+.summary h1{font:300 clamp(2.4rem,4vw,3.4rem)/1.02 var(--ks-font-display);font-variation-settings:'wght' 300;color:var(--ks-ink)}
+.sheet{display:grid;grid-template-columns:repeat(auto-fill,minmax(200px,1fr));gap:28px 24px}
+.card{display:flex;flex-direction:column;gap:10px;padding:0;border:0;background:none;text-align:left;color:inherit;min-width:0}
+.card-thumb .focus-box{box-shadow:0 0 0 1px var(--ks-ink),0 0 0 100vmax oklch(13% 0 0 / .3);outline-width:1.5px}
+.card-thumb{height:118px;display:flex;align-items:center;justify-content:center;background:var(--ks-paper-deep);box-shadow:0 0 0 1px var(--ks-rule);overflow:hidden;transition:box-shadow var(--ks-quick) var(--ks-ease)}
+.card:hover .card-thumb{box-shadow:0 0 0 1px var(--ks-edge)}
+.card-pic{position:relative;display:block;max-height:100%;overflow:hidden}
+.card-text{display:flex;flex-direction:column;gap:2px;min-width:0}
+.card-name{font-weight:500;color:var(--ks-ink);white-space:nowrap;overflow:hidden;text-overflow:ellipsis}
+.card-state{display:inline-flex;align-items:center;gap:5px;font-size:var(--ks-type-label-size);color:var(--ks-text-muted)}
+.card-state svg{width:13px;height:13px;stroke-width:2}
+.card.approved .card-state{color:var(--ks-state-ink)}
+.card.revise .card-state,.card.reclassify .card-state{color:var(--ks-ink);font-weight:500}
+.card.pending .card-state{color:var(--ks-vermilion)}
+.card-note{font-size:var(--ks-type-label-size);color:var(--ks-text-muted);display:-webkit-box;-webkit-line-clamp:2;-webkit-box-orient:vertical;overflow:hidden}
+.coverage{display:flex;flex-direction:column;gap:18px;padding-top:32px;border-top:1px solid var(--ks-rule)}
+.coverage h2{font:300 clamp(1.8rem,2.6vw,2.3rem)/1.05 var(--ks-font-display);font-variation-settings:'wght' 300;color:var(--ks-ink)}
+.coverage-grid{display:grid;grid-template-columns:minmax(0,1fr) 300px;gap:32px;align-items:start}
+.map-space .map{width:100%}
+.side-panel{display:flex;flex-direction:column;gap:14px;align-items:stretch}
+.side-panel.quiet p{color:var(--ks-text-muted);font-size:var(--ks-type-ui-size)}
+.side-panel.quiet .ks-button{align-self:flex-start}
+.side-panel h3{font-size:var(--ks-type-subhead-size,1.25rem);font-weight:500;color:var(--ks-ink)}
+.side-panel .eyebrow.missing{color:var(--ks-vermilion)}
+.panel-crop{position:relative;width:100%;max-height:180px;overflow:hidden;box-shadow:0 0 0 1px var(--ks-rule);background:var(--ks-paper-deep)}
+.panel-form{display:flex;flex-direction:column;gap:12px}
+.marking-hint{color:var(--ks-ink)!important;font-weight:500}
+.missing-list{list-style:none;margin:0;padding:0;display:flex;flex-direction:column;gap:6px;font-size:var(--ks-type-ui-size)}
+.summary{padding-bottom:40px}
+.send-row{position:sticky;bottom:0;z-index:10;margin-top:auto;background:var(--ks-paper-raised);border-top:1px solid var(--ks-rule)}
+.send-inner{max-width:1240px;margin:0 auto;display:flex;align-items:center;justify-content:flex-end;gap:20px;padding:14px 48px 18px}
+.send-row p{font-size:var(--ks-type-ui-size);color:var(--ks-text-muted);text-align:right}
+
+/* The comp overlay (C). */
+@keyframes overlay-in{from{opacity:0;transform:scale(.985)}to{opacity:1;transform:none}}
+.overlay{position:absolute;inset:0;z-index:40;display:flex;flex-direction:column;background:var(--ks-paper);animation:overlay-in 200ms var(--ks-ease) both}
+.overlay-head{flex-shrink:0;height:56px;display:flex;align-items:center;justify-content:space-between;padding:0 16px 0 28px;border-bottom:1px solid var(--ks-rule)}
+.overlay-body{flex:1;min-height:0;display:flex;align-items:center;justify-content:center;padding:28px}
+
+@media (max-width:1100px){.intro{grid-template-columns:1fr;gap:28px;overflow:auto;align-content:start}.intro-comp{height:auto}.intro-comp .map{width:100%!important;height:auto!important}.coverage-grid{grid-template-columns:1fr}}
+@media (max-width:760px){
+ :host{height:auto;overflow:visible}
+ .rv{height:auto;min-height:100dvh}
+ .bar{grid-template-columns:1fr auto;grid-template-rows:auto auto;height:auto;gap:8px 12px;padding:10px 16px}
+ .bar-title{grid-column:1}
+ .bar-locator{display:block;grid-column:2;grid-row:1}
+ .lights{grid-column:1/-1;flex-wrap:wrap}
+ .screen{overflow:visible}
+ .intro{padding:24px 16px}
+ .stage{padding:18px 16px 8px}
+ .figures{flex:none}
+ .locator{display:none}
+ .decide-bar{position:sticky;bottom:0;z-index:10;padding:12px 16px calc(12px + env(safe-area-inset-bottom))}
+ .decisions{flex-wrap:wrap;width:100%}
+ .decisions .ks-button{flex:1 1 40%;min-width:0}
+ .cap{display:none}
+
+ .summary{padding:24px 16px 0}
+ .send-inner{padding:12px 16px;flex-wrap:wrap}
+ .send-row p{text-align:left}
+}
+@media (prefers-reduced-motion:reduce){*,*::before{animation:none!important;transition:none!important}}
+`;var He=new Map;function Ei(e){let n=e.querySelector('.ks-instrument-key:is(.is-active, [aria-selected="true"], [aria-pressed="true"])');if(!n){if(e.classList.contains("has-thumb"))e.classList.remove("has-thumb");return}let o=e.getBoundingClientRect(),a=n.getBoundingClientRect();if(!o.width)return;let t=getComputedStyle(e),p=o.width/parseFloat(t.width)||1,y=parseFloat(t.borderLeftWidth)||0,g=Math.round(((a.left-o.left)/p-y+e.scrollLeft)*100)/100,b=Math.round(a.width/p*100)/100,z=e.querySelector(":scope > .ks-thumb"),v=e.dataset.ksStrip;if(!z){z=document.createElement("span"),z.className="ks-thumb",z.setAttribute("aria-hidden","true"),e.appendChild(z);let M=v?He.get(v):void 0;if(M&&(M.x!==g||M.w!==b))z.style.transition="none",z.style.width=`${M.w}px`,z.style.transform=`translateX(${M.x}px)`,z.offsetWidth,z.style.transition=""}if(v)He.set(v,{x:g,w:b});if(z.style.width!==`${b}px`)z.style.width=`${b}px`;let w=`translateX(${g}px)`;if(z.style.transform!==w)z.style.transform=w;if(!e.classList.contains("has-thumb"))e.classList.add("has-thumb")}function rr(e,n,o){if(e.dataset.thumb)return;e.dataset.thumb="1",Ei(e);let a=new MutationObserver((M)=>{if(M.some((u)=>u.target!==e&&!u.target.classList?.contains("ks-thumb")))Ei(e)});a.observe(e,{subtree:!0,attributes:!0,attributeFilter:["class","aria-selected","aria-pressed"],childList:!0});let t=new ResizeObserver(()=>Ei(e));t.observe(e);let p=null,y=!1,g=0,b=null,z=(M,u)=>n.elementFromPoint(M,u)?.closest(".ks-instrument-key")??null;e.addEventListener("pointerdown",(M)=>{if(!["mouse","pen"].includes(M.pointerType)||!M.isPrimary||M.button!==0||p!==null)return;p=M.pointerId,y=!1,g=M.clientX,b=z(M.clientX,M.clientY)}),e.addEventListener("pointermove",(M)=>{if(M.pointerId!==p)return;if(!y&&Math.abs(M.clientX-g)<6)return;y=!0;let u=z(M.clientX,M.clientY);if(u&&u!==b&&e.contains(u))b=u,u.click()});let v=()=>{p=null,y=!1,b=null},w=(M)=>{if(M.pointerId===p)v()};window.addEventListener("pointerup",w),window.addEventListener("pointercancel",w),window.addEventListener("blur",v),o.push(()=>{a.disconnect(),t.disconnect(),window.removeEventListener("pointerup",w),window.removeEventListener("pointercancel",w),window.removeEventListener("blur",v)})}function Yi(e){let n=[];return e.querySelectorAll(".ks-instrument-strip").forEach((o)=>rr(o,e,n)),document.fonts?.ready.then(()=>e.querySelectorAll(".ks-instrument-strip").forEach(Ei)),()=>n.forEach((o)=>o())}var Y=(e)=>e.replace(/[&<>"']/g,(n)=>({"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#39;"})[n]),Xi=(e)=>`${e*100}%`,Hn=(e)=>{let n=new URL(e,location.href);if(!["http:","https:"].includes(n.protocol))throw Error("Unsupported preview URL");return Y(n.href)},Sn=(e)=>`left:${Xi(e.x)};top:${Xi(e.y)};width:${Xi(e.w)};height:${Xi(e.h)}`,We=(e)=>`<svg viewBox="0 0 16 16" aria-hidden="true" focusable="false">${e}</svg>`,Ji={check:We('<path d="m3 8.5 3 3 7-7"/>'),alert:We('<path d="M8 2 1.5 13.5h13L8 2Z"/><path d="M8 6.5v3.2M8 11.6v.1"/>')},jn=(e)=>`<kbd class="cap">${e}</kbd>`,An={plate:"illustration",image:"photo",texture:"texture"};function ar(e){let n=e.match(/^review is stale:\s*(.+?)\s+changed\b/i);if(n)return`${n[1]} changed after this round was prepared.`;let o=e.replace(/;?\s*prepare a new round\.?\s*$/i,"").trim();return o?`${o[0].toUpperCase()}${o.slice(1)}${/[.!?]$/.test(o)?"":"."}`:""}var Ie={get(e){try{return localStorage.getItem(e)}catch{return null}},set(e,n){try{localStorage.setItem(e,n)}catch{}}};function Oe(e,n,o){let a=e.shadowRoot??e.attachShadow({mode:"open"}),t={...Ge(n),...structuredClone(o.initialDraft??{})};t.reclassify??=[];let p=Fi(n),y=Ti(n),g=o.history??null,b=new URLSearchParams(location.search),z=!!o.completed,v=z?"summary":["intro","stage","summary"].includes(b.get("view")??"")?b.get("view"):"intro",w=(b.get("item")&&p.some((r)=>r.id===b.get("item"))?b.get("item"):void 0)??p.find((r)=>yn(r,t)==="pending")?.id??p[0]?.id,M=null,u=null,f=null,Q=!1,Z=!1,dn=!1,xn={},U=!1,Qn=!1,Yn="",W=null,en=()=>W?`<p class="hint undo-line" role="status">${Y(W.label)} <button type="button" class="text-action" id="undo">Undo${jn("⌘Z")}</button></p>`:"",Tn=Ie.get("impeccable.review.flipHint")==="1",I=null,Wn=null,ln=new Map,Xn=new Map,C=null,qn=()=>matchMedia("(prefers-reduced-motion: reduce)").matches,rn=(r)=>n.components.find((s)=>s.id===r),Ln=(r)=>y.find((s)=>s.id===r),L=()=>z||U||!!o.status,hn=(r)=>r.w*n.comp.width/(r.h*n.comp.height),an=new Image;an.onload=()=>{try{let r=Math.min(1,480/an.naturalWidth),s=document.createElement("canvas");s.width=Math.max(1,Math.round(an.naturalWidth*r)),s.height=Math.max(1,Math.round(an.naturalHeight*r));let l=s.getContext("2d",{willReadFrequently:!0});if(l.drawImage(an,0,0,s.width,s.height),C={data:l.getImageData(0,0,s.width,s.height).data,width:s.width,height:s.height},v==="stage")A()}catch{}},an.src=new URL(n.comp.url,location.href).href;function ni(r){if(!Xn.has(r.id)&&C)Xn.set(r.id,Ze(Qe(C.data,C.width,C.height,r.box))??"");return Xn.get(r.id)||n.comp.background||"var(--ks-paper-deep)"}function Zn(r,s){if(r.material?.alpha==="transparent")return!0;if(r.material?.alpha==="opaque")return!1;if(ln.has(s))return ln.get(s);if(ln.set(s,!1),!/\.(png|webp)(\?|$)/i.test(s))return!1;let l=new Image;return l.onload=()=>{try{let h=Math.min(1,160/Math.max(l.naturalWidth,l.naturalHeight)),m=document.createElement("canvas");m.width=Math.max(1,Math.round(l.naturalWidth*h)),m.height=Math.max(1,Math.round(l.naturalHeight*h));let k=m.getContext("2d",{willReadFrequently:!0});k.drawImage(l,0,0,m.width,m.height);let x=k.getImageData(0,0,m.width,m.height).data;for(let c=3;c<x.length;c+=4)if(x[c]<250){if(ln.set(s,!0),v==="stage")A();break}}catch{}},l.src=new URL(s,location.href).href,!1}function on(r,s,l="fade"){if(s)w=s;if(M=qn()?null:l,v=r,u=null,dn=!1,Z=!1,r!=="summary")f=null,Q=!1;A();let h=r==="intro"?"start":r==="stage"?"decide-yes":"send";a.getElementById(h)?.focus({preventScroll:!0})}function ii(r){if(v!=="stage"||!p.length)return;let s=p.findIndex((l)=>l.id===w)+r;if(s>=p.length)return on("summary",void 0,"next");if(s<0)return;on("stage",p[s].id,r>0?"next":"prev")}function In(r,s){if(W)clearTimeout(W.timer);W={label:r,before:s,view:v,current:w,timer:window.setTimeout(()=>{W=null,a.querySelector(".undo-line")?.classList.add("gone")},6000)}}function Un(r,s){let l=t;t=r,u=null,Yn="",In(s,l)}function Jn(){let r=p.findIndex((l)=>l.id===w),s=[...p.slice(r+1),...p.slice(0,r+1)].find((l)=>yn(l,t)==="pending");if(s)on("stage",s.id,"next");else on("summary",void 0,"next")}function li(){let r=rn(w);if(v!=="stage"||!r||L()||u)return;Un(Si(t,r,"approve"),`${r.role==="asset"?"Approved":"Kept in code"}: ${r.name}.`),Jn()}function $n(r,s,l=!1){if(L())return;let h=s?Ln(s):void 0,m=h?void 0:rn(w),k=m??h;if(!k||m&&r==="reclassify"&&m.role!=="plan")return;let x=m?zn(m,t):void 0,c=h?qi(t,h.id):void 0,V=x?.action===r&&!!x.split===l;u={type:r,split:l,id:k.id,region:!!h,text:V?x.feedback:l?Ae:c?.feedback??"",kind:x?.kind??c?.kind??Ci({name:k.name,note:k.note??"",flags:m?.flags})},A(),a.getElementById("form-text")?.focus()}function On(){if(!u||L())return;let r=u;if(r.region){let l=Ln(r.id);Un(ne(t,l.id,{kind:r.kind,feedback:r.text}),`${l.name} will become ${An[r.kind]}.`),A();return}let s=rn(r.id);if(r.type==="revise"&&s.role==="plan"&&!r.text.trim()){a.getElementById("form-text")?.focus();return}Un(Si(t,s,r.type,{feedback:r.text,kind:r.kind,split:r.split}),r.split?`Split into layers: ${s.name}.`:r.type==="revise"?`Noted: ${s.name}.`:`${s.name} will become ${An[r.kind]}.`),Jn()}function di(){if(!W||L())return;let r=W;clearTimeout(r.timer),W=null,t=r.before,on(r.view,r.current,"prev")}async function ei(){let r=Pn(n,t);if(U||z||u||!r.canSubmit||o.status)return;U=!0,Yn="",A();try{await o.onSubmit($e(n,t)),z=!0,Qn=!0,Q=!1,W=null}catch(s){Yn=s instanceof Error?s.message:"The review could not be saved."}finally{U=!1,A()}}function G(r){let s=`missing-${crypto.randomUUID()}`;t={...t,inventoryConfirmed:!1,missing:[...t.missing,{id:s,name:"",feedback:"",box:r}]},Q=!1,f={type:"missing",id:s},A(),a.getElementById("missing-name")?.focus()}let X=(r)=>{let s=yn(r,t);if(s==="approved")return r.role==="asset"?"Looks good":"Code is fine";if(s==="revise")return ae(zn(r,t))?"Split into layers":"Needs work";if(s==="reclassify")return`Becomes ${An[zn(r,t).kind]}`;return z?"Not decided":"To decide"},J=(r,s="")=>`<span class="pic crop ${s}"><img src="${Hn(n.comp.url)}" alt="" draggable="false" style="width:${100/r.w}%;left:${-100*r.x/r.w}%;top:${-100*r.y/r.h}%"></span>`,_=(r,s,l="gen")=>{let h=Zn(r,s),m=xn[r.id]??"comp",k=!h?"":m==="light"?"var(--ks-paper-raised)":m==="dark"?"var(--ks-instrument)":ni(r);return`<span class="pic ${l}" style="${k?`background:${Y(k)}`:""}"><img src="${Hn(s)}" alt="" draggable="false"></span>`};function H(r){return[...r.code?y.map((l)=>({kind:"region",id:l.id,name:l.name,box:l.box,cls:`code ${qi(t,l.id)?"reclassify":""}`})):[],...n.components.map((l)=>({kind:"item",id:l.id,name:l.name,box:l.box,cls:`is-${l.role} ${Ri(l)||re(l)?"flagged":""} ${yn(l,t)}`})),...t.missing.map((l)=>({kind:"missing",id:l.id,name:l.name||"Missing",box:l.box,cls:"missing"}))].sort((l,h)=>h.box.w*h.box.h-l.box.w*l.box.h).map((l)=>{let h=f?.id===l.id||Z&&v==="stage"&&l.id===w,m=`<span class="tag">${Y(l.name)}</span>`;return r.interactive?`<button type="button" class="region ${l.cls} ${h?"selected":""} ${l.box.y<0.06?"tag-below":""} ${l.box.x>0.7?"tag-right":""}" style="${Sn(l.box)}" data-${l.kind}="${Y(l.id)}" aria-label="${Y(l.name)}">${m}</button>`:`<span class="region ${l.cls}" style="${Sn(l.box)}"></span>`}).join("")}function R(){let r=_e(n,t,v==="stage"?w:void 0),s=r.filter((l)=>l.state!=="pending").length;return`<header class="bar">
+ <div class="bar-title"><span class="bar-name">${Y(n.title)}</span><span class="bar-round">Round ${n.round}</span></div>
+ ${p.length?`<nav class="lights ${r.length>20?"dense":""}" aria-label="Progress, ${s} of ${r.length} decided">${r.map((l,h)=>`<button type="button" class="light ${l.state==="pending"?"":"decided"} ${l.current?"current":""}" data-go="${Y(l.id)}" aria-label="${Y(`${h+1}. ${l.name}: ${X(rn(l.id))}`)}" ${l.current?'aria-current="step"':""}><span class="tip">${Y(l.name)}${l.state==="pending"?"":`<span class="tip-state"> · ${Y(X(rn(l.id)))}</span>`}</span></button>`).join("")}<button type="button" class="lights-summary ${v==="summary"?"current":""}" id="to-summary">Summary</button></nav>`:""}
+ ${v==="stage"?`<button type="button" class="bar-locator" id="open-map-bar" aria-label="Open the comp">${J({x:0,y:0,w:1,h:1})}</button>`:""}
+ </header>`}function Gn(){if(o.status)return`<div class="banner stale" role="alert">${Ji.alert}<div><strong>This review is out of date.</strong><p>${Y(ar(o.status))} Ask the agent to prepare a new round, then reload this page.</p></div><button id="reload" class="ks-button ks-button-secondary">Reload</button></div>`;if(Yn)return`<div class="banner error" role="alert">${Ji.alert}<div><strong>Your decisions were not sent.</strong><p>${Y(Yn)}</p></div><button id="retry" class="ks-button ks-button-secondary">Try again</button></div>`;return""}function P(){let r=!!g&&n.round>1;return`<div class="intro ${M?`enter-${M}`:""}">
+ <div class="intro-copy">
+ <p class="eyebrow">${r?`Round ${n.round}`:"Before any page code"}</p>
+ <h1>${r?"Check what changed.":"Review the plan and assets."}</h1>
+ <p class="lead">${Y(Ue(n,t,g))}</p>
+ <dl class="kinds-explained">
+ <div><dt><i class="swatch asset"></i>A generated image</dt><dd>Does it match the comp?</dd></div>
+ <div><dt><i class="swatch plan"></i>A region drawn in code</dt><dd>Can code do it justice, or should it be an image?</dd></div>
+ </dl>
+ <button type="button" class="ks-button ks-button-primary" id="start">Start${jn("↵")}${Bn}</button>
+ </div>
+ <figure class="intro-comp"><div class="map" style="aspect-ratio:${n.comp.width}/${n.comp.height}"><img class="comp" src="${Hn(n.comp.url)}" alt="The approved comp" draggable="false">${H({code:!1,interactive:!1})}</div></figure>
+ </div>`}function ri(r){let s=Vi(r.id,g),l=hn(r.box),h=`${r.box.w*n.comp.width}x${r.box.h*n.comp.height}`;if(r.role==="asset"&&r.preview.url){let m=r.preview.url,k=Zn(r,m),x=xn[r.id]??"comp",c=k?`<button type="button" class="ks-switch backdrop-switch" id="backdrop" aria-pressed="${x!=="comp"}" title="Backdrop behind the transparent image"><span class="ks-switch-track" aria-hidden="true"><span class="ks-switch-knob"></span></span><span class="ks-switch-label">${x==="comp"?"On comp colour":x==="light"?"On light":"On dark"}</span></button>`:"",V=`<figure class="fig" data-role="generated"><figcaption><span class="eyebrow">${dn?"In the comp":s?.beforeUrl?"After":"Generated"}</span>${c}</figcaption><div class="frame ${dn?"flipped":""}">${_(r,m)}${J(r.box,"flip")}</div></figure>`,O=`<figure class="fig"><figcaption><span class="eyebrow">In the comp</span></figcaption><div class="frame">${J(r.box)}</div></figure>`;if(s?.beforeUrl){let N=`<figure class="fig"><figcaption><span class="eyebrow">Before · round ${s.round}</span></figcaption><div class="frame">${_(r,s.beforeUrl,"gen before")}</div></figure>`;return`<div class="figures" data-ratios="${l},${l},${l}" data-natural="${h}">${N}${V}${O}</div>`}return`<div class="figures" data-ratios="${l},${l}" data-natural="${h}">${O}${V}</div>`}if(r.role==="asset")return'<div class="figures empty"><p>This image has no generated file.</p></div>';return`<div class="figures single" data-box="${Y(JSON.stringify(r.box))}"><figure class="fig"><figcaption><span class="eyebrow">In the comp</span></figcaption><div class="frame">${J(r.box)}<span class="focus-box"></span></div></figure></div>`}function $i(r){if(z)return`<div class="decide-bar"><p class="record">${Y(X(r))}${zn(r,t)?.feedback?`: “${Y(zn(r,t).feedback)}”`:"."}</p></div>`;if(u&&!u.region){let h=u.type==="reclassify",m=!h&&r.role==="plan",k=!!u.split;return`<form class="decide-bar form" id="decision-form">
+ ${h?`<div class="form-row"><span class="eyebrow" id="kinds-label">Make it</span><div class="ks-instrument-strip is-paper" data-ks-strip="kind" role="group" aria-labelledby="kinds-label">${Di.map((x)=>`<button type="button" class="ks-instrument-key" data-kind="${x.kind}" aria-pressed="${u.kind===x.kind}">${x.label}</button>`).join("")}</div></div>`:""}
+ <label class="field"><span class="eyebrow">${h?"Anything the image should keep? Optional":k?"How should it come apart? Edit or keep":m?"What should change?":"What needs to change? Optional"}</span><textarea id="form-text" rows="2" placeholder="${h?"For example: keep the brushed direction horizontal.":m?"For example: extend the hero photo under the nav.":"For example: the figure should face the sea."}">${Y(u.text)}</textarea></label>
+ <div class="form-actions"><button type="button" id="form-cancel" class="ks-button ks-button-ghost">Cancel${jn("Esc")}</button><button type="submit" class="ks-button ks-button-primary">${h?"Make it an image":k?"Split into layers":"Save note"}${jn("⌘↵")}</button></div>
+ </form>`}let s=zn(r,t),l=r.role==="asset";return`<div class="decide-bar">
+ ${s?`<p class="current-decision">${s.action==="approve"?Ji.check:""}<span>${Y(X(r))}${s.feedback?`: “${Y(s.feedback)}”`:"."}</span><button type="button" class="text-action" id="decision-clear">Clear</button></p>`:""}
+ <div class="decisions">
+ <button type="button" id="decide-yes" class="ks-button ks-button-primary">${l?"Looks good":"Code is fine"}${jn("A")}</button>
+ <button type="button" id="decide-no" class="ks-button ks-button-secondary">${l?"Needs work":"Make it an image"}${jn("N")}</button>
+ ${l?`<button type="button" id="decide-split" class="ks-button ${re(r)?"ks-button-secondary":"ks-button-ghost"}">Split into layers${jn("S")}</button>`:`<button type="button" id="decide-other" class="ks-button ks-button-ghost">Something else…${jn("F")}</button>`}
+ </div>
+ </div>`}function Gi(){let r=rn(w);if(!r)return'<div class="stage"><p>Nothing to review.</p></div>';let s=p.findIndex((x)=>x.id===r.id)+1,l=Vi(r.id,g),h=r.role==="plan"?[...(r.flags??[]).map(Pi),...r.codeDrawn?["The plan draws this artwork in code."]:[]]:ee(r).map(Pi),m=(r.note??"").trim(),k=r.role==="plan"?`<p class="sentence"><strong>Will be drawn in code:</strong> ${Y(m||Xe(r).toLowerCase())}</p>`:l?.wasCode?`<p class="sentence"><s>Was going to be drawn in code: ${Y(l.wasNote)}</s> Now a generated ${Y(An[r.kind]??r.kind)}.</p>`:m?`<p class="sentence muted">${Y(m)}</p>`:"";return`<div class="stage ${r.role==="plan"?"is-single":""} ${M?`enter-${M}`:""}">
+ <div class="stage-head">
+ <p class="eyebrow">${r.role==="asset"?`Generated ${Y(An[r.kind]??r.kind)}`:`Drawn in code · ${Y(r.kind)}`} · ${s} of ${p.length}</p>
+ <h1>${Y(r.name)}</h1>
+ ${l?.splitFrom?`<blockquote class="asked"><span class="eyebrow">A layer of ${Y(l.splitFrom)} · you asked to split it in round ${l.round}</span>${l.words?`<p>“${Y(l.words)}”</p>`:""}</blockquote>`:l?.words?`<blockquote class="asked"><span class="eyebrow">You asked in round ${l.round}</span><p>“${Y(l.words)}”</p></blockquote>`:""}
+ </div>
+ ${ri(r)}
+ <div class="stage-foot">
+ ${k}
+ ${h.map((x)=>`<p class="flag">${Y(x)}</p>`).join("")}
+ ${W?en():r.role==="asset"&&!Tn&&!z?`<p class="hint">Hold ${jn("Space")} to flip to the comp. Hover to magnify both.</p>`:""}
+ </div>
+ <button type="button" class="locator" id="open-map" aria-label="Open the comp"><span class="locator-map" style="aspect-ratio:${n.comp.width}/${n.comp.height}"><img src="${Hn(n.comp.url)}" alt="" draggable="false"><span class="locator-box" style="${Sn(r.box)}"></span></span><span class="locator-label">Comp ${jn("C")}</span></button>
+ </div>
+ ${$i(r)}`}function Qi(){if(f?.type==="missing"){let r=t.missing.find((s)=>s.id===f.id);if(!r)return"";return`<div class="side-panel"><p class="eyebrow missing">Missing from the review</p>
+ <label class="field"><span class="eyebrow">Name</span><input id="missing-name" value="${Y(r.name)}" placeholder="For example: harbour boat" ${L()?"disabled":""}></label>
+ <label class="field"><span class="eyebrow">What is missing? Optional</span><textarea id="missing-feedback" rows="2" ${L()?"disabled":""}>${Y(r.feedback)}</textarea></label>
+ <div class="form-actions start"><button type="button" id="panel-done" class="ks-button ks-button-secondary">Done</button>${L()?"":'<button type="button" id="missing-remove" class="ks-button ks-button-ghost">Remove</button>'}</div></div>`}if(f?.type==="region"){let r=Ln(f.id);if(!r)return"";let s=qi(t,r.id),l=u?.region&&u.id===r.id;return`<div class="side-panel"><p class="eyebrow">Set in code · ${Y(r.kind)}</p><h3>${Y(r.name)}</h3>
+ <div class="panel-crop" style="aspect-ratio:${Math.max(0.5,Math.min(6,hn(r.box)))}">${J(r.box)}</div>
+ ${l?`<form id="decision-form" class="panel-form"><div class="ks-instrument-strip is-paper" data-ks-strip="region-kind" role="group" aria-label="Make it">${Di.map((h)=>`<button type="button" class="ks-instrument-key" data-kind="${h.kind}" aria-pressed="${u.kind===h.kind}">${An[h.kind][0].toUpperCase()+An[h.kind].slice(1)}</button>`).join("")}</div><textarea id="form-text" rows="2" placeholder="Anything the image should keep? Optional">${Y(u.text)}</textarea><div class="form-actions start"><button type="submit" class="ks-button ks-button-primary">Make it an image</button><button type="button" id="form-cancel" class="ks-button ks-button-ghost">Cancel</button></div></form>`:s?`<p class="current-decision"><span>Becomes ${Y(An[s.kind])}${s.feedback?`: “${Y(s.feedback)}”`:"."}</span>${L()?"":'<button type="button" class="text-action" id="region-keep">Keep in code</button>'}</p>`:`<p class="muted">Checked in the first-viewport review, once the page is built.</p><div class="form-actions start">${L()?"":'<button type="button" class="ks-button ks-button-secondary" id="region-image">Make it an image</button>'}<button type="button" id="panel-done" class="ks-button ks-button-ghost">Close</button></div>`}
+ </div>`}return`<div class="side-panel quiet"><p>Every outlined region above was on your list. Hover the comp to see what is set in code; click a region to make it an image.</p>${L()?"":`<button type="button" class="ks-button ks-button-secondary" id="mark" aria-pressed="${Q}">${Q?"Cancel marking":"Mark missing"}</button>`}${Q?'<p class="marking-hint">Drag on the comp around what is missing.</p>':""}${t.missing.length?`<ul class="missing-list">${t.missing.map((r)=>`<li><button type="button" class="text-action" data-missing="${Y(r.id)}">${Y(r.name||"Unnamed missing piece")}</button></li>`).join("")}</ul>`:""}</div>`}function xi(){let r=Pn(n,t),s=o.status?"This round can no longer be sent.":r.pending&&!r.hasChanges?`${r.pending} still to decide.`:r.mode==="approve"?"Approval confirms nothing is missing from the comp.":`${r.pending?`${r.pending} undecided stay open. `:""}The agent applies your notes and opens a new round.`,l=(h)=>{let m=zn(h,t),k=yn(h,t),x;if(h.role==="asset"&&h.preview.url){let c=hn(h.box);x=`<span class="card-pic" style="aspect-ratio:${c};width:min(100%, ${Math.round(118*c)}px)">${_(h,h.preview.url)}</span>`}else{let c=ie(h.box,n.comp.width,n.comp.height,220,118),V=c.view;x=`<span class="card-pic" style="width:${Math.floor(c.width)}px;height:${Math.floor(c.height)}px"><span class="pic crop"><img src="${Hn(n.comp.url)}" alt="" draggable="false" style="width:${100/V.w}%;left:${-100*V.x/V.w}%;top:${-100*V.y/V.h}%"></span><span class="focus-box" style="${Sn({x:(h.box.x-V.x)/V.w,y:(h.box.y-V.y)/V.h,w:h.box.w/V.w,h:h.box.h/V.h})}"></span></span>`}return`<button type="button" class="card ${k}" data-go="${Y(h.id)}"><span class="card-thumb">${x}</span><span class="card-text"><span class="card-name">${Y(h.name)}</span><span class="card-state">${k==="approved"?Ji.check:""}${Y(X(h))}</span>${m?.feedback?`<span class="card-note">“${Y(m.feedback)}”</span>`:""}</span></button>`};return`<div class="summary ${M?`enter-${M}`:""}">
+ <div class="summary-head">
+ <p class="eyebrow">${z?`Round ${n.round} · sent`:"Summary"}</p>
+ <h1>${z?r.hasChanges?"Notes sent.":"Plan and assets approved.":r.pending?"Almost there.":"Your decisions."}</h1>
+ ${z?`<p class="lead">${r.hasChanges?"The agent applies them and opens a new round for anything that changed.":"The agent continues to the first viewport."}${Qn?"":" This round is read-only."}</p>`:""}
+ </div>
+ <div class="sheet">${p.map(l).join("")}</div>
+ <section class="coverage" aria-label="Coverage">
+ <h2>Anything on the comp we didn't cover?</h2>
+ <div class="coverage-grid">
+ <div class="map-space"><div class="map ${Q?"marking":""} ${f?"has-selection":""}" id="summary-map" style="aspect-ratio:${n.comp.width}/${n.comp.height}"><img class="comp" src="${Hn(n.comp.url)}" alt="The approved comp" draggable="false">${H({code:!0,interactive:!0})}<div class="draw-box" hidden></div></div></div>
+ ${Qi()}
+ </div>
+ </section>
+ </div>
+ ${z?"":`<div class="send-row"><div class="send-inner">${W?en():`<p>${Y(s)}</p>`}<button type="button" class="ks-button ks-button-primary" id="send" ${!r.canSubmit||!!u||U||!!o.status?"disabled":""}>${U?"Sending…":Y(Ke(n,t))}${U?"":Bn}</button></div></div>`}`}function hi(){if(!Z)return"";return`<div class="overlay" role="dialog" aria-modal="true" aria-label="The comp"><div class="overlay-head"><span class="eyebrow">The comp · click a region to go to it</span><button type="button" class="ks-button ks-button-ghost" id="close-map">Close${jn("Esc")}</button></div>
+ <div class="overlay-body"><div class="map has-selection" id="overlay-map" style="aspect-ratio:${n.comp.width}/${n.comp.height}"><img class="comp" src="${Hn(n.comp.url)}" alt="The approved comp" draggable="false">${H({code:!0,interactive:!0})}</div></div></div>`}function A(){I?.disconnect(),Wn?.();let s=a.activeElement?.id,l=v==="summary"?a.querySelector(".view-summary .screen")?.scrollTop??0:0;a.innerHTML=`<style>${Be}</style><section class="rv view-${v} ${z?"is-submitted":""}" aria-label="Plan and asset review">
+ ${R()}${Gn()}
+ <main class="screen">${v==="intro"?P():v==="stage"?Gi():xi()}</main>
+ ${hi()}
+ </section>`,M=null;let h=a.querySelector(".screen");if(h&&l)h.scrollTop=l;if(s)a.getElementById(s)?.focus({preventScroll:!0});if(kn(),ki(),I=new ResizeObserver(ki),I.observe(a.querySelector(".screen")),Wn=Yi(a),!z)o.onDraftChange?.(structuredClone(t))}function ki(){let r=matchMedia("(max-width: 760px)").matches,s=a.querySelector(".figures[data-ratios]");if(s&&s.clientWidth){let h=s.dataset.ratios.split(",").map(Number),[m,k]=(s.dataset.natural??"0x0").split("x").map(Number),x=r?{direction:"column",sizes:h.map((c)=>({w:Math.min(s.clientWidth,360*c),h:Math.min(s.clientWidth,360*c)/c}))}:Ne(h,s.clientWidth,s.clientHeight,28,30,4,{w:m,h:k});s.dataset.direction=x.direction,s.querySelectorAll(":scope > .fig > .frame").forEach((c,V)=>{c.style.width=`${Math.floor(x.sizes[V].w)}px`,c.style.height=`${Math.floor(x.sizes[V].h)}px`}),F(s)}let l=a.querySelector(".figures.single");if(l?.clientWidth){let h=JSON.parse(l.dataset.box),m=l.closest(".stage"),k=m.clientHeight-36-28-(m.querySelector(".stage-head")?.offsetHeight??0)-(m.querySelector(".stage-foot")?.offsetHeight??0)-30-80,x=ie(h,n.comp.width,n.comp.height,Math.min(l.clientWidth,1120),r?320:Math.max(80,k)),c=l.querySelector(".frame"),V=c.querySelector("img"),O=c.querySelector(".focus-box"),N=x.view;c.style.width=`${Math.floor(x.width)}px`,c.style.height=`${Math.floor(x.height)}px`,V.style.cssText=`width:${100/N.w}%;left:${-100*N.x/N.w}%;top:${-100*N.y/N.h}%`,O.style.cssText=Sn({x:(h.x-N.x)/N.w,y:(h.y-N.y)/N.h,w:h.w/N.w,h:h.h/N.h}),F(l)}for(let h of a.querySelectorAll(".overlay-body .map, .intro-comp .map")){let m=h.parentElement,k=getComputedStyle(m),x=m.clientWidth-parseFloat(k.paddingLeft)-parseFloat(k.paddingRight),c=m.clientHeight-parseFloat(k.paddingTop)-parseFloat(k.paddingBottom);if(!x||!c)continue;let V=Math.min(x/n.comp.width,c/n.comp.height);h.style.width=`${n.comp.width*V}px`,h.style.height=`${n.comp.height*V}px`}}let $=78,D=3;function F(r){r.querySelectorAll(".frame").forEach((s)=>{s.querySelector(".lens")?.remove();let l=document.createElement("span");l.className="lens",l.setAttribute("aria-hidden","true");let h=document.createElement("span");h.className="lens-inner",h.style.width=`${s.clientWidth}px`,h.style.height=`${s.clientHeight}px`,s.querySelectorAll(":scope > .pic, :scope > .focus-box").forEach((m)=>h.append(m.cloneNode(!0))),l.append(h),s.append(l)})}function tn(r,s){a.querySelectorAll(".figures .frame").forEach((l)=>{let h=l.querySelector(".lens"),m=h?.querySelector(".lens-inner");if(!h||!m)return;let{clientWidth:k,clientHeight:x}=l;h.style.transform=`translate(${r*k-$}px, ${s*x-$}px)`;let c=Le(r,s,k,x,$,D);m.style.transform=`translate(${c.x}px, ${c.y}px) scale(${D})`})}function kn(){let r=(k,x)=>a.getElementById(k)?.addEventListener("click",x);r("start",()=>{let k=p.find((x)=>yn(x,t)==="pending")??p[0];if(k)on("stage",k.id,"next");else on("summary")}),a.querySelectorAll("[data-go]").forEach((k)=>k.addEventListener("click",()=>{let x=k.dataset.go,c=p.findIndex((V)=>V.id===w);on("stage",x,v!=="stage"?"fade":p.findIndex((V)=>V.id===x)>=c?"next":"prev")})),r("to-summary",()=>on("summary",void 0,"next")),r("decide-yes",li),r("decide-no",()=>$n(rn(w)?.role==="asset"?"revise":"reclassify")),r("decide-other",()=>$n("revise")),r("decide-split",()=>$n("revise",void 0,!0)),r("decision-clear",()=>{let k=rn(w);if(k&&!L())Un(Je(t,k.id),`Cleared: ${k.name}.`),A()}),r("form-cancel",()=>{u=null,A()}),a.getElementById("decision-form")?.addEventListener("submit",(k)=>{k.preventDefault(),On()}),a.getElementById("form-text")?.addEventListener("input",(k)=>{if(u)u.text=k.target.value}),a.querySelectorAll("[data-kind]").forEach((k)=>k.addEventListener("click",()=>{if(!u)return;u.kind=k.dataset.kind,a.querySelectorAll("[data-kind]").forEach((x)=>x.setAttribute("aria-pressed",String(x===k)))})),r("backdrop",()=>{let k=rn(w);if(!k)return;let x=["comp","light","dark"];xn[k.id]=x[(x.indexOf(xn[k.id]??"comp")+1)%3],A()}),r("undo",di),r("send",()=>void ei()),r("retry",()=>void ei()),r("reload",()=>location.reload());let s=()=>{Z=!0,A(),a.getElementById("close-map")?.focus()};if(r("open-map",s),r("open-map-bar",s),r("close-map",()=>{Z=!1,A()}),r("mark",()=>{if(L())return;Q=!Q,f=null,u=null,A()}),r("panel-done",()=>{f=null,u=null,A()}),r("region-image",()=>{if(f?.type==="region")$n("reclassify",f.id)}),r("region-keep",()=>{let k=f?.type==="region"?Ln(f.id):void 0;if(k&&!L())Un(ne(t,k.id,null),`${k.name} stays in code.`),A()}),r("missing-remove",()=>{if(f?.type!=="missing")return;let k=f.id;t={...t,missing:t.missing.filter((x)=>x.id!==k)},f=null,A()}),a.getElementById("missing-name")?.addEventListener("input",(k)=>{let x=t.missing.find((c)=>c.id===f?.id);if(x){x.name=k.target.value;let c=a.getElementById("send");if(c)c.disabled=!Pn(n,t).canSubmit||U||!!o.status;o.onDraftChange?.(structuredClone(t))}}),a.getElementById("missing-feedback")?.addEventListener("input",(k)=>{let x=t.missing.find((c)=>c.id===f?.id);if(x)x.feedback=k.target.value,o.onDraftChange?.(structuredClone(t))}),L())a.querySelectorAll("#decide-yes,#decide-no,#decide-other,#decide-split,#decision-clear,#mark,#region-image").forEach((k)=>k.disabled=!0);a.querySelectorAll(".map [data-item]").forEach((k)=>k.addEventListener("click",()=>{if(!Q)on("stage",k.dataset.item,"fade")}));let l=(k)=>{if(Q)return;if(f=k,u=null,v!=="summary")v="summary",Z=!1,M=qn()?null:"fade";A(),a.querySelector(".coverage")?.scrollIntoView({block:"start"})};a.querySelectorAll("[data-region]").forEach((k)=>k.addEventListener("click",()=>l({type:"region",id:k.dataset.region}))),a.querySelectorAll("[data-missing]").forEach((k)=>k.addEventListener("click",()=>l({type:"missing",id:k.dataset.missing})));let h=a.querySelector(".figures");h?.querySelectorAll(":scope > .fig > .frame").forEach((k)=>{k.addEventListener("pointerenter",(x)=>{if(x.pointerType==="mouse")h.classList.add("looking")}),k.addEventListener("pointerleave",()=>h.classList.remove("looking")),k.addEventListener("pointermove",(x)=>{let c=k.getBoundingClientRect();tn((x.clientX-c.left)/c.width,(x.clientY-c.top)/c.height)})});let m=a.getElementById("summary-map");if(m){let k=(V)=>{let O=m.getBoundingClientRect();return{x:Math.max(0,Math.min(1,(V.clientX-O.left)/O.width)),y:Math.max(0,Math.min(1,(V.clientY-O.top)/O.height))}},x=null,c=null;m.addEventListener("pointerdown",(V)=>{if(!Q)return;x=k(V),c=null,m.setPointerCapture(V.pointerId),V.preventDefault()}),m.addEventListener("pointermove",(V)=>{if(!x)return;let O=k(V);c={x:Math.min(x.x,O.x),y:Math.min(x.y,O.y),w:Math.abs(O.x-x.x),h:Math.abs(O.y-x.y)};let N=a.querySelector(".draw-box");N.hidden=!1,N.style.cssText=Sn(c)}),m.addEventListener("pointerup",()=>{if(c&&c.w>0.01&&c.h>0.01)G(c);x=null,c=null}),m.addEventListener("pointercancel",()=>{x=null,c=null,A()})}}function _n(r){if(dn===r)return;dn=r,a.querySelectorAll('[data-role="generated"] .frame').forEach((l)=>l.classList.toggle("flipped",r));let s=a.querySelector('[data-role="generated"] figcaption .eyebrow');if(s)s.textContent=r?"In the comp":Vi(w??"",g)?.beforeUrl?"After":"Generated";if(r&&!Tn)Tn=!0,Ie.set("impeccable.review.flipHint","1"),a.querySelector(".hint")?.classList.add("gone")}let ai=(r)=>{let s=r;if(!e.isConnected||s.defaultPrevented)return;let l=s.composedPath()[0],h=l instanceof HTMLTextAreaElement||l instanceof HTMLInputElement;if(s.key==="Escape"){if(Z)s.preventDefault(),Z=!1,A();else if(u)s.preventDefault(),u=null,A();else if(Q)s.preventDefault(),Q=!1,A();else if(f)s.preventDefault(),f=null,A();return}if(s.key==="Enter"&&(s.metaKey||s.ctrlKey)&&u){s.preventDefault(),On();return}if(h||s.altKey||s.isComposing)return;if((s.metaKey||s.ctrlKey)&&s.key.toLowerCase()==="z"){if(W)s.preventDefault(),di();return}if(s.metaKey||s.ctrlKey)return;if(v==="intro"&&s.key==="Enter"&&l?.tagName!=="BUTTON"){s.preventDefault(),a.getElementById("start")?.click();return}if(Z||u)return;let m=s.key.toLowerCase();if(s.key===" "&&v==="stage"&&rn(w)?.role==="asset"&&l?.tagName!=="BUTTON"&&l?.tagName!=="A"){if(s.preventDefault(),!s.repeat)_n(!0);return}if(s.key===" "&&v==="stage"&&rn(w)?.role==="asset"){if(s.preventDefault(),!s.repeat)_n(!0);return}if(m==="c"&&v!=="intro"){s.preventDefault(),Z=!0,A();return}if(v!=="stage"||L()){if(v==="summary"&&(m==="k"||s.key==="ArrowLeft")&&p.length&&!L())s.preventDefault(),on("stage",p[p.length-1].id,"prev");return}if(m==="a")s.preventDefault(),li();else if(m==="n")s.preventDefault(),a.getElementById("decide-no")?.click();else if(m==="f"&&rn(w)?.role==="plan")s.preventDefault(),$n("revise");else if(m==="s"&&rn(w)?.role==="asset")s.preventDefault(),$n("revise",void 0,!0);else if(m==="j"||s.key==="ArrowRight")s.preventDefault(),ii(1);else if(m==="k"||s.key==="ArrowLeft")s.preventDefault(),ii(-1)},oi=(r)=>{if(r.key===" "&&dn)r.preventDefault(),_n(!1)},vn=()=>_n(!1);return document.addEventListener("keydown",ai),document.addEventListener("keyup",oi),window.addEventListener("blur",vn),A(),{destroy(){I?.disconnect(),Wn?.(),document.removeEventListener("keydown",ai),document.removeEventListener("keyup",oi),window.removeEventListener("blur",vn),a.replaceChildren()},getDraft(){return structuredClone(t)}}}var T=(e)=>e.replace(/[&<>"']/g,(n)=>({"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#39;"})[n]),Nn=(e)=>`${e*100}%`,Mn=(e)=>{let n=new URL(e,location.href);if(!["http:","https:"].includes(n.protocol))throw Error("Unsupported preview URL");return T(n.href)};function De(e,n,o){if(Mi(n))return Oe(e,n,{...o,history:o.history,initialDraft:o.initialDraft,onDraftChange:o.onDraftChange,onSubmit:o.onSubmit});let a=e.attachShadow({mode:"open"}),t=structuredClone(o.initialDraft??fe(n)),p=n.stage==="hero"&&n.components.length===1&&!t.missing.length,y=()=>[...n.components].sort((X,J)=>bn(X,t,o.history).priority-bn(J,t,o.history).priority),g=y().find((X)=>bn(X,t,o.history).kind!=="approved")?.id??n.components[0]?.id,b=Cn(n,t).pending?"pending":"reviewed",z=!1,v=!1,w=o.completed??!1,M="",u={},f=!!o.completed||!Cn(n,t).pending,Q=null,Z=!0,dn=/Mac|iPhone|iPad/.test(navigator.platform)?"⌘Enter":"Ctrl+Enter",xn=!1,U=!1,Qn=!1,Yn=null,W=!1,en=!0,Tn=!1,I="comp",Wn=I,ln="fit",Xn="checker",C=!1,qn="isolated",rn,Ln="fit",L=null,hn=null,an=null,ni=null,Zn='<svg viewBox="0 0 16 16" aria-hidden="true"><path d="m3 8 3 3 7-7"/></svg>',on='<svg viewBox="0 0 16 16" aria-hidden="true"><path d="m3 11 1 2 2-1 7-7-3-3-7 7v2Z"/></svg>',ii=(X,J)=>{if(X.stage==="hero")return"";let _=yi(X,J);if(!_.related.length)return"";let H=_.related.map((R)=>T(R.name)).join(" · ");return`<div class="review-scope" aria-label="Review scope"><p><strong>Reviewing</strong> ${T(_.description||J.name)}</p><p class="separate-reviews"><strong>Outlined · reviewed separately</strong> ${H}</p>${_.excluded.length?`<p class="scope-excluded">Hidden in this preview: ${_.excluded.map((R)=>T(R.name)).join(" · ")}</p>`:""}</div>`},In=(X)=>`left:${Nn(X.x)};top:${Nn(X.y)};width:${Nn(X.w)};height:${Nn(X.h)}`,Un=(X,J)=>X.stage==="hero"?"":yi(X,J).related.map((_)=>{let H=J.box,R=_.box,Gn=Math.max(H.x,R.x),P=Math.max(H.y,R.y),ri={x:(Gn-H.x)/H.w,y:(P-H.y)/H.h,w:Math.max(0,Math.min(H.x+H.w,R.x+R.w)-Gn)/H.w,h:Math.max(0,Math.min(H.y+H.h,R.y+R.h)-P)/H.h};return`<span class="reference-layer" style="${In(ri)}" title="Reviewed separately: ${T(_.name)}" aria-label="Reviewed separately: ${T(_.name)}"><span>${T(_.name)}</span></span>`}).join("");function Jn(X){a.getElementById(X)?.focus({preventScroll:!0})}function li(X){let J=ye(n,t,X);if(f=!J,J)g=J;I="component",C=!1,xn=!1,ln="fit",qn="isolated",Z=!0,b=f?"reviewed":"pending";let _=()=>{G(),Jn(f?"review-summary":u[g]?"feedback":"approve")};if(f&&U&&Yn)Yn(_);else _()}async function $n(){if(v||w||C||Object.keys(u).length)return;v=!0,M="",G();try{await o.onSubmit(me(n,t)),w=!0,f=!0,z=!1,b="reviewed"}catch(X){M=X instanceof Error?X.message:"Could not save. Try again."}finally{v=!1,G()}}function On(X){if(v||w||C||Qn)return;let J=n.components.find((P)=>P.id===g);if(!J||!pi(n,t,J,Z,Object.keys(u)).length)return;let _=t.decisions[J.id],H=_?.revision===J.revision?_:void 0,R=pi(n,t,J,Z,Object.keys(u));Q={id:J.id,name:R.length>1?`${J.reviewGroup} · ${R.length} instances`:J.name,action:X,previous:Object.fromEntries(R.map((P)=>[P.id,t.decisions[P.id]?{...t.decisions[P.id]}:void 0]))};let Gn=u[J.id]??H;for(let P of R)t.decisions[P.id]={revision:P.revision,action:X,feedback:X==="revise"?Gn?.feedback??"":"",split:X==="revise"&&(Gn?.split??!1)};if(delete u[J.id],Tn)en=!0,Tn=!1;if(p)t.inventoryConfirmed=X==="approve",Q=null,$n();else li(J.id)}function di(){if(v||w||C||Qn)return;let X=n.components.find((H)=>H.id===g);if(!X||!pi(n,t,X,Z,Object.keys(u)).length)return;let J=t.decisions[X.id],_=J?.revision===X.revision?J:void 0;if(u[X.id]??={feedback:_?.feedback??"",split:_?.split??!1},en&&(a.querySelector(".workbench")?.clientHeight??0)<420)Tn=!0,en=!1;f=!1,G(),Jn("feedback")}function ei(X){let J=`missing-${crypto.randomUUID()}`;t.missing.push({id:J,name:"Missing component",feedback:"",box:X}),t.inventoryConfirmed=!1,f=!1,g=J,I="component",z=!1,L=null,hn=null,G(),a.querySelector("#missing-name")?.focus()}function G(){if(an?.disconnect(),ni?.(),w||f&&!p)U=!1;let X=a.activeElement,J=X?.id,_=X?.dataset.select,H=window.scrollX,R=window.scrollY,Gn=a.querySelector(".inventory")?.scrollLeft??0,P=rn===g,ri=I==="component"&&(!P||Wn!==I);Wn=I;let $i=P?a.querySelector(".inspection-content")?.scrollTop??0:0,Gi=P&&(a.querySelector(".changed-files")?.open??!1),Qi=a.querySelector(".comparison-slot")?.clientHeight??200,xi=a.querySelector(".pan-viewport"),hi=rn===g&&Ln===ln,A=hi?xi?.scrollLeft??0:0,ki=hi?xi?.scrollTop??0:0;rn=g,Ln=ln;let $=n.components.find((i)=>i.id===g),D=t.missing.find((i)=>i.id===g),F=ze(n,t,o.history),tn=F.find((i)=>i.members.some((d)=>d.id===g)),kn=!!tn&&tn.members.length>1&&Z,_n=kn?tn.box:$?.box??D?.box,ai=tn?F.indexOf(tn)+1:F.length+t.missing.findIndex((i)=>i.id===g)+1,oi=$?t.decisions[$.id]:void 0,vn=oi?.revision===$?.revision?oi:void 0,r=$?u[$.id]:void 0,s=Object.keys(u).length>0,l=$?mi(n,$):[],h=$?pi(n,t,$,Z,Object.keys(u)):[],m=$?!n.components.some((i)=>!h.some((d)=>d.id===i.id)&&bn(i,t).kind==="pending"):!1,k=Q&&!w?`<div class="decision-notice"><span role="status">${T(Q.name)} ${Q.action==="approve"?"approved":"flagged for repair"}.</span><button id="undo-decision" class="text-action">Undo</button></div>`:"",x=Cn(n,t),c=o.history,V=$?wi($.id,c):void 0,O=c?.packet.components.find((i)=>i.id===$?.id),N=C&&!!O,q=N?O:$,pn=N?c.packet:n,oe=Object.values(c?.changes??{}),te=oe.filter((i)=>i.kind==="changed").length,se=oe.filter((i)=>i.kind==="added").length,Zi=n.components.filter((i)=>bn(i,t,c).kind==="approved"&&wi(i.id,c).carried).length,Ui=(i)=>{let d=bn(i,t,c);return w&&d.kind==="feedback"?{...d,label:"Changes requested"}:d},ti=F.filter((i)=>i.kind==="pending").length,Re=F.length-ti+t.missing.length,pe=F.filter((i)=>b==="all"||i.kind==="pending"===(b==="pending")).map((i)=>i.representative),Fe=(i)=>F.find((d)=>d.members.some((j)=>j.id===i))?.label??i,Ce=[x.revisions+t.missing.length?`${x.revisions+t.missing.length} feedback ready`:"",Zi?`${Zi} ${Zi===1?"approval":"approvals"} kept`:"",te?`${te} changed`:"",se?`${se} added`:"",c?.removed.length?`${c.removed.length} removed`:""].filter(Boolean).join(" · "),Pe=M||(s?"Save or cancel your open feedback before sending.":w?o.preview?"Preview submitted. No run changed.":"Review submitted.":x.hasFeedback?"Ready to send for corrections.":x.pending?`${ti} left to review`:!t.inventoryConfirmed?"Confirm the map is complete.":"Ready to continue."),Vn=q?Fn(q):null,Ai=q?.preview.kind==="image"&&!Vn?.code,Ni=Ai||q?.material?.alpha==="transparent",fn=!!(q?.context&&qn==="context"),le=q&&(fn?q.context?.kind!=="image":q.preview.kind==="page"),Li=fn&&q?.context?q.context.url:q?.preview.url,de=q?yi(pn,q):null,Se=Vn?.code?`${Vn.label} · ${Vn.captured?"captured from code":"live preview"}`:q?.material?`${q.material.alpha==="transparent"?"Transparent":q.material.alpha==="opaque"?"Opaque":"Transparency unverified"} ${q.material.format}`:"Raster · transparency unverified";a.innerHTML=`<style>${Ee}</style><section class="review ${p?"assembled-review":""}" aria-label="${p?"Assembled page review":"Component review"}" style="--comp-background:${/^#[0-9a-f]{6}$/i.test(n.comp.background??"")?n.comp.background:"#eeeeee"}">
+ <header><div><h1>${w?"Review record.":p?"Review the assembled page.":"Review the components."}</h1><p>${T(n.title)} <span>· Round ${n.round}</span></p></div>${w?'<span class="badge">Submitted · read-only</span>':o.preview?'<span class="badge">Interactive preview</span>':""}</header>
+ ${o.preview?'<p class="preview-note">Historical hotel artwork for testing this interface. Decisions stay in this preview; no run is changed.</p>':""}
+ ${c&&!p?`<section class="round-summary" aria-label="Changes since previous round"><p><strong>${ti} ${ti===1?"item":"items"} to review</strong><span>${Ce}</span></p>${x.pending?`<button id="review-changes" class="ks-icon-button" aria-label="Next to review" title="Next to review">${mn("next")}</button>`:""}${c.removed.length?`<details><summary>Removed from the map</summary><p>${c.removed.map((i)=>T(i.name)).join(" · ")}. Confirm these omissions are intentional before accepting the map.</p></details>`:""}</section>`:""}
+ ${!p?`<div class="mobile-panes"><div class="ks-instrument-strip is-paper" data-ks-strip="pane" role="group" aria-label="Inspection view"><button type="button" class="ks-instrument-key" id="show-comp" aria-pressed="${I==="comp"}">Approved comp</button><button type="button" class="ks-instrument-key" id="show-component" aria-pressed="${I==="component"}">Component ${ai}</button></div></div>`:""}
+ <div class="workbench" data-mobile-pane="${I}">${!p?`<svg class="connector" aria-hidden="true"><path /></svg>
<section class="reference" aria-label="Approved composition">
- <div class="section-head"><h2>Approved comp</h2>${!z?`<button id="mark" class="label-icon" aria-pressed="${Z}">${T(Z?"close":"mark")}${Z?"Cancel":"Mark missing"}</button>`:""}</div>
- <div class="map-space"><div class="map ${Z?"marking":""}" style="aspect-ratio:${o.comp.width}/${o.comp.height}">
- <img class="comp" src="${C(o.comp.url)}" alt="Approved composition for ${l(o.title)}" draggable="false">
- ${so&&!k?`<div class="region" style="${Qi(so)}"></div>`:""}
- ${E.map((i,r)=>{let t=i.representative,h={kind:i.kind,label:i.stateLabel},R=!k&&G?.id===i.id;return`<button class="pin ${h.kind} ${R?"selected":""}" data-select="${l(t.id)}" style="left:${hi(Math.min(0.96,i.box.x+i.box.w/2))};top:${hi(Math.max(0.035,i.box.y))}" aria-label="Inspect ${l(i.label)}${i.members.length>1?` · ${i.members.length} instances`:""} — ${l(h.label)}" title="${r+1}. ${l(i.label)} · ${l(h.label)}" aria-pressed="${R}">${h.kind==="approved"?Hi:h.kind==="feedback"?Ki:""}<span>${r+1}</span>${i.members.length>1?`<small>×${i.members.length}</small>`:""}</button>`}).join("")}
- ${D&&!k?G.members.map((i)=>`<div class="region instance-region" style="${Qi(i.box)}"></div>`).join(""):""}
- ${n.missing.map((i,r)=>`<button class="pin feedback ${!k&&g===i.id?"selected":""}" data-select="${l(i.id)}" style="left:${hi(i.box.x+i.box.w/2)};top:${hi(i.box.y)}" aria-label="Inspect missing ${l(i.name)}" title="Missing: ${l(i.name)}">${Ki}<span>${E.length+r+1}</span></button>`).join("")}
+ <div class="section-head"><h2>Approved comp</h2>${!w?`<button id="mark" class="ks-button ks-button-ghost" aria-pressed="${z}">${z?"Cancel":"Mark missing"}</button>`:""}</div>
+ <div class="map-space"><div class="map ${z?"marking":""}" style="aspect-ratio:${n.comp.width}/${n.comp.height}">
+ <img class="comp" src="${Mn(n.comp.url)}" alt="Approved composition for ${T(n.title)}" draggable="false">
+ ${_n&&!f?`<div class="region" style="${In(_n)}"></div>`:""}
+ ${F.map((i,d)=>{let j=i.representative,E={kind:i.kind,label:i.stateLabel},cn=!f&&tn?.id===i.id;return`<button class="pin ${E.kind} ${cn?"selected":""}" data-select="${T(j.id)}" style="left:${Nn(Math.min(0.96,i.box.x+i.box.w/2))};top:${Nn(Math.max(0.035,i.box.y))}" aria-label="Inspect ${T(i.label)}${i.members.length>1?` · ${i.members.length} instances`:""} — ${T(E.label)}" title="${d+1}. ${T(i.label)} · ${T(E.label)}" aria-pressed="${cn}">${E.kind==="approved"?Zn:E.kind==="feedback"?on:""}<span>${d+1}</span>${i.members.length>1?`<small>×${i.members.length}</small>`:""}</button>`}).join("")}
+ ${kn&&!f?tn.members.map((i)=>`<div class="region instance-region" style="${In(i.box)}"></div>`).join(""):""}
+ ${t.missing.map((i,d)=>`<button class="pin feedback ${!f&&g===i.id?"selected":""}" data-select="${T(i.id)}" style="left:${Nn(i.box.x+i.box.w/2)};top:${Nn(i.box.y)}" aria-label="Inspect missing ${T(i.name)}" title="Missing: ${T(i.name)}">${on}<span>${F.length+d+1}</span></button>`).join("")}
<div class="draw-box" hidden></div>
</div></div>
- <div class="map-legend" aria-label="Map status legend"><span><i class="legend-pending">#</i> To review</span><span><i class="legend-feedback">${Ki}</i> ${z?"Changes requested":"Feedback ready"}</span><span><i class="legend-approved">${Hi}</i> Approved</span></div>
- ${Z?'<div class="map-caption">Draw around the missing piece.<button id="add-box">Add an adjustable box</button></div>':""}
+ <div class="map-legend" aria-label="Map status legend"><span><i class="legend-pending">#</i> To review</span><span><i class="legend-feedback">${on}</i> ${w?"Changes requested":"Feedback ready"}</span><span><i class="legend-approved">${Zn}</i> Approved</span></div>
+ ${z?'<div class="map-caption">Draw around the missing piece.<button id="add-box">Add an adjustable box</button></div>':""}
</section>`:""}
<section class="inspector" aria-label="${p?"Page comparison":"Selected component"}">
- ${!p?`<div class="section-head"><h2>${k?"Review summary":`<span class="number">${wo}</span> ${l(D?G.label:m?.name??J?.name??"Component")}`}</h2></div>`:""}<div class="inspection-content" role="region" aria-label="${p?"Page comparison":"Component comparison"}" tabindex="0">
- ${k&&!p?`<section class="review-summary" id="review-summary" tabindex="-1"><div class="completion-mark" aria-hidden="true">${Hi}</div><h2>${z?"Review sent.":"All components reviewed."}</h2><p>${M.approved} approved · ${M.revisions} flagged for repair${n.missing.length?` · ${n.missing.length} missing`:""}</p><p>${z?"Your decisions are saved.":M.hasFeedback?"Send your feedback to start the next repair round.":"Confirm nothing is missing, then approve and continue."}</p><div class="summary-decisions">${E.map((i)=>{let r=i.representative,t=n.decisions[r.id],h=Di(r);return`<button data-select="${l(r.id)}"><strong>${l(i.label)}</strong><span>${i.kind==="pending"?"Not reviewed":h.kind==="feedback"?"Needs work":"Approved"}</span>${t?.action==="revise"?`<small>${l(t.feedback||"No note — agent will diagnose.")}</small>`:""}</button>`}).join("")}${n.missing.map((i)=>`<button data-select="${l(i.id)}"><strong>${l(i.name)}</strong><span>Missing</span><small>${l(i.feedback)}</small></button>`).join("")}</div></section></div>${Ri?`<div class="review-form">${Ri}</div>`:""}`:m?`
- ${$?`<div class="repair-context">
- ${oi&&B?.prior?.action==="revise"?`<section class="previous-feedback" aria-label="Previous feedback"><h3>Previous feedback <span>· Round ${B.feedbackRound}</span></h3><blockquote>${l(B.prior.feedback||"No written feedback was supplied.")}</blockquote>${B.prior.split?"<p>Requested: split into separately reviewable components.</p>":""}</section>`:B?.carried?'<p class="kept-approval">Unchanged · approval kept</p>':""}
- ${B?.change?.kind==="changed"?`<details class="changed-files" ${Ao?"open":""}><summary>${B.change.files.length?`${B.change.files.length} changed ${B.change.files.length===1?"file":"files"}`:B.change.reasons.includes("region")?"Region changed":ci?.note!==m.note?"Description changed · files unchanged":"Component definition changed · files unchanged"}</summary>${B.change.files.length?`<ul>${B.change.files.map((i)=>`<li>${l(i)}</li>`).join("")}</ul>`:""}${ci&&ci.note!==m.note?`<dl class="description-diff"><dt>Previous description</dt><dd>${l(ci.note)}</dd><dt>Current description</dt><dd>${l(m.note)}</dd></dl>`:""}</details>`:""}
+ ${!p?`<div class="section-head"><h2>${f?"Review summary":`<span class="number">${ai}</span> ${T(kn?tn.label:$?.name??D?.name??"Component")}`}</h2></div>`:""}<div class="inspection-content" role="region" aria-label="${p?"Page comparison":"Component comparison"}" tabindex="0">
+ ${f&&!p?`<section class="review-summary" id="review-summary" tabindex="-1"><div class="completion-mark" aria-hidden="true">${Zn}</div><h2>${w?"Review sent.":"All components reviewed."}</h2><p>${x.approved} approved · ${x.revisions} flagged for repair${t.missing.length?` · ${t.missing.length} missing`:""}</p><p>${w?"Your decisions are saved.":x.hasFeedback?"Send your feedback to start the next repair round.":"Confirm nothing is missing, then approve and continue."}</p><div class="summary-decisions">${F.map((i)=>{let d=i.representative,j=t.decisions[d.id],E=Ui(d);return`<button data-select="${T(d.id)}"><strong>${T(i.label)}</strong><span>${i.kind==="pending"?"Not reviewed":E.kind==="feedback"?"Needs work":"Approved"}</span>${j?.action==="revise"?`<small>${T(j.feedback||"No note — agent will diagnose.")}</small>`:""}</button>`}).join("")}${t.missing.map((i)=>`<button data-select="${T(i.id)}"><strong>${T(i.name)}</strong><span>Missing</span><small>${T(i.feedback)}</small></button>`).join("")}</div></section></div>${k?`<div class="review-form">${k}</div>`:""}`:$?`
+ ${c?`<div class="repair-context">
+ ${N&&V?.prior?.action==="revise"?`<section class="previous-feedback" aria-label="Previous feedback"><h3>Previous feedback <span>· Round ${V.feedbackRound}</span></h3><blockquote>${T(V.prior.feedback||"No written feedback was supplied.")}</blockquote>${V.prior.split?"<p>Requested: split into separately reviewable components.</p>":""}</section>`:V?.carried?'<p class="kept-approval">Unchanged · approval kept</p>':""}
+ ${V?.change?.kind==="changed"?`<details class="changed-files" ${Gi?"open":""}><summary>${V.change.files.length?`${V.change.files.length} changed ${V.change.files.length===1?"file":"files"}`:V.change.reasons.includes("region")?"Region changed":O?.note!==$.note?"Description changed · files unchanged":"Component definition changed · files unchanged"}</summary>${V.change.files.length?`<ul>${V.change.files.map((i)=>`<li>${T(i)}</li>`).join("")}</ul>`:""}${O&&O.note!==$.note?`<dl class="description-diff"><dt>Previous description</dt><dd>${T(O.note)}</dd><dt>Current description</dt><dd>${T($.note)}</dd></dl>`:""}</details>`:""}
</div>`:""}
- <div class="comparison-slot"><div class="comparison-panel ${D?"group-overview":""}"><h2 class="expanded-title">${l(D?G.label:d.name)}</h2>${mo.length>1?`<div class="review-peers"><strong>${mo.length} instances</strong>${!D?'<button id="all-instances" class="quiet">All instances</button>':'<span class="group-hint">Select to inspect</span>'}</div>`:""}<div class="compare-toolbar">${ci?`<div class="round-switch" role="group" aria-label="Preview version"><button id="current-round" aria-label="Current · round ${o.round}" title="Current · round ${o.round}" aria-pressed="${!oi}">Current</button><button id="previous-round" aria-label="Previous · round ${$.packet.round}" title="Previous · round ${$.packet.round}" aria-pressed="${oi}">Previous</button></div>`:""}<label class="zoom-control" title="Comparison zoom · based on comp pixels">${T("zoom")}<select id="zoom" aria-label="Comparison zoom">${[["fit","Fit"],["1","100%"],["2","200%"],["4","400%"]].map(([i,r])=>`<option value="${i}" ${String(ni)===i?"selected":""}>${r}</option>`).join("")}</select>${T("chevronDown")}</label><button id="overlay" class="overlay-control" aria-label="Overlay comp" title="Overlay approved comp" aria-pressed="${li}"><svg viewBox="0 0 20 20" aria-hidden="true"><rect x="3" y="3" width="10" height="10"/><rect x="7" y="7" width="10" height="10"/></svg><span class="overlay-label">Overlay</span></button><div class="comparison-actions" role="group" aria-label="Comparison view actions"><button id="expand-comparison" class="icon-button" aria-label="${H?"Restore comparison":"Enlarge comparison"}" title="${H?"Restore comparison (Esc)":"Enlarge comparison"}" aria-expanded="${H}">${T(H?"compact":"expand")}</button>${d?.preview.kind==="image"?`<a class="icon-button source-link" href="${C(Ci)}" target="_blank" rel="noopener" aria-label="${S?"Open context capture":ri.fileLabel}" title="${S?"Open context capture":ri.fileLabel}">${T("external")}</a>`:""}</div></div>
- ${D?`<div class="instance-grid" aria-label="All instances of ${l(G.label)}"><div class="instance-grid-labels"><span>Full comp crop</span><span>Component preview</span></div>${G.members.map((i,r)=>{let t=Di(i);return`<button class="instance-row ${t.kind}" data-instance="${l(i.id)}" aria-label="Inspect instance ${r+1}: ${l(i.name)} — ${l(t.label)}"><span class="instance-caption"><strong>${l(i.name)}</strong><span>${l(t.label)}</span></span><span class="instance-pair"><span class="instance-reference" style="width:min(100%,${i.box.w*o.comp.width}px,${180*i.box.w*o.comp.width/(i.box.h*o.comp.height)}px);aspect-ratio:${i.box.w*o.comp.width}/${i.box.h*o.comp.height}"><img src="${C(o.comp.url)}" alt="Comp: ${l(i.name)}" loading="lazy" style="width:${100/i.box.w}%;left:${-100*i.box.x/i.box.w}%;top:${-100*i.box.y/i.box.h}%">${to(o,i)}</span><span class="instance-produced" style="width:min(100%,${i.box.w*o.comp.width}px,${180*i.box.w*o.comp.width/(i.box.h*o.comp.height)}px);aspect-ratio:${i.box.w*o.comp.width}/${i.box.h*o.comp.height}">${i.preview.kind==="image"?`<img src="${C(i.preview.url)}" alt="Produced: ${l(i.name)}" loading="lazy">`:i.thumbnail?`<img src="${C(i.thumbnail.url)}" alt="Preview: ${l(i.name)}" loading="lazy">`:"Open live component"}</span></span>${xo(o,i)}</button>`}).join("")}</div>`:""}
- ${!D&&d?xo(L,d):""}<div class="compare">
- <figure><figcaption>${oi?`Comp · Round ${$.packet.round}`:p?"Approved comp":ko?.related.length?"Full comp crop":"In the comp"}</figcaption><div class="pan-viewport" aria-label="Reference comparison canvas" tabindex="0"><div class="crop-stage"><img class="crop-image" src="${C(L.comp.url)}" alt="Reference region for ${l(d.name)}" style="width:${100/d.box.w}%;left:${-100*d.box.x/d.box.w}%;top:${-100*d.box.y/d.box.h}%">${to(L,d)}</div></div></figure>
- <figure><figcaption>${oi?`Previous · Round ${$.packet.round}`:p?"Assembled page":S?"In context":$?`${ri.caption} · Round ${o.round}`:ri.caption}</figcaption><div class="pan-viewport" aria-label="Produced comparison canvas" tabindex="0"><div class="output crop-stage ${Fi&&!S&&!zo&&qi==="checker"?"checker":""}">${!zo?`<img class="asset" src="${C(Ci)}" alt="Produced ${l(d.name)}" style="object-position:${l(d.preview.position??"center")}">`:`<iframe aria-hidden="true" title="Rendered ${l(d.name)}" src="${C(Ci)}" sandbox="" tabindex="-1" width="${L.comp.width}" height="${L.comp.height}"></iframe>`}${li?`<img class="crop-image overlay-image" src="${C(L.comp.url)}" alt="Reference overlay" style="width:${100/d.box.w}%;left:${-100*d.box.x/d.box.w}%;top:${-100*d.box.y/d.box.h}%">`:""}</div></div></figure>
+ <div class="comparison-slot"><div class="comparison-panel ${kn?"group-overview":""}"><h2 class="expanded-title">${T(kn?tn.label:q.name)}</h2>${l.length>1?`<div class="review-peers"><strong>${l.length} instances</strong>${!kn?'<button id="all-instances" class="quiet">All instances</button>':'<span class="group-hint">Select to inspect</span>'}</div>`:""}<div class="compare-toolbar">${O?`<div class="round-switch ks-instrument-strip is-paper" data-ks-strip="round" role="group" aria-label="Preview version"><button type="button" class="ks-instrument-key" id="current-round" aria-label="Current · round ${n.round}" title="Current · round ${n.round}" aria-pressed="${!N}">Current</button><button type="button" class="ks-instrument-key" id="previous-round" aria-label="Previous · round ${c.packet.round}" title="Previous · round ${c.packet.round}" aria-pressed="${N}">Previous</button></div>`:""}<div class="ks-instrument-strip is-paper zoom-strip" data-ks-strip="zoom" role="group" aria-label="Comparison zoom">${[["fit","Fit"],["1","100%"],["2","200%"],["4","400%"]].map(([i,d])=>`<button type="button" class="ks-instrument-key" data-zoom="${i}" aria-pressed="${String(ln)===i}">${d}</button>`).join("")}</div><button id="overlay" type="button" class="ks-switch" title="Overlay the approved comp" aria-pressed="${xn}"><span class="ks-switch-track" aria-hidden="true"><span class="ks-switch-knob"></span></span><span class="ks-switch-label">Overlay</span></button><div class="comparison-actions" role="group" aria-label="Comparison view actions"><button id="expand-comparison" class="ks-icon-button" aria-label="${U?"Restore comparison":"Enlarge comparison"}" title="${U?"Restore comparison (Esc)":"Enlarge comparison"}" aria-expanded="${U}">${mn(U?"compact":"expand")}</button>${q?.preview.kind==="image"?`<a class="ks-icon-button source-link" href="${Mn(Li)}" target="_blank" rel="noopener" aria-label="${fn?"Open context capture":Vn.fileLabel}" title="${fn?"Open context capture":Vn.fileLabel}">${mn("external")}</a>`:""}</div></div>
+ ${kn?`<div class="instance-grid" aria-label="All instances of ${T(tn.label)}"><div class="instance-grid-labels"><span>Full comp crop</span><span>Component preview</span></div>${tn.members.map((i,d)=>{let j=Ui(i);return`<button class="instance-row ${j.kind}" data-instance="${T(i.id)}" aria-label="Inspect instance ${d+1}: ${T(i.name)} — ${T(j.label)}"><span class="instance-caption"><strong>${T(i.name)}</strong><span>${T(j.label)}</span></span><span class="instance-pair"><span class="instance-reference" style="width:min(100%,${i.box.w*n.comp.width}px,${180*i.box.w*n.comp.width/(i.box.h*n.comp.height)}px);aspect-ratio:${i.box.w*n.comp.width}/${i.box.h*n.comp.height}"><img src="${Mn(n.comp.url)}" alt="Comp: ${T(i.name)}" loading="lazy" style="width:${100/i.box.w}%;left:${-100*i.box.x/i.box.w}%;top:${-100*i.box.y/i.box.h}%">${Un(n,i)}</span><span class="instance-produced" style="width:min(100%,${i.box.w*n.comp.width}px,${180*i.box.w*n.comp.width/(i.box.h*n.comp.height)}px);aspect-ratio:${i.box.w*n.comp.width}/${i.box.h*n.comp.height}">${i.preview.kind==="image"?`<img src="${Mn(i.preview.url)}" alt="Produced: ${T(i.name)}" loading="lazy">`:i.thumbnail?`<img src="${Mn(i.thumbnail.url)}" alt="Preview: ${T(i.name)}" loading="lazy">`:"Open live component"}</span></span>${ii(n,i)}</button>`}).join("")}</div>`:""}
+ ${!kn&&q?ii(pn,q):""}<div class="compare">
+ <figure><figcaption>${N?`Comp · Round ${c.packet.round}`:p?"Approved comp":de?.related.length?"Full comp crop":"In the comp"}</figcaption><div class="pan-viewport" aria-label="Reference comparison canvas" tabindex="0"><div class="crop-stage"><img class="crop-image" src="${Mn(pn.comp.url)}" alt="Reference region for ${T(q.name)}" style="width:${100/q.box.w}%;left:${-100*q.box.x/q.box.w}%;top:${-100*q.box.y/q.box.h}%">${Un(pn,q)}</div></div></figure>
+ <figure><figcaption>${N?`Previous · Round ${c.packet.round}`:p?"Assembled page":fn?"In context":c?`${Vn.caption} · Round ${n.round}`:Vn.caption}</figcaption><div class="pan-viewport" aria-label="Produced comparison canvas" tabindex="0"><div class="output crop-stage ${Ni&&!fn&&!le&&Xn==="checker"?"checker":""}">${!le?`<img class="asset" src="${Mn(Li)}" alt="Produced ${T(q.name)}" style="object-position:${T(q.preview.position??"center")}">`:`<iframe aria-hidden="true" title="Rendered ${T(q.name)}" src="${Mn(Li)}" sandbox="" tabindex="-1" width="${pn.comp.width}" height="${pn.comp.height}"></iframe>`}${xn?`<img class="crop-image overlay-image" src="${Mn(pn.comp.url)}" alt="Reference overlay" style="width:${100/q.box.w}%;left:${-100*q.box.x/q.box.w}%;top:${-100*q.box.y/q.box.h}%">`:""}</div></div></figure>
</div>
- ${Fi||d.context?`<div class="view-controls">${d.context?`<div role="group" aria-label="Component view"><button id="isolated" aria-pressed="${!S}">${Si?"Asset only":"Component only"}</button><button id="context" aria-pressed="${S}">In context</button></div>`:""}${Fi?`<div class="background-options" role="group" aria-label="Asset preview background"><button id="background-checker" class="swatch-button" aria-label="Checkerboard background" title="Checkerboard background" aria-pressed="${qi==="checker"}" ${S?"disabled":""}><span class="background-swatch checker"></span></button><button id="background-page" class="swatch-button" aria-label="${L.comp.background?"Page color":"Neutral"} background" title="${L.comp.background?"Page color":"Neutral"} background" aria-pressed="${qi==="page"}" ${S?"disabled":""}><span class="background-swatch page-swatch"></span></button></div>`:""}</div>`:""}
- </div></div>${!p&&!D?`<div class="component-details"><div class="material">${T(ri.code?"code":"image")}<strong>${l(Po)}</strong><span>${d?.material?`${d.material.width} × ${d.material.height} px`:""}</span></div>${L.stage==="components"&&ri?.captured&&!d?.preview.isolation?'<p class="layering">Legacy region capture · may include overlapping components.</p>':""}${d?.context?.layering&&(Si||S)?`<p class="layering">${l(d.context.layering)}</p>`:""}
- <p class="component-note">${!ko?.related.length?l(d.note):""}</p>
- </div>`:""}</div><div class="review-form">${Ri}${oi?'<p class="previous-notice">Viewing the previous round. Return to Current to make a decision.</p>':""}${z?`<div class="record-verdict"><strong>${ti?.action==="approve"?"Approved":ti?.action==="revise"?"Changes requested":"Not reviewed"}</strong><span>Submitted in round ${o.round} · read-only</span></div>`:`<div class="decisions" role="group" aria-label="Decision for ${l(m.name)}">${!p?`<div class="decision-title"><strong>Your review <span>Round ${o.round}</span></strong>${oi?"<p>Return to Current to review this round.</p>":""}</div>`:""}<button id="approve" ${!wi.length?"disabled":""} class="decision-approve ${ti?.action==="approve"?"approved":""}" aria-pressed="${ti?.action==="approve"}">${p?s?"Sending…":"Approve & continue":wi.length>1?`Approve ${wi.length} instances`:"Looks good"}</button><button id="revise" ${!wi.length?"disabled":""} class="decision-revise ${ti?.action==="revise"?"revise":""}" aria-pressed="${ti?.action==="revise"}">${wi.length>1?`Revise ${wi.length} instances`:"Needs work"}</button>${ti&&!p&&!D?`<button id="clear" class="quiet icon-button" aria-label="Clear decision" title="Clear decision">${T("undo")}</button>`:""}</div>`}
- ${Yi?`<form id="feedback-form"><div class="feedback-fields"><label class="feedback-field">What needs to change?<textarea id="feedback" aria-describedby="feedback-hint">${l(Yi.feedback)}</textarea></label><p id="feedback-hint" class="feedback-hint">Optional — leave blank for the agent to diagnose.</p>${!p?`<label class="check"><input id="split" type="checkbox" ${Yi.split?"checked":""}> Split into separately reviewable components</label>`:""}</div><div class="feedback-actions"><button id="cancel-feedback" type="button" class="quiet">Cancel</button><button id="save-feedback" type="submit" class="primary">${p?"Send feedback":Oo?"Save & finish review":"Save & next"} <svg viewBox="0 0 24 24" aria-hidden="true"><path d="M4 12h15m-6-6 6 6-6 6"/></svg></button><span class="shortcut-hint">${Wo}</span></div></form>`:ti?.action==="revise"?`<p class="saved-feedback">${l(ti.feedback||"No note — agent will diagnose.")}</p>`:""}
- ${p?`<p class="page-review-status" role="status">${l($i||(z?"Your decision is saved.":s?"Sending…":Yi?"":"Approval confirms the composition and that nothing is missing."))}</p>`:""}</div>`:J?`<p>This piece will be added to the unresolved inventory.</p><label class="feedback-field">Name<input id="missing-name" value="${l(J.name)}"></label><label class="feedback-field">What is missing?<textarea id="missing-feedback">${l(J.feedback)}</textarea></label><div class="coordinates">${["x","y","w","h"].map((i)=>`<label>${{x:"Left",y:"Top",w:"Width",h:"Height"}[i]} %<input type="number" data-coordinate="${i}" value="${Math.round(J.box[i]*1000)/10}" min="0" max="100" step="0.1"></label>`).join("")}</div><button id="remove-missing">Remove this mark</button></div>`:"<p>No components supplied.</p></div>"}
+ ${Ni||q.context?`<div class="view-controls">${q.context?`<div class="ks-instrument-strip is-paper" data-ks-strip="view" role="group" aria-label="Component view"><button type="button" class="ks-instrument-key" id="isolated" aria-pressed="${!fn}">${Ai?"Asset only":"Component only"}</button><button type="button" class="ks-instrument-key" id="context" aria-pressed="${fn}">In context</button></div>`:""}${Ni?`<div class="background-options ks-instrument-strip is-paper" data-ks-strip="background" role="group" aria-label="Asset preview background"><button type="button" id="background-checker" class="ks-instrument-key" aria-label="Checkerboard background" title="Checkerboard background" aria-pressed="${Xn==="checker"}" ${fn?"disabled":""}>Checker</button><button type="button" id="background-page" class="ks-instrument-key" aria-label="${pn.comp.background?"Page color":"Neutral"} background" title="${pn.comp.background?"Page color":"Neutral"} background" aria-pressed="${Xn==="page"}" ${fn?"disabled":""}>Page</button></div>`:""}</div>`:""}
+ </div></div>${!p&&!kn?`<div class="component-details"><div class="material">${mn(Vn.code?"code":"image")}<strong>${T(Se)}</strong><span>${q?.material?`${q.material.width} × ${q.material.height} px`:""}</span></div>${pn.stage==="components"&&Vn?.captured&&!q?.preview.isolation?'<p class="layering">Legacy region capture · may include overlapping components.</p>':""}${q?.context?.layering&&(Ai||fn)?`<p class="layering">${T(q.context.layering)}</p>`:""}
+ <p class="component-note">${!de?.related.length?T(q.note):""}</p>
+ </div>`:""}</div><div class="review-form">${k}${N?'<p class="previous-notice">Viewing the previous round. Return to Current to make a decision.</p>':""}${w?`<div class="record-verdict"><strong>${vn?.action==="approve"?"Approved":vn?.action==="revise"?"Changes requested":"Not reviewed"}</strong><span>Submitted in round ${n.round} · read-only</span></div>`:`<div class="decisions" role="group" aria-label="Decision for ${T($.name)}">${!p?`<div class="decision-title"><strong>Your review <span>Round ${n.round}</span></strong>${N?"<p>Return to Current to review this round.</p>":""}</div>`:""}<button id="approve" ${!h.length?"disabled":""} class="ks-button ks-button-primary decision-approve ${vn?.action==="approve"?"approved":""}" aria-pressed="${vn?.action==="approve"}">${p?v?"Sending…":`Approve & continue${Bn}`:h.length>1?`Approve ${h.length} instances`:"Looks good"}</button><button id="revise" ${!h.length?"disabled":""} class="ks-button ks-button-secondary decision-revise ${vn?.action==="revise"?"revise":""}" aria-pressed="${vn?.action==="revise"}">${h.length>1?`Revise ${h.length} instances`:"Needs work"}</button>${vn&&!p&&!kn?`<button id="clear" class="ks-icon-button" aria-label="Clear decision" title="Clear decision">${mn("undo")}</button>`:""}</div>`}
+ ${r?`<form id="feedback-form"><div class="feedback-fields"><label class="feedback-field">What needs to change?<textarea id="feedback" aria-describedby="feedback-hint">${T(r.feedback)}</textarea></label><p id="feedback-hint" class="feedback-hint">Optional — leave blank for the agent to diagnose.</p>${!p?`<label class="check"><input id="split" type="checkbox" ${r.split?"checked":""}> Split into separately reviewable components</label>`:""}</div><div class="feedback-actions"><button id="cancel-feedback" type="button" class="ks-button ks-button-ghost">Cancel</button><button id="save-feedback" type="submit" class="ks-button ks-button-primary">${p?"Send feedback":m?"Save & finish review":"Save & next"}${Bn}</button><span class="shortcut-hint">${dn}</span></div></form>`:vn?.action==="revise"?`<p class="saved-feedback">${T(vn.feedback||"No note — agent will diagnose.")}</p>`:""}
+ ${p?`<p class="page-review-status" role="status">${T(M||(w?"Your decision is saved.":v?"Sending…":r?"":"Approval confirms the composition and that nothing is missing."))}</p>`:""}</div>`:D?`<p>This piece will be added to the unresolved inventory.</p><label class="feedback-field">Name<input id="missing-name" value="${T(D.name)}"></label><label class="feedback-field">What is missing?<textarea id="missing-feedback">${T(D.feedback)}</textarea></label><div class="coordinates">${["x","y","w","h"].map((i)=>`<label>${{x:"Left",y:"Top",w:"Width",h:"Height"}[i]} %<input type="number" data-coordinate="${i}" value="${Math.round(D.box[i]*1000)/10}" min="0" max="100" step="0.1"></label>`).join("")}</div><button id="remove-missing">Remove this mark</button></div>`:"<p>No components supplied.</p></div>"}
</section>
</div>
- ${!p?`<section class="inventory-section ${W?"":"tray-collapsed"} ${di&&W?"tray-expanded":""}" aria-label="Component inventory"><div class="section-head"><h2>Components</h2><div class="inventory-filters" role="group" aria-label="Filter components"><button data-filter="pending" aria-pressed="${v==="pending"}">To review <b>${Mi}</b></button><button data-filter="reviewed" aria-pressed="${v==="reviewed"}">Reviewed <b>${Do}</b></button><button data-filter="all" aria-pressed="${v==="all"}">All <b>${E.length+n.missing.length}</b></button></div><div class="tray-actions"><button id="show-all" class="icon-button" aria-pressed="${di}" aria-controls="component-tray" aria-label="${di?"Compact":"Expand"} tray" title="${di?"Compact":"Expand"} tray">${T(di?"compact":"expand")}</button><button id="toggle-tray" class="icon-button" aria-expanded="${W}" aria-controls="component-tray" aria-label="${W?"Hide":"Show"} component tray" title="${W?"Hide":"Show"} component tray">${T(W?"hideTray":"showTray")}</button></div></div>
- <div id="component-tray" class="inventory ${di?"all":""}">${yo.map((i)=>{let r=E.find((R)=>R.members.some((U)=>U.id===i.id)),t=E.indexOf(r),h={kind:r.kind,label:r.stateLabel};return`<button class="item ${h.kind} ${!k&&G?.id===r.id?"active":""}" data-select="${l(i.id)}" aria-pressed="${!k&&G?.id===r.id}">${i.thumbnail?`<span class="item-thumb">${i.thumbnail.box?`<span class="thumb-crop" style="width:min(100%,${76*i.thumbnail.box.w*o.comp.width/(i.thumbnail.box.h*o.comp.height)}px);aspect-ratio:${i.thumbnail.box.w*o.comp.width}/${i.thumbnail.box.h*o.comp.height}"><img alt="" loading="lazy" src="${C(i.thumbnail.url)}" style="position:absolute;width:${100/i.thumbnail.box.w}%;max-width:none;left:${-100*i.thumbnail.box.x/i.thumbnail.box.w}%;top:${-100*i.thumbnail.box.y/i.thumbnail.box.h}%;"></span>`:`<img alt="" loading="lazy" src="${C(i.thumbnail.url)}">`}</span>`:""}<span class="item-number">${h.kind==="approved"?Hi:h.kind==="feedback"?Ki:""}${t+1}<span class="item-medium">${T(zi(i).code?"code":"image")}${l(zi(i).label)}</span></span><strong>${l(So(i.id))}${r.members.length>1?` <small>×${r.members.length}</small>`:""}</strong><span class="state ${h.kind}">${l(h.label)}</span></button>`}).join("")}${(v==="pending"?[]:n.missing).map((i,r)=>`<button class="item feedback ${g===i.id?"active":""}" data-select="${l(i.id)}"><span class="item-number">${E.length+r+1}</span><strong>${l(i.name)}</strong><span class="state revise">Missing</span></button>`).join("")}${!yo.length&&(v==="pending"||!n.missing.length)?`<p class="inventory-empty">${v==="pending"?"Nothing left to review. Your decisions are ready.":"No components reviewed yet."}</p>`:""}</div></section>`:""}
- ${p?"":z?`<footer class="record-footer"><span>Round ${o.round} submitted · read-only</span><span>${M.approved} approved · ${M.revisions} changes requested</span></footer>`:`<footer class="${!M.pending&&!si?"queue-complete":""}"><div>${!M.pending&&!si?`<button id="show-summary" class="completion-link">${Hi}${z?"Review sent":"All components reviewed"}</button>`:""}<button id="approve-rest" ${!M.pending?"hidden":""} ${!M.pending||si?"disabled":""}>Approve ${M.approved||M.revisions?"remaining":"all"}</button><label class="check"><input id="inventory-confirm" type="checkbox" ${n.inventoryConfirmed?"checked":""}> Nothing missing from the comp</label></div><div class="submit-area"><p role="status">${l(Co)}</p><button id="submit" class="primary" ${!M.canSubmit||si||s||z?"disabled":""}>${s?"Sending…":z?"Review sent":M.hasFeedback?"Send feedback":"Approve & continue"}</button></div></footer>`}
- </section><dialog id="comparison-dialog" aria-label="${p?"Enlarged page comparison":"Enlarged component comparison"}"></dialog>`;let N=e.querySelector("#comparison-dialog"),I=e.querySelector(".comparison-panel"),mi=e.querySelector(".comparison-slot"),ei=e.querySelector(".inspector > .review-form"),ir=e.querySelector(".inspector"),jo=()=>{if(N.append(I),ei)N.append(ei)};if(H&&I&&mi)mi.style.height=`${Bo}px`,jo(),N.showModal();if(oi)e.querySelectorAll(".decisions button,#feedback,#split,#save-feedback,#cancel-feedback,#undo-decision,#approve-rest,#submit,#inventory-confirm").forEach((i)=>i.disabled=!0);if(e.querySelector(".inspection-content").scrollTop=Uo,z||s)e.querySelectorAll(".decisions button,#save-feedback,#cancel-feedback,#undo-decision,#approve-rest,#mark,#inventory-confirm,#missing-name,#missing-feedback,#feedback,#split,#remove-missing,[data-coordinate]").forEach((i)=>i.disabled=!0);let qo=e.querySelector(".inventory");if(qo)qo.scrollLeft=fi;if(!X&&W)Array.from(e.querySelectorAll(".inventory [data-select]")).find((i)=>i.dataset.select===g)?.scrollIntoView({block:"nearest",inline:"nearest"});if(c)e.getElementById(c)?.focus({preventScroll:!0});else if(j)Array.from(e.querySelectorAll(".item[data-select]")).find((i)=>i.dataset.select===j)?.focus({preventScroll:!0});let u=(i,r)=>e.querySelector(`#${i}`)?.addEventListener("click",r);function Pi(i,r=!1,t=!1){if(Z)return;if(!t)i=E.find((h)=>h.members.some((R)=>R.id===i))?.representative.id??i;if(ii=!t,k=!1,g=i,Y="component",li=!1,ni="fit",gi="isolated",A=!1,w(),r)e.querySelector("#expand-comparison")?.click()}e.querySelectorAll("[data-select]").forEach((i)=>i.onclick=()=>Pi(i.dataset.select,i.classList.contains("pin")&&o.components.some((r)=>r.id===i.dataset.select))),u("previous-round",()=>{A=!0,w()}),u("current-round",()=>{A=!1,w()}),u("review-changes",()=>{let i=y().filter((h)=>Di(h).kind==="pending"),r=i.findIndex((h)=>h.id===g),t=i[(r+1)%i.length];if(t)ii=!0,k=!1,g=t.id,Y="component",v="pending",A=!1,ni="fit",li=!1,gi="isolated",w()}),e.querySelectorAll("[data-filter]").forEach((i)=>i.onclick=()=>{v=i.dataset.filter,k=!M.pending&&v==="pending";let r=E.filter((h)=>v==="all"||h.kind==="pending"===(v==="pending")).map((h)=>h.representative);if(!(v!=="pending"&&n.missing.some((h)=>h.id===g))&&!r.some((h)=>h.id===g)&&r.length)ii=!0,g=r[0].id,Y="component",A=!1,ni="fit",li=!1,gi="isolated";w()}),u("show-summary",()=>{k=!0,Y="component",v="reviewed",w(),vi("review-summary")}),u("approve",()=>Bi("approve")),u("revise",To),u("clear",()=>{if(m)delete n.decisions[m.id],delete V[m.id];P=null,k=!1,v="pending",w()}),u("cancel-feedback",()=>{if(m)delete V[m.id];if(bi)W=!0,bi=!1;w(),vi("revise")}),e.querySelector("#feedback-form")?.addEventListener("submit",(i)=>{i.preventDefault(),Bi("revise")}),e.querySelector("#feedback")?.addEventListener("keydown",(i)=>{let r=i;if(r.key==="Enter"&&(r.metaKey||r.ctrlKey)&&!r.isComposing)r.preventDefault(),r.stopPropagation(),Bi("revise")}),u("undo-decision",()=>{if(!P||s||z)return;let i=P;for(let[r,t]of Object.entries(i.previous))if(t)n.decisions[r]=t;else delete n.decisions[r];delete V[i.id],g=i.id,k=!1,A=!1,Y="component",v="all",P=null,w(),vi("approve")}),u("all-instances",()=>{ii=!0,g=G.representative.id,A=!1,w()}),e.querySelectorAll("[data-instance]").forEach((i)=>i.onclick=()=>Pi(i.dataset.instance,!1,!0)),u("overlay",()=>{li=!li,w()}),u("isolated",()=>{gi="isolated",w()}),u("context",()=>{gi="context",w()}),e.querySelector("#zoom")?.addEventListener("change",(i)=>{let r=i.target.value;ni=r==="fit"?"fit":Number(r),w()}),u("background-checker",()=>{qi="checker",w()}),u("background-page",()=>{qi="page",w()}),u("show-all",()=>{di=!di,W=!0,w()}),u("toggle-tray",()=>{bi=!1,W=!W,w()}),u("show-comp",()=>{Y="comp",w()}),u("show-component",()=>{Y="component",w()}),u("mark",()=>{Z=!Z,w()}),u("add-box",()=>ho({x:0.35,y:0.35,w:0.2,h:0.2})),u("remove-missing",()=>{n.missing=n.missing.filter((i)=>i.id!==g),g=o.components[0]?.id,w()}),u("approve-rest",()=>{if(si)return;n=Yo(o,n),P=null,k=!0,v="reviewed",Y="component",w(),vi("review-summary")}),e.querySelector("#inventory-confirm")?.addEventListener("change",(i)=>{n.inventoryConfirmed=i.target.checked,w()}),e.querySelector("#feedback")?.addEventListener("input",(i)=>{if(m&&V[m.id])V[m.id].feedback=i.target.value}),e.querySelector("#split")?.addEventListener("change",(i)=>{if(m&&V[m.id])V[m.id].split=i.target.checked}),e.querySelector("#missing-name")?.addEventListener("input",(i)=>{if(J)J.name=i.target.value;let r=e.querySelector("#submit");if(r)r.disabled=si||s||z||!ki(o,n).canSubmit}),e.querySelector("#missing-feedback")?.addEventListener("input",(i)=>{if(J)J.feedback=i.target.value}),e.querySelectorAll("[data-coordinate]").forEach((i)=>i.addEventListener("change",()=>{if(!J)return;let r=i.dataset.coordinate,t=Number(i.value)/100;if(Number.isFinite(t))J.box[r]=Math.max(r==="w"||r==="h"?0.001:0,Math.min(1,t));J.box.w=Math.min(J.box.w,1-J.box.x),J.box.h=Math.min(J.box.h,1-J.box.y),w()})),u("submit",()=>{lo()});let F=e.querySelector(".map");function io(i){let r=F.getBoundingClientRect();return{x:Math.max(0,Math.min(1,(i.clientX-r.left)/r.width)),y:Math.max(0,Math.min(1,(i.clientY-r.top)/r.height))}}function Ho(i){let r=io(i);return o.components.filter(({box:t})=>r.x>=t.x&&r.x<=t.x+t.w&&r.y>=t.y&&r.y<=t.y+t.h).sort((t,h)=>t.box.w*t.box.h-h.box.w*h.box.h)[0]}F?.addEventListener("click",(i)=>{if(Z||i.target.closest("[data-select]"))return;let r=Ho(i);if(r)Pi(r.id,!0)}),F?.addEventListener("pointermove",(i)=>{if(!Z)F.style.cursor=Ho(i)?"zoom-in":""}),F?.addEventListener("pointerdown",(i)=>{if(!Z)return;ai=io(i),F.setPointerCapture(i.pointerId),i.preventDefault()}),F?.addEventListener("pointermove",(i)=>{if(!ai)return;let r=io(i);pi={x:Math.min(ai.x,r.x),y:Math.min(ai.y,r.y),w:Math.abs(r.x-ai.x),h:Math.abs(r.y-ai.y)};let t=e.querySelector(".draw-box");t.hidden=!1,t.style.cssText=Qi(pi)}),F?.addEventListener("pointerup",()=>{if(pi&&pi.w>0.01&&pi.h>0.01)ho(pi);else ai=null,pi=null}),F?.addEventListener("pointercancel",()=>{ai=null,pi=null,w()});let Mo=e.querySelector(".output"),_i=e.querySelector("iframe"),Vo=e.querySelector(".workbench"),ui=e.querySelector(".inspection-content"),oo=e.querySelector(".inspector");function ro(){if(!ui||!oo)return;oo.dataset.scrollAbove=String(ui.scrollTop>1),oo.dataset.scrollBelow=String(ui.scrollHeight-ui.clientHeight-ui.scrollTop>1)}ui?.addEventListener("scroll",ro,{passive:!0});function Xi(){let i=e.querySelector(".map-space");if(i&&i.clientWidth&&i.clientHeight){let b=eo(o.comp.width,o.comp.height,Math.max(1,i.clientWidth-32),Math.max(1,i.clientHeight-32),"fit");F.style.width=`${b.width}px`,F.style.height=`${b.height}px`}let r=e.querySelector(".inspection-content"),t=Array.from(e.querySelectorAll(".pan-viewport"));if(r?.clientHeight){let b=H?Math.max(100,N.clientHeight-(I?.querySelector(".compare-toolbar")?.clientHeight??0)-(I?.querySelector(".expanded-title")?.clientHeight??0)-(I?.querySelector(".view-controls")?.clientHeight??0)-(ei?.getBoundingClientRect().height??0)-124):Math.min(p?Number.POSITIVE_INFINITY:248,Math.max(100,r.clientHeight-((t[0]?.getBoundingClientRect().top??r.getBoundingClientRect().top)-r.getBoundingClientRect().top+r.scrollTop)-(I?.querySelector(".view-controls")?.clientHeight??0)-12));t.forEach((K)=>K.style.height=`${b}px`)}if(d&&t.length&&!D){let b=eo(d.box.w*L.comp.width,d.box.h*L.comp.height,Math.min(...t.map((K)=>K.clientWidth)),Math.min(...t.map((K)=>K.clientHeight)),ni);e.querySelectorAll(".crop-stage").forEach((K)=>{K.style.width=`${b.width}px`,K.style.height=`${b.height}px`})}if(t.forEach((b)=>{let K=b.scrollWidth>b.clientWidth+1||b.scrollHeight>b.clientHeight+1;b.classList.toggle("pannable",K),b.style.cursor=H?"":"zoom-in",b.setAttribute("role",H?"region":"button"),b.title=H?K?"Move your pointer to pan. You can also scroll, swipe, or use arrow keys.":"":"Click to enlarge comparison"}),Mo&&_i&&d){let b=Mo.clientWidth/(d.box.w*L.comp.width);_i.style.transform=`scale(${b})`,_i.style.left=`${-d.box.x*L.comp.width*b}px`,_i.style.top=`${-d.box.y*L.comp.height*b}px`}let h=Vo.getBoundingClientRect(),R=e.querySelector(".region"),U=e.querySelector(".number"),Ni=e.querySelector(".connector path");if(R&&U&&Ni){let b=R.getBoundingClientRect(),K=U.getBoundingClientRect(),Zi=b.right-h.left,Q=b.top+b.height/2-h.top,Vi=K.left-h.left-8,Li=K.top+K.height/2-h.top;Ni.setAttribute("d",`M ${Zi} ${Q} H ${Vi-14} V ${Li} H ${Vi}`)}}function yi(i,r){if(!I||!mi||i===H)return;let t=e.querySelector("#expand-comparison"),h=(H?N:I).getBoundingClientRect(),R=window.matchMedia("(prefers-reduced-motion: reduce)").matches,U=I.querySelector(".pan-viewport"),Ni=U?U.scrollLeft/Math.max(1,U.scrollWidth-U.clientWidth):0,b=U?U.scrollTop/Math.max(1,U.scrollHeight-U.clientHeight):0,K=()=>I.querySelectorAll(".pan-viewport").forEach((Q)=>{Q.scrollLeft=Ni*Math.max(0,Q.scrollWidth-Q.clientWidth),Q.scrollTop=b*Math.max(0,Q.scrollHeight-Q.clientHeight)}),Zi=()=>{if(mi.append(I),ei)ir.append(ei),ei.inert=!1;N.close(),mi.style.height="",ji=!1,H=!1,t.innerHTML=T("expand"),t.setAttribute("aria-label","Enlarge comparison"),t.title="Enlarge comparison",t.setAttribute("aria-expanded","false"),Xi(),K(),t.focus({preventScroll:!0}),r?.()};if(i){mi.style.height=`${h.height}px`,jo(),N.showModal(),H=!0,t.innerHTML=T("compact"),t.setAttribute("aria-label","Restore comparison"),t.title="Restore comparison (Esc)",t.setAttribute("aria-expanded","true"),Xi(),K(),t.focus({preventScroll:!0});let Q=N.getBoundingClientRect();if(!R)N.animate([{transform:`translate(${h.x-Q.x}px,${h.y-Q.y}px) scale(${h.width/Q.width},${h.height/Q.height})`,opacity:0.6},{transform:"none",opacity:1}],{duration:240,easing:"cubic-bezier(.2,.8,.2,1)"})}else{if(t.disabled)return;let Q=mi.getBoundingClientRect();if(R){Zi();return}if(t.disabled=!0,ji=!0,ei)ei.inert=!0;let Vi=N.animate([{transform:"none",opacity:1},{transform:`translate(${Q.x-h.x}px,${Q.y-h.y}px) scale(${Q.width/h.width},${Q.height/h.height})`,opacity:0.6}],{duration:200,easing:"cubic-bezier(.4,0,.2,1)",fill:"forwards"});N.inert=!0;let Li=()=>{if(Vi.cancel(),t.disabled=!1,N.inert=!1,N.isConnected)Zi();else ji=!1,H=!1,w(),r?.()};Vi.finished.then(Li,Li)}}if(Ui=(i)=>yi(!1,i),u("expand-comparison",()=>yi(!H)),N.addEventListener("cancel",(i)=>{i.preventDefault(),i.stopPropagation(),yi(!1)}),N.addEventListener("keydown",(i)=>{if(i.key==="Escape")i.preventDefault(),i.stopPropagation(),yi(!1)}),xi=new ResizeObserver(()=>{Xi(),ro()}),xi.observe(Vo),xi.observe(N),ei)xi.observe(ei);let Jo=e.querySelector(".inspection-content");if(Jo)xi.observe(Jo);let $o=e.querySelector(".repair-context");if($o)xi.observe($o);let Ko=I?.querySelector(".compare-toolbar");if(Ko)xi.observe(Ko);Xi();let Ei=Array.from(e.querySelectorAll(".pan-viewport"));if(Ei.forEach((i)=>{i.scrollLeft=Io,i.scrollTop=Ro}),Ei.forEach((i)=>{i.querySelectorAll("img").forEach((r)=>r.draggable=!1),i.addEventListener("click",()=>{if(!H)yi(!0)}),i.addEventListener("pointermove",(r)=>{if(r.pointerType!=="mouse"||r.buttons||!i.classList.contains("pannable"))return;let t=i.getBoundingClientRect();i.scrollLeft=no(r.clientX,t.left,i.clientWidth,i.scrollWidth),i.scrollTop=no(r.clientY,t.top,i.clientHeight,i.scrollHeight)}),i.addEventListener("keydown",(r)=>{if(!H&&(r.key==="Enter"||r.key===" ")){r.preventDefault(),r.stopPropagation(),yi(!0);return}let h={ArrowLeft:[-48,0],ArrowRight:[48,0],ArrowUp:[0,-48],ArrowDown:[0,48]}[r.key];if(!h)return;r.preventDefault(),r.stopPropagation(),i.scrollLeft+=h[0],i.scrollTop+=h[1]})}),Ei.forEach((i)=>i.addEventListener("scroll",()=>{for(let r of Ei)if(r!==i){if(r.scrollLeft!==i.scrollLeft)r.scrollLeft=i.scrollLeft;if(r.scrollTop!==i.scrollTop)r.scrollTop=i.scrollTop}})),Ii&&window.matchMedia("(max-width:800px)").matches){let i=e.querySelector(".inspection-content"),r=e.querySelector(".compare");if(i&&r)i.scrollTop+=r.getBoundingClientRect().top-i.getBoundingClientRect().top}if(ro(),window.scrollTo(q,_),!z)x.onDraftChange?.(structuredClone(n))}return w(),{destroy(){xi?.disconnect(),e.replaceChildren()},getDraft(){return structuredClone(n)}}}async function er(){let a=document.getElementById("review"),o=await fetch("/packet",{cache:"no-store"});if(!o.ok)throw Error("The review packet could not be loaded. Reload to retry.");let x=await o.json();if(x.sourceStatus){let e=document.createElement("p");e.textContent=x.sourceStatus,a.before(e)}Lo(a,x.packet,{initialDraft:x.draft,history:x.history,completed:!!x.receipt,onSubmit:async(e)=>{let n=await fetch("/decision",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)}),p=await n.json();if(!n.ok)throw Error(p.error??"The review could not be saved. Try again.")}})}er().catch((a)=>{let o=document.createElement("p");o.textContent=a instanceof Error?a.message:String(a),document.getElementById("review")?.replaceChildren(o)});})();
+ ${!p?`<section class="inventory-section ${en?"":"tray-collapsed"} ${W&&en?"tray-expanded":""}" aria-label="Component inventory"><div class="section-head"><h2>Components</h2><div class="inventory-filters ks-instrument-strip is-paper" data-ks-strip="filter" role="group" aria-label="Filter components"><button type="button" class="ks-instrument-key" data-filter="pending" aria-pressed="${b==="pending"}">To review <b>${ti}</b></button><button type="button" class="ks-instrument-key" data-filter="reviewed" aria-pressed="${b==="reviewed"}">Reviewed <b>${Re}</b></button><button type="button" class="ks-instrument-key" data-filter="all" aria-pressed="${b==="all"}">All <b>${F.length+t.missing.length}</b></button></div><div class="tray-actions"><button id="show-all" class="ks-icon-button" aria-pressed="${W}" aria-controls="component-tray" aria-label="${W?"Compact":"Expand"} tray" title="${W?"Compact":"Expand"} tray">${mn(W?"compact":"expand")}</button><button id="toggle-tray" class="ks-icon-button" aria-expanded="${en}" aria-controls="component-tray" aria-label="${en?"Hide":"Show"} component tray" title="${en?"Hide":"Show"} component tray">${mn(en?"hideTray":"showTray")}</button></div></div>
+ <div id="component-tray" class="inventory ${W?"all":""}">${pe.map((i)=>{let d=F.find((cn)=>cn.members.some((gn)=>gn.id===i.id)),j=F.indexOf(d),E={kind:d.kind,label:d.stateLabel};return`<button class="item ${E.kind} ${!f&&tn?.id===d.id?"active":""}" data-select="${T(i.id)}" aria-pressed="${!f&&tn?.id===d.id}">${i.thumbnail?`<span class="item-thumb">${i.thumbnail.box?`<span class="thumb-crop" style="width:min(100%,${76*i.thumbnail.box.w*n.comp.width/(i.thumbnail.box.h*n.comp.height)}px);aspect-ratio:${i.thumbnail.box.w*n.comp.width}/${i.thumbnail.box.h*n.comp.height}"><img alt="" loading="lazy" src="${Mn(i.thumbnail.url)}" style="position:absolute;width:${100/i.thumbnail.box.w}%;max-width:none;left:${-100*i.thumbnail.box.x/i.thumbnail.box.w}%;top:${-100*i.thumbnail.box.y/i.thumbnail.box.h}%;"></span>`:`<img alt="" loading="lazy" src="${Mn(i.thumbnail.url)}">`}</span>`:""}<span class="item-number">${E.kind==="approved"?Zn:E.kind==="feedback"?on:""}${j+1}<span class="item-medium">${mn(Fn(i).code?"code":"image")}${T(Fn(i).label)}</span></span><strong>${T(Fe(i.id))}${d.members.length>1?` <small>×${d.members.length}</small>`:""}</strong><span class="state ${E.kind}">${T(E.label)}</span></button>`}).join("")}${(b==="pending"?[]:t.missing).map((i,d)=>`<button class="item feedback ${g===i.id?"active":""}" data-select="${T(i.id)}"><span class="item-number">${F.length+d+1}</span><strong>${T(i.name)}</strong><span class="state revise">Missing</span></button>`).join("")}${!pe.length&&(b==="pending"||!t.missing.length)?`<p class="inventory-empty">${b==="pending"?"Nothing left to review. Your decisions are ready.":"No components reviewed yet."}</p>`:""}</div></section>`:""}
+ ${p?"":w?`<footer class="record-footer"><span>Round ${n.round} submitted · read-only</span><span>${x.approved} approved · ${x.revisions} changes requested</span></footer>`:`<footer class="${!x.pending&&!s?"queue-complete":""}"><div>${!x.pending&&!s?`<button id="show-summary" class="completion-link">${Zn}${w?"Review sent":"All components reviewed"}</button>`:""}<button id="approve-rest" class="ks-button ks-button-secondary" ${!x.pending?"hidden":""} ${!x.pending||s?"disabled":""}>Approve ${x.approved||x.revisions?"remaining":"all"}</button><label class="check ks-checkbox"><input id="inventory-confirm" type="checkbox" ${t.inventoryConfirmed?"checked":""}> Nothing missing from the comp</label></div><div class="submit-area"><p role="status">${T(Pe)}</p><button id="submit" class="ks-button ks-button-primary" ${!x.canSubmit||s||v||w?"disabled":""}>${v?"Sending…":w?"Review sent":x.hasFeedback?"Send feedback":"Approve & continue"}${v||w?"":Bn}</button></div></footer>`}
+ </section><dialog id="comparison-dialog" aria-label="${p?"Enlarged page comparison":"Enlarged component comparison"}"></dialog>`;let sn=a.querySelector("#comparison-dialog"),un=a.querySelector(".comparison-panel"),Kn=a.querySelector(".comparison-slot"),En=a.querySelector(".inspector > .review-form"),nr=a.querySelector(".inspector"),xe=()=>{if(sn.append(un),En)sn.append(En)};if(U&&un&&Kn)Kn.style.height=`${Qi}px`,xe(),sn.showModal();if(N)a.querySelectorAll(".decisions button,#feedback,#split,#save-feedback,#cancel-feedback,#undo-decision,#approve-rest,#submit,#inventory-confirm").forEach((i)=>i.disabled=!0);if(a.querySelector(".inspection-content").scrollTop=$i,w||v)a.querySelectorAll(".decisions button,#save-feedback,#cancel-feedback,#undo-decision,#approve-rest,#mark,#inventory-confirm,#missing-name,#missing-feedback,#feedback,#split,#remove-missing,[data-coordinate]").forEach((i)=>i.disabled=!0);let he=a.querySelector(".inventory");if(he)he.scrollLeft=Gn;if(!P&&en)Array.from(a.querySelectorAll(".inventory [data-select]")).find((i)=>i.dataset.select===g)?.scrollIntoView({block:"nearest",inline:"nearest"});if(J)a.getElementById(J)?.focus({preventScroll:!0});else if(_)Array.from(a.querySelectorAll(".item[data-select]")).find((i)=>i.dataset.select===_)?.focus({preventScroll:!0});let B=(i,d)=>a.querySelector(`#${i}`)?.addEventListener("click",d);function _i(i,d=!1,j=!1){if(z)return;if(!j)i=F.find((E)=>E.members.some((cn)=>cn.id===i))?.representative.id??i;if(Z=!j,f=!1,g=i,I="component",xn=!1,ln="fit",qn="isolated",C=!1,G(),d)a.querySelector("#expand-comparison")?.click()}a.querySelectorAll("[data-select]").forEach((i)=>i.onclick=()=>_i(i.dataset.select,i.classList.contains("pin")&&n.components.some((d)=>d.id===i.dataset.select))),B("previous-round",()=>{C=!0,G()}),B("current-round",()=>{C=!1,G()}),B("review-changes",()=>{let i=y().filter((E)=>Ui(E).kind==="pending"),d=i.findIndex((E)=>E.id===g),j=i[(d+1)%i.length];if(j)Z=!0,f=!1,g=j.id,I="component",b="pending",C=!1,ln="fit",xn=!1,qn="isolated",G()}),a.querySelectorAll("[data-filter]").forEach((i)=>i.onclick=()=>{b=i.dataset.filter,f=!x.pending&&b==="pending";let d=F.filter((E)=>b==="all"||E.kind==="pending"===(b==="pending")).map((E)=>E.representative);if(!(b!=="pending"&&t.missing.some((E)=>E.id===g))&&!d.some((E)=>E.id===g)&&d.length)Z=!0,g=d[0].id,I="component",C=!1,ln="fit",xn=!1,qn="isolated";G()}),B("show-summary",()=>{f=!0,I="component",b="reviewed",G(),Jn("review-summary")}),B("approve",()=>On("approve")),B("revise",di),B("clear",()=>{if($)delete t.decisions[$.id],delete u[$.id];Q=null,f=!1,b="pending",G()}),B("cancel-feedback",()=>{if($)delete u[$.id];if(Tn)en=!0,Tn=!1;G(),Jn("revise")}),a.querySelector("#feedback-form")?.addEventListener("submit",(i)=>{i.preventDefault(),On("revise")}),a.querySelector("#feedback")?.addEventListener("keydown",(i)=>{let d=i;if(d.key==="Enter"&&(d.metaKey||d.ctrlKey)&&!d.isComposing)d.preventDefault(),d.stopPropagation(),On("revise")}),B("undo-decision",()=>{if(!Q||v||w)return;let i=Q;for(let[d,j]of Object.entries(i.previous))if(j)t.decisions[d]=j;else delete t.decisions[d];delete u[i.id],g=i.id,f=!1,C=!1,I="component",b="all",Q=null,G(),Jn("approve")}),B("all-instances",()=>{Z=!0,g=tn.representative.id,C=!1,G()}),a.querySelectorAll("[data-instance]").forEach((i)=>i.onclick=()=>_i(i.dataset.instance,!1,!0)),B("overlay",()=>{xn=!xn,G()}),B("isolated",()=>{qn="isolated",G()}),B("context",()=>{qn="context",G()}),a.querySelectorAll("[data-zoom]").forEach((i)=>i.addEventListener("click",()=>{let d=i.dataset.zoom;ln=d==="fit"?"fit":Number(d),G()})),B("background-checker",()=>{Xn="checker",G()}),B("background-page",()=>{Xn="page",G()}),B("show-all",()=>{W=!W,en=!0,G()}),B("toggle-tray",()=>{Tn=!1,en=!en,G()}),B("show-comp",()=>{I="comp",G()}),B("show-component",()=>{I="component",G()}),B("mark",()=>{z=!z,G()}),B("add-box",()=>ei({x:0.35,y:0.35,w:0.2,h:0.2})),B("remove-missing",()=>{t.missing=t.missing.filter((i)=>i.id!==g),g=n.components[0]?.id,G()}),B("approve-rest",()=>{if(s)return;t=we(n,t),Q=null,f=!0,b="reviewed",I="component",G(),Jn("review-summary")}),a.querySelector("#inventory-confirm")?.addEventListener("change",(i)=>{t.inventoryConfirmed=i.target.checked,G()}),a.querySelector("#feedback")?.addEventListener("input",(i)=>{if($&&u[$.id])u[$.id].feedback=i.target.value}),a.querySelector("#split")?.addEventListener("change",(i)=>{if($&&u[$.id])u[$.id].split=i.target.checked}),a.querySelector("#missing-name")?.addEventListener("input",(i)=>{if(D)D.name=i.target.value;let d=a.querySelector("#submit");if(d)d.disabled=s||v||w||!Cn(n,t).canSubmit}),a.querySelector("#missing-feedback")?.addEventListener("input",(i)=>{if(D)D.feedback=i.target.value}),a.querySelectorAll("[data-coordinate]").forEach((i)=>i.addEventListener("change",()=>{if(!D)return;let d=i.dataset.coordinate,j=Number(i.value)/100;if(Number.isFinite(j))D.box[d]=Math.max(d==="w"||d==="h"?0.001:0,Math.min(1,j));D.box.w=Math.min(D.box.w,1-D.box.x),D.box.h=Math.min(D.box.h,1-D.box.y),G()})),B("submit",()=>{$n()});let wn=a.querySelector(".map");function Ki(i){let d=wn.getBoundingClientRect();return{x:Math.max(0,Math.min(1,(i.clientX-d.left)/d.width)),y:Math.max(0,Math.min(1,(i.clientY-d.top)/d.height))}}function ke(i){let d=Ki(i);return n.components.filter(({box:j})=>d.x>=j.x&&d.x<=j.x+j.w&&d.y>=j.y&&d.y<=j.y+j.h).sort((j,E)=>j.box.w*j.box.h-E.box.w*E.box.h)[0]}wn?.addEventListener("click",(i)=>{if(z||i.target.closest("[data-select]"))return;let d=ke(i);if(d)_i(d.id,!0)}),wn?.addEventListener("pointermove",(i)=>{if(!z)wn.style.cursor=ke(i)?"zoom-in":""}),wn?.addEventListener("pointerdown",(i)=>{if(!z)return;L=Ki(i),wn.setPointerCapture(i.pointerId),i.preventDefault()}),wn?.addEventListener("pointermove",(i)=>{if(!L)return;let d=Ki(i);hn={x:Math.min(L.x,d.x),y:Math.min(L.y,d.y),w:Math.abs(d.x-L.x),h:Math.abs(d.y-L.y)};let j=a.querySelector(".draw-box");j.hidden=!1,j.style.cssText=In(hn)}),wn?.addEventListener("pointerup",()=>{if(hn&&hn.w>0.01&&hn.h>0.01)ei(hn);else L=null,hn=null}),wn?.addEventListener("pointercancel",()=>{L=null,hn=null,G()});let ge=a.querySelector(".output"),gi=a.querySelector("iframe"),ve=a.querySelector(".workbench"),Dn=a.querySelector(".inspection-content"),Bi=a.querySelector(".inspector");function Hi(){if(!Dn||!Bi)return;Bi.dataset.scrollAbove=String(Dn.scrollTop>1),Bi.dataset.scrollBelow=String(Dn.scrollHeight-Dn.clientHeight-Dn.scrollTop>1)}Dn?.addEventListener("scroll",Hi,{passive:!0});function vi(){let i=a.querySelector(".map-space");if(i&&i.clientWidth&&i.clientHeight){let K=Ii(n.comp.width,n.comp.height,Math.max(1,i.clientWidth-32),Math.max(1,i.clientHeight-32),"fit");wn.style.width=`${K.width}px`,wn.style.height=`${K.height}px`}let d=a.querySelector(".inspection-content"),j=Array.from(a.querySelectorAll(".pan-viewport"));if(d?.clientHeight){let K=U?Math.max(100,sn.clientHeight-(un?.querySelector(".compare-toolbar")?.clientHeight??0)-(un?.querySelector(".expanded-title")?.clientHeight??0)-(un?.querySelector(".view-controls")?.clientHeight??0)-(En?.getBoundingClientRect().height??0)-124):Math.min(p?Number.POSITIVE_INFINITY:248,Math.max(100,d.clientHeight-((j[0]?.getBoundingClientRect().top??d.getBoundingClientRect().top)-d.getBoundingClientRect().top+d.scrollTop)-(un?.querySelector(".view-controls")?.clientHeight??0)-12));j.forEach((S)=>S.style.height=`${K}px`)}if(q&&j.length&&!kn){let K=Ii(q.box.w*pn.comp.width,q.box.h*pn.comp.height,Math.min(...j.map((S)=>S.clientWidth)),Math.min(...j.map((S)=>S.clientHeight)),ln);a.querySelectorAll(".crop-stage").forEach((S)=>{S.style.width=`${K.width}px`,S.style.height=`${K.height}px`})}if(j.forEach((K)=>{let S=K.scrollWidth>K.clientWidth+1||K.scrollHeight>K.clientHeight+1;K.classList.toggle("pannable",S),K.style.cursor=U?"":"zoom-in",K.setAttribute("role",U?"region":"button"),K.title=U?S?"Move your pointer to pan. You can also scroll, swipe, or use arrow keys.":"":"Click to enlarge comparison"}),ge&&gi&&q){let K=ge.clientWidth/(q.box.w*pn.comp.width);gi.style.transform=`scale(${K})`,gi.style.left=`${-q.box.x*pn.comp.width*K}px`,gi.style.top=`${-q.box.y*pn.comp.height*K}px`}let E=ve.getBoundingClientRect(),cn=a.querySelector(".region"),gn=a.querySelector(".number"),ci=a.querySelector(".connector path");if(cn&&gn&&ci){let K=cn.getBoundingClientRect(),S=gn.getBoundingClientRect(),bi=K.right-E.left,nn=K.top+K.height/2-E.top,si=S.left-E.left-8,fi=S.top+S.height/2-E.top;ci.setAttribute("d",`M ${bi} ${nn} H ${si-14} V ${fi} H ${si}`)}}function Rn(i,d){if(!un||!Kn||i===U)return;let j=a.querySelector("#expand-comparison"),E=(U?sn:un).getBoundingClientRect(),cn=window.matchMedia("(prefers-reduced-motion: reduce)").matches,gn=un.querySelector(".pan-viewport"),ci=gn?gn.scrollLeft/Math.max(1,gn.scrollWidth-gn.clientWidth):0,K=gn?gn.scrollTop/Math.max(1,gn.scrollHeight-gn.clientHeight):0,S=()=>un.querySelectorAll(".pan-viewport").forEach((nn)=>{nn.scrollLeft=ci*Math.max(0,nn.scrollWidth-nn.clientWidth),nn.scrollTop=K*Math.max(0,nn.scrollHeight-nn.clientHeight)}),bi=()=>{if(Kn.append(un),En)nr.append(En),En.inert=!1;sn.close(),Kn.style.height="",Qn=!1,U=!1,j.innerHTML=mn("expand"),j.setAttribute("aria-label","Enlarge comparison"),j.title="Enlarge comparison",j.setAttribute("aria-expanded","false"),vi(),S(),j.focus({preventScroll:!0}),d?.()};if(i){Kn.style.height=`${E.height}px`,xe(),sn.showModal(),U=!0,j.innerHTML=mn("compact"),j.setAttribute("aria-label","Restore comparison"),j.title="Restore comparison (Esc)",j.setAttribute("aria-expanded","true"),vi(),S(),j.focus({preventScroll:!0});let nn=sn.getBoundingClientRect();if(!cn)sn.animate([{transform:`translate(${E.x-nn.x}px,${E.y-nn.y}px) scale(${E.width/nn.width},${E.height/nn.height})`,opacity:0.6},{transform:"none",opacity:1}],{duration:240,easing:"cubic-bezier(.2,.8,.2,1)"})}else{if(j.disabled)return;let nn=Kn.getBoundingClientRect();if(cn){bi();return}if(j.disabled=!0,Qn=!0,En)En.inert=!0;let si=sn.animate([{transform:"none",opacity:1},{transform:`translate(${nn.x-E.x}px,${nn.y-E.y}px) scale(${nn.width/E.width},${nn.height/E.height})`,opacity:0.6}],{duration:200,easing:"cubic-bezier(.4,0,.2,1)",fill:"forwards"});sn.inert=!0;let fi=()=>{if(si.cancel(),j.disabled=!1,sn.inert=!1,sn.isConnected)bi();else Qn=!1,U=!1,G(),d?.()};si.finished.then(fi,fi)}}if(Yn=(i)=>Rn(!1,i),B("expand-comparison",()=>Rn(!U)),sn.addEventListener("cancel",(i)=>{i.preventDefault(),i.stopPropagation(),Rn(!1)}),sn.addEventListener("keydown",(i)=>{if(i.key==="Escape")i.preventDefault(),i.stopPropagation(),Rn(!1)}),ni=Yi(a),an=new ResizeObserver(()=>{vi(),Hi()}),an.observe(ve),an.observe(sn),En)an.observe(En);let ue=a.querySelector(".inspection-content");if(ue)an.observe(ue);let ce=a.querySelector(".repair-context");if(ce)an.observe(ce);let be=un?.querySelector(".compare-toolbar");if(be)an.observe(be);vi();let ui=Array.from(a.querySelectorAll(".pan-viewport"));if(ui.forEach((i)=>{i.scrollLeft=A,i.scrollTop=ki}),ui.forEach((i)=>{i.querySelectorAll("img").forEach((d)=>d.draggable=!1),i.addEventListener("click",()=>{if(!U)Rn(!0)}),i.addEventListener("pointermove",(d)=>{if(d.pointerType!=="mouse"||d.buttons||!i.classList.contains("pannable"))return;let j=i.getBoundingClientRect();i.scrollLeft=Oi(d.clientX,j.left,i.clientWidth,i.scrollWidth),i.scrollTop=Oi(d.clientY,j.top,i.clientHeight,i.scrollHeight)}),i.addEventListener("keydown",(d)=>{if(!U&&(d.key==="Enter"||d.key===" ")){d.preventDefault(),d.stopPropagation(),Rn(!0);return}let E={ArrowLeft:[-48,0],ArrowRight:[48,0],ArrowUp:[0,-48],ArrowDown:[0,48]}[d.key];if(!E)return;d.preventDefault(),d.stopPropagation(),i.scrollLeft+=E[0],i.scrollTop+=E[1]})}),ui.forEach((i)=>i.addEventListener("scroll",()=>{for(let d of ui)if(d!==i){if(d.scrollLeft!==i.scrollLeft)d.scrollLeft=i.scrollLeft;if(d.scrollTop!==i.scrollTop)d.scrollTop=i.scrollTop}})),ri&&window.matchMedia("(max-width:800px)").matches){let i=a.querySelector(".inspection-content"),d=a.querySelector(".compare");if(i&&d)i.scrollTop+=d.getBoundingClientRect().top-i.getBoundingClientRect().top}if(Hi(),window.scrollTo(H,R),!w)o.onDraftChange?.(structuredClone(t))}return G(),{destroy(){an?.disconnect(),ni?.(),a.replaceChildren()},getDraft(){return structuredClone(t)}}}function or(){let e=document.createElement("style");e.textContent=[["Albert Sans","albertsans"],["Alumni Sans","alumnisans"],["JetBrains Mono","jetbrainsmono"]].map(([n,o])=>`@font-face{font-family:"${n}";src:url(/fonts/${o}.ttf);font-weight:100 900}`).join(""),document.head.append(e)}function tr(e){let n=document.createElement("div");n.setAttribute("role","alert"),n.style.cssText="max-width:560px;margin:18vh auto 0;padding:0 0 0 18px;border-left:2px solid oklch(52% 0.16 35);color:oklch(22% 0 0);font:400 15px/1.55 var(--font-sans,Arial,sans-serif)";let o=document.createElement("p");o.textContent="Review unavailable",o.style.cssText="margin:0 0 8px;font:400 11px/1.3 var(--font-mono,monospace);letter-spacing:.14em;text-transform:uppercase;color:oklch(46% 0 0)";let a=document.createElement("strong");a.textContent="The review could not be opened.",a.style.cssText="display:block;font-weight:500;color:oklch(13% 0 0)";let t=document.createElement("p");t.style.cssText="margin:4px 0 18px;color:oklch(46% 0 0)",t.textContent=`${e} If the review server stopped, ask the agent to serve the review again, then reload.`;let p=document.createElement("button");return p.textContent="Reload",p.style.cssText="font:500 15px/1 var(--font-sans,Arial,sans-serif);min-height:44px;padding:0 22px;border:1px solid oklch(13% 0 0);border-radius:3px;background:oklch(13% 0 0);color:oklch(99.5% 0 0);cursor:pointer",p.onclick=()=>location.reload(),n.append(o,a,t,p),n}async function sr(){or(),document.body.style.background="oklch(97.8% 0 0)";let e=document.getElementById("review"),n=await fetch("/packet",{cache:"no-store"});if(!n.ok)throw Error("The review packet could not be loaded.");let o=await n.json(),a=Mi(o.packet);if(o.sourceStatus&&!a){let t=document.createElement("p");t.textContent=o.sourceStatus,e.before(t)}De(e,o.packet,{initialDraft:o.draft,history:o.history,completed:!!o.receipt,status:a?o.sourceStatus:null,onSubmit:async(t)=>{let p=await fetch("/decision",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)}),y=await p.json().catch(()=>({}));if(!p.ok)throw Error(y.error??"The review could not be saved. Try again.")}})}sr().catch((e)=>{document.getElementById("review")?.replaceChildren(tr(e instanceof Error?e.message:String(e)))});})();
diff --git a/crates/context/src/component_review/capture.rs b/crates/context/src/component_review/capture.rs
index 3a29934e9..d14516de5 100644
--- a/crates/context/src/component_review/capture.rs
+++ b/crates/context/src/component_review/capture.rs
@@ -14,3 +14,52 @@ pub trait ComponentCapturer {
inputs: &BTreeMap<String, Vec<u8>>,
) -> Result<CapturedPreviews, String>;
}
+
+pub const NATIVE_SCHEMA: &str = "native-component-previews-v1";
+pub const PLAN_SCHEMA: &str = "plan-review-proof-v1";
+/// The evidence schema a packet must carry: the plan review is proven without a browser.
+pub fn schema_for(packet: &Value) -> &'static str {
+ if packet["schemaVersion"] == 3 { PLAN_SCHEMA } else { NATIVE_SCHEMA }
+}
+pub fn verified(state: &Value) -> bool {
+ state["capture"]["schema"] == schema_for(&state["packet"])
+}
+
+/// Proof for the plan and asset review: raster assets are their pinned source
+/// bytes, plan items are a box on the pinned comp. No browser, no rendering.
+pub struct PlanCapturer;
+impl ComponentCapturer for PlanCapturer {
+ fn capture(&mut self, packet: &mut Value, inputs: &BTreeMap<String, Vec<u8>>) -> Result<CapturedPreviews, String> {
+ use super::manifest::digest;
+ use serde_json::json;
+ if packet["schemaVersion"] != 3 {
+ return Err("the plan capturer only proves schemaVersion 3 packets".into());
+ }
+ let source = |view: &Value| -> Result<String, String> {
+ view["url"].as_str().and_then(|u| u.strip_prefix("/files/")).map(String::from).ok_or_else(|| "preview is not pinned".into())
+ };
+ let comp_path = source(&packet["comp"])?;
+ let comp = inputs.get(&comp_path).ok_or("missing approved reference")?;
+ if impeccable_comp::png_io::is_png(comp) && comp.len() >= 24
+ && (u64::from(u32::from_be_bytes(comp[16..20].try_into().unwrap())) != packet["comp"]["width"].as_u64().unwrap_or(0)
+ || u64::from(u32::from_be_bytes(comp[20..24].try_into().unwrap())) != packet["comp"]["height"].as_u64().unwrap_or(0))
+ {
+ return Err("comp dimensions do not match its image".into());
+ }
+ let comp_hash = digest(comp);
+ let mut evidence = Vec::new();
+ for c in packet["components"].as_array_mut().ok_or("missing components")? {
+ let proof = if c["preview"]["kind"] == "comp-crop" {
+ json!({"kind":"comp-crop","compPath":comp_path,"compSha256":comp_hash,"box":c["box"]})
+ } else {
+ let path = source(&c["preview"])?;
+ let bytes = inputs.get(&path).ok_or("missing raster source")?;
+ c["thumbnail"] = json!({"url":c["preview"]["url"]});
+ json!({"kind":"raster-source","path":path,"sha256":digest(bytes)})
+ };
+ evidence.push(json!({"id":c["id"],"views":{"preview":proof}}));
+ }
+ Ok(CapturedPreviews { files: BTreeMap::new(), evidence: json!({"schema":PLAN_SCHEMA,"components":evidence,
+ "scope":"Pinned raster sources and comp-crop geometry. No browser capture; no visual, semantic or human-identity approval."}) })
+ }
+}
diff --git a/crates/context/src/component_review/history.rs b/crates/context/src/component_review/history.rs
index a747e6d1f..3fbf89432 100644
--- a/crates/context/src/component_review/history.rs
+++ b/crates/context/src/component_review/history.rs
@@ -91,8 +91,12 @@ pub fn between(previous: &Value, current: &Value) -> Value {
json!({"kind":"added","files":[],"reasons":[]})
};
change["carried"] = json!(current["draft"]["decisions"][id]["action"] == "approve");
- let decision = &previous["draft"]["decisions"][id];
- if decision["action"] == "revise" && !previous["receipt"].is_null() {
+ // A code region reclassified last round comes back as a component under the same id.
+ let listed = previous["draft"]["reclassify"].as_array()
+ .and_then(|all| all.iter().find(|r| r["id"] == id))
+ .map(|r| json!({"action":"reclassify","kind":r["kind"],"feedback":r["feedback"].as_str().unwrap_or("")}));
+ let decision = listed.as_ref().unwrap_or(&previous["draft"]["decisions"][id]);
+ if matches!(decision["action"].as_str(), Some("revise" | "reclassify")) && !previous["receipt"].is_null() {
feedback.insert(
id.into(),
json!({"round":previous["packet"]["round"],"decision":decision}),
diff --git a/crates/context/src/component_review/lifecycle.rs b/crates/context/src/component_review/lifecycle.rs
index 40880e1e8..b77dcb464 100644
--- a/crates/context/src/component_review/lifecycle.rs
+++ b/crates/context/src/component_review/lifecycle.rs
@@ -5,7 +5,7 @@ use serde_json::{json, Value};
use std::path::{Path, PathBuf};
pub fn accepted(state: &Value) -> bool {
- state["capture"]["schema"] == "native-component-previews-v1"
+ super::capture::verified(state)
&& state["receipt"]["captureVerified"] == true
&& state["receipt"]["visualDecision"] == "approved"
&& state["packet"]["revision"].is_string()
@@ -20,7 +20,7 @@ pub fn closed(state: &Value) -> bool {
}
/// Stored flags are claims; acceptance also needs the session's capture to be intact.
-fn accepted_in(dir: &Path, state: &Value) -> bool {
+pub(crate) fn accepted_in(dir: &Path, state: &Value) -> bool {
accepted(state) && super::verify::capture_intact(dir, state).is_ok()
}
diff --git a/crates/context/src/component_review/manifest.rs b/crates/context/src/component_review/manifest.rs
index f4244cf3a..d6534da7d 100644
--- a/crates/context/src/component_review/manifest.rs
+++ b/crates/context/src/component_review/manifest.rs
@@ -85,11 +85,18 @@ fn view(
pub fn freeze(project: &Path, input: &Value) -> Result<(Value, BTreeMap<String, Vec<u8>>), String> {
let canonical = project.canonicalize().map_err(|e| e.to_string())?;
let project = canonical.as_path();
- if !matches!(input["schemaVersion"].as_u64(), Some(1 | 2)) {
- return Err("manifest schemaVersion must be 1 or 2".into());
+ let v3 = input["schemaVersion"] == 3;
+ if !matches!(input["schemaVersion"].as_u64(), Some(1..=3)) {
+ return Err("manifest schemaVersion must be 1, 2 or 3".into());
}
- if input["schemaVersion"] == 2 && !matches!(input["stage"].as_str(), Some("components" | "hero")) {
- return Err("schemaVersion 2 requires stage components or hero".into());
+ if input["schemaVersion"] == 2 && input["stage"] == "components" {
+ return Err("schemaVersion 2 component manifests are retired. Run impeccable component-review plan to write the plan and asset review (schemaVersion 3) from the measured spec.".into());
+ }
+ if input["schemaVersion"] == 2 && input["stage"] != "hero" {
+ return Err("schemaVersion 2 requires stage hero".into());
+ }
+ if v3 && input["stage"] != "components" {
+ return Err("schemaVersion 3 requires stage components".into());
}
let mut packet = input.clone();
for key in ["capture", "captureVerified"] {
@@ -124,13 +131,35 @@ pub fn freeze(project: &Path, input: &Value) -> Result<(Value, BTreeMap<String,
// These checks are independent. Report the complete inventory repair in
// one response before any browser work, without publishing partial proof.
let mut errors = Vec::new();
- for region in &measured_regions {
- match input["components"].as_array().and_then(|items| items.iter().find(|c| c["id"] == region["id"])) {
- None => errors.push(format!("component review omitted measured region {}", region["id"])),
- Some(component) if matches!(region["kind"].as_str(), Some("text" | "control")) && component["preview"]["kind"] != "page" => {
- errors.push(format!("semantic region {} requires a rendered code preview", region["id"]));
+ if v3 {
+ if input["specSha256"].as_str() != Some(digest(&files[spec_path]).as_str()) {
+ return Err("spec.json changed since this packet was written; run impeccable component-review plan again".into());
+ }
+ let listed = |key: &str| input[key].as_array().into_iter().flatten().filter_map(|c| c["id"].as_str()).map(String::from).collect::<Vec<_>>();
+ let (components, code) = (listed("components"), listed("codeRegions"));
+ let measured: BTreeSet<&str> = measured_regions.iter().filter_map(|r| r["id"].as_str()).collect();
+ for region in &measured {
+ if !components.iter().chain(&code).any(|id| id == region) {
+ errors.push(format!("plan review omitted measured region {region:?}; list it as a component or in codeRegions"));
+ }
+ }
+ let mut seen = BTreeSet::new();
+ for id in components.iter().chain(&code) {
+ if !measured.contains(id.as_str()) {
+ errors.push(format!("plan review lists {id:?}, which is not a measured region"));
+ } else if !seen.insert(id) {
+ errors.push(format!("plan review lists {id:?} twice"));
+ }
+ }
+ } else {
+ for region in &measured_regions {
+ match input["components"].as_array().and_then(|items| items.iter().find(|c| c["id"] == region["id"])) {
+ None => errors.push(format!("component review omitted measured region {}", region["id"])),
+ Some(component) if matches!(region["kind"].as_str(), Some("text" | "control")) && component["preview"]["kind"] != "page" => {
+ errors.push(format!("semantic region {} requires a rendered code preview", region["id"]));
+ }
+ _ => {}
}
- _ => {}
}
}
if !errors.is_empty() {
@@ -139,27 +168,12 @@ pub fn freeze(project: &Path, input: &Value) -> Result<(Value, BTreeMap<String,
}
view(&mut packet["comp"], project, &mut files, &mut comp_files)?;
- // Selector ownership is part of each shared document's input contract. A peer
- // target changing must invalidate captures that previously excluded it.
- let mut targets: BTreeMap<String, Vec<Value>> = BTreeMap::new();
- if input["schemaVersion"] == 2 && input["stage"] == "components" {
- for c in input["components"].as_array().ok_or("components must be an array")? {
- if c["preview"]["kind"] != "page" && c["preview"].get("selector").is_some() {
- return Err("only code previews can declare a selector; place raster DOM targets in context".into());
- }
- let target = if c["preview"]["kind"] == "page" { Some(&c["preview"]) }
- else if c["context"]["kind"] == "page" { Some(&c["context"]) } else { None };
- if let Some(target) = target {
- let selector = string(target, "selector")?;
- if selector.len() > 1024 { return Err("component selector too long".into()); }
- let path = string(target, "path")?;
- targets.entry(path.into()).or_default().push(json!({"id":c["id"],"selector":selector}));
- }
- }
- }
let mut groups: BTreeMap<String, String> = BTreeMap::new();
for c in input["components"].as_array().ok_or("components must be an array")? {
if let Some(group) = c.get("reviewGroup") {
+ if v3 {
+ return Err("reviewGroup is not used in the plan and asset review (schemaVersion 3)".into());
+ }
let name = group.as_str().filter(|s| !s.trim().is_empty() && s.len() <= 120)
.ok_or("reviewGroup needs a nonempty name of at most 120 bytes")?;
if input["stage"] != "components" || c["preview"]["kind"] != "page" {
@@ -178,10 +192,24 @@ pub fn freeze(project: &Path, input: &Value) -> Result<(Value, BTreeMap<String,
if let Some(group) = input["components"].as_array().and_then(|cs| cs.iter().find(|c| c["id"] == region["id"]))
.and_then(|c| c.get("reviewGroup")) { region["reviewGroup"] = group.clone(); }
}
- let group_issues = impeccable_comp::review_groups::issues(&measured_regions);
+ let group_issues = if v3 { vec![] } else { impeccable_comp::review_groups::issues(&measured_regions) };
if !group_issues.is_empty() {
return Err(group_issues.iter().map(|(id, message)| format!("component {id}: {message}")).collect::<Vec<_>>().join("\n"));
}
+ if v3 {
+ let code = packet["codeRegions"].as_array_mut().ok_or("codeRegions must be an array")?;
+ if code.len() > 400 {
+ return Err("codeRegions exceeds 400 entries".into());
+ }
+ for r in code {
+ let id = string(r, "id")?.to_string();
+ if !valid_box(&r["box"]) || !r["name"].is_string() || !r["note"].is_string() || !r["kind"].is_string() {
+ return Err(format!("code region {id:?} needs name, kind, note and a normalized box"));
+ }
+ }
+ } else if packet.get("codeRegions").is_some() || packet.get("specSha256").is_some() {
+ return Err("codeRegions and specSha256 belong to schemaVersion 3".into());
+ }
let mut ids = BTreeSet::new();
let components = packet["components"]
.as_array_mut()
@@ -214,7 +242,17 @@ pub fn freeze(project: &Path, input: &Value) -> Result<(Value, BTreeMap<String,
return Err(format!("component needs {k}"));
}
}
- if !matches!(c["preview"]["kind"].as_str(), Some("image" | "page")) {
+ if v3 {
+ let (role, kind) = (c["role"].as_str().unwrap_or(""), c["kind"].as_str().unwrap_or(""));
+ let ok = match role {
+ "asset" => matches!(kind, "plate" | "image" | "texture") && c["preview"]["kind"] == "image",
+ "plan" => matches!(kind, "text" | "control" | "chrome") && c["preview"] == json!({"kind":"comp-crop"}),
+ _ => false,
+ };
+ if !ok || c.get("context").is_some() || c.get("thumbnail").is_some() {
+ return Err(format!("component {id:?}: an asset is a plate, image or texture previewed by its image; a plan item is text, control or chrome previewed as {{\"kind\":\"comp-crop\"}}; neither carries context or thumbnail"));
+ }
+ } else if !matches!(c["preview"]["kind"].as_str(), Some("image" | "page")) {
return Err("preview kind must be image or page".into());
}
let deps = c["dependencies"]
@@ -226,6 +264,13 @@ pub fn freeze(project: &Path, input: &Value) -> Result<(Value, BTreeMap<String,
let p = dep.as_str().ok_or("dependency must be a path")?;
used.insert(p.into(), pin(project, p, &mut files)?);
}
+ if c["preview"]["kind"] == "comp-crop" {
+ // The UI crops the pinned comp; comp and spec hashes are already in `used`.
+ c.as_object_mut().unwrap().remove("material");
+ c.as_object_mut().unwrap().remove("revision");
+ c["revision"] = json!(digest(&serde_json::to_vec(&json!({"component":c,"files":used,"specSha256":input["specSha256"]})).unwrap()));
+ continue;
+ }
let preview_path = string(&c["preview"], "path")?.to_string();
view(&mut c["preview"], project, &mut files, &mut used)?;
c.as_object_mut().unwrap().remove("material");
@@ -257,11 +302,7 @@ pub fn freeze(project: &Path, input: &Value) -> Result<(Value, BTreeMap<String,
}
c.as_object_mut().unwrap().remove("revision");
let mut identity = json!({"component":c,"files":used});
- let target_path = if c["preview"]["kind"] == "page" { Some(preview_path.as_str()) }
- else { c["context"]["url"].as_str().and_then(|url| url.strip_prefix("/files/")) };
- if let Some(peers) = target_path.and_then(|path| targets.get(path)) {
- identity["targets"] = json!(peers);
- }
+ if v3 { identity["specSha256"] = input["specSha256"].clone(); }
c["revision"] = json!(digest(&serde_json::to_vec(&identity).unwrap()));
}
let total: usize = files.values().map(Vec::len).sum();
diff --git a/crates/context/src/component_review/mod.rs b/crates/context/src/component_review/mod.rs
index 4d7f8653f..99f8dccc3 100644
--- a/crates/context/src/component_review/mod.rs
+++ b/crates/context/src/component_review/mod.rs
@@ -3,6 +3,7 @@ pub mod capture;
mod history;
mod lifecycle;
mod manifest;
+pub mod plan;
mod server;
mod store;
#[cfg(test)]
@@ -67,6 +68,18 @@ pub fn run_with_capturer(
io.out(&format!("{}\n", lifecycle::inspect(&sessions, &required)?));
Ok(0)
}
+ Some("plan") => {
+ let out = arg(args, "--out").unwrap_or_else(|| plan::DEFAULT_OUT.into());
+ let packet = plan::write(&io.cwd, &out)?;
+ let components = packet["components"].as_array().unwrap();
+ let count = |role: &str| components.iter().filter(|c| c["role"] == role).count();
+ let flagged = components.iter().filter(|c| c["role"] == "plan" && (c["flags"].is_array() || c["codeDrawn"] == true)).count();
+ let flagged_assets = components.iter().filter(|c| c["role"] == "asset" && c["flags"].is_array()).count();
+ let s = io.env("IMPECCABLE_SELF").filter(|v| !v.trim().is_empty()).unwrap_or("impeccable").to_string();
+ io.out(&format!("PLAN {out}: {} assets{}, {} plan items ({flagged} flagged or code-drawn), {} code regions\nNEXT {s} component-review capture --manifest {out}, then {s} component-review serve --session <session from capture>\n",
+ count("asset"), if flagged_assets > 0 { format!(" ({flagged_assets} flagged)") } else { String::new() }, count("plan"), packet["codeRegions"].as_array().map_or(0, Vec::len)));
+ Ok(0)
+ }
Some("prepare") | Some("capture") => {
let path = arg(args, "--manifest")
.ok_or("prepare needs --manifest <project-relative file>")?;
@@ -76,7 +89,14 @@ pub fn run_with_capturer(
}
}
let project = io.cwd.canonicalize().map_err(|e| e.to_string())?;
- let renderer=if args[0]=="capture" {Some(capturer.take().ok_or("native component capturer unavailable")?)}else{None};
+ // The plan review is proven without a browser; only v1/v2 packets reach the native capturer.
+ let v3 = std::fs::read(project.join(manifest::relative(&path)?)).ok()
+ .and_then(|b| serde_json::from_slice::<serde_json::Value>(&b).ok())
+ .is_some_and(|m| m["schemaVersion"] == 3);
+ let mut plan_capturer = capture::PlanCapturer;
+ let renderer: Option<&mut dyn capture::ComponentCapturer> = if args[0] != "capture" { None }
+ else if v3 { Some(&mut plan_capturer) }
+ else { Some(capturer.take().ok_or("native component capturer unavailable")?) };
let dir=store::prepare_file(&store,&project,&path,renderer)?;
let state = store::read(&dir.join("current.json"))?;
let status = state["receipt"]["visualDecision"]
@@ -145,7 +165,7 @@ pub fn run_with_capturer(
Ok(0)
}
}
- _ => Err("usage: impeccable component-review prepare|capture|verify --manifest <file> | lifecycle [--session-dir <dir>] [--require components|hero] [--hosted] | serve --session <id> [--port 0] [--idle-timeout <seconds>] | status|refresh-approvals --session <id> [--store <outside-project-dir>]".into())
+ _ => Err("usage: impeccable component-review plan [--out .impeccable/review/components.json] | prepare|capture|verify --manifest <file> | lifecycle [--session-dir <dir>] [--require components|hero] [--hosted] | serve --session <id> [--port 0] [--idle-timeout <seconds>] | status|refresh-approvals --session <id> [--store <outside-project-dir>]".into())
}
})();
match result {
diff --git a/crates/context/src/component_review/plan.rs b/crates/context/src/component_review/plan.rs
new file mode 100644
index 000000000..84a6f5230
--- /dev/null
+++ b/crates/context/src/component_review/plan.rs
@@ -0,0 +1,253 @@
+//! The plan and asset review packet (schemaVersion 3) is derived from the measured
+//! spec, never authored: raster regions are reviewed as their plates, code regions
+//! that need a human decision are reviewed as comp crops, the rest are listed.
+use super::manifest::{digest, relative, valid_box};
+use serde_json::{json, Value};
+use std::path::Path;
+
+pub const SPEC: &str = ".impeccable/build/spec.json";
+pub const DEFAULT_OUT: &str = ".impeccable/review/components.json";
+
+fn raster(kind: &str) -> bool {
+ matches!(kind, "plate" | "image" | "texture")
+}
+fn flagged(region: &Value) -> bool {
+ region["flags"].as_array().is_some_and(|f| !f.is_empty()) || region["codeDrawn"] == true
+}
+/// A code region needs a decision when it is flagged, drawn in code, or
+/// non-container chrome that holds more than a bare ground or straight rules
+/// (comp-spec's `surface` reading; a spec without it keeps every such chrome).
+fn plan_item(region: &Value) -> bool {
+ let kind = region["kind"].as_str().unwrap_or("");
+ let plain = region["surface"]["flat"] == true || region["surface"]["rules"] == true;
+ matches!(kind, "text" | "control" | "chrome")
+ && (flagged(region) || (kind == "chrome" && region["container"] != true && !plain))
+}
+/// Whether a spec yields any component to decide on; without one there is nothing to review.
+pub fn needs_review(spec: &Value) -> bool {
+ spec["regions"].as_array().is_some_and(|rs| {
+ rs.iter().any(|r| raster(r["kind"].as_str().unwrap_or("")) || plan_item(r))
+ })
+}
+fn name(id: &str) -> String {
+ let words = id.replace(['-', '_'], " ");
+ let mut chars = words.trim().chars();
+ chars.next().map(|c| c.to_uppercase().chain(chars).collect()).unwrap_or_default()
+}
+/// Spec boxes are rounded to four places; keep the far edge inside the frame.
+fn clamp_box(b: &Value) -> Value {
+ if valid_box(b) {
+ return json!({"x":b["x"],"y":b["y"],"w":b["w"],"h":b["h"]});
+ }
+ let n = |k: &str| b[k].as_f64().unwrap_or(f64::NAN);
+ let (x, y) = (n("x").max(0.), n("y").max(0.));
+ json!({"x":x,"y":y,"w":n("w").min(1. - x),"h":n("h").min(1. - y)})
+}
+fn png_size(bytes: &[u8]) -> Option<(u64, u64)> {
+ (impeccable_comp::png_io::is_png(bytes) && bytes.len() >= 24).then(|| {
+ (u64::from(u32::from_be_bytes(bytes[16..20].try_into().unwrap())),
+ u64::from(u32::from_be_bytes(bytes[20..24].try_into().unwrap())))
+ })
+}
+/// A spec path as a project-relative, `/`-separated path. Comp-spec may record an
+/// absolute path (inside the project) or a Windows one; the project is matched as
+/// the caller spelled it and canonicalized (`\\?\` on Windows, `/private/tmp` on macOS).
+fn project_path(roots: &[&Path], value: &str) -> String {
+ fn slashes(p: &str) -> String {
+ let p = p.replace('\\', "/");
+ p.strip_prefix("//?/").map(String::from).unwrap_or(p)
+ }
+ let v = slashes(value);
+ let within = |root: &Path, v: &str| {
+ let root = slashes(&root.to_string_lossy());
+ let root = root.trim_end_matches('/');
+ (!root.is_empty()).then(|| v.strip_prefix(root)).flatten()
+ .and_then(|rest| rest.strip_prefix('/')).map(String::from)
+ };
+ if let Some(rest) = roots.iter().find_map(|root| within(root, &v)) {
+ return rest;
+ }
+ // An absolute path reached through a symlinked prefix of the project.
+ if Path::new(value).is_absolute() {
+ if let Ok(full) = Path::new(value).canonicalize() {
+ let full = slashes(&full.to_string_lossy());
+ if let Some(rest) = roots.iter().filter_map(|r| r.canonicalize().ok()).find_map(|root| within(&root, &full)) {
+ return rest;
+ }
+ }
+ }
+ v
+}
+
+/// Build the v3 manifest from the current spec, comp and plate files.
+pub fn build(cwd: &Path) -> Result<Value, String> {
+ let project = cwd.canonicalize().map_err(|e| e.to_string())?;
+ let roots = [cwd, project.as_path()];
+ let bytes = std::fs::read(project.join(SPEC))
+ .map_err(|_| format!("no measured spec at {SPEC}; run comp-spec --comp <png> --regions <json> first"))?;
+ let spec: Value = serde_json::from_slice(&bytes).map_err(|e| format!("{SPEC}: {e}"))?;
+ let regions = spec["regions"].as_array().ok_or("measured spec needs regions")?;
+ let state = super::store::read(&project.join(".impeccable/build/state.json")).unwrap_or(Value::Null);
+ let comp = spec["comp"].as_str().or_else(|| state["comp"].as_str()).filter(|s| !s.is_empty())
+ .ok_or("the spec names no comp; rerun comp-spec --comp <png> --regions <json>")?;
+ let comp = project_path(&roots, comp);
+ relative(&comp)?;
+ let (width, height) = match (spec["compSize"]["width"].as_u64(), spec["compSize"]["height"].as_u64()) {
+ (Some(w), Some(h)) => (w, h),
+ _ => png_size(&std::fs::read(project.join(&comp)).map_err(|e| format!("{comp}: {e}"))?)
+ .ok_or("the spec records no comp size and the comp is not a PNG")?,
+ };
+ let mut missing = Vec::new();
+ let (mut first, mut assets, mut rest, mut code) = (vec![], vec![], vec![], vec![]);
+ for r in regions {
+ let id = r["id"].as_str().filter(|s| !s.is_empty()).ok_or("a measured region has no id")?;
+ let kind = r["kind"].as_str().unwrap_or("");
+ let b = clamp_box(&r["box"]);
+ if !valid_box(&b) {
+ return Err(format!("region {id} has no valid normalized box; rerun comp-spec"));
+ }
+ let note = r["note"].as_str().unwrap_or("");
+ if raster(kind) {
+ let plate = r["plate"].as_str().map(|p| project_path(&roots, p))
+ .unwrap_or_else(|| format!("assets/plates/{id}.png"));
+ if relative(&plate).is_err() || !project.join(&plate).is_file() {
+ missing.push(format!(" - {id} ({kind}): {plate}"));
+ continue;
+ }
+ let mut item = json!({"id":id,"name":name(id),"kind":kind,"role":"asset","box":b,"note":note,
+ "medium":"raster","preview":{"kind":"image","path":plate}});
+ // A flagged asset (a frame baked around its view) is a decision too: it sorts first.
+ let flags = r["flags"].as_array().filter(|f| !f.is_empty());
+ if let Some(flags) = flags { item["flags"] = json!(flags); }
+ item["dependencies"] = json!([]);
+ if flags.is_some() { first.push(item) } else { assets.push(item) }
+ } else if plan_item(r) {
+ let mut item = json!({"id":id,"name":name(id),"kind":kind,"role":"plan","box":b,"note":note,
+ "medium":"code","preview":{"kind":"comp-crop"}});
+ if let Some(flags) = r["flags"].as_array().filter(|f| !f.is_empty()) {
+ item["flags"] = json!(flags);
+ }
+ item["codeDrawn"] = json!(r["codeDrawn"] == true);
+ item["dependencies"] = json!([]);
+ if flagged(r) { first.push(item) } else { rest.push(item) }
+ } else {
+ code.push(json!({"id":id,"name":name(id),"kind":kind,"box":b,"note":note}));
+ }
+ }
+ if !missing.is_empty() {
+ return Err(format!("{} raster region(s) lack their plate; the plan and asset review opens once every plate exists:\n{}\nProduce these plates (the build-phase plates step), then run component-review plan again.", missing.len(), missing.join("\n")));
+ }
+ let components: Vec<Value> = first.into_iter().chain(assets).chain(rest).collect();
+ if components.is_empty() {
+ return Err("the spec has no raster region and no code region that needs a decision; there is nothing to review, and build-phase advance does not wait for this review".into());
+ }
+ let title = state["artifact"].as_str().map(|a| format!("Plan and asset review · {a}"))
+ .unwrap_or_else(|| "Plan and asset review".into());
+ Ok(json!({"schemaVersion":3,"stage":"components","id":"components","title":title,
+ "comp":{"path":comp,"width":width,"height":height},"specSha256":digest(&bytes),
+ "components":components,"codeRegions":code}))
+}
+
+/// Write the packet to `out` (project-relative) and return it.
+pub fn write(project: &Path, out: &str) -> Result<Value, String> {
+ let rel = relative(out)?;
+ let packet = build(project)?;
+ let full = project.canonicalize().map_err(|e| e.to_string())?.join(rel);
+ super::store::write(&full, &packet)?;
+ Ok(packet)
+}
+
+/// build-phase refuses page work until the plan review for this journey is accepted
+/// against the current spec. An accepted first viewport has already closed review.
+/// `s` is how the caller spells the binary in the commands it prints.
+pub fn gate(store: &Path, project: &Path, s: &str) -> Result<(), String> {
+ let project = project.canonicalize().map_err(|e| e.to_string())?;
+ if super::lifecycle::final_session(store, &project)?.is_some() {
+ return Ok(());
+ }
+ let steps = format!("Run {s} component-review plan, then {s} component-review capture --manifest {DEFAULT_OUT} and {s} component-review serve --session <session>, and wait for the user's decision.");
+ decide(&super::lifecycle::project_sessions(store, &project)?, &project, s, &steps)
+}
+
+/// Whether the user accepted an assembled first viewport for this build journey,
+/// locally (`store`) or in the host's named `sessions`. Once one is accepted, the
+/// review store hands back that session, so no new first-viewport review can open.
+pub fn first_viewport_accepted(store: Option<&Path>, sessions: &[std::path::PathBuf], project: &Path) -> bool {
+ let Ok(project) = project.canonicalize() else { return false };
+ if let Some(store) = store {
+ if matches!(super::lifecycle::final_session(store, &project), Ok(Some(_))) { return true; }
+ }
+ sessions.iter().any(|dir| super::store::read(&dir.join("current.json"))
+ .is_ok_and(|state| state["packet"]["stage"] == "hero" && super::lifecycle::accepted_in(dir, &state)))
+}
+
+/// A hosted review lives in the host's store and its captures use snapshots, so the
+/// host names its trusted session directories (as `lifecycle --hosted --session-dir`
+/// does) and the same acceptance, integrity and spec-digest rules apply to them.
+pub fn gate_hosted(sessions: &[std::path::PathBuf], project: &Path, s: &str, tool: &str) -> Result<(), String> {
+ let project = project.canonicalize().map_err(|e| e.to_string())?;
+ for dir in sessions {
+ let state = super::store::read(&dir.join("current.json")).map_err(|e| format!("hosted review session {}: {e}", dir.display()))?;
+ if state["packet"]["stage"] == "hero" && super::lifecycle::accepted_in(dir, &state) {
+ return Ok(());
+ }
+ }
+ let steps = format!("Write it with {s} component-review plan, call {tool} with manifest_path=\"{DEFAULT_OUT}\", and wait for the user's decision.");
+ decide(sessions, &project, s, &steps)
+}
+
+fn decide(sessions: &[std::path::PathBuf], project: &Path, s: &str, steps: &str) -> Result<(), String> {
+ let bytes = std::fs::read(project.join(SPEC)).map_err(|_| format!("no measured spec at {SPEC}; run comp-spec first"))?;
+ let spec: Value = serde_json::from_slice(&bytes).map_err(|e| format!("{SPEC}: {e}"))?;
+ if !needs_review(&spec) {
+ return Ok(());
+ }
+ let sha = digest(&bytes);
+ let steps = format!("{steps} Write no page code before it is accepted.");
+ let mut plans = Vec::new();
+ let mut stale = None;
+ for dir in sessions {
+ let state = super::store::read(&dir.join("current.json"))?;
+ if state["packet"]["schemaVersion"] == 3 && state["packet"]["stage"] == "components" {
+ if super::lifecycle::accepted_in(dir, &state) && state["packet"]["specSha256"] == sha.as_str() {
+ // The user judged these plate bytes; a plate replaced since is unreviewed.
+ match super::store::sources_current(&state) {
+ Ok(()) => return Ok(()),
+ Err(why) => stale = Some(why),
+ }
+ }
+ plans.push(state);
+ }
+ }
+ if let Some(why) = stale {
+ let why = why.strip_prefix("review is stale: ").unwrap_or(&why).trim_end_matches("; prepare a new round");
+ return Err(format!("A reviewed plate changed after the user accepted the plan and asset review ({why}). Present a new round; unchanged decisions carry over. {steps}"));
+ }
+ Err(match plans.iter().find(|s| super::lifecycle::accepted(s)) {
+ Some(_) => format!("The plan and asset review was accepted for an earlier spec.json; the spec changed since. {steps} Unchanged decisions carry over."),
+ None if plans.iter().any(|s| s["receipt"]["visualDecision"] == "changes-requested") => format!("The user requested changes in the plan and asset review. Read the receipt with {s} component-review status --session <session>, apply it (reclassify regions in the regions file and rerun {s} comp-spec --comp <comp.png> --regions <regions.json>; regenerate revised plates), then present a new round. {steps}"),
+ None => format!("The plan and asset review is not accepted for this build. {steps}"),
+ })
+}
+
+#[cfg(test)]
+mod tests {
+ use super::project_path;
+ use std::path::Path;
+
+ #[test]
+ fn spec_paths_become_project_relative_with_forward_slashes() {
+ let raw = Path::new("/tmp/site");
+ let canonical = Path::new("/private/tmp/site");
+ let roots = [raw, canonical];
+ assert_eq!(project_path(&roots, "comp.png"), "comp.png");
+ assert_eq!(project_path(&roots, r"assets\plates\art.png"), "assets/plates/art.png");
+ assert_eq!(project_path(&roots, "/tmp/site/comp.png"), "comp.png");
+ assert_eq!(project_path(&roots, "/private/tmp/site/assets/art.png"), "assets/art.png");
+ // A sibling that shares the prefix is not inside the project.
+ assert_eq!(project_path(&roots, "/tmp/site-2/comp.png"), "/tmp/site-2/comp.png");
+ let windows = [Path::new(r"C:\work\site"), Path::new(r"\\?\C:\work\site")];
+ assert_eq!(project_path(&windows, r"C:\work\site\assets\art.png"), "assets/art.png");
+ assert_eq!(project_path(&windows, r"\\?\C:\work\site\comp.png"), "comp.png");
+ }
+}
diff --git a/crates/context/src/component_review/store.rs b/crates/context/src/component_review/store.rs
index 38c1dc4b8..033c13b0c 100644
--- a/crates/context/src/component_review/store.rs
+++ b/crates/context/src/component_review/store.rs
@@ -150,7 +150,7 @@ fn prepare_bound(
}
files.insert(path, bytes);
}
- if captured.evidence["schema"] != "native-component-previews-v1"
+ if captured.evidence["schema"] != super::capture::schema_for(&packet)
|| captured.evidence["components"].as_array().map(Vec::len)
!= packet["components"].as_array().map(Vec::len)
{
@@ -327,6 +327,7 @@ pub fn submit(dir: &Path, body: &Value) -> Result<Value, String> {
"decisions",
"missing",
"inventoryConfirmed",
+ "reclassify",
]
.contains(&k.as_str())
})
@@ -354,8 +355,11 @@ pub fn submit(dir: &Path, body: &Value) -> Result<Value, String> {
let components = packet["components"]
.as_array()
.ok_or("missing components")?;
+ let v3 = packet["schemaVersion"] == 3;
let mut approved = 0;
let mut revisions = 0;
+ let mut reclassified = 0;
+ let target_kind = |d: &Value| matches!(d["kind"].as_str(), Some("plate" | "image" | "texture"));
for (id, d) in decisions {
let c = components
.iter()
@@ -370,12 +374,41 @@ pub fn submit(dir: &Path, body: &Value) -> Result<Value, String> {
{
return Err("invalid component feedback".into());
}
+ if d.get("kind").is_some() && d["action"] != "reclassify" {
+ return Err("only a reclassify decision carries kind".into());
+ }
match d["action"].as_str() {
Some("approve") if d["split"] == false => approved += 1,
- Some("revise") => revisions += 1,
+ // On an asset, split: true asks for the region to come back as layers (a frame plate
+ // with a transparent opening, the view, each moving part); feedback is optional.
+ Some("revise") if !v3 || c["role"] == "asset" => revisions += 1,
+ // A plan item can need a map change neither medium fixes (artwork spilling over a
+ // code region). Revise then carries the reviewer's words and must not be empty.
+ Some("revise") if d["split"] == false && !d["feedback"].as_str().unwrap().trim().is_empty() => revisions += 1,
+ Some("revise") => return Err(format!("{id} is a plan item; revise on a plan item needs feedback describing the region map change")),
+ Some("reclassify") if v3 && c["role"] == "plan" && d["split"] == false && target_kind(d) => reclassified += 1,
+ Some("reclassify") => return Err("reclassify applies to plan items and needs kind plate, image or texture".into()),
_ => return Err("invalid decision action".into()),
}
}
+ let reclassify = body.get("reclassify").map(|r| r.as_array().cloned().ok_or("reclassify must be an array")).transpose()?.unwrap_or_default();
+ if !reclassify.is_empty() && !v3 {
+ return Err("reclassify belongs to the plan and asset review".into());
+ }
+ let mut reclassify_ids = std::collections::BTreeSet::new();
+ for r in &reclassify {
+ let id = string(r, "id")?;
+ let listed = packet["codeRegions"].as_array().is_some_and(|code| code.iter().any(|c| c["id"] == id));
+ if !listed || !reclassify_ids.insert(id) || !target_kind(r)
+ || r.as_object().is_some_and(|m| m.keys().any(|k| !["id", "kind", "feedback"].contains(&k.as_str())))
+ || r.get("feedback").is_some_and(|f| f.as_str().is_none_or(|f| f.len() > 8000))
+ {
+ return Err("invalid reclassification: name a codeRegions id once, with kind plate, image or texture".into());
+ }
+ }
+ if reclassify.len() > 400 {
+ return Err("too many reclassifications".into());
+ }
let missing = body["missing"]
.as_array()
.ok_or("missing must be an array")?;
@@ -392,12 +425,13 @@ pub fn submit(dir: &Path, body: &Value) -> Result<Value, String> {
if missing.len() > 200 || !body["inventoryConfirmed"].is_boolean() {
return Err("invalid inventory confirmation".into());
}
- let has_feedback = revisions > 0 || !missing.is_empty();
+ let has_feedback = revisions > 0 || reclassified > 0 || !reclassify.is_empty() || !missing.is_empty();
if !has_feedback && (approved != components.len() || body["inventoryConfirmed"] != true) {
return Err("approve every component and confirm inventory completeness".into());
}
- let receipt = json!({"schemaVersion":1,"reviewer":"local-browser","visualDecision":if has_feedback{"changes-requested"}else{"approved"},"captureVerified":state["capture"]["schema"]=="native-component-previews-v1","capture":state["capture"],"submission":body});
+ let receipt = json!({"schemaVersion":1,"reviewer":"local-browser","visualDecision":if has_feedback{"changes-requested"}else{"approved"},"captureVerified":super::capture::verified(&state),"capture":state["capture"],"submission":body});
state["draft"] = json!({"packetRevision":body["packetRevision"],"decisions":decisions,"missing":missing,"inventoryConfirmed":body["inventoryConfirmed"]});
+ if v3 { state["draft"]["reclassify"] = json!(reclassify); }
state["receipt"] = receipt.clone();
write(&dir.join("current.json"), &state)?;
// current.json is the authoritative atomic commit; a receipt export is not approval authority.
diff --git a/crates/context/src/component_review/tests.rs b/crates/context/src/component_review/tests.rs
index aad536e22..951656ad1 100644
--- a/crates/context/src/component_review/tests.rs
+++ b/crates/context/src/component_review/tests.rs
@@ -580,39 +580,18 @@ fn measured_inventory_is_bound_without_repeated_author_dependencies() {
}
#[test]
-fn isolated_components_require_targets_and_pin_their_ownership() {
+fn schema_v2_component_manifests_are_retired_but_v2_hero_still_freezes() {
let f = Fixture::new();
fs::create_dir_all(f.project.join(".impeccable/build")).unwrap();
fs::write(f.project.join(".impeccable/build/spec.json"), br#"{"regions":[{"id":"art","kind":"plate"},{"id":"control","kind":"control"}]}"#).unwrap();
let mut input = f.manifest();
input["schemaVersion"] = json!(2);
input["stage"] = json!("components");
- assert!(manifest::freeze(&f.project, &input).unwrap_err().contains("selector"));
- input["components"][1]["preview"]["selector"] = json!("button");
- let (first, _) = manifest::freeze(&f.project, &input).unwrap();
- input["components"][1]["preview"]["selector"] = json!("#cta");
- let (changed, _) = manifest::freeze(&f.project, &input).unwrap();
- assert_ne!(first["components"][1]["revision"], changed["components"][1]["revision"]);
- assert_eq!(first["components"][0]["revision"], changed["components"][0]["revision"]);
- input["components"][0]["preview"]["selector"] = json!("#fake-raster-target");
- assert!(manifest::freeze(&f.project, &input).is_err());
-}
-
-#[test]
-fn shared_target_changes_invalidate_other_isolated_components() {
- let f = Fixture::new();
- fs::create_dir_all(f.project.join(".impeccable/build")).unwrap();
- fs::write(f.project.join(".impeccable/build/spec.json"), br#"{"regions":[{"id":"art","kind":"chrome"},{"id":"control","kind":"control"}]}"#).unwrap();
- let mut input = f.manifest();
- input["schemaVersion"] = json!(2); input["stage"] = json!("components");
- input["components"][0]["preview"] = json!({"kind":"page","path":"control.html","selector":"#background"});
- input["components"][1]["preview"]["selector"] = json!("button");
- let (before,_) = manifest::freeze(&f.project,&input).unwrap();
- input["components"][1]["preview"]["selector"] = json!("#cta");
- let (after,_) = manifest::freeze(&f.project,&input).unwrap();
- assert_ne!(before["components"][0]["revision"],after["components"][0]["revision"]);
+ assert!(manifest::freeze(&f.project, &input).unwrap_err().contains("component-review plan"));
+ input["stage"] = json!("hero");
+ assert!(manifest::freeze(&f.project, &input).is_ok());
input["stage"] = Value::Null;
- assert!(manifest::freeze(&f.project,&input).is_err());
+ assert!(manifest::freeze(&f.project, &input).is_err());
}
#[test]
@@ -958,3 +937,363 @@ fn forged_acceptance_never_closes_review_in_lifecycle() {
assert_eq!(result["status"], "pending");
assert!(super::lifecycle::final_session(&f.store, &f.project.canonicalize().unwrap()).unwrap().is_none());
}
+
+// ---- plan and asset review (schemaVersion 3) --------------------------------
+
+const PLAN_SPEC: &str = r#"{"comp":"comp.png","compSize":{"width":100,"height":100},"regions":[
+ {"id":"nav","kind":"chrome","note":"Top bar","box":{"x":0,"y":0,"w":1,"h":0.1}},
+ {"id":"art","kind":"plate","note":"Figure","box":{"x":0.5,"y":0.1,"w":0.5,"h":0.5},"plate":"assets/art.png"},
+ {"id":"photo","kind":"image","note":"Harbour photo","box":{"x":0,"y":0.6,"w":0.5,"h":0.4},"plate":"assets/photo.png"},
+ {"id":"headline","kind":"text","note":"A little closer","box":{"x":0.05,"y":0.2,"w":0.4,"h":0.2}},
+ {"id":"brushed-panel","kind":"chrome","note":"Brushed steel","box":{"x":0,"y":0.4,"w":0.5,"h":0.1},"flags":[{"id":"painted-pixels","message":"soft gradients"}]},
+ {"id":"ground","kind":"chrome","container":true,"note":"Page ground","box":{"x":0,"y":0,"w":1,"h":1}},
+ {"id":"strip","kind":"band","note":"Band","box":{"x":0,"y":0.9,"w":1,"h":0.1}},
+ {"id":"table","kind":"text","codeDrawn":true,"note":"Tide table","box":{"x":0.5,"y":0.6,"w":0.5,"h":0.3}}]}"#;
+
+impl Fixture {
+ fn plan_project(&self) {
+ fs::create_dir_all(self.project.join(".impeccable/build")).unwrap();
+ fs::write(self.project.join(".impeccable/build/spec.json"), PLAN_SPEC).unwrap();
+ fs::write(self.project.join(".impeccable/build/state.json"), r#"{"startedAt":"build-1","artifact":"index.html"}"#).unwrap();
+ }
+ fn plates(&self) {
+ fs::create_dir_all(self.project.join("assets")).unwrap();
+ fs::write(self.project.join("assets/art.png"), b"art plate").unwrap();
+ fs::write(self.project.join("assets/photo.png"), b"photo plate").unwrap();
+ }
+ fn io(&self) -> (impeccable_common::Io, impeccable_common::Captured) {
+ impeccable_common::Io::captured("", self.project.clone(), std::collections::HashMap::from([("HOME".into(), self.root.to_string_lossy().into_owned())]))
+ }
+ /// `component-review <args> --store <store>` with no native capturer at all.
+ fn cli(&self, args: &[&str]) -> (i32, String, String) {
+ let (mut io, captured) = self.io();
+ let mut argv: Vec<String> = args.iter().map(|a| a.to_string()).collect();
+ argv.extend(["--store".into(), self.store.to_string_lossy().into_owned()]);
+ let code = super::run_with_capturer(&argv, &mut io, None);
+ let text = |b: &std::cell::RefCell<Vec<u8>>| String::from_utf8(b.borrow().clone()).unwrap();
+ (code, text(&captured.stdout), text(&captured.stderr))
+ }
+ fn plan_round(&self) -> PathBuf {
+ assert_eq!(self.cli(&["plan"]).0, 0);
+ let (code, out, err) = self.cli(&["capture", "--manifest", ".impeccable/review/components.json"]);
+ assert_eq!(code, 0, "{err}");
+ let session: Value = serde_json::from_str(&out).unwrap();
+ self.store.join(session["session"].as_str().unwrap())
+ }
+ fn gate(&self) -> Result<(), String> {
+ super::plan::gate(&self.store, &self.project, "impeccable")
+ }
+}
+
+#[test]
+fn plan_refuses_listing_every_missing_plate_then_orders_roles_from_the_spec() {
+ let f = Fixture::new();
+ f.plan_project();
+ let (code, _, err) = f.cli(&["plan"]);
+ assert_eq!(code, 1);
+ assert!(err.contains("2 raster region(s) lack their plate") && err.contains("art (plate): assets/art.png") && err.contains("photo (image): assets/photo.png"), "{err}");
+ assert!(!f.project.join(".impeccable/review/components.json").exists());
+ f.plates();
+ let (code, out, err) = f.cli(&["plan"]);
+ assert_eq!(code, 0, "{err}");
+ assert!(out.contains("2 assets, 3 plan items (2 flagged or code-drawn), 3 code regions") && out.contains("NEXT impeccable component-review capture --manifest .impeccable/review/components.json"), "{out}");
+ let packet = store::read(&f.project.join(".impeccable/review/components.json")).unwrap();
+ let ids = |key: &str| packet[key].as_array().unwrap().iter().map(|c| c["id"].as_str().unwrap().to_string()).collect::<Vec<_>>();
+ assert_eq!(ids("components"), ["brushed-panel", "table", "art", "photo", "nav"]);
+ assert_eq!(ids("codeRegions"), ["headline", "ground", "strip"]);
+ assert_eq!(packet["schemaVersion"], 3);
+ assert_eq!(packet["stage"], "components");
+ assert_eq!(packet["comp"], json!({"path":"comp.png","width":100,"height":100}));
+ assert_eq!(packet["specSha256"], manifest::digest(PLAN_SPEC.as_bytes()));
+ let c = &packet["components"];
+ assert_eq!((c[0]["role"].as_str(), c[0]["name"].as_str(), c[0]["codeDrawn"].as_bool()), (Some("plan"), Some("Brushed panel"), Some(false)));
+ assert_eq!(c[0]["flags"][0]["id"], "painted-pixels");
+ assert_eq!(c[0]["preview"], json!({"kind":"comp-crop"}));
+ assert_eq!(c[1]["codeDrawn"], true);
+ assert_eq!(c[2]["preview"], json!({"kind":"image","path":"assets/art.png"}));
+ assert_eq!((c[2]["role"].as_str(), c[2]["medium"].as_str()), (Some("asset"), Some("raster")));
+ assert!(c[4]["flags"].is_null());
+ assert_eq!(packet["codeRegions"][0], json!({"id":"headline","name":"Headline","kind":"text","box":{"x":0.05,"y":0.2,"w":0.4,"h":0.2},"note":"A little closer"}));
+}
+
+#[test]
+fn plan_capture_needs_no_browser_and_approval_verifies_against_the_pinned_spec() {
+ let f = Fixture::new();
+ f.plan_project();
+ f.plates();
+ let dir = f.plan_round();
+ let state = store::read(&dir.join("current.json")).unwrap();
+ assert_eq!(state["capture"]["schema"], super::capture::PLAN_SCHEMA);
+ let proofs = state["capture"]["components"].as_array().unwrap();
+ assert_eq!(proofs[0]["views"]["preview"], json!({"kind":"comp-crop","compPath":"comp.png","compSha256":manifest::digest(b"comp"),"box":state["packet"]["components"][0]["box"]}));
+ assert_eq!(proofs[2]["views"]["preview"]["kind"], "raster-source");
+ assert!(state["packet"]["components"][0]["preview"]["url"].is_null());
+ assert_eq!(state["packet"]["codeRegions"].as_array().unwrap().len(), 3);
+ assert!(f.gate().unwrap_err().contains("not accepted"));
+ let receipt = store::submit(&dir, &approve(&state)).unwrap();
+ assert_eq!((receipt["visualDecision"].as_str(), receipt["captureVerified"].as_bool()), (Some("approved"), Some(true)));
+ assert_eq!(super::verify::approved(&f.store, &f.project, ".impeccable/review/components.json").unwrap(), receipt);
+ assert_eq!(super::lifecycle::inspect(&[dir.clone()], &["components".into()]).unwrap()["status"], "approved");
+ f.gate().unwrap();
+ // Stored flags are claims: a packet digest that no longer matches the pinned spec fails integrity.
+ let mut forged = store::read(&dir.join("current.json")).unwrap();
+ forged["packet"]["specSha256"] = json!("0".repeat(64));
+ assert!(super::verify::capture_intact(&dir, &forged).unwrap_err().contains("spec digest"));
+ let mut moved = store::read(&dir.join("current.json")).unwrap();
+ moved["capture"]["components"][0]["views"]["preview"]["box"]["x"] = json!(0.3);
+ moved["receipt"]["capture"] = moved["capture"].clone();
+ assert!(super::verify::capture_intact(&dir, &moved).unwrap_err().contains("comp-crop evidence"));
+ // A native-schema claim is not plan evidence.
+ let mut native = store::read(&dir.join("current.json")).unwrap();
+ native["capture"]["schema"] = json!(super::capture::NATIVE_SCHEMA);
+ native["receipt"]["capture"] = native["capture"].clone();
+ assert!(!super::lifecycle::accepted(&native));
+ // A spec change after acceptance reopens the gate and needs a new round.
+ let mut spec: Value = serde_json::from_str(PLAN_SPEC).unwrap();
+ spec["regions"][3]["note"] = json!("A little closer to the sea");
+ fs::write(f.project.join(".impeccable/build/spec.json"), spec.to_string()).unwrap();
+ assert!(f.gate().unwrap_err().contains("earlier spec.json"));
+ assert!(super::verify::approved(&f.store, &f.project, ".impeccable/review/components.json").is_err());
+}
+
+#[test]
+fn plan_freeze_binds_the_spec_and_the_complete_inventory() {
+ let f = Fixture::new();
+ f.plan_project();
+ f.plates();
+ let packet = super::plan::build(&f.project).unwrap();
+ manifest::freeze(&f.project, &packet).unwrap();
+ let mut omitted = packet.clone();
+ omitted["codeRegions"].as_array_mut().unwrap().remove(0);
+ assert!(manifest::freeze(&f.project, &omitted).unwrap_err().contains("omitted measured region \"headline\""));
+ let mut foreign = packet.clone();
+ foreign["codeRegions"][0]["id"] = json!("elsewhere");
+ assert!(manifest::freeze(&f.project, &foreign).unwrap_err().contains("not a measured region"));
+ let mut rendered = packet.clone();
+ rendered["components"][0]["preview"] = json!({"kind":"page","path":"control.html"});
+ assert!(manifest::freeze(&f.project, &rendered).unwrap_err().contains("comp-crop"));
+ let mut stale = packet.clone();
+ stale["specSha256"] = json!("0".repeat(64));
+ assert!(manifest::freeze(&f.project, &stale).unwrap_err().contains("component-review plan"));
+ let mut grouped = packet;
+ grouped["components"][4]["reviewGroup"] = json!("bars");
+ assert!(manifest::freeze(&f.project, &grouped).unwrap_err().contains("reviewGroup"));
+}
+
+#[test]
+fn an_asset_split_into_layers_requests_changes_and_a_plan_item_cannot_split() {
+ let f = Fixture::new();
+ f.plan_project();
+ f.plates();
+ let dir = f.plan_round();
+ let state = store::read(&dir.join("current.json")).unwrap();
+ let components = state["packet"]["components"].as_array().unwrap();
+ let asset = components.iter().find(|c| c["role"] == "asset").unwrap();
+ let plan = components.iter().find(|c| c["role"] == "plan").unwrap();
+ let (asset_id, plan_id) = (asset["id"].as_str().unwrap(), plan["id"].as_str().unwrap());
+ let mut body = approve(&state);
+ body["decisions"][asset_id]["split"] = json!(true);
+ assert!(store::submit(&dir, &body).is_err(), "an approval never splits");
+ body["decisions"][asset_id] = json!({"revision":asset["revision"],"action":"revise","feedback":"","split":true});
+ body["decisions"][plan_id] = json!({"revision":plan["revision"],"action":"revise","feedback":"Split it","split":true});
+ assert!(store::submit(&dir, &body).is_err(), "split is for assets");
+ body["decisions"][plan_id] = json!({"revision":plan["revision"],"action":"approve","feedback":"","split":false});
+ let receipt = store::submit(&dir, &body).unwrap();
+ assert_eq!(receipt["visualDecision"], "changes-requested");
+ assert_eq!(receipt["submission"]["decisions"][asset_id]["split"], true);
+}
+
+#[test]
+fn a_plan_item_revise_carries_the_map_change_and_requests_changes() {
+ let f = Fixture::new();
+ f.plan_project();
+ f.plates();
+ let dir = f.plan_round();
+ let state = store::read(&dir.join("current.json")).unwrap();
+ let mut body = approve(&state);
+ let rev = state["packet"]["components"][0]["revision"].clone();
+ body["decisions"]["brushed-panel"] = json!({"revision":rev,"action":"revise","feedback":"Extend the photo under the band","split":false});
+ let receipt = store::submit(&dir, &body).unwrap();
+ assert_eq!(receipt["visualDecision"], "changes-requested");
+ assert_eq!(receipt["submission"]["decisions"]["brushed-panel"]["feedback"], "Extend the photo under the band");
+ assert!(f.gate().unwrap_err().contains("requested changes"));
+}
+
+#[test]
+fn reclassification_requests_changes_and_carries_unchanged_decisions_into_the_next_round() {
+ let f = Fixture::new();
+ f.plan_project();
+ f.plates();
+ let dir = f.plan_round();
+ let state = store::read(&dir.join("current.json")).unwrap();
+ let rev = |i: usize| state["packet"]["components"][i]["revision"].clone();
+ let mut body = approve(&state);
+ // A plan item takes reclassify with a raster kind, or revise with the reviewer's words.
+ body["decisions"]["brushed-panel"] = json!({"revision":rev(0),"action":"revise","feedback":" ","split":false});
+ assert!(store::submit(&dir, &body).unwrap_err().contains("needs feedback"));
+ body["decisions"]["brushed-panel"] = json!({"revision":rev(0),"action":"reclassify","kind":"svg","feedback":"","split":false});
+ assert!(store::submit(&dir, &body).is_err());
+ body["decisions"]["art"] = json!({"revision":rev(2),"action":"reclassify","kind":"image","feedback":"","split":false});
+ body["decisions"]["brushed-panel"]["kind"] = json!("texture");
+ assert!(store::submit(&dir, &body).is_err(), "assets are not reclassified");
+ body["decisions"]["art"] = json!({"revision":rev(2),"action":"approve","feedback":"","split":false});
+ let mut unknown = body.clone();
+ unknown["reclassify"] = json!([{"id":"nav","kind":"plate"}]);
+ assert!(store::submit(&dir, &unknown).unwrap_err().contains("codeRegions"), "a component is decided in decisions");
+ body["reclassify"] = json!([{"id":"headline","kind":"plate","feedback":"This lettering is painted"}]);
+ let receipt = store::submit(&dir, &body).unwrap();
+ assert_eq!(receipt["visualDecision"], "changes-requested");
+ assert!(f.gate().unwrap_err().contains("requested changes"));
+ // Apply the receipt: headline becomes a plate, the panel a texture.
+ let mut spec: Value = serde_json::from_str(PLAN_SPEC).unwrap();
+ spec["regions"][3]["kind"] = json!("plate");
+ spec["regions"][3]["plate"] = json!("assets/headline.png");
+ spec["regions"][4]["kind"] = json!("texture");
+ spec["regions"][4]["plate"] = json!("assets/panel.png");
+ spec["regions"][4].as_object_mut().unwrap().remove("flags");
+ fs::write(f.project.join(".impeccable/build/spec.json"), spec.to_string()).unwrap();
+ fs::write(f.project.join("assets/headline.png"), b"headline plate").unwrap();
+ fs::write(f.project.join("assets/panel.png"), b"panel plate").unwrap();
+ let next_dir = f.plan_round();
+ assert_eq!(next_dir, dir);
+ let next = store::read(&next_dir.join("current.json")).unwrap();
+ assert_eq!(next["packet"]["round"], 2);
+ let carried: Vec<&str> = next["draft"]["decisions"].as_object().unwrap().keys().map(String::as_str).collect();
+ assert_eq!(carried, ["table", "art", "photo", "nav"], "unchanged approvals carry across a spec change");
+ assert_eq!(next["history"]["feedback"]["headline"]["decision"]["action"], "reclassify");
+ assert_eq!(next["history"]["feedback"]["brushed-panel"]["decision"]["kind"], "texture");
+ store::submit(&next_dir, &approve(&next)).unwrap();
+ f.gate().unwrap();
+}
+
+#[test]
+fn approving_every_component_while_reclassifying_a_code_region_is_not_approval() {
+ let f = Fixture::new();
+ f.plan_project();
+ f.plates();
+ let dir = f.plan_round();
+ let state = store::read(&dir.join("current.json")).unwrap();
+ let mut body = approve(&state);
+ body["inventoryConfirmed"] = json!(false);
+ assert!(store::submit(&dir, &body).unwrap_err().contains("confirm inventory"));
+ body["reclassify"] = json!([{"id":"headline","kind":"plate"},{"id":"headline","kind":"image"}]);
+ assert!(store::submit(&dir, &body).is_err(), "one reclassification per region");
+ body["reclassify"] = json!([{"id":"headline","kind":"plate"}]);
+ let receipt = store::submit(&dir, &body).unwrap();
+ assert_eq!(receipt["visualDecision"], "changes-requested");
+ assert!(super::verify::approved(&f.store, &f.project, ".impeccable/review/components.json").is_err());
+ // v1/v2 reviews have no reclassification.
+ let legacy = Fixture::new();
+ let legacy_dir = legacy.prepare();
+ let mut legacy_body = approve(&store::read(&legacy_dir.join("current.json")).unwrap());
+ legacy_body["reclassify"] = json!([{"id":"art","kind":"plate"}]);
+ assert!(store::submit(&legacy_dir, &legacy_body).is_err());
+}
+
+#[test]
+fn hosted_gate_requires_an_accepted_intact_review_in_the_named_sessions() {
+ let f = Fixture::new();
+ f.plan_project();
+ f.plates();
+ let hosted = |dirs: &[PathBuf]| super::plan::gate_hosted(dirs, &f.project, "impeccable", "component_review");
+ assert!(hosted(&[]).unwrap_err().contains("not accepted"));
+ let dir = f.plan_round();
+ let err = hosted(&[dir.clone()]).unwrap_err();
+ assert!(err.contains("not accepted") && err.contains("call component_review"), "{err}");
+ let state = store::read(&dir.join("current.json")).unwrap();
+ store::submit(&dir, &approve(&state)).unwrap();
+ hosted(&[dir.clone()]).unwrap();
+ // A forged or tampered session is not acceptance.
+ let good = store::read(&dir.join("current.json")).unwrap();
+ let mut forged = good.clone();
+ forged["capture"]["components"].as_array_mut().unwrap().pop();
+ forged["receipt"]["capture"] = forged["capture"].clone();
+ store::write(&dir.join("current.json"), &forged).unwrap();
+ assert!(hosted(&[dir.clone()]).is_err());
+ store::write(&dir.join("current.json"), &good).unwrap();
+ let blob = good["files"]["assets/art.png"].as_str().unwrap();
+ fs::write(dir.join("blobs").join(blob), b"swapped").unwrap();
+ assert!(hosted(&[dir.clone()]).is_err());
+ fs::write(dir.join("blobs").join(blob), b"art plate").unwrap();
+ hosted(&[dir.clone()]).unwrap();
+ // A spec changed since the review, or an unreadable session, refuses.
+ fs::write(f.project.join(".impeccable/build/spec.json"), PLAN_SPEC.replace("Top bar", "Top rail")).unwrap();
+ assert!(hosted(&[dir.clone()]).unwrap_err().contains("earlier spec.json"));
+ assert!(hosted(&[f.root.join("nowhere")]).is_err());
+}
+
+#[test]
+fn plan_leaves_bare_grounds_and_straight_rules_to_code_unless_flagged() {
+ let f = Fixture::new();
+ f.plan_project();
+ f.plates();
+ let mut spec: Value = serde_json::from_str(PLAN_SPEC).unwrap();
+ let regions = spec["regions"].as_array_mut().unwrap();
+ regions[0]["surface"] = json!({"flat": true, "rules": false});
+ regions.push(json!({"id":"rule","kind":"chrome","note":"Brass hairline","box":{"x":0,"y":0.5,"w":1,"h":0.01},"surface":{"flat":false,"rules":true}}));
+ regions.push(json!({"id":"mark","kind":"chrome","note":"Wave mark","box":{"x":0.9,"y":0,"w":0.05,"h":0.05},"surface":{"flat":false,"rules":false}}));
+ regions.push(json!({"id":"moulding","kind":"chrome","note":"Moulded frieze","box":{"x":0,"y":0.95,"w":1,"h":0.05},"surface":{"flat":false,"rules":true},"flags":[{"id":"painted-pixels","message":"Looks painted"}]}));
+ fs::write(f.project.join(".impeccable/build/spec.json"), serde_json::to_vec(&spec).unwrap()).unwrap();
+ let (code, _, err) = f.cli(&["plan"]);
+ assert_eq!(code, 0, "{err}");
+ let packet = store::read(&f.project.join(".impeccable/review/components.json")).unwrap();
+ let ids = |key: &str| packet[key].as_array().unwrap().iter().map(|c| c["id"].as_str().unwrap().to_string()).collect::<Vec<_>>();
+ assert_eq!(ids("components"), ["brushed-panel", "table", "moulding", "art", "photo", "mark"]);
+ assert_eq!(ids("codeRegions"), ["nav", "headline", "ground", "strip", "rule"]);
+}
+
+#[test]
+fn plan_puts_flagged_assets_first_with_their_flags() {
+ let f = Fixture::new();
+ f.plan_project();
+ f.plates();
+ let mut spec: Value = serde_json::from_str(PLAN_SPEC).unwrap();
+ spec["regions"][2]["flags"] = json!([{"id":"baked-composite","message":"Frame and view are one image here, so the page can't swap the view on its own."}]);
+ fs::write(f.project.join(".impeccable/build/spec.json"), serde_json::to_vec(&spec).unwrap()).unwrap();
+ let (code, out, err) = f.cli(&["plan"]);
+ assert_eq!(code, 0, "{err}");
+ assert!(out.contains("2 assets (1 flagged), 3 plan items (2 flagged or code-drawn)"), "{out}");
+ let packet = store::read(&f.project.join(".impeccable/review/components.json")).unwrap();
+ let ids: Vec<&str> = packet["components"].as_array().unwrap().iter().map(|c| c["id"].as_str().unwrap()).collect();
+ // Flagged items of either role keep spec order at the front.
+ assert_eq!(ids, ["photo", "brushed-panel", "table", "art", "nav"]);
+ assert_eq!(packet["components"][0]["flags"][0]["id"], "baked-composite");
+ assert_eq!(packet["components"][0]["role"], "asset");
+ assert!(packet["components"][3]["flags"].is_null());
+}
+
+#[test]
+fn a_plate_replaced_after_acceptance_reopens_the_plan_review() {
+ let f = Fixture::new();
+ f.plan_project();
+ f.plates();
+ let dir = f.plan_round();
+ let state = store::read(&dir.join("current.json")).unwrap();
+ store::submit(&dir, &approve(&state)).unwrap();
+ f.gate().unwrap();
+ fs::write(f.project.join("assets/art.png"), b"a different art plate").unwrap();
+ let err = f.gate().unwrap_err();
+ assert!(err.contains("A reviewed plate changed") && err.contains("assets/art.png changed") && err.contains("Present a new round; unchanged decisions carry over"), "{err}");
+ // A new round over the new plate is reviewable, and its acceptance opens the gate again.
+ let dir = f.plan_round();
+ let state = store::read(&dir.join("current.json")).unwrap();
+ store::submit(&dir, &approve(&state)).unwrap();
+ f.gate().unwrap();
+}
+
+#[test]
+fn plan_accepts_absolute_and_backslashed_spec_paths_inside_the_project() {
+ let f = Fixture::new();
+ f.plan_project();
+ f.plates();
+ let mut spec: Value = serde_json::from_str(PLAN_SPEC).unwrap();
+ spec["comp"] = json!(f.project.join("comp.png").to_string_lossy());
+ spec["regions"][1]["plate"] = json!(f.project.canonicalize().unwrap().join("assets/art.png").to_string_lossy());
+ spec["regions"][2]["plate"] = json!(r"assets\photo.png");
+ fs::write(f.project.join(".impeccable/build/spec.json"), spec.to_string()).unwrap();
+ let packet = super::plan::build(&f.project).unwrap();
+ assert_eq!(packet["comp"]["path"], "comp.png");
+ let preview = |id: &str| packet["components"].as_array().unwrap().iter().find(|c| c["id"] == id).unwrap()["preview"]["path"].clone();
+ assert_eq!(preview("art"), "assets/art.png");
+ assert_eq!(preview("photo"), "assets/photo.png");
+}
diff --git a/crates/context/src/component_review/verify.rs b/crates/context/src/component_review/verify.rs
index a3334676b..d12eeac5c 100644
--- a/crates/context/src/component_review/verify.rs
+++ b/crates/context/src/component_review/verify.rs
@@ -16,7 +16,7 @@ pub fn approved(store_root: &Path, project: &Path, manifest_path: &str) -> Resul
let _guard = store::lock(&directory)?;
let state = store::read(&directory.join("current.json"))?;
store::sources_current(&state)?;
- if state["capture"]["schema"] != "native-component-previews-v1"
+ if !super::capture::verified(&state)
|| state["receipt"]["captureVerified"] != true
|| state["receipt"]["visualDecision"] != "approved"
|| state["receipt"]["submission"]["packetRevision"] != state["packet"]["revision"]
@@ -48,9 +48,7 @@ pub fn approved(store_root: &Path, project: &Path, manifest_path: &str) -> Resul
/// every served file matches its blob, and code views point at captured pixels.
pub fn capture_intact(dir: &Path, state: &Value) -> Result<(), String> {
let fail = |why: &str| Err(format!("component review capture is not intact: {why}"));
- if state["capture"]["schema"] != "native-component-previews-v1"
- || state["receipt"]["capture"] != state["capture"]
- {
+ if !super::capture::verified(state) || state["receipt"]["capture"] != state["capture"] {
return fail("no native capture bound to the receipt");
}
let files = state["files"].as_object().ok_or("missing pinned files")?;
@@ -73,6 +71,12 @@ pub fn capture_intact(dir: &Path, state: &Value) -> Result<(), String> {
if pinned(&state["packet"]["comp"]).is_none() {
return fail("comp is not pinned");
}
+ let v3 = state["packet"]["schemaVersion"] == 3;
+ if v3 && (state["packet"]["specSha256"].as_str().is_none()
+ || sources.get(super::plan::SPEC) != Some(&state["packet"]["specSha256"]))
+ {
+ return fail("the reviewed spec digest does not match the pinned spec");
+ }
let components = state["packet"]["components"].as_array().ok_or("missing components")?;
let evidence = state["capture"]["components"].as_array().ok_or("missing capture evidence")?;
if evidence.len() != components.len() {
@@ -83,6 +87,18 @@ pub fn capture_intact(dir: &Path, state: &Value) -> Result<(), String> {
let Some(proof) = evidence.iter().find(|e| e["id"] == id) else {
return fail(&format!("{id} has no capture evidence"));
};
+ if v3 && c["preview"]["kind"] == "comp-crop" {
+ let (comp, proof) = (pinned(&state["packet"]["comp"]), &proof["views"]["preview"]);
+ if c["role"] != "plan" || !c["context"].is_null() || !c["thumbnail"].is_null() || proof["kind"] != "comp-crop"
+ || proof["box"] != c["box"] || comp.as_ref().map(|(p, h)| (p.as_str(), h.as_str())) != Some((proof["compPath"].as_str().unwrap_or(""), proof["compSha256"].as_str().unwrap_or("")))
+ {
+ return fail(&format!("{id} lacks comp-crop evidence"));
+ }
+ continue;
+ }
+ if v3 && (c["role"] != "asset" || !c["context"].is_null()) {
+ return fail(&format!("{id} lacks raster-source evidence"));
+ }
for key in ["preview", "context", "thumbnail"] {
if c[key].is_null() && key != "preview" {
continue;
@@ -96,7 +112,7 @@ pub fn capture_intact(dir: &Path, state: &Value) -> Result<(), String> {
} else if view["kind"] == "raster-source" {
key == "preview" && c[key]["kind"] == "image" && view["path"] == path.as_str() && view["sha256"] == hash.as_str()
} else {
- c[key]["kind"] == "image" && c[key]["sourceKind"] == "page"
+ !v3 && c[key]["kind"] == "image" && c[key]["sourceKind"] == "page"
&& path == format!("_review_captures/{hash}.png") && view["screenshotSha256"] == hash.as_str()
};
if !ok {
diff --git a/crates/context/src/component_review/visual_approval.rs b/crates/context/src/component_review/visual_approval.rs
index bb894533d..c06edc3f9 100644
--- a/crates/context/src/component_review/visual_approval.rs
+++ b/crates/context/src/component_review/visual_approval.rs
@@ -4,7 +4,7 @@ use serde_json::{json, Value};
use std::path::Path;
fn identity(state: &Value, component: &Value, blobs: &Path) -> Option<Value> {
- if state["capture"]["schema"] != "native-component-previews-v1" {
+ if !super::capture::verified(state) {
return None;
}
let evidence = state["capture"]["components"]
@@ -36,6 +36,12 @@ fn identity(state: &Value, component: &Value, blobs: &Path) -> Option<Value> {
if view.is_null() {
continue;
}
+ if key == "preview" && view["kind"] == "comp-crop" {
+ // A plan item's pixels are the comp crop: its box is in the definition, the comp in `comp`.
+ if evidence["views"]["preview"]["kind"] != "comp-crop" { return None; }
+ views.insert(key.into(), view.clone());
+ continue;
+ }
let path = view["url"].as_str()?.strip_prefix(&prefix)?;
let hash = state["files"][path].as_str()?;
if hash.len() != 64 || !hash.bytes().all(|b| b.is_ascii_hexdigit()) {
diff --git a/docs/CLI-CONTRACT.md b/docs/CLI-CONTRACT.md
index 2b9af67c0..f6a13db55 100644
--- a/docs/CLI-CONTRACT.md
+++ b/docs/CLI-CONTRACT.md
@@ -449,7 +449,7 @@ retain their local-development trust behavior. See [bundle signing](BUNDLE-SIGNI
Ported from the former `skill/scripts/{comp-spec,comp-diff,font-match,build-phase}.mjs` (+ `lib/{png,raster,image-metrics,font-fingerprint,font-index,hero-checks}.mjs`) into the engine; invoked as `{{scripts_path}}/impeccable <verb>`. All four resolve paths against the process cwd. Printed commands spell the launcher via `IMPECCABLE_SELF` (default `impeccable`), so they name `{{scripts_path}}/impeccable <verb>`, never `node …mjs`. ISO `createdAt`/`startedAt` timestamps in stdout and written JSON are the only run-dependent output.
-- **`comp-spec`** — turns an approved comp into a measured build spec. `--schema` prints the region-map JSON schema without reading or writing a project. `--comp <png> --regions <json> --inspect-map` writes reference-only crops, overlay and report in a new directory; exit 2 means diagnosed hard errors, exit 1 means command/input failure. Masked assets also produce paginated, comp-derived `comparison-N.png` sheets (six original/checker pairs per image, matched scale and aspect ratio), listed by `COMPARE` lines and the JSON `comparisonSheets` array. Every affected instance is retained; sheets do not change matcher inputs or approvals. Partial foreground masks are warnings naming the excluding regions and remain in the inspector’s main inspection queue even with zero hard errors. The CLI summary counts them separately; they do not imply an asset failure or visual approval. Code rectangles exclude their full overlap, so separate text elements need separate bounds. Mapping metadata (`parentId`, `reviewGroup`) survives measurement. Review groups must contain peer code regions of one kind and container status; mixed groups and grouped raster assets are refused both at measurement and at component-review preparation. `--comp <png> --grid` writes `.impeccable/build/comp-grid.png` (10x10 labeled grid) and prints PALETTE/BANDS/NEXT; `--comp <png> --regions <json>` measures regions into `.impeccable/build/spec.json` (region box, sampled palette, medium, aspect, detail energy, plate path for raster kinds) and prints the spec; `--comp <png> --auto [--out <draft.json>]` writes approximate bands to a new draft file (default `.impeccable/build/regions.draft.json`), without modifying the measured spec or build state; `--print` prints the compact spec; `--crop <id> [--out f] [--scale n] [--raw]` writes a reference crop; `--plate-prompt <id>` prints the regeneration prompt. `--spec <path>` overrides the spec path (default `.impeccable/build/spec.json`). Validation refusals (stderr, exit 1) are the JS strings verbatim: a region with no id / duplicate id / no note (bands included) / a missing or unknown kind, a `box` that is not numeric, leaves the 0..1 frame, or rounds below one comp pixel, a code-kind region whose note names painted material, a code region over 25% of the comp, a grid span that is not `<colrow>:<colrow>`, uncovered ink cells without `allowUncovered`. spec.json is byte-identical to the JS output.
+- **`comp-spec`** — turns an approved comp into a measured build spec. `--schema` prints the region-map JSON schema without reading or writing a project. `--comp <png> --regions <json> --inspect-map` writes reference-only crops, overlay and report in a new directory; exit 2 means diagnosed hard errors, exit 1 means command/input failure. Masked assets also produce paginated, comp-derived `comparison-N.png` sheets (six original/checker pairs per image, matched scale and aspect ratio), listed by `COMPARE` lines and the JSON `comparisonSheets` array. Every affected instance is retained; sheets do not change matcher inputs or approvals. Partial foreground masks are warnings naming the excluding regions and remain in the inspector’s main inspection queue even with zero hard errors. The CLI summary counts them separately; they do not imply an asset failure or visual approval. Code rectangles exclude their full overlap, so separate text elements need separate bounds. Mapping metadata (`parentId`, `reviewGroup`) survives measurement. Review groups must contain peer code regions of one kind and container status; mixed groups and grouped raster assets are refused both at measurement and at component-review preparation. `--comp <png> --grid` writes `.impeccable/build/comp-grid.png` (10x10 labeled grid) and prints PALETTE/BANDS/NEXT; `--comp <png> --regions <json>` measures regions into `.impeccable/build/spec.json` (region box, sampled palette, medium, aspect, detail energy, plate path for raster kinds) and prints the spec; `--comp <png> --auto [--out <draft.json>]` writes approximate bands to a new draft file (default `.impeccable/build/regions.draft.json`), without modifying the measured spec or build state; `--print` prints the compact spec; `--crop <id> [--out f] [--scale n] [--raw]` writes a reference crop; `--plate-prompt <id>` prints the regeneration prompt. `--spec <path>` overrides the spec path (default `.impeccable/build/spec.json`). Validation refusals (stderr, exit 1) are the JS strings verbatim: a region with no id / duplicate id / no note (bands included) / a missing or unknown kind, a `box` that is not numeric, leaves the 0..1 frame, or rounds below one comp pixel, a code-kind region whose note names painted material, a code region over 25% of the comp, a grid span that is not `<colrow>:<colrow>`, uncovered ink cells without `allowUncovered`. Every `text`, `control` and `chrome` region (containers included) gets `surface: {flat, rules}` and, when any 64px window of its comp crop reads as painted (pixels inside raster regions left out), `flags: [{"id":"painted-pixels","message":...}]` plus a `FLAG <id> painted-pixels: <message> <agent advice>` line in the printed spec; docs/PLAN-REVIEW.md defines both readings. The flag is never a refusal, and `codeDrawn` does not suppress it. A raster region whose note names a frame and then the view it opens onto gets `flags: [{"id":"baked-composite","message":...}]` and its own `FLAG` line (docs/PLAN-REVIEW.md). Apart from these additions, spec.json is byte-identical to the JS output.
Automatic drafts require decomposition into actual visible elements before measurement; a draft flag blocks accidental submission, and existing draft files are never overwritten. Successful `--regions` measurements record the source path and SHA-256. Spec and plate gates reject changed or missing source files, so a failed region edit cannot silently reuse the previous measurements. Legacy specs without source metadata remain readable.
Region inputs support three coordinate representations: inclusive `grid` cells, normalized `box: {x,y,w,h}`, or `pixelBox: {x,y,w,h}` in whole original-comp pixels. Pixel boxes cannot be combined with the other formats and must be positive-sized and contained in the comp; they avoid snapping an asset boundary to a neighbouring grid cell. Foreground UI excluded from a plate reference is excluded at the same aligned coordinates from the candidate during scoring; unmasked asset bytes still undergo provenance checks.
- **`comp-diff`** — `--comp <png> --build <png> [--spec spec.json] [--out-dir dir] [--align top|stretch|cover] [--label name] [--threshold t] [--json] [--no-files]`. Scores structure / color / detail / bands and per-region verdicts (`match`/`drift`/`missing`/`contradicted`); writes `side-by-side.png`, `heatmap.png`, `regions/<id>.png`, and `report.json` under `--out-dir` (unless `--no-files`); prints the text summary or, with `--json`, the report. Exit 0 measured, 1 usage/unreadable input, 3 below `--threshold`. The JSON report and text summary are byte-identical to the JS.
@@ -1837,11 +1837,45 @@ Conventions: every script's "run directly" guard is `process.argv[1]` ending wit
- Fake agent polls `GET /poll?token&timeout=5000` (no lease override → 30 s lease), replies via `POST /poll` with `{token,type:'done',sourceEventType:'generate',id,file}`, `steer_done {message,file}`, `error`, accept/discard completions with `data:{carbonize:true,_acceptResult}`/`{_acceptResult}`, manual apply via `live-poll.mjs --reply <id> done --data <json>`. Variant format: 3 variants (font-weights 300/900/600 for render proof), params `lightness` (range), `face` (steps), `italic` (toggle). Scenarios: core, manual, annotations, exit, missed-done, params, mount-failure, republish, storage-loss (fixtures README). Fixture `runtime` block schema is authoritative for what a reimplementation must satisfy end-to-end.
-## Component review (native, opt-in)
-
-This development command does not yet replace the skill's build-phase gates.
-The packet and evidence contract is documented in
-[`ui/component-review/README.md`](../ui/component-review/README.md).
+## Component review (native)
+
+The component stage is the plan and asset review (packet `schemaVersion: 3`,
+contract in [`docs/PLAN-REVIEW.md`](PLAN-REVIEW.md)); the assembled first
+viewport is the `hero` stage. The shared UI and the v1/v2 packet shape are
+documented in [`ui/component-review/README.md`](../ui/component-review/README.md).
+
+- `component-review plan [--out <project-relative JSON>]` writes the v3 packet
+ (default `.impeccable/review/components.json`) from `.impeccable/build/spec.json`,
+ the comp it names (`comp`, `compSize`; the build state's `comp` as a fallback)
+ and the plate files. `id` is `components`; `title` is `Plan and asset review`
+ plus ` · <artifact>` when the build state names one. Raster regions
+ (`plate`, `image`, `texture`) become `role: "asset"` previewed by their plate;
+ `text`, `control` and `chrome` regions with a nonempty `flags` array, with
+ `codeDrawn: true`, or non-container `chrome` whose comp-spec `surface` is
+ neither `flat` nor `rules` become `role: "plan"` with
+ `preview: {"kind":"comp-crop"}`, their `flags` passed through and `codeDrawn`
+ always present; every other region (bands, containers, plain text and
+ controls) is listed in `codeRegions` as `{id,name,kind,box,note}`. Components
+ are ordered flagged items (flagged or code-drawn plan items and flagged
+ assets, which keep their `flags`), remaining assets, remaining plan items,
+ each in spec order. `name` is the id with `-`/`_` as spaces, first letter
+ capitalized. `specSha256` is the SHA-256 of the spec bytes. stdout is
+ `PLAN <out>: <n> assets[ (<n> flagged)], <n> plan items (<n> flagged or code-drawn), <n> code regions`
+ and a `NEXT` line naming `capture` then `serve`. It exits 1 without writing
+ when any raster region's plate file is missing (every missing plate is
+ listed as ` - <id> (<kind>): <path>`), when there is no spec, or when the
+ spec has nothing to review (no raster region and no plan item).
+- `prepare` / `capture` accept `schemaVersion` 1 (legacy), 2 with stage `hero`,
+ and 3 with stage `components`. A `schemaVersion: 2` component manifest is
+ refused with a message naming `component-review plan`. A v3 packet must match
+ the pinned spec (`specSha256`), list every measured region exactly once as a
+ component or in `codeRegions`, name no other id, and carry no `reviewGroup`,
+ `context` or `thumbnail`. `capture` of a v3 packet never starts a browser: it
+ records `capture.schema: "plan-review-proof-v1"` with a `raster-source` proof
+ (`path`, `sha256`) per asset and a `comp-crop` proof (`compPath`,
+ `compSha256`, `box`) per plan item. v1/v2 captures keep
+ `native-component-previews-v1`.
+- `component-review prepare --manifest <project-relative JSON>` snapshots the
- `component-review prepare --manifest <project-relative JSON>` snapshots the
declared comp, components and dependencies into an out-of-project store.
@@ -1880,6 +1914,17 @@ The packet and evidence contract is documented in
Session IDs are 64 hexadecimal characters. Errors write
`component-review: <reason>` to stderr and return 1; successful non-server
operations return 0. There are no external network or model calls.
+- Submissions for a v3 round: each decision is `{revision, action, feedback,
+ split: false}`; `action` is `approve`, `revise` (assets only) or `reclassify`
+ (plan items only, with `kind` `plate`, `image` or `texture`). The optional
+ top-level `reclassify: [{id, kind, feedback?}]` names `codeRegions` ids, each
+ once. Any `revise`, `reclassify` or `missing` entry makes the receipt
+ `changes-requested`; `approved` needs every component approved, no
+ reclassification and `inventoryConfirmed: true`. The draft keeps the
+ `reclassify` list, and the next round's `history.feedback` reports a
+ reclassified id under `{round, decision: {action: "reclassify", kind, feedback}}`.
+ Unchanged approvals carry across rounds (same component definition, preview
+ bytes and comp), including across a spec change.
- Receipt identity remains `local-browser`. `captureVerified` is false after
plain `prepare`, and true only for native `capture` evidence committed by the
trusted in-process adapter. Producer-written capture claims are discarded.
@@ -1894,13 +1939,19 @@ The packet and evidence contract is documented in
`component-review lifecycle [--session-dir <private directory>] [--require components|hero] [--hosted]` reports the native review decision. Both options may repeat. With `--hosted`, only the supplied private sessions are considered; ordinary sessions resolve acceptance from the project in the local store. The result has `schemaVersion: 1`, `status` (`pending`, `approved`, or `accepted`), `reviewClosed`, and nullable `completionFeedback`. Accepted assembly returns `scope: "first-viewport"` and the original request/revision. Hosts transport that result without adding file-hash approval policy.
+For a v3 round, `verify`, `lifecycle` and the gate below apply the same integrity check with the plan proofs: assets need their `raster-source` proof, plan items a `comp-crop` proof whose box equals the component's and whose comp path and hash equal the pinned comp, and the packet's `specSha256` must equal the pinned `.impeccable/build/spec.json` source.
+
+`build-phase advance` from `plates` or `hero`, and `build-phase record hero`, wait for the plan and asset review. They pass when the first viewport is already accepted for this journey, when the spec has nothing to review, or when a v3 component session of the current journey is accepted (intact capture, approved receipt), its `specSha256` equals the current spec's SHA-256, and every file it pinned (plates, comp, spec, manifest) still has its reviewed bytes. Otherwise `advance` fails the plates or hero gate with one added reason and `record hero` exits 1 with `build-phase: record hero refused. <reason>` on stderr. The reason is one of: not accepted for this build; accepted for an earlier spec.json; a reviewed plate changed after acceptance (names the file; present a new round, unchanged decisions carry over); or the user requested changes (read the receipt with `component-review status`). Each names `component-review plan`, `capture --manifest .impeccable/review/components.json` and `serve --session <session>`. The review store is `~/.impeccable/component-reviews`. When `IMPECCABLE_COMPONENT_REVIEW_TOOL` is set the review lives in the host, and the host must name its trusted session directories in `IMPECCABLE_COMPONENT_REVIEW_SESSIONS` (an OS path list, as `lifecycle --hosted --session-dir` takes them). The gate then applies the same rules to those directories (accepted first viewport, or accepted intact v3 review with the current `specSha256`) and names the tool in its refusal; an unreadable directory refuses. Without the variable a hosted session is refused: the message calls it a harness configuration problem to stop and report, and deliberately does not name the variable, so the agent is not invited to set it. `IMPECCABLE_COMPONENT_REVIEW_PENDING` is not read by this gate (only by the hosted capture service). A quoted `--force --reason` that satisfies the existing plates rule waives this reason together with the plate readings and is recorded the same way; the hero phase then does not ask for the review again. `record hero` has no force.
+
Assembly acceptance closes component and assembly reviews for this journey. The agent completes the rest of the page using the accepted direction, without reopening review for shared CSS, responsive changes, finish checks, or new manifest IDs. Needs-work rounds remain possible before acceptance. Original receipts and captures remain immutable. A separately requested new design journey uses a fresh review store; changing a manifest alone never starts one. Source-bound metric evidence below remains separate from this lifecycle.
### Human-reviewed text at the final comp gate
-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 and source 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 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.
+
+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`.
-This does not waive missing regions, overall comp fidelity, controls, raster production/placement, source integrity, or native capture checks. Changed reviewed sources, an unreviewed current dependency, 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.
+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.
### Visual approval carry-forward
diff --git a/docs/PLAN-REVIEW.md b/docs/PLAN-REVIEW.md
new file mode 100644
index 000000000..9e4bbf4ab
--- /dev/null
+++ b/docs/PLAN-REVIEW.md
@@ -0,0 +1,116 @@
+# Plan and asset review (component review v3)
+
+Comp-led builds fail most expensively when the agent decides a painted region (an illustrated figure, a metal texture, a photograph) can be drawn in code, then draws a stick figure or CSS stripes. That decision is made in the region map (`comp-spec`), long before any code exists. The human checkpoint before code therefore reviews two things: the generated raster assets, and the production plan for everything else. It no longer asks for HTML/CSS previews of text, controls and chrome; those are judged in the assembled first-viewport review, where they can be judged in context.
+
+## Where it sits
+
+`comps → spec → plates → [plan and asset review] → hero → [first-viewport review] → sections → motion → responsive → review`
+
+The review opens once every raster region has its plate. Nothing in the page is written before it. `build-phase advance` from plates or hero (and `record hero`) refuses until the review for the current build journey is accepted, its reviewed spec digest equals the current `.impeccable/build/spec.json`, and the plates it pinned are unchanged. A later spec change (for example a reclassified region) or a replaced plate needs a new round; unchanged decisions carry over. Score the plates before opening the review, so a plate fixed for the gate does not reopen it.
+
+## Packet: schemaVersion 3, stage `components`
+
+The stage keeps its name so hosts and `lifecycle --require components hero` keep working. The model does not author this packet. `impeccable component-review plan` writes `.impeccable/review/components.json` from the spec, the comp and the plate files, and refuses (listing every missing plate) while any raster region lacks its plate.
+
+```json
+{
+ "schemaVersion": 3,
+ "stage": "components",
+ "id": "<from spec/build journey>",
+ "title": "<surface title>",
+ "comp": {"path": "<approved comp>", "width": 1440, "height": 900},
+ "specSha256": "<sha256 of .impeccable/build/spec.json>",
+ "components": [
+ {
+ "id": "hero-figure", "name": "Hero figure", "kind": "plate", "role": "asset",
+ "box": {"x": 0.52, "y": 0.1, "w": 0.4, "h": 0.6},
+ "note": "Illustrated fisherman mending a net",
+ "medium": "raster",
+ "preview": {"kind": "image", "path": "assets/hero-figure.png"},
+ "dependencies": []
+ },
+ {
+ "id": "brushed-panel", "name": "Brushed panel", "kind": "chrome", "role": "plan",
+ "box": {"x": 0, "y": 0.7, "w": 1, "h": 0.1},
+ "note": "Brushed steel band under the nav",
+ "medium": "code",
+ "preview": {"kind": "comp-crop"},
+ "flags": [{"id": "painted-pixels", "message": "Looks painted: 41 colours beyond its two main tones and soft shading across 47% of it. Drawn in code, this becomes a flat copy."}],
+ "codeDrawn": false,
+ "dependencies": []
+ }
+ ],
+ "codeRegions": [
+ {"id": "headline", "name": "Headline", "kind": "text", "box": {"x": 0.06, "y": 0.2, "w": 0.4, "h": 0.2}, "note": "A little closer to the sea."}
+ ]
+}
+```
+
+- `role: "asset"`: every raster region (`plate`, `image`, `texture`). Preview is its plate file, pinned by hash as today.
+- `role: "plan"`: a code region (`text`, `control`, `chrome`) that needs a human decision: it carries a `flags` entry, or `codeDrawn: true`, or it is non-container `chrome` whose `surface` is neither `flat` nor `rules`. Preview is `comp-crop` (no file; the UI crops the pinned comp by `box`).
+- `codeRegions`: every other code region. Listed for completeness and clickable on the map, but no decision is required. Containers (`container: true`) and bands are listed here.
+- Order of `components`: flagged items first (plan items with `flags` or `codeDrawn`, and assets with `flags`), in spec order, then the remaining assets, then the remaining plan items. An asset passes its `flags` through.
+- `reviewGroup` is not used in v3. `revision` per component is computed as today (component JSON plus pinned file hashes plus `specSha256`).
+
+## Decisions
+
+Per component: `{revision, action, feedback, split: false}` plus, for `reclassify`, `kind`:
+
+- `approve`: asset looks right / code is the right medium.
+- `revise`: on an asset, regenerate with `feedback`. With `split: true` (assets only; feedback optional) the asset is a baked composite that should come back as layers: a frame plate with a transparent opening at the same box, the view as its own image region at the opening, and each moving part as its own plate. On a plan item, `feedback` is required and describes a region-map change neither medium fixes (for example, artwork from a neighbouring photo spills over a code region: extend that photo under it, or split the material into its own plate). The region's kind can stay.
+- `reclassify` (plan items, and any `codeRegions` id): `kind` is `plate`, `image` or `texture`; `feedback` optional. Allowed for ids in `codeRegions` without a component entry; those go in `submission.reclassify: [{id, kind, feedback}]`.
+
+`missing` and `inventoryConfirmed` stay. The UI sets `inventoryConfirmed: true` when the user approves with nothing marked missing (the approve button says so). A submission with any `revise`, `reclassify` or `missing` entry is `changes-requested`. Approval requires every component approved and no reclassification.
+
+## Capture
+
+v3 needs no browser. `component-review capture` records the raster-source proof for each asset (as today) and a `comp-crop` proof (comp hash plus box) for each plan item. `verify` and `lifecycle` apply `capture_intact` to v3: blobs match hashes, sources match, every packet component has proof, raster previews match their raster-source proof, and `specSha256` matches the pinned spec.
+
+## After feedback
+
+The agent applies the receipt: for `reclassify`, change the region's kind (and note) in the regions file, rerun `comp-spec --comp <comp.png> --regions <regions.json>`, produce the new plates; for `revise` on an asset, regenerate the plate with the feedback; for `revise` on a plan item, change the regions file as the feedback says, rerun `comp-spec --comp <comp.png> --regions <regions.json>` and produce any new plates. Then `component-review plan`, `capture`, `serve` again. Unchanged decisions carry.
+
+## Hero
+
+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.
+
+## 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.
+
+The reading is taken over 64px windows (half-window stride; a smaller crop is one window) and the strongest window counts, so a painted patch reads the same in a tight box and in a generous one, and a container is judged on what shows between its raster children. Per window: `colours`, the distinct colours on a 2x-averaged copy that sit off the line between the window's two main tones, and `soft`, the share of mid-tone pixels in its 8x8 blocks with any contrast. A window reads painted at (colours, soft) of at least (18, 0.44) or (28, 0.38), or 60 colours alone.
+
+Calibration: 556 regions from 12 eval comps plus the 24-run replay. Every photograph and about half the plates read painted when scored as code regions (the misses are small single-ink sprigs and flat plaques that look like type). No text or control region that shows only type flags; the ones that do hold painted material (foliage over a nav bar, a painted shutter button, a plaque).
+
+The stored `message` is an observation for the reviewer ("Looks painted: 35 colours beyond its two main tones and soft shading across 45% of it. Drawn in code, this becomes a flat copy."). The instruction for the agent lives only in comp-spec's printed `FLAG <id> painted-pixels: ...` line.
+
+## Baked-composite flag (`comp-spec`)
+
+A raster region (`plate`, `image`, `texture`) whose note names a frame and then an opening onto content gets `flags: [{"id":"baked-composite","message":...}]`. Frame words: surround, frame, framing, window, doorway, door, arch, archway, shutter, cartouche, portal, niche, alcove, mirror, porthole, casement, proscenium. Opening words, which must come after the first frame word: view, vista, showing, reveals, looking out/through/into, inside, interior, through, beyond, opening onto, glimpse, "photograph/scene/picture/image of". "Full-frame" and "full-bleed" do not count as frames. Two cases never flag: a note whose leading clause is the content ("photograph through window: guest room, balcony doors open to the sea"), where later frame words are subject matter; and a raster region at least half covered by another plate whose note names a frame with its own opening ("window surround ..., transparent opening"), because that composite is already split.
+
+The order rule keeps the frame-as-content cases clean: "a photograph of a window", "coast photograph seen through a carriage window" and "sea window photo" do not flag. "Framed portrait photo" does not flag either: nothing in it says the frame is a separate object with the portrait behind it rather than the photo's own composition, and flagging every framed photo would bury the real case. Checked on 128 raster notes from the calibration comps, the 24-run replay and the plan-review eval workspaces: 11 hits (the hotel run's three windows, seven painted room windows "showing a bright hotel bedroom interior", one "painted window ... photograph of stone terrace"), all real frame-plus-view composites, and no false positives. No pixel signal is used; the note is enough on this data.
+
+The message is an observation for the reviewer and names a moving part when the note has one: "Frame and view are one image here, so the page can't swap the view or move the shutters on their own." The printed `FLAG` line adds the instruction for the agent: a frame plate with a transparent opening, the view as its own image region beneath it, and moving parts as their own plates, composited in the page. It is a flag, not a refusal.
+
+## Surface reading (`comp-spec`)
+
+Every code region also gets `"surface": {"flat": bool, "rules": bool}`, measured on its own pixels: raster regions and smaller regions inside it (its text, its controls) are set aside.
+
+- `flat`: under 2% of those pixels leave the main tone. A bare ground: a nav field, a section background.
+- `rules`: the box is at most 6px on its short side, or at least 80% of its ink lies on straight horizontal or vertical runs of 12px or more that are at most 6px thick. Frame edges, ticks, dividers, hairline grids.
+
+`component-review plan` keeps non-container `chrome` as a plan item only when it is neither `flat` nor `rules`, so emblems, marks, icons and ornaments stay in the review and grounds and rules move to `codeRegions`. A flagged or `codeDrawn` region is a plan item regardless. A spec written before this reading carries no `surface` and keeps every non-container chrome.
+
+## Engine notes
+
+Details the engine settles that the sections above leave open (full wording in `docs/CLI-CONTRACT.md`, "Component review"):
+
+- Packet identity: `id` is `components` for every round, so rounds share one session and decisions carry; `title` is `Plan and asset review`, plus ` · <artifact>` when the build state names one. `name` is derived from the region id.
+- v3 capture evidence has its own schema, `plan-review-proof-v1`, so a browser capture can never stand in for it or the reverse. Plan items carry no `context` or `thumbnail`; assets get `thumbnail` equal to their preview.
+- Decisions keep today's required `feedback` string (empty allowed) for every action; `feedback` is optional only in `submission.reclassify` entries.
+- A spec with no raster region and no plan item has nothing to review: `plan` refuses to write an empty packet, and the build-phase gate does not wait.
+- Hosted sessions (`IMPECCABLE_COMPONENT_REVIEW_TOOL` set) keep their review in the host's store. The host names its trusted session directories in `IMPECCABLE_COMPONENT_REVIEW_SESSIONS` (an OS path list, the same directories `lifecycle --hosted --session-dir` takes), and the gate applies the local rules to them: an accepted first viewport, or an accepted, capture-intact v3 review whose `specSha256` matches the current spec. Without that variable a hosted session is refused (fail closed). `IMPECCABLE_COMPONENT_REVIEW_PENDING` plays no part in this gate; only the hosted capture service reads it.
+- The plates `--force` rule is unchanged and not widened: a reason that passes it (a quoted user downgrade of the comp) waives the review reason along with the plate readings, and is recorded. `record hero` has no force.
diff --git a/package.json b/package.json
index efb2b18fd..98eb26801 100644
--- a/package.json
+++ b/package.json
@@ -74,11 +74,11 @@
"build:component-review": "bun scripts/build-component-review.mjs"
},
"optionalDependencies": {
- "@impeccable/cli-darwin-arm64": "0.1.6",
- "@impeccable/cli-darwin-x64": "0.1.6",
- "@impeccable/cli-linux-x64": "0.1.6",
- "@impeccable/cli-linux-arm64": "0.1.6",
- "@impeccable/cli-windows-x64": "0.1.6"
+ "@impeccable/cli-darwin-arm64": "0.1.7",
+ "@impeccable/cli-darwin-x64": "0.1.7",
+ "@impeccable/cli-linux-x64": "0.1.7",
+ "@impeccable/cli-linux-arm64": "0.1.7",
+ "@impeccable/cli-windows-x64": "0.1.7"
},
"devDependencies": {
"@ai-sdk/anthropic": "^4.0.7",
diff --git a/scripts/lib/kit-css-module.mjs b/scripts/lib/kit-css-module.mjs
new file mode 100644
index 000000000..25e185d50
--- /dev/null
+++ b/scripts/lib/kit-css-module.mjs
@@ -0,0 +1,11 @@
+// Writes ui/component-review/vendor/kit-css.ts from the vendored stylesheets so both the
+// Bun bundle and Vite hosts (the eval dashboard imports this source) can load them;
+// neither `with { type: 'text' }` nor `?raw` works in both.
+import { readFileSync, writeFileSync } from 'node:fs';
+export function writeKitCssModule(dir) {
+ const read = (name) => readFileSync(dir + name, 'utf8');
+ const body = [['tokens', 'kinpaku-tokens.css'], ['kit', 'kinpaku-kit.css'], ['rail', 'docs-rail.css']]
+ .map(([name, file]) => `export const ${name} = ${JSON.stringify(read(file))};`).join('\n');
+ writeFileSync(dir + 'kit-css.ts', `// GENERATED from the vendored stylesheets by scripts/sync-kinpaku-kit.mjs. Do not edit.\n${body}\n`);
+}
+if (import.meta.url === `file://${process.argv[1]}`) writeKitCssModule(new URL('../../ui/component-review/vendor/', import.meta.url).pathname);
diff --git a/scripts/sync-kinpaku-kit.mjs b/scripts/sync-kinpaku-kit.mjs
new file mode 100644
index 000000000..dc6c517b0
--- /dev/null
+++ b/scripts/sync-kinpaku-kit.mjs
@@ -0,0 +1,33 @@
+// Copies the Impeccable design-system kit from the private site repo into
+// ui/component-review/vendor/. The site is the source of truth; these files
+// are verbatim excerpts so a future sync is this script, not a hand edit.
+// node scripts/sync-kinpaku-kit.mjs [path-to-impeccable-site]
+import { readFileSync, writeFileSync } from 'node:fs';
+import { writeKitCssModule } from './lib/kit-css-module.mjs';
+import { homedir } from 'node:os';
+import { resolve } from 'node:path';
+const site = resolve(process.argv[2] ?? `${homedir()}/code/impeccable-site`, 'site');
+const out = new URL('../ui/component-review/vendor/', import.meta.url).pathname;
+const read = f => readFileSync(resolve(site, f), 'utf8');
+// A section runs from its "/* ===" banner to the next banner. Pick sections by
+// a selector they define, so line drift upstream does not matter.
+function sections(css, wanted) {
+ const parts = css.split(/(?=^\/\* =+\n)/m);
+ return wanted.map(sel => {
+ const hit = parts.find(p => p.includes(`\n${sel} {`) || p.includes(`\n${sel},`));
+ if (!hit) throw new Error(`kit section defining ${sel} not found`);
+ return hit.trimEnd();
+ }).join('\n\n');
+}
+const kit = read('styles/kinpaku-kit.css');
+const header = src => `/* VENDORED from impeccable-site/site/${src} (the source of truth).
+ Do not edit here: change the site, then run node scripts/sync-kinpaku-kit.mjs. */\n`;
+writeFileSync(out + 'kinpaku-tokens.css', header('styles/kinpaku-tokens.css') + read('styles/kinpaku-tokens.css'));
+writeFileSync(out + 'kinpaku-kit.css', header('styles/kinpaku-kit.css (buttons, tabs, select, icon button, instrument strip, grain, switch, paper strip, thumb)') +
+ sections(kit, ['.ks-button', '.ks-tab-list', '.ks-checkbox', '.ks-icon-button', '.ks-instrument-key', ':root', '.ks-switch', '.ks-tag', '.ks-thumb']) + '\n');
+const docs = read('styles/docs-kinpaku.css');
+const rail = docs.slice(docs.indexOf('/* Group headings are ink and bold'), docs.indexOf('/* Commands reuse the navigation above'));
+writeFileSync(out + 'docs-rail.css', header('styles/docs-kinpaku.css (the command rail list: the site\'s selected-row pattern)') + rail.trimEnd() + '\n');
+writeFileSync(out + 'instrument-strip.js', `// VENDORED from impeccable-site/site/scripts/instrument-strip.js (the source of truth).\n// Do not edit here: change the site, then run node scripts/sync-kinpaku-kit.mjs.\n` + read('scripts/instrument-strip.js'));
+console.log('synced kit into', out);
+writeKitCssModule(out);
diff --git a/scripts/test-suites.mjs b/scripts/test-suites.mjs
index 6fdca94e7..38d7c3c0e 100644
--- a/scripts/test-suites.mjs
+++ b/scripts/test-suites.mjs
@@ -47,6 +47,7 @@ export const SUITES = {
'tests/build.test.js',
'tests/component-review-bundle.test.js',
'ui/component-review/model.test.ts',
+ 'ui/component-review/plan-model.test.ts',
'ui/component-review/viewport.test.ts',
'tests/lib/provider-blocks.test.js',
'tests/lib/transformers/provider-blocks.test.js',
diff --git a/skill/agents/impeccable-asset-producer.md b/skill/agents/impeccable-asset-producer.md
index dbf9fc11a..5ba1386eb 100644
--- a/skill/agents/impeccable-asset-producer.md
+++ b/skill/agents/impeccable-asset-producer.md
@@ -26,7 +26,7 @@ When the parent hands you a decision card packet instead of an approved mock, th
## Review handoff
-After the initial production batch, return the actual files and any unresolved drift to the parent for the user-facing component review in [component-review.md](../reference/component-review.md). The parent includes rendered code regions alongside these rasters. A parent or automatic visual check is not a substitute for that human checkpoint. Apply requested repairs and preserve unchanged assets; do not self-approve them. This checkpoint does not apply to the Decision Comps job above.
+Return the actual files and any unresolved drift to the parent for the user's plan and asset review in [component-review.md](../reference/component-review.md). A parent or automatic visual check is not a substitute for that human checkpoint. The parent may call you again after it: for regions the user reclassified from code to raster (the spec now lists them with a plate path), or for plates the user asked to revise, with their feedback as the prompt notes. Produce only those, preserve unchanged assets, and hand off real files as before; never self-approve. This checkpoint does not apply to the Decision Comps job above.
## Input Contract
@@ -44,6 +44,7 @@ Per region, in the spec's order:
2. Choose the background from the approved region: an isolated figure, object, or line drawing on the page ground is a **transparent cutout**; a photograph, full-frame illustration, or texture stays **opaque**. Save `{{scripts_path}}/impeccable comp-spec --plate-prompt <id> --background transparent` to a UTF-8 prompt file for a cutout; use `--background opaque` otherwise. The transparent prompt preserves reference placement and clear margins, white paint, fine edges, and interior holes.
3. Produce the plate at its exact spec `plate` path. Create the output directory first and choose a supported output size matching the region's aspect, at least 1.5x its pixel dimensions. Prefer the harness-native image tool with the crop as input and the saved prompt; request a transparent PNG for cutouts, then run `{{scripts_path}}/impeccable embed-prompt <plate> --prompt-file <prompt.txt>` (if you refine the prompt, save and embed the exact text sent). With the API fallback, run `{{scripts_path}}/impeccable generate-image --ref <crop.png> --prompt-file <prompt.txt> --out <plate.png> --size <WxH> --quality high --background transparent` for a cutout, or `--background opaque` otherwise. The API fallback embeds the prompt and records the background in the sidecar. The output must be PNG; the fallback requests native alpha and performs no chroma-keying.
4. Open the plate beside the crop and compare subject, placement, scale, palette, and style. For cutouts, verify a real alpha channel and inspect composites on light and dark grounds: white paint must stay solid, interior holes must clear, and fine edges must avoid halos. Inspect glass and soft shadows carefully; partial alpha alone does not ensure convincing translucency. Never chroma-key native transparent output or flatten it before saving. If a native tool returns opaque pixels or a painted checkerboard, retry with the API fallback when available; otherwise report the transparency blocker. On a visual miss, tighten the prompt and regenerate once. Two misses on one region: keep the better plate, mark it `needs_parent_review`, and name the drift. The parent runs the plates gate after all assets exist; report `unscored` until a gate score is available.
+5. A frame plate (a window, a doorway, an arch) is a transparent cutout with an opening: generate it with a transparent background and keep the opening fully transparent. Verify the alpha inside the opening before saving: no baked view, no glow or vignette halo across it. The content seen through the opening is its own image region; produce it separately at the opening's size.
<codex>
Codex: the imagegen skill's built-in `image_gen` path is the native tool here; prefer it for generation and editing, with the crop as the input image.
diff --git a/skill/reference/component-review.md b/skill/reference/component-review.md
index 668e68d8c..9f7dc1d9f 100644
--- a/skill/reference/component-review.md
+++ b/skill/reference/component-review.md
@@ -1,71 +1,36 @@
-# Component review
+# Plan and asset review
-Use this checkpoint on comp-led builds after producing the initial component kit and before composing the page. The approved comp is the reference. The user reviews the actual produced components, including code; a list of planned assets or screenshots supplied by the builder is not a review of what will ship.
+Use this checkpoint on comp-led builds once every raster region has its plate and the plates gate has scored them, before any page code exists. The approved comp is the reference. The user reviews two things: the plates that will ship, and the production plan for everything else, meaning which regions code draws. A painted region planned as code is the most expensive mistake a comp-led build makes, and this is where the user catches it. Text, controls and chrome are judged later, in the assembled first viewport.
-## Prepare the component kit
+## Plan, capture, serve
-Keep the measured spec's region IDs. Include every visible region: produced raster assets and working HTML/CSS/SVG for text, controls, patterns, decoration and layout elements. A region rendered in code needs an actual review document, not a promise to implement it later. Use semantic HTML for content and controls. Do not flatten the page or combine unrelated regions to avoid review. Report omitted regions so the user can mark what is missing.
+Run `{{scripts_path}}/impeccable component-review plan`. It writes `.impeccable/review/components.json` from the measured spec, the comp and the plate files, and refuses, naming each one, while any raster region lacks its plate. Never write or edit that file for this stage: the packet is derived from the spec, so every change belongs in the regions file.
-For a repeated code pattern, give instances of the same component and role the same `reviewGroup` name. Group peers of the same kind, not a container with its contents or unrelated text roles. Keep every instance and its region ID in the manifest, in the same kit document. The review opens with one item per group and shows its instances together. One explicit group decision applies to its unreviewed instances; the user can open an instance to leave an exception. Existing decisions are preserved. Unique raster assets still require their own review; grouping never removes inventory or gate checks.
+If the harness exposes `component_review`, call it with `manifest_path` set to `.impeccable/review/components.json`. The host captures, presents the review and returns the user's decisions. A suspended request is waiting for the user; it is not a failed build or an approval.
-Before producing assets, inspect each reference crop against its named subject. Coarse grid cells and automatic ink snapping can include neighbors or omit parts of a compound element. Correct the measured region with an explicit normalized `box`; do not build to a known bad crop. Check the code preview contains the complete component before presenting it. The capture tool refuses content cut off by the review crop.
+Otherwise run `{{scripts_path}}/impeccable component-review capture --manifest .impeccable/review/components.json`, then start `{{scripts_path}}/impeccable component-review serve --session <returned session>` in the background. Open the URL it prints in the available browser and wait for the user; `serve` exits 0 once they submit. Read the decisions with `{{scripts_path}}/impeccable component-review status --session <id>`; `{{scripts_path}}/impeccable component-review verify --manifest .impeccable/review/components.json` confirms approval and refuses pending, needs-work and stale input. Never submit the page or write a receipt on the user's behalf.
-Write `.impeccable/review/components.json` with this manifest format:
+`serve` exits 2 when this session has no browser (the same signal as the decision page) and 4 when it closes after 30 idle minutes without a decision. Either way no one is reviewing: stop waiting, do not approve anything yourself, and do not build past this checkpoint. End the run and report the plan and asset review as pending with its session ID, so the user can resume it. A waiting review is pending work, not a completed build.
-```json
-{
- "schemaVersion": 2,
- "id": "components",
- "title": "Component review",
- "stage": "components",
- "comp": {"path": ".impeccable/mocks/comp-2.png", "width": 1536, "height": 1024},
- "components": [
- {
- "id": "illustration",
- "name": "Illustration",
- "medium": "raster",
- "box": {"x": 0.5, "y": 0.2, "w": 0.45, "h": 0.7},
- "note": "Produced cutout; positioned over the page ground.",
- "preview": {"kind": "image", "path": "assets/illustration.png"},
- "dependencies": []
- },
- {
- "id": "headline",
- "name": "Headline",
- "medium": "html",
- "box": {"x": 0.05, "y": 0.2, "w": 0.4, "h": 0.25},
- "note": "Rendered semantic heading and its typography.",
- "preview": {"kind": "page", "path": ".impeccable/review/components/kit.html", "selector": "#headline"},
- "dependencies": ["assets/type.woff2"]
- }
- ]
-}
-```
+## Act on the receipt
-The coordinates above only illustrate the schema. Use the approved comp's actual pixel dimensions and each measured region's normalized bounds (the spec’s `box` is already normalized; divide only pixel coordinates by comp dimensions). Each code preview requires a `selector` matching exactly one component element inside the document body. Shared kit documents are supported: the native capturer preserves layout and authored styles, hides other components, and crops to the measured box. A separately targeted child is excluded from its parent's isolated preview. Background fields therefore show their own paint, not the text and controls laid over them. Place components at the comp coordinates in the review document.
+Apply the user's decisions as given, never your own favorable verdict in their place.
-For a raster placed inside the kit, add `context: {"kind":"page","path":".impeccable/review/components/kit.html","selector":"#illustration"}` and declare that document's dependencies. This identifies its DOM placement so a containing code component excludes it too; the raster preview remains the original image bytes.
+- **approve**: once every item is approved and the inventory is confirmed, advance to the hero.
+- **revise** (a plate): regenerate that plate at the same path with the user's feedback.
+- **revise with split** (an asset): replace that region in the regions file with its layers: a frame plate with a transparent opening (kind `plate`, same box), the content as its own `image` region at the opening's box, and each moving part (a shutter, a door) as its own plate. Name each layer after the original region, as `<id>-frame`, `<id>-view` or `<id>-shutter-left`, so the next round shows it as part of the user's request. Rerun `{{scripts_path}}/impeccable comp-spec --comp <comp.png> --regions <regions.json>` and produce the plates.
+- **revise** (a plan item): change the regions file as the feedback says (resize or extend a raster region, split material into its own plate region, or adjust the code region), rerun `{{scripts_path}}/impeccable comp-spec --comp <comp.png> --regions <regions.json>`, and produce any new plates.
+- **reclassify** (a code region): in the regions file, change that region's `kind` to the one the user chose and rewrite its `note` to describe the material. Rerun `{{scripts_path}}/impeccable comp-spec --comp <comp.png> --regions <regions.json>`, then produce the new plates, with the asset producer when subagents are available.
+- **missing**: add the region to the regions file, rerun `{{scripts_path}}/impeccable comp-spec --comp <comp.png> --regions <regions.json>`, and produce its plate if it is raster.
-The runtime also captures an unmodified **In context** view from that same document. This assembled view is reference only, not another component to approve. Keep each review target independently meaningful; use context to show a group together rather than submitting the same content for approval as both a combined component and its children. The final assembled hero still has its own review checkpoint. Include every file the document uses in `dependencies`, including linked CSS, fonts and images. The runtime also binds the measured spec for the component stage and checks its inventory. Local paths only. Static PNG, WebP and JPEG previews retain their original bytes and actual transparency; never draw a checkerboard into the asset.
-
-Component capture supports stable HTML/CSS and inline SVG. Supply a static review state for motion and keep the implementation's real inputs. A scripted, canvas or otherwise unsupported component is a blocker to report, not permission to substitute a raster or omit it.
-
-Keep the implementation's intended fonts in the review document. Vendor external fonts locally and declare them as dependencies; removing their imports changes the component being reviewed. Capture rejects unavailable primary font families rather than presenting a silent fallback.
-
-## Present and wait
-
-If the harness exposes `component_review`, call it with `manifest_path` set to `.impeccable/review/components.json`. The host captures the component files, presents this same review interface and returns the user's decisions. A suspended request is waiting for the user; it is not a failed build or an approval.
-
-Otherwise run `{{scripts_path}}/impeccable component-review capture --manifest .impeccable/review/components.json`, then start `{{scripts_path}}/impeccable component-review serve --session <returned session>` in the background. Open the URL it prints in the available browser and wait for the user; `serve` exits 0 once they submit. Read the result with `{{scripts_path}}/impeccable component-review verify --manifest .impeccable/review/components.json`; pending, needs-work and stale input all refuse approval. Never submit the page or write a receipt on the user's behalf.
-
-`serve` exits 2 when this session has no browser (the same signal as the decision page) and 4 when it closes after 30 idle minutes without a decision. Either way no one is reviewing: stop waiting, do not approve anything yourself, and do not build past this checkpoint. End the run and report the component review as pending with its session ID, so the user can resume it. A waiting review is pending work, not a completed build.
-
-The user can approve components, request changes, and mark missing regions. Act on their feedback without replacing it with your own favorable verdict. Keep component IDs stable, update the actual implementation and dependency list, and present another round. The UI carries only approvals whose component inputs have not changed. Selector ownership is an input too; changing a target invalidates affected captures. Do not ask the user to reapprove unchanged work. Continue only when the inventory is confirmed and all components are approved.
+Then run `plan`, `capture` and `serve` again. Unchanged decisions carry over, so the user sees only what changed. Any spec change, or a plate replaced after acceptance, needs a new round; the build-phase gate stays closed until the review of the current spec is accepted.
## Assemble and review
-Build the first viewport from the approved component files and run the existing plates and hero gates. Resolve component changes before presenting the assembled first viewport; human review does not waive integrity checks.
+Build the first viewport from the approved plates and plan, and run the hero gate. Human review does not waive its integrity checks. After three failed hero attempts, stop iterating and present the first-viewport review with the current build; the user's eye settles what the readings could not.
+
+Present a second manifest at `.impeccable/review/hero.json`, with `id` and `stage` set to `hero`. Use one page-preview component covering the assembled first viewport, its real HTML entry, and its complete dependency list (local paths only). The reference stays the approved comp. Call the same host review tool, or run `capture`, `serve` and `verify` with this manifest. Needs-work feedback starts another assembly round.
-Once the first viewport is ready for calibration, present a second manifest at `.impeccable/review/hero.json`, with `id` and `stage` set to `hero`. Use one page-preview component covering the assembled first viewport, its real HTML entry, and its complete dependency list. The reference stays the approved comp. Call the same host review tool (or native capture/serve/verify workflow). Needs-work feedback starts another assembly round. Acceptance closes both review stages for this build: never request component or assembly approval again. Complete the rest of the page, responsive behavior, finish checks and documentation using the accepted first viewport as the visual direction. This is first-viewport calibration, not a claim that the user reviewed the rest of the page. Shared stylesheet edits do not reopen approval. Preserve the accepted direction; a later explicit user change is a new task.
+Acceptance closes human review for this build: never request plan, asset or assembly approval again. While the page renders what the user accepted, the hero score, the palette check and every numeric reading are advisories; material vetoes still hold (a missing or unreferenced plate, an SVG illustration, an organic clip, a clipped plate, invented ink, failed rendered presence). When the capture no longer matches the accepted screenshot, restore what the user accepted; until then the readings apply. Complete the rest of the page, responsive behavior, finish checks and documentation with the accepted first viewport as the visual direction. This is first-viewport calibration, not a claim that the user reviewed the rest of the page. Shared stylesheet edits do not reopen approval. Preserve the accepted direction; a later explicit user change is a new task.
Assembled-page capture executes inline and declared local scripts from the pinned inputs. Network APIs, frames and workers are unavailable; the initial viewport must settle before capture. Keep the real page and declare its scripts rather than removing behavior to pass review.
diff --git a/skill/reference/new-work.md b/skill/reference/new-work.md
index aa2a0081f..a77b5d511 100644
--- a/skill/reference/new-work.md
+++ b/skill/reference/new-work.md
@@ -50,7 +50,7 @@ The script deals three of your structures; the dice pick which three reach the u
The standing exit: every direction round offers one quiet, permanent alternative, the category standard, played straight. It is the user's door, never yours: never recommend it, never weigh it against the roll, never let it soften the dealt directions; the counterweights bind the unchosen default, not the chosen one. When the user takes it (the canon action, a safer-steer, or plain words asking for the familiar or competitor-like path), convention becomes the commitment: ask once for two or three products this should sit alongside, make their craft level the bar, and execute the canon at full fidelity, without irony or smuggled quirk. Record a standing preference as a brand commitment in PRODUCT.md. <!-- rule:skill-canon-standing-exit --> Re-roll eliminates every direction already shown, grounded and challenger alike; after two consecutive re-rolls, ask what quality is missing. Re-roll on your own only on named factual grounds, when the assigned direction cannot carry the product's truth or task; taste is never grounds. The user may re-roll freely, and a user- or brief-pinned direction beats the roll, always. Resolve collisions field by field: preserve every user- or brief-pinned constraint. In dimensions the brief leaves open, the assignment still binds through its topology, controls, state vocabulary, and ritual; when only its materials conflict with a pinned visual direction or PRODUCT.md brand commitment, translate that material expression and name the translation in the presented direction. A look mismatch is not grounds to re-roll. <!-- rule:skill-assigned-plus-reroll --> Present the decision visually: write an options payload with the assigned direction leading, its raised lines included; the pick card when one exists; the dealt challengers as alternates with their QUALITY BAR cards, verdicts, and kept lines; re-roll with its safer and bolder registers; steer; canon enabled; and `buildPath` carrying the recorded default with `toggle: true` whenever image generation exists (details in the build-path paragraph below). A degraded roll with no challengers still uses the page, as a single text-only card with re-roll. Give every card the same anatomy: thesis, palette, materials, first viewport, honest risk, and the challengers' case lines (`--schema` prints the exact shape); the page renders identity from these fields, demotes declined challengers to their row on its own, and a challenger's catalog image rides as labeled inspiration, never the promise of the build. Author `canonCard` too: the category standard as one honest card, same anatomy; the page keeps it subordinate, and the counterweights still bind you. Run `{{scripts_path}}/impeccable serve-question --start --payload <file>` (`--schema` first for the payload shape). It daemonizes, prints the page URL and a key, and exits; open that URL for the user, in-app browser first, then the system opener, then showing the URL. Collect the choice with `--wait --key <key>`, repeating while it exits 3; the ANSWER prints as JSON. An ANSWER of `{"optionId":"reroll"}` keeps the server alive and the page open on a loading hand: rerun concept-seed with the same `--scope` and `--mode` plus `--from <seed-key> --reroll <n>` (1 on the first re-roll, counting up), build the next payload, deliver it with `--update --key <same key> --payload <file>`, then return to `--wait` on that key. Never `--start` a second server or fall back to chat here: either strands the open tab on a hand that never arrives. Exit 4 means the page closed unanswered: re-present once through the structured question tool, and with no answer there either, proceed unattended with the assigned direction and state the assumptions. A harness that can leave a shell blocked in the background may run the script without `--start` and let it auto-open and block. Never predict the fallback: run the script, and only exit code 2 from starting it routes the decision to the structured tool; that exit is the fallback, never an error to retry. <!-- rule:skill-visual-decision-page -->
-When image generation exists, every card also declares a `comp` path under `.impeccable/mocks/decision/`, the canon card included. Where the harness sandboxes its shell, start the page through the least-sandboxed command path it offers: a sandboxed shell cannot bind the board's port, and the first-attempt failure costs a retry every session. Serve the page first, then produce the comps; the page shimmer-waits per slot and the user may answer before they land. Each card's image is that direction's north-star comp at full fidelity under [visualize.md](visualize.md)'s comp discipline: the requested surface's first viewport, structure-led prompt, real product name and real content, no invented commercial claims, in that card's own palette, type character, and material world, committed all the way. Generation takes the same time at any fidelity, so an unfinished draft pays comp cost for draft quality; fairness between cards is equal fidelity in each card's own grammar, one surface, one aspect, never shared unfinishedness. The frame's aspect is the surface's own: portrait at device viewport for a native app or mobile-first surface, landscape for desktop web; the decision page adapts to either, and a phone screen comped landscape is a broken frame, not a neutral default. Produce in reading order, the assigned card, then the pick, then the full-card hand, then canon, each file written with its prompt sidecar the moment it is done, so a re-roll's spend front-loads onto the cards read first; declined challengers get no comp, their catalog thumb is their face. With parallel subagents, fan out one agent per card: each spawn is the shipped asset producer with a single-comp packet, that card's fields, PRODUCT.md, the shared frame, and the card's declared path, up to four in flight. Regenerate inline any slot still empty when its agent returns; drop without ceremony any slot still empty when the user answers. No other supervision is owed. Without parallel subagents, generate in the main thread after serving, same order, and let the harness's own generation display carry the progress; the wait for the answer follows the last file. The chosen card's comp is not spent by the choice: comp-led, it enters the comp round as compositional option one; code-led, it returns at the finish review as the critique reference, what the image dared that the build did not. Unchosen comps stay in `.impeccable/mocks/decision/` as the round's spent hand; they carry no approval and imply none. With no image generation, cards carry their identity in palette chips and facts, and that page is complete, not a lesser version; the page then also demotes every challenger's catalog art to a labeled thumbnail on its own, because salience must encode the verdict, never the accident of which cards have images. <!-- rule:skill-decision-comps-full-fidelity --> <!-- rule:skill-salience-parity -->
+When image generation exists, every card also declares a `comp` path under `.impeccable/mocks/decision/`, the canon card included. Where the harness sandboxes its shell, start the page through the least-sandboxed command path it offers: a sandboxed shell cannot bind the board's port, and the first-attempt failure costs a retry every session. Serve the page first, then produce the comps; the page shimmer-waits per slot and the user may answer before they land. Load [visualize.md](visualize.md) before writing the first decision comp prompt, not at the comp round: each card's image is that direction's north-star comp at full fidelity under its comp discipline, and a prompt written before reading it misses every rule there: the requested surface as the real page, its first viewport and the start of the section below it, held like every comp to visualize.md's rule that a template skeleton stays the template whatever world paints it (your own pick included: a safe layout under a world skin is the template), structure-led prompt, real product name and real content, no invented commercial claims, in that card's own palette, type character, and material world, committed all the way. Generation takes the same time at any fidelity, so an unfinished draft pays comp cost for draft quality; fairness between cards is equal fidelity in each card's own grammar, one surface, one aspect, never shared unfinishedness. The frame's aspect is the surface's own: portrait at device viewport for a native app or mobile-first surface, landscape for desktop web; the decision page adapts to either, and a phone screen comped landscape is a broken frame, not a neutral default. Produce in reading order, the assigned card, then the pick, then the full-card hand, then canon, each file written with its prompt sidecar the moment it is done, so a re-roll's spend front-loads onto the cards read first; declined challengers get no comp, their catalog thumb is their face. With parallel subagents, fan out one agent per card: each spawn is the shipped asset producer with a single-comp packet, that card's fields, PRODUCT.md, the shared frame, the path to visualize.md for its comp discipline, and the card's declared path, up to four in flight. Regenerate inline any slot still empty when its agent returns; drop without ceremony any slot still empty when the user answers. No other supervision is owed. Without parallel subagents, generate in the main thread after serving, same order, and let the harness's own generation display carry the progress; the wait for the answer follows the last file. The chosen card's comp is not spent by the choice: comp-led, it enters the comp round as compositional option one; code-led, it returns at the finish review as the critique reference, what the image dared that the build did not. Unchosen comps stay in `.impeccable/mocks/decision/` as the round's spent hand; they carry no approval and imply none. With no image generation, cards carry their identity in palette chips and facts, and that page is complete, not a lesser version; the page then also demotes every challenger's catalog art to a labeled thumbnail on its own, because salience must encode the verdict, never the accident of which cards have images. <!-- rule:skill-decision-comps-full-fidelity --> <!-- rule:skill-salience-parity -->
The execution contract, comp-led or code-led, is a workflow preference, not a per-surface decision; no round asks it. The recorded default rides every round and the page's toggle handles the exception. Read the default from `.impeccable/config.json` (`buildPath`), the gitignored `.impeccable/config.local.json` winning where one machine differs from the team's committed value; with neither, comp-led is the default whenever image generation exists. Author every direction and surface payload with `buildPath: { "value": <default>, "toggle": true }`; the page renders a footer toggle with the trade stated beside it, and the ANSWER returns `buildPath` plus `buildPathFlipped`. A flipped value binds that session only and is never written back, with one exception, the only question this preference ever earns inside a round (init records it up front on projects that get the chance): when `buildPathFlipped` comes back true on a project that records no `buildPath` at all, ask once after the round closes whether to keep it as the standing default. Either answer writes `.impeccable/config.json`; the answer picks the value, never whether to record one. Yes writes the flipped value; "no, just this once" writes the value they flipped away from, the standing default they just confirmed by declining. Ask on the flip, never on the untouched default: a user who left the toggle alone told you nothing. A declined offer nothing writes down is an offer the next session makes again. When the user asks in words to change the standing default, update the file without asking. **Comp-led**: the chosen card's comp is law, generated before building when it does not yet exist, and the finish review audits the build against it; boldest composition on the table, fix rounds expected, and the comp is non-optional, no silent skipping. **Code-led**: no comp of this page and no apology for it; the QUALITY BAR boards still calibrate finish, and the ambition moves into the written contract, the FIRST VIEWPORT block plus a named signature interaction and motion grammar, which the finish reviewer audits in behavior; code-led is not a discount on commitment. A code-led round still declares each card's comp path as a flip reserve: when the user flips the toggle to comp mid-round, `--wait` returns once with BUILD PATH FLIPPED while the page shimmers the slots; generate each open card's comp into its declared path then, lead first, and wait again. The flip back is free, and a comp that already rendered rides at the finish review as the critique reference. Without image generation there is no toggle and no choice: code-led is the only path, stated in one line rather than asked. The old two-card execution-contract round is retired; `followup: true` remains the general mechanism for delivering any later round over the same table via `--update`. <!-- rule:skill-build-path-round -->
@@ -109,12 +109,12 @@ Then, in order, each closed by `{{scripts_path}}/impeccable build-phase advance`
0. **comps.** The comp round from [visualize.md](visualize.md): three compositional comps of the requested surface at its own viewport under `.impeccable/mocks/`, each with a prompt sidecar, put in front of the user; the chosen one's sidecar gets `"approved": true`. The gate counts them and reads the approval; a `start --comp` skips this phase because it already happened.
The comp-led path is a frontier-tier job: it asks the builder to hold a measured layout, place plates at their boxes, and act on numeric readings across a dozen attempts. Smaller or faster models produce a recognisable page and stall under the hero gate; if the model in hand is one of those, say so before the direction round and take the code-led path, or expect the run to end at the hero with its readings unmet.
-1. **spec.** Measure the comp: `impeccable comp-spec --comp <comp> --grid` writes a coordinate grid over the comp; open it, name every salient region by grid span in a regions file (text and control regions narrow to an ink cluster only when it retains at least 95% of the span’s contrasting pixels; inspect the resulting crop, especially for compound controls and multiline text; `snap: false` keeps the span, and an explicit `box` is taken as drawn) (kind `plate` / `image` / `texture` for anything painted: every illustration, photograph, figure, product object, and material texture; `text` / `control` / `chrome` for what code draws; every region carries a `note` saying what the comp shows there, which the plate prompt and the gate messages read), and run `impeccable comp-spec --comp <comp> --regions <file>`. The spec carries each region's box, sampled palette, and medium; `impeccable comp-spec --print` is the build's reference from here on. Type is measured, not guessed: `impeccable font-match --measure <text region>` reads the comp's cap height, width class, and weight off the pixels, and `impeccable font-match --rank <region> --text "..."` takes its candidates from a fingerprint index of the Google Fonts catalog (the nearest faces to the crop's shape) plus any names you pass with `--candidates`, renders them at that cap height with the region's words, and ranks them by fingerprint distance (its `USE` line is the CSS; its proof sheet shows the comp over the top three); with no browser resolvable it records the catalog's nearest face and says the size is estimated, which is still the choice to build on. Do not install a browser to rank, and never write a `chosen` face into the spec by hand: the gate accepts only what font-match wrote. The spec gate refuses to close until the lead text region is measured and ranked. A region note that describes painted material (a diagram, drawing, photograph, texture) under a code kind is refused at the spec: reclassify it as a plate, or reword the note if code really draws it. The script refuses a regions file that leaves comp ink unnamed (callouts, a parts table, a notes block): what is never named can never be missing, so everything the comp shows gets a region. It also refuses a `text` / `control` / `chrome` region larger than a quarter of the comp: that is a column, not an element, and a column scored as one region hides the plates, tables, and notes inside it. Name each element inside it (`container: true` only when it truly is one undivided element). Anything drawn is a plate: an inline SVG past an icon's budget (a diagram, notation, leader lines with arrows, a "quick approximation" of the artwork) is refused at the hero; icon-sized SVG (under 64px, a few paths) is fine, and a chart the page draws from data at runtime is a chart, not an illustration. Callout lines and arrows that annotate a drawing belong to that drawing's plate, with only their labels set as text. A crop of the comp is never a plate (the plates gate refuses a file that is a resample of the comp region: the comp's grain, its neighbours' edges, and its resolution would ship as the artwork); the crop is the reference the plate is generated from. A plate region's box has to hold its whole artwork with a margin: the spec measures the artwork's contact with the box edges and refuses a box that cuts through it (`bleed: true` only when the page really crops it there), because a plate placed with `object-fit: cover` on such a box shows the artwork minus the side the box lost. Anything not in the spec does not exist on the page: no borders, rules, containers, or chrome the comp does not show. Only three concessions exist: fonts (the closest obtainable face), icon glyphs (close enough, exact if the user chose an icon library; this covers the pictogram only, never a control's chrome, so a chevron, an arrow, a dropdown's border and fill, a button's shape are the comp's), and genuine defects in the comp such as spelling errors. <!-- rule:skill-comp-spec -->
-Inspect the proposed map before producing assets: `impeccable comp-spec --comp <comp> --regions <file> --inspect-map` writes a numbered overlay, exact crops, foreground-mask previews, and a consolidated report without changing the spec or build state. Inspect boundaries and excluded pixels together; an empty reference needs corrected geometry. `parentId` names an enclosing `container`; `reviewGroup` names repeated instances of the same code component and role, not all parts of one component. Neither removes regions or approves assets. The report diagnoses geometry, not semantic completeness.
+1. **spec.** Measure the comp: `impeccable comp-spec --comp <comp> --grid` writes a coordinate grid over the comp; open it, name every salient region by grid span in a regions file (text and control regions narrow to an ink cluster only when it retains at least 95% of the span’s contrasting pixels; inspect the resulting crop, especially for compound controls and multiline text; `snap: false` keeps the span, and an explicit `box` is taken as drawn) (kind `plate` / `image` / `texture` for anything painted: every illustration, photograph, figure, product object, and material texture; `text` / `control` / `chrome` for what code draws; every region carries a `note` saying what the comp shows there, which the plate prompt and the gate messages read), and run `impeccable comp-spec --comp <comp> --regions <file>`. The spec carries each region's box, sampled palette, and medium; `impeccable comp-spec --print` is the build's reference from here on. Type is measured, not guessed: `impeccable font-match --measure <text region>` reads the comp's cap height, width class, and weight off the pixels, and `impeccable font-match --rank <region> --text "..."` takes its candidates from a fingerprint index of the Google Fonts catalog (the nearest faces to the crop's shape) plus any names you pass with `--candidates`, renders them at that cap height with the region's words, and ranks them by fingerprint distance (its `USE` line is the CSS); with no browser resolvable it records the catalog's nearest face and says the size is estimated, which is still the choice to build on. Do not install a browser to rank, and never write a `chosen` face into the spec by hand: the gate accepts only what font-match wrote. The spec gate refuses to close until the lead text region is measured and ranked. A region note that describes painted material (a diagram, drawing, photograph, texture) under a code kind is refused at the spec: reclassify it as a plate, or reword the note if code really draws it. The script refuses a regions file that leaves comp ink unnamed: what is never named can never be missing. It also refuses a `text` / `control` / `chrome` region larger than a quarter of the comp: that is a column, not an element. Name each element inside it (`container: true` only when it truly is one undivided element). Anything drawn is a plate: an inline SVG past an icon's budget (a diagram, notation, leader lines with arrows, a "quick approximation" of the artwork) is refused at the hero; icon-sized SVG (under 64px, a few paths) is fine, and a chart the page draws from data at runtime is a chart, not an illustration. Callout lines and arrows that annotate a drawing belong to that drawing's plate, with only their labels set as text. Split regions by what varies independently, as [region-map.md](region-map.md) sets out; a framed view is a frame plate over its own image region. A crop of the comp is never a plate (the plates gate refuses a resample of the comp region); the crop is the reference the plate is generated from. A plate region's box has to hold its whole artwork with a margin: the spec measures the artwork's contact with the box edges and refuses a box that cuts through it (`bleed: true` only when the page really crops it there), because a plate placed with `object-fit: cover` on such a box shows the artwork minus the side the box lost. Anything not in the spec does not exist on the page: no borders, rules, containers, or chrome the comp does not show. Only three concessions exist: fonts (the closest obtainable face), icon glyphs (close enough, exact if the user chose an icon library; this covers the pictogram only, never a control's chrome, so a chevron, an arrow, a dropdown's border and fill, a button's shape are the comp's), and genuine defects in the comp such as spelling errors. <!-- rule:skill-comp-spec -->
+Inspect the proposed map before producing assets: `impeccable comp-spec --comp <comp> --regions <file> --inspect-map` writes a numbered overlay, exact crops, foreground-mask previews, and a consolidated report without changing the spec or build state. Inspect boundaries and excluded pixels together; an empty reference needs corrected geometry. `parentId` names an enclosing `container`; it never removes regions or approves assets. The report diagnoses geometry, not semantic completeness.
-2. **plates.** Every raster region ships as a plate: an illustration, photo, or figure regenerated at asset resolution from its comp crop, UI text removed, at its `plate` path (isolated ink, figures, or objects use native transparent PNG so they sit on the page's own ground; photos and textures stay opaque); a texture (paper, cloth, grain) is a clean patch of the comp region mirror-tiled to size, generated only when no clean patch exists. `impeccable comp-spec --crop <id>` writes the reference; save `impeccable comp-spec --plate-prompt <id> --background transparent` to a prompt file for a cutout, or use `--background opaque` otherwise. Prefer the harness-native image tool with that crop and prompt, then `impeccable embed-prompt <plate> --prompt-file <prompt.txt>`. The API fallback is `impeccable generate-image --ref <crop.png> --prompt-file <prompt.txt> --out <plate.png> --size <WxH> --quality high --background transparent` (use `--background opaque` for full-frame assets); create the output directory first. Verify actual alpha, white foregrounds, fine edges, and clear holes on light and dark grounds; do not chroma-key native output. After the initial assets exist, prepare the isolated code component previews and complete [component-review.md](component-review.md) before further gate-driven repair: the user reviews the whole component kit, including code, before page assembly. This checkpoint keeps the existing gates; it does not require passing them first. After the first viewport is ready, use the assembled-hero checkpoint to calibrate the direction. Once the user accepts it, both human review stages are closed; complete the remaining page and finish checks without reopening them. <!-- rule:skill-human-component-review --> The plates gate scores the assets against the comp; also inspect placement and scale visually. With parallel subagents, spawn the shipped asset producer (`impeccable-asset-producer`; `impeccable_asset_producer` in codex; `/impeccable-asset-producer` in Cursor; on GitHub Copilot say "Use the impeccable-asset-producer agent") with the spec path and let it produce them all; without subagents, produce them here. A crop of the comp is a reference, never a shipping pixel. The gate checks every plate exists, is at least 1.5x the region's size, and reads as the region. Page code waits for this gate: a page written before its plates exist is a page that draws its material in CSS. A single-file deliverable changes nothing here: the plate is produced the same way and inlined as a data URI. `--force` exists for one case only, the user downgrading the comp's authority in words you quote in `--reason`; the script refuses every other reason. <!-- rule:skill-plates-before-page -->
+2. **plates.** Every raster region ships as a plate: an illustration, photo, or figure regenerated at asset resolution from its comp crop, UI text removed, at its `plate` path (isolated ink, figures, or objects use native transparent PNG so they sit on the page's own ground; photos and textures stay opaque); a texture (paper, cloth, grain) is a clean patch of the comp region mirror-tiled to size, generated only when no clean patch exists. `impeccable comp-spec --crop <id>` writes the reference; save `impeccable comp-spec --plate-prompt <id> --background transparent` to a prompt file for a cutout, or use `--background opaque` otherwise. Prefer the harness-native image tool with that crop and prompt, then `impeccable embed-prompt <plate> --prompt-file <prompt.txt>`. The API fallback is `impeccable generate-image --ref <crop.png> --prompt-file <prompt.txt> --out <plate.png> --size <WxH> --quality high --background transparent` (use `--background opaque` for full-frame assets); create the output directory first. Verify actual alpha, white foregrounds, fine edges, and clear holes on light and dark grounds; do not chroma-key native output. The plates gate scores the assets against the comp; also inspect placement and scale visually. With parallel subagents, spawn the shipped asset producer (`impeccable-asset-producer`; `impeccable_asset_producer` in codex; `/impeccable-asset-producer` in Cursor; on GitHub Copilot say "Use the impeccable-asset-producer agent") with the spec path and let it produce them all; without subagents, produce them here. A crop of the comp is a reference, never a shipping pixel. The gate checks every plate exists, is at least 1.5x the region's size, and reads as the region. Page code waits for this gate: a page written before its plates exist is a page that draws its material in CSS. A single-file deliverable changes nothing here: the plate is produced the same way and inlined as a data URI. `--force` exists for one case only, the user downgrading the comp's authority in words you quote in `--reason`; the script refuses every other reason. <!-- rule:skill-plates-before-page --> Score the plates before the review opens: once `build-phase advance` reports nothing but the pending review, run the plan and asset review in [component-review.md](component-review.md), where the user checks the plates and which regions code draws. A plate replaced after they accept needs a new round. No page code is written before they accept it; `build-phase advance` refuses until they do. <!-- rule:skill-human-component-review -->
-3. **hero.** `impeccable build-phase scaffold` first: it writes the measured layout as CSS custom properties (`.impeccable/build/scaffold/layout.css`: `--r-<id>-x/y/w/h` in % of the comp, plus cap height, font-size, family, and weight where measured) and a reference page (`hero-reference.html`) with every region at its box and every plate placed. Bind the numbers to your own semantic structure, an element per region; the reference is a check on positions, never the page, and overlapping boxes are overlapping boxes. Then build only the first viewport, at the comp's own dimensions, the comp's words copied verbatim (the user approved that comp with those words; rewording is a stated decision after the hero passes, never a silent one inside it), every text region sized from its measured cap height and set in its ranked face, plates first: place every plate at its spec box (`object-fit: cover`, an `<img>`, a background image, or an inlined data URI named for it) before any text or control, capture into `.impeccable/review/hero-repro.png`, run `impeccable build-phase record hero` once so you see the plate regions read as match before any text exists, then lay the semantic layer over the plates from the spec's palette and boxes and advance. The gate first refuses while any plate is unreferenced by the source, then runs `impeccable comp-diff`, writes `.impeccable/review/diff/hero/` (side-by-side, heatmap, one paired crop per region, `report.json`; `raw-report.json` preserves the uninterpreted measurements). The report and crop labels use the gate's verdicts; `gate.reasons` lists the remaining blockers even when a region is called drift. An accepted plate is revalidated if its file, measured region, or comp changes. The gate passes at 72% overall with no hard veto outstanding (a missing region, a contradicted plate or text block, an SVG illustration, a clipped plate, invented ink block at any score); above the bar, the numeric readings become advisories printed with the pass, and the polish pass before responsive is where they get fixed: the gate also reads each text region's cap height, line count, weight, ink colour, and position against the comp, each chrome strip's height off its rule, and the frame for ink where the comp is calm (a kicker, an extra nav item, a divider), and says each miss as a number ("cap height 78px in the build, 103px in the comp"); those numbers are the edit. When it fails, open the region crops it lists, in order, before editing: a region scored `missing` needs its material, `contradicted` needs its structure re-derived from the spec box, `drift` is where size and spacing edits belong; repeated attempts do not clear unresolved blockers. This is where the run's ambition is won or lost, and a retry here costs minutes where a rebuild verdict at the finish costs the run. <!-- rule:skill-hero-gate -->
+3. **hero.** `impeccable build-phase scaffold` first: it writes the measured layout as CSS custom properties (`.impeccable/build/scaffold/layout.css`: `--r-<id>-x/y/w/h` in % of the comp, plus cap height, font-size, family, and weight where measured) and a reference page (`hero-reference.html`) with every region at its box and every plate placed. Bind the numbers to your own semantic structure, an element per region; the reference is a check on positions, never the page, and overlapping boxes are overlapping boxes. Then build only the first viewport, at the comp's own dimensions, the comp's words copied verbatim (the user approved that comp with those words; rewording is a stated decision after the hero passes, never a silent one inside it), every text region sized from its measured cap height and set in its ranked face, plates first: place every plate at its spec box (`object-fit: cover`, an `<img>`, a background image, or an inlined data URI named for it) before any text or control, capture into `.impeccable/review/hero-repro.png`, run `impeccable build-phase record hero` once so you see the plate regions read as match before any text exists, then lay the semantic layer over the plates from the spec's palette and boxes and advance. The gate first refuses while any plate is unreferenced by the source, then runs `impeccable comp-diff`, writes `.impeccable/review/diff/hero/` (side-by-side, heatmap, one paired crop per region, `report.json`; `raw-report.json` preserves the uninterpreted measurements). The report and crop labels use the gate's verdicts; `gate.reasons` lists the remaining blockers even when a region is called drift. An accepted plate is revalidated if its file, measured region, or comp changes. The gate passes at 72% overall with no hard veto outstanding (a missing region, a contradicted plate or text block, an SVG illustration, a clipped plate, invented ink block at any score); above the bar, the numeric readings become advisories printed with the pass, and the polish pass before responsive is where they get fixed: the gate also reads each text region's cap height, line count, weight, ink colour, and position against the comp, each chrome strip's height off its rule, and the frame for ink where the comp is calm (a kicker, an extra nav item, a divider), and says each miss as a number ("cap height 78px in the build, 103px in the comp"); those numbers are the edit. When it fails, open the region crops it lists, in order, before editing: a region scored `missing` needs its material, `contradicted` needs its structure re-derived from the spec box, `drift` is where size and spacing edits belong; repeated attempts do not clear unresolved blockers. After three failed attempts, present the first-viewport review from [component-review.md](component-review.md) instead of iterating. Once the user accepts a first viewport, the overall bar, the palette check and every numeric reading are advisories while the capture still matches it; a missing or unreferenced plate, an SVG illustration, an organic clip, a clipped plate, invented ink and failed rendered presence still block. When the capture drifts from what they accepted, restore it: that review is closed and is never requested again. This is where the run's ambition is won or lost, and a retry here costs minutes where a rebuild verdict at the finish costs the run. <!-- rule:skill-hero-gate -->
4. **sections.** Build the rest of the surface inside the spec's system: the same corner language, line weights, and palette, and nothing the comp never shows. Where the comp does not cover a region, it inherits the recorded system.
5. **motion.** The signature interaction, reveals, and motion, orchestrated once rather than scattered.
6. **responsive.** The other viewports, and the first viewport at common desktop widths (1280 to 1600), not only at the comp's exact size: fluid columns, no fixed-pixel grid that wraps a hundred pixels narrower. Capture `desktop.png` (1440 wide, full page) and `mobile.png` (390 wide) into `.impeccable/review/`; the gate diffs the desktop capture against the comp and refuses a first viewport that only held at the comp's width. A comp'd surface that is mobile-first was comped portrait; the plates were produced for that frame.
diff --git a/skill/reference/region-map.md b/skill/reference/region-map.md
index 3dc125e44..de8c5c1f8 100644
--- a/skill/reference/region-map.md
+++ b/skill/reference/region-map.md
@@ -11,10 +11,16 @@ If the request ends at mapping, stop with the map, inspection report and unresol
`--auto` produces horizontal band scaffolding, not element identification. It is optional and does not replace authoring a map.
-## Containment and repetition
+## Containment
`parentId` identifies an enclosing `container: true` region. Parent and children keep separate IDs and crops. Containment never transfers approval.
-`reviewGroup` identifies repeated instances of the same code component and role. Members must have the same kind and container status and be peers, not ancestors and children. Sharing a card or section is not a reason to group its different parts. Keep every instance in the map and component kit. Raster assets remain individually reviewable. Grouping does not waive crop checks or approve anything; applying a decision to peers remains the user’s choice.
+## What varies independently
+
+Split regions by what varies independently: content the site swaps (room photos, products, people), moving parts (anything a hover or the signature interaction moves), and structure (frames, surrounds, ornament). A window with open shutters onto a room is three kinds of region: the surround as a plate with a transparent opening, the room as an image region beneath it, and each shutter as its own plate. Overlapping regions are composited in the page. `comp-spec` flags a raster region whose note names a frame and the view it opens onto (`baked-composite`), and the plan and asset review shows it to the user first.
+
+## Painted material
+
+When measuring, `comp-spec` flags a `text`, `control` or `chrome` region, containers included, whose crop looks painted (`painted-pixels`: many colours, soft gradients) and lists it in its summary. The plan and asset review shows flagged regions, and those marked `codeDrawn` (painted material you chose to draw in code), to the user first. Do not leave the catch to them: if a region is painted material (a figure, a photograph, a metal or paper surface), classify it `plate`, `image` or `texture` now.
Comp crops are reference evidence only, never production assets. The map inspector marks its PNGs as comp-derived.
diff --git a/skill/reference/visualize.md b/skill/reference/visualize.md
index e270ee81b..4f006d4a5 100644
--- a/skill/reference/visualize.md
+++ b/skill/reference/visualize.md
@@ -8,12 +8,13 @@ A probe tests composition, narrative, hierarchy, density, focal moment, signatur
The comp round runs inside the build's phase state: `impeccable build-phase start --direction <seed key> --kind <...>` has already run (the roll's output names the command) and its `comps` phase is open before the first comp is generated; a comp rendered before that sits outside the state, and a session resumed from that point has no phases to follow. `impeccable generate-image` refuses to write under `.impeccable/mocks/` until start has run; a harness-native image tool is bound by the same order.
-Render three distinct high-fidelity north-star comps of the requested surface, saved under `.impeccable/mocks/` so they survive the session. Comp at the surface's own viewport: portrait at device size for a native app or mobile-first surface, desktop landscape otherwise; a phone screen comped landscape misstates the composition before anything is built against it. Comps are the build thread's own work, never delegated: the thread that writes the prompts holds the direction's full context and has seen every comp when the build starts. Open every image by its workspace-relative path; sandboxed viewers reject absolute paths, and everything under the project root has a relative one. Base the comps on real content and the surface concepts already developed with the user. On an established world, anchor every comp on the real identity: capture a screenshot of a representative existing page and pass it as a reference image (the harness image tool's input image, or `impeccable generate-image --ref`); the prompt leads with the new surface's structure while the reference carries palette, type, and component character, because DESIGN.md words alone drift where a pixel reference does not. Name what the reference contributes and what it must not: chrome, palette, type, and component character carry over; the reference page's own content does not, and a banner, hero, or card lifted verbatim is the reference leaking, not fidelity. Three is the number: one comp invites rubber-stamping; the spread between three surfaces the composition worth building. The chosen card's decision comp is the first of the three: it already renders this direction at full fidelity under this discipline, so generate two more that vary what the first held fixed, and send all three to the approval point together. Only a round arriving with no decision comp (a degraded roll, an identity-mode page, a direction pinned without the decision round) renders all three here.
+Render three distinct high-fidelity north-star comps of the requested surface, saved under `.impeccable/mocks/` so they survive the session. Comp at the surface's own viewport: portrait at device size for a native app or mobile-first surface, desktop landscape otherwise; a phone screen comped landscape misstates the composition before anything is built against it. Comps are the build thread's own work, never delegated: the thread that writes the prompts holds the direction's full context and has seen every comp when the build starts. Open every image by its workspace-relative path; sandboxed viewers reject absolute paths, and everything under the project root has a relative one. Base the comps on real content and the surface concepts already developed with the user. On an established world, anchor every comp on the real identity: capture a screenshot of a representative existing page and pass it as a reference image (the harness image tool's input image, or `impeccable generate-image --ref`); the prompt leads with the new surface's structure while the reference carries palette, type, and component character, because DESIGN.md words alone drift where a pixel reference does not. Name what the reference contributes and what it must not: chrome, palette, type, and component character carry over; the reference page's own content does not, and a banner, hero, or card lifted verbatim is the reference leaking, not fidelity. Three is the number: one comp invites rubber-stamping; the spread between three surfaces the composition worth building. The chosen card's decision comp is the first of the three: it already renders this direction at full fidelity under this discipline, so generate two more that vary what the first held fixed, from the direction in words rather than with the first comp as an input image (a reference image anchors the layout, and three comps collapse into one composition). Each goes further than the first, never cleaner: a bolder use of the same world, where the world's material carries more of the page's structure (still one dominant move, per the depth rule below), a larger or stranger focal move, or a composition the category would not attempt. A variant that simplifies the first into a tidier version of itself adds no choice to the round. Send all three to the approval point together. Only a round arriving with no decision comp (a degraded roll, an identity-mode page, a direction pinned without the decision round) renders all three here.
-- A comp is a designed surface, not a picture of the subject. Lead the prompt with the surface's own structure: the regions this design has, named in order with their scale relationships; a page with no navigation says so instead of inventing one, and an unconventional surface states its unconventional skeleton. A prompt that leads with atmosphere gets a vignette back: the model paints the fish market instead of the fish market's website. Self-check every render: if it could hang as a poster, or reads as a photograph with some text on it, it is not a comp; regenerate with the layout scaffold stated more literally.
+- A comp is a designed surface, not a picture of the subject. Lead the prompt with the surface's own structure: the regions this design has, named in order with their scale relationships; a page with no navigation says so instead of inventing one, and an unconventional surface states its unconventional skeleton. A prompt that leads with atmosphere gets a vignette back: the model paints the fish market instead of the fish market's website. The world may be the carrier of the page, never a picture of it: a facade, a shutter or a book can be what the page is built on, while a viewport painted whole as a facade, a book cover or a travel poster, with no working parts in it, is a picture of the world, not its website. Material coverage is wanted: the world's material is the ground and the major surfaces, its type sets the headlines, and a world reduced to an accent on a neutral template is the category default with a sticker on it. Coverage is not performance: how many regions act out the concept is limited by the depth rule below, and the rest stay in the world's material without performing it. Both ends erase the direction: the painted poster, and the generic product page (a headline over subcopy and a button, a row of equal cards below). The dealt composition sets the skeleton, and the compositions you write for comps two and three answer to the same test: a split hero (copy on one side, the product on the other, a badge row under it) or a centred headline over a row of cards is the template whatever world paints it. The world carries the page's parts and never absorbs them, so wherever it puts one, the page still works as a page: navigation set into a facade reads as links, copy on a shutter as set text a visitor reads, an action on a door plaque as plainly clickable, text reads against whatever sits behind it, the sections keep a steady vertical rhythm, the primary action is unmistakable, and the section below starts as a section rather than more painting. Fix a poster by making its parts work where the world put them, never by moving them into a standard layout on the world's colour: a cover that becomes copy beside a device on marigold has lost the cover. When the world is an object, the page is that one object seen once, at one scale and from one point of view, and the object keeps its real form: a book opens to two pages on one gutter, never a third panel, and a spine that carries the navigation belongs to the book on the page, never a second book beside it. More content goes on the object's own surfaces or on the next spread below, never on extra copies or impossible folds. Render the page itself edge to edge: no browser window, address bar, device or desk around it, so prompt it as the page, never as a screenshot of a browser. Self-check every render: if it could hang as a poster, or reads as a photograph with some text on it, it is not a comp; regenerate with the dealt composition's regions named and its parts working in place.
- The inverse is also a failure: a surface with none of its subject in it. The subject appears as the content the regions hold; the world dresses the frame and never displaces what the frame shows. The deletion usually rides in on the prompt's exclusion list, so exclusions bind invented claims, and a medium ban belongs to the committed imagery stance, never to caution. Before accepting a render, point at the subject; a render that depicts everything about the world and nothing of the subject fails however faithful its atmosphere. Regenerate with the subject's content named region by region.
- Judge a comp as the shipped screen: the visitor's job must be readable from the image alone. Name the surface's mode from the render with no caption; a render whose mode cannot be read back is art direction without a surface. Regenerate with the visitor's job as the prompt's spine.
-- Commitment is depth, not coverage. The world enters through one dominant move plus the material, type, and spacing that support it; the remaining regions hold still so that move can be read. A region that simply does its job in the world's grammar carries the direction further than a region performing the concept. The check cuts competition, never content: a quieted region keeps its information and stops performing. A second element competing with the named focal moment at the same scale means the comp is shouting; with no named focal moment, several regions performing the concept at once is the same shout. Regenerate keeping the strongest move and quieting the rest. Busy is louder, not bolder.
+- How far the world reaches depends on the surface's mode. On a Persuade or Experience surface it may own and structure the page as above. On an Operate or Read surface the visitor came to use the screen, so the world enters through material, type, colour, density, and one signature move, and every control is a real web component the visitor already knows how to use: buttons, tabs, inputs, selects, filters, tables with sortable headers, navigation that reads as navigation. Never a costume of the world's own interface: a terminal's function-key bar or command prompt, an instrument's bezel, ruled ledger paper standing in for a table. A comp an engineer could not build from standard web components is a picture of the tool, not the tool.
+- Commitment is depth, not performance spread across regions. The world enters through one dominant move plus the material, type, and spacing that support it; the remaining regions hold still in that material so the move can be read. A region that simply does its job in the world's grammar carries the direction further than a region performing the concept. The check cuts competition, never content: a quieted region keeps its information and stops performing, and the page still carries its content (a way to navigate, the offer, its supporting copy, an action, a glimpse of what follows) at real reading size (body text near 16px on a 1440px-wide page). That is a list of content, not a layout: where each piece sits is the composition's call. A second element competing with the named focal moment at the same scale means the comp is shouting; with no named focal moment, several regions performing the concept at once is the same shout. Regenerate keeping the strongest move and quieting the rest. Busy is louder, not bolder.
- When the user shortlisted multiple concepts, spread the three across them.
- When one direction is committed, vary the structural uncertainty an image can resolve: topology, sequence, density, hierarchy, focal composition, or interaction framing.
- Show enough beyond the opening moment to prove the concept can govern the whole surface.
diff --git a/skill/scripts/VERSION b/skill/scripts/VERSION
index c946ee616..11808190d 100644
--- a/skill/scripts/VERSION
+++ b/skill/scripts/VERSION
@@ -1 +1 @@
-0.1.6
+0.1.7
diff --git a/tests/oracle/DELTAS.md b/tests/oracle/DELTAS.md
index 2076accf3..0e7fd505b 100644
--- a/tests/oracle/DELTAS.md
+++ b/tests/oracle/DELTAS.md
@@ -229,3 +229,20 @@ should-flag. `detect-fixture-{json,text}-italic-serif-display-html` go from 7 to
420. Every other finding, count, snippet and exit status is unchanged. Hidden
heading descendants and sans-serif or small italics stay exempt; Rust
regressions in `crates/html/tests/italic_heading.rs` pin both sides.
+
+## Recorded 2026-09-25: plan and asset review (component review v3)
+
+Three new cases, recorded from the binary and reviewed by hand; no existing
+golden changed. `component-review-usage` is the usage refusal, which now leads
+with `plan [--out .impeccable/review/components.json]`. `component-review-plan-missing-plates`
+runs `plan` on the comp-basic spec before its one plate exists: exit 1, the
+missing plate listed, nothing written. `component-review-plan` adds the plate
+and pins the written v3 packet: `art` as an asset previewed by its plate, `top`
+(non-container chrome) as a plan item with a `comp-crop` preview, `body` in
+`codeRegions`, and `specSha256` of the fixture spec. Contract:
+`docs/PLAN-REVIEW.md`. The build-phase plates next-step text gained one
+sentence naming the review; no golden prints it.
+
+## Recorded 2026-09-25: surface reading on code regions
+
+`comp-spec-regions`: the written spec adds `"surface": {"flat": false, "rules": false}` to the two code regions (`top`, `body`). The raster region, every other field, measurement, stdout, stderr and exit status are unchanged, and no region in the fixture reads painted, so no `flags` entry or `FLAG` line appears. No frozen function vectors changed. Rust regressions cover the readings: a painted patch reads the same in tight and generous boxes, containers flag only on unmapped painted material, and grounds and rules separate from marks.
diff --git a/tests/oracle/cases/comp.mjs b/tests/oracle/cases/comp.mjs
index e2660ccb1..b47a5c560 100644
--- a/tests/oracle/cases/comp.mjs
+++ b/tests/oracle/cases/comp.mjs
@@ -86,6 +86,39 @@ const cases = [
steps: [{ args: ['start', '--comp', 'comp.png'] }, { args: ['status'] }],
},
{ id: 'build-phase-usage', verb: 'build-phase', workspace: WS, args: [], env: env() },
+
+ // component-review plan: the v3 packet derives from the measured spec. The
+ // spec fixture has one plate region (art), one non-container chrome (top,
+ // a plan item) and one text region (body, a code region).
+ { id: 'component-review-usage', verb: 'component-review', workspace: WS, args: [], env: env() },
+ {
+ id: 'component-review-plan-missing-plates', verb: 'component-review', workspace: WS,
+ setup: (ws) => write(ws, '.impeccable/build/spec.json', fs.readFileSync(path.join(ws, 'spec.json'))),
+ args: ['plan'], env: env(),
+ },
+ {
+ id: 'component-review-plan', verb: 'component-review', workspace: WS,
+ setup: (ws) => {
+ write(ws, '.impeccable/build/spec.json', fs.readFileSync(path.join(ws, 'spec.json')));
+ write(ws, 'assets/plates/art.png', fs.readFileSync(path.join(ws, 'comp.png')));
+ },
+ args: ['plan'], files: ['.impeccable/review/components.json'], env: env(),
+ },
+ // Absolute paths inside the project and backslashed ones come back project-relative
+ // with forward slashes (comp-spec may record either).
+ {
+ id: 'component-review-plan-absolute-paths', verb: 'component-review', workspace: WS,
+ setup: (ws) => {
+ const spec = JSON.parse(fs.readFileSync(path.join(ws, 'spec.json'), 'utf8'));
+ spec.comp = path.join(fs.realpathSync(ws), 'comp.png');
+ for (const r of spec.regions) if (r.id === 'art') r.plate = 'assets\\plates\\art.png';
+ write(ws, '.impeccable/build/spec.json', JSON.stringify(spec));
+ write(ws, 'assets/plates/art.png', fs.readFileSync(path.join(ws, 'comp.png')));
+ },
+ args: ['plan'], files: ['.impeccable/review/components.json'], env: env(),
+ // The spec names the staged workspace, so its digest is run-dependent.
+ normalize: [['("specSha256": ")[0-9a-f]{64}', 'g', '$1<SHA256>']],
+ },
];
export default cases;
diff --git a/tests/oracle/golden/comp-spec-regions.json b/tests/oracle/golden/comp-spec-regions.json
index f70cb2f69..099d43731 100644
--- a/tests/oracle/golden/comp-spec-regions.json
+++ b/tests/oracle/golden/comp-spec-regions.json
@@ -4,6 +4,6 @@
"exit": 0,
"signal": null,
"files": {
- ".impeccable/build/spec.json": "{\n \"tool\": \"comp-spec\",\n \"version\": 1,\n \"createdAt\": \"<ISO>\",\n \"comp\": \"comp.png\",\n \"warnings\": [],\n \"uncoveredInkCells\": [\n \"A2\",\n \"B2\",\n \"C2\",\n \"E5\",\n \"F5\",\n \"G5\",\n \"H5\",\n \"I5\",\n \"J5\",\n \"E6\",\n \"A9\",\n \"B9\",\n \"C9\"\n ],\n \"compSize\": {\n \"width\": 768,\n \"height\": 512\n },\n \"aspect\": 1.5,\n \"orientation\": \"landscape\",\n \"palette\": [\n {\n \"hex\": \"#f7e8e8\",\n \"coverage\": 0.6868\n },\n {\n \"hex\": \"#182838\",\n \"coverage\": 0.1403\n },\n {\n \"hex\": \"#9a9aa5\",\n \"coverage\": 0.0683\n },\n {\n \"hex\": \"#c5c5d1\",\n \"coverage\": 0.0672\n },\n {\n \"hex\": \"#7c7c82\",\n \"coverage\": 0.0374\n }\n ],\n \"bands\": [\n {\n \"y\": 0.0588,\n \"strength\": 1\n },\n {\n \"y\": 0.0941,\n \"strength\": 0.4087\n },\n {\n \"y\": 0.1412,\n \"strength\": 0.7036\n },\n {\n \"y\": 0.1765,\n \"strength\": 0.6963\n },\n {\n \"y\": 0.2,\n \"strength\": 0.6026\n },\n {\n \"y\": 0.2353,\n \"strength\": 0.6125\n },\n {\n \"y\": 0.4706,\n \"strength\": 0.3982\n },\n {\n \"y\": 0.5059,\n \"strength\": 0.9754\n },\n {\n \"y\": 0.5412,\n \"strength\": 0.5699\n },\n {\n \"y\": 0.5765,\n \"strength\": 0.8782\n },\n {\n \"y\": 0.6,\n \"strength\": 0.3576\n },\n {\n \"y\": 0.6353,\n \"strength\": 0.4894\n },\n {\n \"y\": 0.6588,\n \"strength\": 0.5699\n },\n {\n \"y\": 0.6941,\n \"strength\": 0.8782\n },\n {\n \"y\": 0.7176,\n \"strength\": 0.3576\n },\n {\n \"y\": 0.7529,\n \"strength\": 0.4877\n },\n {\n \"y\": 0.7765,\n \"strength\": 0.5699\n },\n {\n \"y\": 0.8118,\n \"strength\": 0.8782\n },\n {\n \"y\": 0.8353,\n \"strength\": 0.3576\n },\n {\n \"y\": 0.8824,\n \"strength\": 0.4877\n },\n {\n \"y\": 0.9059,\n \"strength\": 0.3028\n },\n {\n \"y\": 0.9765,\n \"strength\": 0.3039\n }\n ],\n \"regions\": [\n {\n \"id\": \"top\",\n \"kind\": \"chrome\",\n \"note\": \"top masthead band area\",\n \"grid\": \"A0:J1\",\n \"box\": {\n \"x\": 0,\n \"y\": 0,\n \"w\": 1,\n \"h\": 0.2\n },\n \"px\": {\n \"x\": 0,\n \"y\": 0,\n \"w\": 768,\n \"h\": 102\n },\n \"aspect\": 7.5294,\n \"palette\": [\n {\n \"hex\": \"#f5e7e8\",\n \"coverage\": 0.392\n },\n {\n \"hex\": \"#182838\",\n \"coverage\": 0.3825\n },\n {\n \"hex\": \"#bdbdc8\",\n \"coverage\": 0.1348\n },\n {\n \"hex\": \"#8b8b96\",\n \"coverage\": 0.0908\n }\n ],\n \"detail\": {\n \"energy\": 39.1367\n },\n \"medium\": \"semantic\",\n \"plate\": null,\n \"text\": null\n },\n {\n \"id\": \"art\",\n \"kind\": \"plate\",\n \"note\": \"an exploded illustration drawing\",\n \"grid\": \"E2:J4\",\n \"box\": {\n \"x\": 0.4,\n \"y\": 0.2,\n \"w\": 0.6,\n \"h\": 0.3\n },\n \"px\": {\n \"x\": 307,\n \"y\": 102,\n \"w\": 461,\n \"h\": 154\n },\n \"aspect\": 2.9935,\n \"palette\": [\n {\n \"hex\": \"#e6dfe5\",\n \"coverage\": 0.5326\n },\n {\n \"hex\": \"#a2a2ad\",\n \"coverage\": 0.383\n },\n {\n \"hex\": \"#7f7f88\",\n \"coverage\": 0.0844\n }\n ],\n \"detail\": {\n \"energy\": 38.5615\n },\n \"medium\": \"raster\",\n \"plate\": \"assets/plates/art.png\",\n \"text\": null\n },\n {\n \"id\": \"body\",\n \"kind\": \"text\",\n \"note\": \"a paragraph of body text content\",\n \"grid\": \"A5:D8\",\n \"box\": {\n \"x\": 0,\n \"y\": 0.5,\n \"w\": 0.4,\n \"h\": 0.4\n },\n \"px\": {\n \"x\": 0,\n \"y\": 256,\n \"w\": 307,\n \"h\": 205\n },\n \"aspect\": 1.4976,\n \"palette\": [\n {\n \"hex\": \"#f8e8e8\",\n \"coverage\": 0.6826\n },\n {\n \"hex\": \"#182838\",\n \"coverage\": 0.223\n },\n {\n \"hex\": \"#787878\",\n \"coverage\": 0.0848\n },\n {\n \"hex\": \"#b82828\",\n \"coverage\": 0.0096\n }\n ],\n \"detail\": {\n \"energy\": 32.0304\n },\n \"medium\": \"semantic\",\n \"plate\": null,\n \"text\": null\n }\n ],\n \"compSha256\": \"4c640a415d36339b4895de01ef99f1ab7726d8e4cf70029652485137c24d914e\",\n \"regionsSource\": {\n \"path\": \"regions.json\",\n \"sha256\": \"868d2c385a36694d057f07d9dc0c5b7bf28d8151ba80b1c95a9809fd7943126c\"\n }\n}"
+ ".impeccable/build/spec.json": "{\n \"tool\": \"comp-spec\",\n \"version\": 1,\n \"createdAt\": \"<ISO>\",\n \"comp\": \"comp.png\",\n \"warnings\": [],\n \"uncoveredInkCells\": [\n \"A2\",\n \"B2\",\n \"C2\",\n \"E5\",\n \"F5\",\n \"G5\",\n \"H5\",\n \"I5\",\n \"J5\",\n \"E6\",\n \"A9\",\n \"B9\",\n \"C9\"\n ],\n \"compSize\": {\n \"width\": 768,\n \"height\": 512\n },\n \"aspect\": 1.5,\n \"orientation\": \"landscape\",\n \"palette\": [\n {\n \"hex\": \"#f7e8e8\",\n \"coverage\": 0.6868\n },\n {\n \"hex\": \"#182838\",\n \"coverage\": 0.1403\n },\n {\n \"hex\": \"#9a9aa5\",\n \"coverage\": 0.0683\n },\n {\n \"hex\": \"#c5c5d1\",\n \"coverage\": 0.0672\n },\n {\n \"hex\": \"#7c7c82\",\n \"coverage\": 0.0374\n }\n ],\n \"bands\": [\n {\n \"y\": 0.0588,\n \"strength\": 1\n },\n {\n \"y\": 0.0941,\n \"strength\": 0.4087\n },\n {\n \"y\": 0.1412,\n \"strength\": 0.7036\n },\n {\n \"y\": 0.1765,\n \"strength\": 0.6963\n },\n {\n \"y\": 0.2,\n \"strength\": 0.6026\n },\n {\n \"y\": 0.2353,\n \"strength\": 0.6125\n },\n {\n \"y\": 0.4706,\n \"strength\": 0.3982\n },\n {\n \"y\": 0.5059,\n \"strength\": 0.9754\n },\n {\n \"y\": 0.5412,\n \"strength\": 0.5699\n },\n {\n \"y\": 0.5765,\n \"strength\": 0.8782\n },\n {\n \"y\": 0.6,\n \"strength\": 0.3576\n },\n {\n \"y\": 0.6353,\n \"strength\": 0.4894\n },\n {\n \"y\": 0.6588,\n \"strength\": 0.5699\n },\n {\n \"y\": 0.6941,\n \"strength\": 0.8782\n },\n {\n \"y\": 0.7176,\n \"strength\": 0.3576\n },\n {\n \"y\": 0.7529,\n \"strength\": 0.4877\n },\n {\n \"y\": 0.7765,\n \"strength\": 0.5699\n },\n {\n \"y\": 0.8118,\n \"strength\": 0.8782\n },\n {\n \"y\": 0.8353,\n \"strength\": 0.3576\n },\n {\n \"y\": 0.8824,\n \"strength\": 0.4877\n },\n {\n \"y\": 0.9059,\n \"strength\": 0.3028\n },\n {\n \"y\": 0.9765,\n \"strength\": 0.3039\n }\n ],\n \"regions\": [\n {\n \"id\": \"top\",\n \"kind\": \"chrome\",\n \"note\": \"top masthead band area\",\n \"grid\": \"A0:J1\",\n \"box\": {\n \"x\": 0,\n \"y\": 0,\n \"w\": 1,\n \"h\": 0.2\n },\n \"px\": {\n \"x\": 0,\n \"y\": 0,\n \"w\": 768,\n \"h\": 102\n },\n \"aspect\": 7.5294,\n \"palette\": [\n {\n \"hex\": \"#f5e7e8\",\n \"coverage\": 0.392\n },\n {\n \"hex\": \"#182838\",\n \"coverage\": 0.3825\n },\n {\n \"hex\": \"#bdbdc8\",\n \"coverage\": 0.1348\n },\n {\n \"hex\": \"#8b8b96\",\n \"coverage\": 0.0908\n }\n ],\n \"detail\": {\n \"energy\": 39.1367\n },\n \"medium\": \"semantic\",\n \"plate\": null,\n \"text\": null,\n \"surface\": {\n \"flat\": false,\n \"rules\": false\n }\n },\n {\n \"id\": \"art\",\n \"kind\": \"plate\",\n \"note\": \"an exploded illustration drawing\",\n \"grid\": \"E2:J4\",\n \"box\": {\n \"x\": 0.4,\n \"y\": 0.2,\n \"w\": 0.6,\n \"h\": 0.3\n },\n \"px\": {\n \"x\": 307,\n \"y\": 102,\n \"w\": 461,\n \"h\": 154\n },\n \"aspect\": 2.9935,\n \"palette\": [\n {\n \"hex\": \"#e6dfe5\",\n \"coverage\": 0.5326\n },\n {\n \"hex\": \"#a2a2ad\",\n \"coverage\": 0.383\n },\n {\n \"hex\": \"#7f7f88\",\n \"coverage\": 0.0844\n }\n ],\n \"detail\": {\n \"energy\": 38.5615\n },\n \"medium\": \"raster\",\n \"plate\": \"assets/plates/art.png\",\n \"text\": null\n },\n {\n \"id\": \"body\",\n \"kind\": \"text\",\n \"note\": \"a paragraph of body text content\",\n \"grid\": \"A5:D8\",\n \"box\": {\n \"x\": 0,\n \"y\": 0.5,\n \"w\": 0.4,\n \"h\": 0.4\n },\n \"px\": {\n \"x\": 0,\n \"y\": 256,\n \"w\": 307,\n \"h\": 205\n },\n \"aspect\": 1.4976,\n \"palette\": [\n {\n \"hex\": \"#f8e8e8\",\n \"coverage\": 0.6826\n },\n {\n \"hex\": \"#182838\",\n \"coverage\": 0.223\n },\n {\n \"hex\": \"#787878\",\n \"coverage\": 0.0848\n },\n {\n \"hex\": \"#b82828\",\n \"coverage\": 0.0096\n }\n ],\n \"detail\": {\n \"energy\": 32.0304\n },\n \"medium\": \"semantic\",\n \"plate\": null,\n \"text\": null,\n \"surface\": {\n \"flat\": false,\n \"rules\": false\n }\n }\n ],\n \"compSha256\": \"4c640a415d36339b4895de01ef99f1ab7726d8e4cf70029652485137c24d914e\",\n \"regionsSource\": {\n \"path\": \"regions.json\",\n \"sha256\": \"868d2c385a36694d057f07d9dc0c5b7bf28d8151ba80b1c95a9809fd7943126c\"\n }\n}"
}
}
diff --git a/tests/oracle/golden/component-review-plan-absolute-paths.json b/tests/oracle/golden/component-review-plan-absolute-paths.json
new file mode 100644
index 000000000..54b33241c
--- /dev/null
+++ b/tests/oracle/golden/component-review-plan-absolute-paths.json
@@ -0,0 +1,9 @@
+{
+ "stdout": "PLAN .impeccable/review/components.json: 1 assets, 1 plan items (0 flagged or code-drawn), 1 code regions\nNEXT impeccable component-review capture --manifest .impeccable/review/components.json, then impeccable component-review serve --session <session from capture>\n",
+ "stderr": "",
+ "exit": 0,
+ "signal": null,
+ "files": {
+ ".impeccable/review/components.json": "{\n \"schemaVersion\": 3,\n \"stage\": \"components\",\n \"id\": \"components\",\n \"title\": \"Plan and asset review\",\n \"comp\": {\n \"path\": \"comp.png\",\n \"width\": 768,\n \"height\": 512\n },\n \"specSha256\": \"<SHA256>\",\n \"components\": [\n {\n \"id\": \"art\",\n \"name\": \"Art\",\n \"kind\": \"plate\",\n \"role\": \"asset\",\n \"box\": {\n \"x\": 0.4,\n \"y\": 0.2,\n \"w\": 0.6,\n \"h\": 0.3\n },\n \"note\": \"an exploded illustration drawing\",\n \"medium\": \"raster\",\n \"preview\": {\n \"kind\": \"image\",\n \"path\": \"assets/plates/art.png\"\n },\n \"dependencies\": []\n },\n {\n \"id\": \"top\",\n \"name\": \"Top\",\n \"kind\": \"chrome\",\n \"role\": \"plan\",\n \"box\": {\n \"x\": 0,\n \"y\": 0,\n \"w\": 1,\n \"h\": 0.2\n },\n \"note\": \"top masthead band area\",\n \"medium\": \"code\",\n \"preview\": {\n \"kind\": \"comp-crop\"\n },\n \"codeDrawn\": false,\n \"dependencies\": []\n }\n ],\n \"codeRegions\": [\n {\n \"id\": \"body\",\n \"name\": \"Body\",\n \"kind\": \"text\",\n \"box\": {\n \"x\": 0,\n \"y\": 0.5,\n \"w\": 0.4,\n \"h\": 0.4\n },\n \"note\": \"a paragraph of body text content\"\n }\n ]\n}"
+ }
+}
diff --git a/tests/oracle/golden/component-review-plan-missing-plates.json b/tests/oracle/golden/component-review-plan-missing-plates.json
new file mode 100644
index 000000000..1c44b327f
--- /dev/null
+++ b/tests/oracle/golden/component-review-plan-missing-plates.json
@@ -0,0 +1,7 @@
+{
+ "stdout": "",
+ "stderr": "component-review: 1 raster region(s) lack their plate; the plan and asset review opens once every plate exists:\n - art (plate): assets/plates/art.png\nProduce these plates (the build-phase plates step), then run component-review plan again.\n",
+ "exit": 1,
+ "signal": null,
+ "files": {}
+}
diff --git a/tests/oracle/golden/component-review-plan.json b/tests/oracle/golden/component-review-plan.json
new file mode 100644
index 000000000..81e881b2d
--- /dev/null
+++ b/tests/oracle/golden/component-review-plan.json
@@ -0,0 +1,9 @@
+{
+ "stdout": "PLAN .impeccable/review/components.json: 1 assets, 1 plan items (0 flagged or code-drawn), 1 code regions\nNEXT impeccable component-review capture --manifest .impeccable/review/components.json, then impeccable component-review serve --session <session from capture>\n",
+ "stderr": "",
+ "exit": 0,
+ "signal": null,
+ "files": {
+ ".impeccable/review/components.json": "{\n \"schemaVersion\": 3,\n \"stage\": \"components\",\n \"id\": \"components\",\n \"title\": \"Plan and asset review\",\n \"comp\": {\n \"path\": \"comp.png\",\n \"width\": 768,\n \"height\": 512\n },\n \"specSha256\": \"57bb758231d8b9ed00b2c6c7aca44c0e81c08a3753d419403ae7303fdbddf81b\",\n \"components\": [\n {\n \"id\": \"art\",\n \"name\": \"Art\",\n \"kind\": \"plate\",\n \"role\": \"asset\",\n \"box\": {\n \"x\": 0.4,\n \"y\": 0.2,\n \"w\": 0.6,\n \"h\": 0.3\n },\n \"note\": \"an exploded illustration drawing\",\n \"medium\": \"raster\",\n \"preview\": {\n \"kind\": \"image\",\n \"path\": \"assets/plates/art.png\"\n },\n \"dependencies\": []\n },\n {\n \"id\": \"top\",\n \"name\": \"Top\",\n \"kind\": \"chrome\",\n \"role\": \"plan\",\n \"box\": {\n \"x\": 0,\n \"y\": 0,\n \"w\": 1,\n \"h\": 0.2\n },\n \"note\": \"top masthead band area\",\n \"medium\": \"code\",\n \"preview\": {\n \"kind\": \"comp-crop\"\n },\n \"codeDrawn\": false,\n \"dependencies\": []\n }\n ],\n \"codeRegions\": [\n {\n \"id\": \"body\",\n \"name\": \"Body\",\n \"kind\": \"text\",\n \"box\": {\n \"x\": 0,\n \"y\": 0.5,\n \"w\": 0.4,\n \"h\": 0.4\n },\n \"note\": \"a paragraph of body text content\"\n }\n ]\n}"
+ }
+}
diff --git a/tests/oracle/golden/component-review-usage.json b/tests/oracle/golden/component-review-usage.json
new file mode 100644
index 000000000..2aacae6fb
--- /dev/null
+++ b/tests/oracle/golden/component-review-usage.json
@@ -0,0 +1,7 @@
+{
+ "stdout": "",
+ "stderr": "component-review: usage: impeccable component-review plan [--out .impeccable/review/components.json] | prepare|capture|verify --manifest <file> | lifecycle [--session-dir <dir>] [--require components|hero] [--hosted] | serve --session <id> [--port 0] [--idle-timeout <seconds>] | status|refresh-approvals --session <id> [--store <outside-project-dir>]\n",
+ "exit": 1,
+ "signal": null,
+ "files": {}
+}
diff --git a/ui/component-review/DESIGN-stage.md b/ui/component-review/DESIGN-stage.md
new file mode 100644
index 000000000..9729e01bf
--- /dev/null
+++ b/ui/component-review/DESIGN-stage.md
@@ -0,0 +1,43 @@
+# Review stage: design brief
+
+The plan and asset review asks a person to make a handful of visual judgments quickly and confidently. Every screen answers one question, at the size it deserves, with context available on demand.
+
+## The user's questions, in order
+
+1. **What am I doing, and how long will it take?** Intro.
+2. **Is this one right?** One item at a time.
+3. **Did they fix what I asked?** Round 2 and later.
+4. **Is anything missing, and am I done?** Summary.
+
+## Flow
+
+**Intro** (a single screen, skipped with Enter). Round 1: "7 things to check before any page code is written. About two minutes." Show the comp large with the regions to decide outlined, and one line on what the two kinds of decision mean (a generated image; a region that will be drawn in code). Round 2+: "The agent worked on your notes for 2 items. 5 approvals are kept." One primary action: Start.
+
+**Stage** (one item). The item fills the viewport between a slim top bar and a decision bar.
+- Asset: comp crop and generated asset side by side at the largest size that fits, equal height, labeled with eyebrows (IN THE COMP, GENERATED). No toggles for the common case.
+- Plan item: the comp crop, large and tight on the region, with a plain sentence under it ("Will be drawn in code: brushed steel band under the hero") and, if flagged, the observation as a quiet vermilion note. No second pane.
+- Round 2+ changed item: open with the user's own words from the last round as a quote ("You asked: Boats should be moored along the quay."). Then Before, After, Comp as a three-up at equal height. For a reclassified region, show the new generated asset next to the comp crop and the old plan sentence struck through.
+- Locator: a small comp thumbnail docked in the stage corner with the region highlighted. Click or press C to open the full comp as an overlay with all regions (the map). The map is context, not a second workspace.
+- Inspection that delights and is useful for fidelity:
+ - Synced loupe: hovering either image shows a magnified circle at the same relative point on both images.
+ - Hold Space to flip: while held, the generated asset is replaced in place by the comp crop at the same size (and back on release), for instant difference-spotting. A small hint shows once.
+ - Backdrop choice only appears for transparent assets, as a kit switch in the image caption, defaulting to the comp colour.
+- Decision bar (bottom, centered): the two kit buttons (primary and secondary) with their key caps inline, plus the quiet third action for plan items. After a decision, the stage advances to the next undecided item with a short slide on --ks-ease; Undo is a toast ("Approved Hero figure. Undo").
+
+**Top bar**: title (small), round, and progress as a row of LEDs, one per item, gold for decided and patina for the current one; each LED is a button (tooltip with the name) for random access. Nothing else.
+
+**Summary** (after the last item, or from the progress row): a contact sheet of every item with its decision (thumbnail, name, state, the user's note), each clickable to revisit. Below it, the full comp with all regions outlined and the question "Anything on the comp we didn't cover?" with Mark missing here (drawing a box, as today). Then the single primary action: "Approve plan and assets" or "Send notes" (with counts). This replaces the separate checkbox, the persistent Mark missing button and the legend.
+
+Code regions without a decision ("set in code") appear only in the summary's comp overlay and the full map, with "Make it an image" available on click, so they never add to the queue.
+
+## Visual language
+
+Site kit only (vendor/): paper, ink, one hairline rule per boundary, eyebrows for labels, kit buttons, strips and switches. The stage uses the paper ground; images get a thin --ks-rule outline and no card. Motion: stage transitions 240ms on --ks-ease, the LED fills 160ms; respect prefers-reduced-motion. Type: Alumni Sans for the one title per screen, Albert Sans elsewhere.
+
+## Keyboard
+
+Enter start or confirm; A approve / code is fine; N needs work / make it an image; F something else; J/K or arrows move; C comp overlay; Space hold to flip; Cmd+Z undo; Esc close. Show key caps on the buttons themselves, not in a separate hint row.
+
+## Narrow widths
+
+Stage stacks the two images vertically (comp above, generated below), the locator moves into the top bar, and the decision bar is sticky at the bottom.
diff --git a/ui/component-review/README.md b/ui/component-review/README.md
index eecfa2e7f..732f54e3d 100644
--- a/ui/component-review/README.md
+++ b/ui/component-review/README.md
@@ -104,3 +104,15 @@ rendered state, not a claim that all future interactive states are covered.
The adapter records observed semantic-control, SVG and raster counts as evidence;
it does not decide that required semantics or visual fidelity pass. Human identity, run routing and exact provider continuation belong to the consuming harness. The hero stage uses the same manifest and native capture contract.
+
+## Plan and asset review (packet schemaVersion 3)
+
+A `components` packet with `schemaVersion: 3` (contract: `docs/PLAN-REVIEW.md`) renders `plan-review.ts` instead of the inventory view; `mountComponentReview` dispatches on the packet, so hosts need no change. The first-viewport (`hero`) stage keeps the view in `review.ts`.
+
+The comp carries region outlines rather than pins: generated assets solid, planned-in-code dashed, flagged plan items (`flags` or `codeDrawn`) amber, and `codeRegions` visible on hover. Every region is clickable. An asset shows its comp crop beside the generated file at the largest same-scale size the panel allows (up to 4x comp pixels); a transparent file sits on the comp colour around its box, with light and dark as alternatives. A plan item shows the comp around it, never shrinking a band below comp scale, with the plan in one sentence and any flag above it. Each item has three decision buttons: "Looks good", "Needs work" and "Split into layers" for assets (split is the primary alternative when the asset reads as a baked composite), and "Code is fine", "Make it an image" and "Something else…" for plan items, where the last one asks for the region-map change as feedback. A `codeRegions` entry needs no decision and offers only "Make it an image", which travels in `submission.reclassify`.
+
+There is no bulk approval and no separate completeness checkbox. "Approve plan and assets" is enabled once every item is approved with nothing changed or missing, and sets `inventoryConfirmed: true`; any feedback, reclassification or missing mark turns it into "Send changes". Pure logic lives in `plan-model.ts` with tests beside it.
+
+## Design-system kit (vendored)
+
+Controls are the Impeccable site kit, not local imitations: `.ks-button`, `.ks-instrument-strip.is-paper` with its sliding `.ks-thumb`, `.ks-switch`, `.ks-checkbox`, `.ks-icon-button`, `.ks-tab-list`, and the docs rail's selected-row pattern. `vendor/` holds verbatim copies of impeccable-site's `kinpaku-tokens.css`, the needed `kinpaku-kit.css` sections, the rail rules from `docs-kinpaku.css`, and `instrument-strip.js`; the site is the source of truth. Refresh with `node scripts/sync-kinpaku-kit.mjs [path-to-impeccable-site]`. `instrument-strip.ts` ports the thumb script to shadow roots and re-rendering views; the region-map inspection page (`crates/comp-verbs/src/map_inspection.html`) inlines the same vendored CSS and script and ships the fonts beside the report.
diff --git a/ui/component-review/app-layout.ts b/ui/component-review/app-layout.ts
index ba55786b5..57be67552 100644
--- a/ui/component-review/app-layout.ts
+++ b/ui/component-review/app-layout.ts
@@ -1,57 +1,51 @@
/** Viewport shell: fixed surfaces frame independently scrolling inspection and component panes. */
export const appLayout = `
:host{height:var(--component-review-height,100dvh);min-height:0;overflow:hidden}
-.review{height:100%;max-width:none;min-height:0;padding:0;display:flex;flex-direction:column;overflow:hidden;background:var(--color-bg,#fafafa)}
+.review{height:100%;max-width:none;min-height:0;padding:0;display:flex;flex-direction:column;overflow:hidden;background:var(--color-bg,var(--ks-paper))}
.review>header{flex-shrink:0;padding:16px 24px;margin:0;border-bottom:1px solid var(--line);gap:16px}.review>header>div{min-width:0}.review h1{font-size:30px;line-height:1}.review>header p{font-size:12px;margin-top:6px;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}.review .badge{font-size:11px}
.review>.preview-note{flex-shrink:0;margin:0;padding:8px 24px;font-size:11px}.review>.round-summary{flex-shrink:0;margin:0;padding:8px 24px;border-top:0;gap:6px 16px;max-height:120px;overflow:auto}.round-summary p{font-size:12px;gap:6px 14px}.round-summary button{font-size:12px;min-height:32px;padding:5px 10px}
-.review>.workbench{flex:1;min-height:0;align-items:stretch;padding:20px 24px;gap:32px;overflow:hidden;grid-template-columns:minmax(0,1.12fr) minmax(0,1fr)}.reference{display:flex;flex-direction:column;min-height:0;width:100%;max-width:none;margin:0}.reference>.section-head{flex-shrink:0;margin-bottom:10px}.map-space{flex:1;min-height:0;display:flex;align-items:center;justify-content:center;background:#eeefec;border:1px solid var(--line);overflow:hidden}.map{flex-shrink:0;max-width:100%;max-height:100%}.map-legend{flex-shrink:0;margin-top:9px;gap:6px 14px}.map-caption{flex-shrink:0;min-height:0;padding-top:6px;font-size:10px}.map-caption button{display:inline-block;margin:0 0 0 8px;min-height:28px;padding:3px 7px}
-.workbench>.inspector{height:100%;min-height:0;padding:0;border:0}.inspector>.section-head{margin-bottom:10px;min-height:32px}.section-head h2{font-size:16px}.inspection-content{padding-bottom:8px}.review-form{max-height:55%;overflow-y:auto;scrollbar-width:thin;scrollbar-gutter:stable}.material{min-height:28px}.material strong{font-size:13px}.compare-toolbar{margin-bottom:12px}.previous-feedback{padding:10px 12px}.repair-context{margin-bottom:12px}.preview-round{margin-bottom:10px}.decision-title p{font-size:11px}.decisions>button{min-height:40px;font-size:13px}.decision-title strong{font-size:13px}.view-controls{margin-top:8px}.component-details{height:auto;max-height:80px}
-.review>.inventory-section{height:236px;flex-shrink:0;display:flex;flex-direction:column;min-height:0;margin:0;padding:10px 24px 8px;border-top:1px solid var(--line);background:var(--color-panel,#f5f5f2);overflow:hidden}.inventory-section>.section-head{margin:0 0 8px;min-height:36px;flex-shrink:0;gap:10px}.inventory-section h2{font-size:14px}.inventory{flex:1;min-height:0;align-items:stretch;margin:0;padding:3px 3px 7px;overflow-x:auto;overflow-y:hidden}.inventory.all{overflow:auto;align-items:start;grid-auto-rows:160px}.inventory .item{flex:0 0 136px;padding:8px;gap:3px;grid-template-rows:auto auto minmax(24px,1fr) auto;min-height:0}.inventory .item-thumb{height:46px;margin-bottom:3px}.inventory .thumb-crop{max-height:46px}.inventory .item-number{font-size:11px;min-height:16px;padding:0}.inventory .item strong{font-size:12px;min-height:26px;line-height:1.2;display:-webkit-box;-webkit-line-clamp:2;-webkit-box-orient:vertical;overflow:hidden}.inventory .state{font-size:11px;padding-top:4px}.tray-actions{display:flex;gap:6px;align-items:center}.tray-actions button{white-space:nowrap;font-size:11px;min-height:32px}.tray-actions #toggle-tray{display:flex;align-items:center;gap:6px}.tray-actions svg{width:14px;height:14px;stroke:currentColor;fill:none;stroke-width:1.5;stroke-linecap:round;stroke-linejoin:round}.review>.inventory-section.tray-expanded{height:min(42dvh,390px)}.review>.inventory-section.tray-collapsed{height:56px;padding-block:10px}.tray-collapsed .inventory{display:none}.tray-collapsed>.section-head{margin-bottom:0}
-.review>footer{flex-shrink:0;margin:0;padding:12px 24px;gap:16px;border-top:1px solid var(--line);background:var(--paper);align-items:center}.review>footer>div:first-child{display:flex;align-items:center;gap:14px;min-width:0}.review>footer .check{margin:0;max-width:240px;font-size:11px}.review>footer #approve-rest{min-height:36px;font-size:12px;max-width:210px;padding:7px 10px}.review>footer .submit-area{gap:12px}.review>footer .submit-area p{font-size:11px;max-width:24ch}.review>footer .primary{min-height:40px;font-size:13px}.mobile-panes{display:none}
+.review>.workbench{flex:1;min-height:0;align-items:stretch;padding:20px 24px;gap:32px;overflow:hidden;grid-template-columns:minmax(0,1.12fr) minmax(0,1fr)}.reference{display:flex;flex-direction:column;min-height:0;width:100%;max-width:none;margin:0}.reference>.section-head{flex-shrink:0;margin-bottom:10px}.map-space{flex:1;min-height:0;display:flex;align-items:center;justify-content:center;background:var(--ks-paper-deep);border:1px solid var(--line);overflow:hidden}.map{flex-shrink:0;max-width:100%;max-height:100%}.map-legend{flex-shrink:0;margin-top:9px;gap:6px 14px}.map-caption{flex-shrink:0;min-height:0;padding-top:6px;font-size:10px}.map-caption button{display:inline-block;margin:0 0 0 8px;min-height:28px;padding:3px 7px}
+.workbench>.inspector{height:100%;min-height:0;padding:0;border:0}.inspector>.section-head{margin-bottom:10px;min-height:32px}.section-head h2{font-size:16px}.inspection-content{padding-bottom:8px}.review-form{max-height:55%;overflow-y:auto;scrollbar-width:thin;scrollbar-gutter:stable}.material{min-height:28px}.material strong{font-size:13px}.compare-toolbar{margin-bottom:12px}.previous-feedback{padding:10px 12px}.repair-context{margin-bottom:12px}.preview-round{margin-bottom:10px}.decision-title p{font-size:11px}.decision-title strong{font-size:13px}.view-controls{margin-top:8px}.component-details{height:auto;max-height:80px}
+.review>.inventory-section{height:236px;flex-shrink:0;display:flex;flex-direction:column;min-height:0;margin:0;padding:10px 24px 8px;border-top:1px solid var(--line);background:var(--color-panel,var(--ks-paper));overflow:hidden}.inventory-section>.section-head{margin:0 0 8px;min-height:36px;flex-shrink:0;gap:10px}.inventory-section h2{font-size:14px}.inventory{flex:1;min-height:0;align-items:stretch;margin:0;padding:3px 3px 7px;overflow-x:auto;overflow-y:hidden}.inventory.all{overflow:auto;align-items:start;grid-auto-rows:160px}.inventory .item{flex:0 0 136px;padding:8px;gap:3px;grid-template-rows:auto auto minmax(24px,1fr) auto;min-height:0}.inventory .item-thumb{height:46px;margin-bottom:3px}.inventory .thumb-crop{max-height:46px}.inventory .item-number{font-size:11px;min-height:16px;padding:0}.inventory .item strong{font-size:12px;min-height:26px;line-height:1.2;display:-webkit-box;-webkit-line-clamp:2;-webkit-box-orient:vertical;overflow:hidden}.inventory .state{font-size:11px;padding-top:4px}.tray-actions{display:flex;gap:6px;align-items:center}.tray-actions button{white-space:nowrap;font-size:11px;min-height:32px}.tray-actions svg{width:14px;height:14px;stroke:currentColor;fill:none;stroke-width:1.5;stroke-linecap:round;stroke-linejoin:round}.review>.inventory-section.tray-expanded{height:min(42dvh,390px)}.review>.inventory-section.tray-collapsed{height:56px;padding-block:10px}.tray-collapsed .inventory{display:none}.tray-collapsed>.section-head{margin-bottom:0}
+.review>footer{flex-shrink:0;margin:0;padding:12px 24px;gap:16px;border-top:1px solid var(--line);background:var(--paper);align-items:center}.review>footer>div:first-child{display:flex;align-items:center;gap:14px;min-width:0}.review>footer .check{margin:0;max-width:240px;font-size:11px}.review>footer .submit-area{gap:12px}.review>footer .submit-area p{font-size:11px;max-width:24ch}.mobile-panes{display:none}
/* Depth describes the shell: recessed work area, raised inspector, anchored docks. */
-.review{--workspace:#e3e6e2;--canvas:#d5dad5;--dock:#f6f7f4;--surface:#fff;background:var(--workspace)}
-.review>header{position:relative;z-index:8;background:var(--surface);border-bottom-color:#d5d9d3}
-.review>.round-summary,.review>.preview-note{position:relative;z-index:7;background:var(--dock);box-shadow:0 3px 6px #202b2510;border-bottom-color:#c8cfc7}
+.review{--workspace:var(--ks-paper);--canvas:var(--ks-paper-deep);--dock:var(--ks-paper);--surface:var(--ks-paper-raised);background:var(--workspace)}
+.review>header{position:relative;z-index:8;background:var(--surface);border-bottom-color:var(--ks-rule)}
+.review>.round-summary,.review>.preview-note{position:relative;z-index:7;background:var(--dock);box-shadow:0 3px 6px oklch(13% 0 0 / 0.06);border-bottom-color:var(--ks-rule)}
.review>.workbench{background:var(--workspace)}
-.map-space{background:var(--canvas);border-color:#bdc6bd;box-shadow:inset 0 2px 7px #263d2a12;border-radius:5px}
-.map{box-shadow:0 3px 10px #182a242b}
-.workbench>.inspector{background:var(--surface);border-radius:6px;box-shadow:0 2px 4px #24332812,0 8px 24px #24332818;scrollbar-gutter:auto;isolation:isolate}
-.inspector>.section-head{position:relative;z-index:2;margin:0;padding:12px 16px;background:var(--surface);border-bottom:1px solid #dce0da}
-.inspection-content{padding:14px 12px 14px 16px;background:#fafbf9}
-.inspector>.review-form{position:relative;z-index:2;padding:12px 12px 12px 16px;background:var(--surface);border-top:1px solid #cdd4ca}
-.inspector[data-scroll-above=true]>.section-head{box-shadow:0 6px 8px -4px #24332838}
-.inspector[data-scroll-below=true]>.review-form{box-shadow:0 -6px 8px -4px #24332838}
-.inspection-content,.review-form,.inventory{scrollbar-width:auto;scrollbar-color:#8d9c91 #e3e8e1;overscroll-behavior:contain}
+.map-space{background:var(--canvas);border-color:var(--ks-rule);box-shadow:inset 0 2px 7px oklch(13% 0 0 / 0.07);border-radius:5px}
+.map{box-shadow:0 3px 10px oklch(13% 0 0 / 0.17)}
+.workbench>.inspector{background:var(--surface);border-radius:6px;box-shadow:0 2px 4px oklch(13% 0 0 / 0.07),0 8px 24px oklch(13% 0 0 / 0.09);scrollbar-gutter:auto;isolation:isolate}
+.inspector>.section-head{position:relative;z-index:2;margin:0;padding:12px 16px;background:var(--surface);border-bottom:1px solid var(--ks-rule)}
+.inspection-content{padding:14px 12px 14px 16px;background:var(--ks-paper)}
+.inspector>.review-form{position:relative;z-index:2;padding:12px 12px 12px 16px;background:var(--surface);border-top:1px solid var(--ks-rule)}
+.inspector[data-scroll-above=true]>.section-head{box-shadow:0 6px 8px -4px oklch(13% 0 0 / 0.22)}
+.inspector[data-scroll-below=true]>.review-form{box-shadow:0 -6px 8px -4px oklch(13% 0 0 / 0.22)}
+.inspection-content,.review-form,.inventory{scrollbar-width:auto;scrollbar-color:var(--ks-gray-2) var(--ks-paper-deep);overscroll-behavior:contain}
.inspection-content::-webkit-scrollbar,.review-form::-webkit-scrollbar,.inventory::-webkit-scrollbar{width:10px;height:10px}
-.inspection-content::-webkit-scrollbar-track,.review-form::-webkit-scrollbar-track,.inventory::-webkit-scrollbar-track{background:#e3e8e1;border-radius:6px}
-.inspection-content::-webkit-scrollbar-thumb,.review-form::-webkit-scrollbar-thumb,.inventory::-webkit-scrollbar-thumb{background:#8d9c91;border:2px solid #e3e8e1;border-radius:6px}
-.review>.inventory-section{position:relative;z-index:8;background:var(--dock);border-top-color:#b9c3b8;box-shadow:0 -3px 5px #2433280c,0 -10px 24px #24332814}
-.inventory-section>.section-head{border-bottom:1px solid #d9dfd5;padding-bottom:8px;margin-bottom:8px}
+.inspection-content::-webkit-scrollbar-track,.review-form::-webkit-scrollbar-track,.inventory::-webkit-scrollbar-track{background:var(--ks-paper-deep);border-radius:6px}
+.inspection-content::-webkit-scrollbar-thumb,.review-form::-webkit-scrollbar-thumb,.inventory::-webkit-scrollbar-thumb{background:var(--ks-gray-2);border:2px solid var(--ks-paper-deep);border-radius:6px}
+.review>.inventory-section{position:relative;z-index:8;background:var(--dock);border-top-color:var(--ks-rule);box-shadow:0 -3px 5px oklch(13% 0 0 / 0.05),0 -10px 24px oklch(13% 0 0 / 0.08)}
+.inventory-section>.section-head{border-bottom:1px solid var(--ks-rule);padding-bottom:8px;margin-bottom:8px}
.tray-collapsed>.section-head{border:0;padding-bottom:0;margin-bottom:0}
.inventory{background:transparent;border-radius:0;padding:3px 3px 7px}
-.inventory .item{background:#fafbf8}
-.inventory .item.active{background:#fff}
-.review>footer{position:relative;z-index:9;background:var(--surface);border-top-color:#ccd4c7;box-shadow:0 -2px 5px #2433280b}
-.mobile-panes{position:relative;z-index:7;box-shadow:0 3px 6px #202b2510}
+.inventory .item{background:var(--ks-paper)}
+.inventory .item.active{background:var(--ks-paper-raised)}
+.review>footer{position:relative;z-index:9;background:var(--surface);border-top-color:var(--ks-rule);box-shadow:0 -2px 5px oklch(13% 0 0 / 0.04)}
+.mobile-panes{position:relative;z-index:7;box-shadow:0 3px 6px oklch(13% 0 0 / 0.06)}
/* Utility actions share a compact icon language; decisions retain explicit labels. */
.utility-icon{width:18px;height:18px;fill:none;stroke:currentColor;stroke-width:1.6;stroke-linecap:round;stroke-linejoin:round;flex-shrink:0}
-:is(.review,.comparison-panel) .icon-button{display:inline-flex;align-items:center;justify-content:center;flex-shrink:0;width:36px;height:36px;min-height:36px;padding:7px;text-decoration:none;border:1px solid transparent;border-radius:4px;background:transparent;color:var(--muted)}
-:is(.review,.comparison-panel) .icon-button:hover{background:#e5ebe4;border-color:#b9c8bd;color:var(--teal)}
-:is(.review,.comparison-panel) .icon-button[aria-pressed=true]{background:#e5eee8;color:var(--teal)}
-:is(.review,.comparison-panel) .icon-button:focus-visible{outline:2px solid var(--teal);outline-offset:2px}
-.review .label-icon{display:inline-flex;align-items:center;justify-content:center;gap:7px}
.review .tray-actions .utility-icon{width:18px;height:18px;stroke-width:1.6}
.material{align-items:center;margin-bottom:10px}
.compare-toolbar{margin-bottom:10px}
-.view-controls{min-height:0}.view-controls>.background-options{margin-left:auto;gap:2px}.view-controls .swatch-button{display:flex;align-items:center;justify-content:center;min-width:32px;height:32px;padding:5px}
-.background-swatch{display:block;width:20px;height:20px;border:1px solid #9ba99d;border-radius:2px;pointer-events:none}.background-swatch.checker{background-size:8px 8px}.page-swatch{background:var(--comp-background,#eee)}
+.view-controls{min-height:0}.view-controls>.background-options{margin-left:auto;gap:2px}.page-swatch{background:var(--comp-background,var(--ks-paper-deep))}
.review>footer .submit-area p{max-width:25ch}
-@media(max-width:1100px) and (min-width:801px){.review>header{padding:12px 20px}.review>.workbench{padding:16px 20px;gap:24px}.review>.round-summary{padding-inline:20px}.round-summary p{max-width:calc(100% - 52px)}.round-summary p>span{font-size:11px}.inventory-section>.section-head h2{max-width:none;white-space:nowrap}.review>footer>div:first-child{gap:8px}.review>footer .submit-area p{max-width:19ch}.inventory-filters button{padding-inline:8px}}
+@media(max-width:1100px) and (min-width:801px){.review>header{padding:12px 20px}.review>.workbench{padding:16px 20px;gap:24px}.review>.round-summary{padding-inline:20px}.round-summary p{max-width:calc(100% - 52px)}.round-summary p>span{font-size:11px}.inventory-section>.section-head h2{max-width:none;white-space:nowrap}.review>footer>div:first-child{gap:8px}.review>footer .submit-area p{max-width:19ch}}
@media(max-width:800px){
.review>header{padding:12px 14px;align-items:center}.review h1{font-size:25px}.review>header p{max-width:68vw;font-size:11px}.review .badge{display:none}.review>.preview-note{padding:6px 14px}.review>.round-summary{padding:6px 14px;max-height:76px;gap:4px 8px}.round-summary p{max-width:calc(100% - 44px);gap:4px 10px;font-size:11px}.round-summary p>span{font-size:10px}.round-summary button{font-size:11px}
- .mobile-panes{display:flex;flex-shrink:0;gap:4px;padding:7px 14px;border-bottom:1px solid var(--line);background:var(--paper)}.mobile-panes button{flex:1;font-size:12px;min-height:32px;padding:5px;border-color:transparent;background:transparent}.mobile-panes button[aria-pressed=true]{background:#e8efec;color:var(--teal);box-shadow:none;border-color:#bdd0c8}
- .review>.workbench{display:block;padding:12px 14px;min-height:0;overflow:hidden}.workbench[data-mobile-pane=component]>.reference,.workbench[data-mobile-pane=comp]>.inspector{display:none}.reference{height:100%;max-width:none}.connector{display:none}.inspector{height:100%;border:0}.map-legend{gap:6px 12px;font-size:10px}.map-caption{font-size:9px}.reference .section-head button{min-height:30px;padding:4px 8px}.reference .section-head h2{font-size:14px}.inspector>.section-head{min-height:26px;margin-bottom:0;padding:9px 12px}.inspection-content{padding:10px 8px 10px 12px}.inspector>.review-form{padding:8px 8px 8px 12px}.number{width:23px;height:23px;font-size:11px}.section-head h2{font-size:14px}.review-form{padding-top:8px}.decision-title strong{font-size:12px}.decision-title p{font-size:10px}.decisions>button{min-height:36px}.review-form .feedback-field{font-size:12px}.review-form .feedback-field textarea{min-height:60px}.compare{max-width:none}
- .review>.inventory-section{height:160px;padding:6px 14px}.inventory-section>.section-head{flex-direction:row;flex-wrap:nowrap;align-items:center;gap:6px;min-height:34px;margin-bottom:4px}.inventory-section h2{display:none}.inventory-filters{flex:1;width:auto;min-width:0;padding:2px}.inventory-filters button{padding:4px 6px;font-size:10px;min-height:28px}.inventory-filters b{margin-left:3px}.tray-actions #show-all{display:none}.tray-actions #toggle-tray{padding:6px;min-width:32px;min-height:32px}.tray-actions #toggle-tray span{display:none}.tray-actions svg{width:16px;height:16px}.review>.inventory-section.tray-collapsed{height:46px;padding:6px 14px}.review>.inventory-section.tray-expanded{height:160px}.inventory .item{flex-basis:130px;grid-template-rows:auto 1fr auto;padding:6px}.inventory .item-thumb{display:none}.inventory.all{display:flex;overflow-x:auto;overflow-y:hidden}.inventory .item strong{font-size:11px;min-height:22px}.inventory .state{font-size:10px}.inventory .item-number{font-size:10px;min-height:14px}.inventory-empty{padding:8px 0;font-size:12px}
- .review>footer{padding:8px 14px calc(8px + env(safe-area-inset-bottom));gap:8px;flex-direction:column;align-items:stretch}.review>footer>div:first-child{gap:10px;justify-content:space-between}.review>footer #approve-rest{font-size:10px;min-height:32px;max-width:47%;padding:5px 8px}.review>footer .check{font-size:10px;max-width:48%;gap:4px}.review>footer .check input{width:14px;height:14px}.review>footer .submit-area{justify-content:space-between;gap:10px}.review>footer .submit-area p{font-size:10px;max-width:22ch}.review>footer .primary{min-height:34px;font-size:12px;padding:6px 10px}
+ .mobile-panes{display:flex;flex-shrink:0;gap:4px;padding:7px 14px;border-bottom:1px solid var(--line);background:var(--paper)}
+ .review>.workbench{display:block;padding:12px 14px;min-height:0;overflow:hidden}.workbench[data-mobile-pane=component]>.reference,.workbench[data-mobile-pane=comp]>.inspector{display:none}.reference{height:100%;max-width:none}.connector{display:none}.inspector{height:100%;border:0}.map-legend{gap:6px 12px;font-size:10px}.map-caption{font-size:9px}.reference .section-head button{min-height:30px;padding:4px 8px}.reference .section-head h2{font-size:14px}.inspector>.section-head{min-height:26px;margin-bottom:0;padding:9px 12px}.inspection-content{padding:10px 8px 10px 12px}.inspector>.review-form{padding:8px 8px 8px 12px}.number{width:23px;height:23px;font-size:11px}.section-head h2{font-size:14px}.review-form{padding-top:8px}.decision-title strong{font-size:12px}.decision-title p{font-size:10px}.review-form .feedback-field{font-size:12px}.review-form .feedback-field textarea{min-height:60px}.compare{max-width:none}
+ .review>.inventory-section{height:160px;padding:6px 14px}.inventory-section>.section-head{flex-direction:row;flex-wrap:nowrap;align-items:center;gap:6px;min-height:34px;margin-bottom:4px}.inventory-section h2{display:none}.tray-actions svg{width:16px;height:16px}.review>.inventory-section.tray-collapsed{height:46px;padding:6px 14px}.review>.inventory-section.tray-expanded{height:160px}.inventory .item{flex-basis:130px;grid-template-rows:auto 1fr auto;padding:6px}.inventory .item-thumb{display:none}.inventory.all{display:flex;overflow-x:auto;overflow-y:hidden}.inventory .item strong{font-size:11px;min-height:22px}.inventory .state{font-size:10px}.inventory .item-number{font-size:10px;min-height:14px}.inventory-empty{padding:8px 0;font-size:12px}
+ .review>footer{padding:8px 14px calc(8px + env(safe-area-inset-bottom));gap:8px;flex-direction:column;align-items:stretch}.review>footer>div:first-child{gap:10px;justify-content:space-between}.review>footer .check{font-size:10px;max-width:48%;gap:4px}.review>footer .check input{width:14px;height:14px}.review>footer .submit-area{justify-content:space-between;gap:10px}.review>footer .submit-area p{font-size:10px;max-width:22ch}
}
`;
diff --git a/ui/component-review/entry.ts b/ui/component-review/entry.ts
index dbe6c652c..aac4ec01b 100644
--- a/ui/component-review/entry.ts
+++ b/ui/component-review/entry.ts
@@ -1,21 +1,59 @@
import { mountComponentReview } from './review';
import type { Draft, ReviewPacket, ReviewHistory } from './model';
+import { isPlanPacket } from './plan-model';
+
+/** The served stylesheet declares the three variable fonts without weight ranges, so a
+ * request for Alumni Sans 300 or Albert Sans 600 would be synthesized. Declare the ranges. */
+function fontRanges() {
+ const style = document.createElement('style');
+ style.textContent = [['Albert Sans','albertsans'],['Alumni Sans','alumnisans'],['JetBrains Mono','jetbrainsmono']]
+ .map(([family,file]) => `@font-face{font-family:"${family}";src:url(/fonts/${file}.ttf);font-weight:100 900}`).join('');
+ document.head.append(style);
+}
+
+/** A load failure replaces the review, so it carries its own styling and a next step.
+ * Values are the --ks-* tokens (see tokens.ts): paper, ink, vermilion mark, hairline rule. */
+function failure(message: string) {
+ const box = document.createElement('div');
+ box.setAttribute('role', 'alert');
+ box.style.cssText = 'max-width:560px;margin:18vh auto 0;padding:0 0 0 18px;border-left:2px solid oklch(52% 0.16 35);color:oklch(22% 0 0);font:400 15px/1.55 var(--font-sans,Arial,sans-serif)';
+ const eyebrow = document.createElement('p');
+ eyebrow.textContent = 'Review unavailable';
+ eyebrow.style.cssText = 'margin:0 0 8px;font:400 11px/1.3 var(--font-mono,monospace);letter-spacing:.14em;text-transform:uppercase;color:oklch(46% 0 0)';
+ const title = document.createElement('strong');
+ title.textContent = 'The review could not be opened.';
+ title.style.cssText = 'display:block;font-weight:500;color:oklch(13% 0 0)';
+ const detail = document.createElement('p');
+ detail.style.cssText = 'margin:4px 0 18px;color:oklch(46% 0 0)';
+ detail.textContent = `${message} If the review server stopped, ask the agent to serve the review again, then reload.`;
+ const retry = document.createElement('button');
+ retry.textContent = 'Reload';
+ retry.style.cssText = 'font:500 15px/1 var(--font-sans,Arial,sans-serif);min-height:44px;padding:0 22px;border:1px solid oklch(13% 0 0);border-radius:3px;background:oklch(13% 0 0);color:oklch(99.5% 0 0);cursor:pointer';
+ retry.onclick = () => location.reload();
+ box.append(eyebrow, title, detail, retry);
+ return box;
+}
async function start() {
+ fontRanges();
+ document.body.style.background='oklch(97.8% 0 0)';
const host=document.getElementById('review')!;
const response=await fetch('/packet',{cache:'no-store'});
- if(!response.ok)throw new Error('The review packet could not be loaded. Reload to retry.');
+ if(!response.ok)throw new Error('The review packet could not be loaded.');
const state=await response.json() as {packet:ReviewPacket;draft:Draft;receipt:unknown;history:ReviewHistory|null;sourceStatus:string|null};
- if(state.sourceStatus){const notice=document.createElement('p');notice.textContent=state.sourceStatus;host.before(notice);}
+ // The plan review shows its own out-of-date banner; earlier stages keep the plain notice.
+ const plan=isPlanPacket(state.packet);
+ if(state.sourceStatus&&!plan){const notice=document.createElement('p');notice.textContent=state.sourceStatus;host.before(notice);}
mountComponentReview(host,state.packet,{
initialDraft:state.draft,
history:state.history,
completed:!!state.receipt,
+ status:plan?state.sourceStatus:null,
onSubmit:async(value)=>{
const response=await fetch('/decision',{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify(value)});
- const result=await response.json();
+ const result=await response.json().catch(()=>({}));
if(!response.ok)throw new Error(result.error??'The review could not be saved. Try again.');
},
});
}
-start().catch(error=>{const p=document.createElement('p');p.textContent=error instanceof Error?error.message:String(error);document.getElementById('review')?.replaceChildren(p);});
+start().catch(error=>{document.getElementById('review')?.replaceChildren(failure(error instanceof Error?error.message:String(error)));});
diff --git a/ui/component-review/instrument-strip.ts b/ui/component-review/instrument-strip.ts
new file mode 100644
index 000000000..d47f5d186
--- /dev/null
+++ b/ui/component-review/instrument-strip.ts
@@ -0,0 +1,86 @@
+/** Port of impeccable-site/site/scripts/instrument-strip.js (vendored at vendor/instrument-strip.js,
+ * the source of truth) for views that live in a shadow root and re-render with innerHTML.
+ * Same behavior: one .ks-thumb per .ks-instrument-strip, measured from the active key and
+ * slid on the kit's curve; mouse and pen can scrub between keys; touch keeps native taps.
+ * The one addition: a strip with data-ks-strip="<name>" remembers where its thumb was, so a
+ * re-render slides the cap from the old key instead of drawing it in place. */
+const ACTIVE = '.is-active, [aria-selected="true"], [aria-pressed="true"]';
+const memory = new Map<string, { x: number; w: number }>();
+
+function place(strip: HTMLElement) {
+ const key = strip.querySelector<HTMLElement>(`.ks-instrument-key:is(${ACTIVE})`);
+ if (!key) {
+ if (strip.classList.contains('has-thumb')) strip.classList.remove('has-thumb');
+ return;
+ }
+ const s = strip.getBoundingClientRect();
+ const k = key.getBoundingClientRect();
+ if (!s.width) return;
+ const styles = getComputedStyle(strip);
+ const scale = s.width / parseFloat(styles.width) || 1;
+ const border = parseFloat(styles.borderLeftWidth) || 0;
+ const x = Math.round(((k.left - s.left) / scale - border + strip.scrollLeft) * 100) / 100;
+ const w = Math.round(k.width / scale * 100) / 100;
+ let thumb = strip.querySelector<HTMLElement>(':scope > .ks-thumb');
+ const name = strip.dataset.ksStrip;
+ if (!thumb) {
+ thumb = document.createElement('span');
+ thumb.className = 'ks-thumb';
+ thumb.setAttribute('aria-hidden', 'true');
+ strip.appendChild(thumb);
+ const was = name ? memory.get(name) : undefined;
+ if (was && (was.x !== x || was.w !== w)) {
+ // Start where the cap was before this render, then let the kit's transition carry it.
+ thumb.style.transition = 'none';
+ thumb.style.width = `${was.w}px`;
+ thumb.style.transform = `translateX(${was.x}px)`;
+ void thumb.offsetWidth;
+ thumb.style.transition = '';
+ }
+ }
+ if (name) memory.set(name, { x, w });
+ if (thumb.style.width !== `${w}px`) thumb.style.width = `${w}px`;
+ const t = `translateX(${x}px)`;
+ if (thumb.style.transform !== t) thumb.style.transform = t;
+ if (!strip.classList.contains('has-thumb')) strip.classList.add('has-thumb');
+}
+
+function attach(strip: HTMLElement, root: Document | ShadowRoot, cleanups: (() => void)[]) {
+ if (strip.dataset.thumb) return;
+ strip.dataset.thumb = '1';
+ place(strip);
+ const mo = new MutationObserver(records => {
+ if (records.some(r => r.target !== strip && !(r.target as Element).classList?.contains('ks-thumb'))) place(strip);
+ });
+ mo.observe(strip, { subtree: true, attributes: true, attributeFilter: ['class', 'aria-selected', 'aria-pressed'], childList: true });
+ const ro = new ResizeObserver(() => place(strip));
+ ro.observe(strip);
+ let pointerId: number | null = null, dragging = false, startX = 0;
+ let last: Element | null = null;
+ const keyAt = (x: number, y: number) => root.elementFromPoint(x, y)?.closest('.ks-instrument-key') ?? null;
+ strip.addEventListener('pointerdown', e => {
+ if (!['mouse', 'pen'].includes(e.pointerType) || !e.isPrimary || e.button !== 0 || pointerId !== null) return;
+ pointerId = e.pointerId; dragging = false; startX = e.clientX; last = keyAt(e.clientX, e.clientY);
+ });
+ strip.addEventListener('pointermove', e => {
+ if (e.pointerId !== pointerId) return;
+ if (!dragging && Math.abs(e.clientX - startX) < 6) return;
+ dragging = true;
+ const key = keyAt(e.clientX, e.clientY);
+ if (key && key !== last && strip.contains(key)) { last = key; (key as HTMLElement).click(); }
+ });
+ const resetDrag = () => { pointerId = null; dragging = false; last = null; };
+ const end = (e: PointerEvent) => { if (e.pointerId === pointerId) resetDrag(); };
+ window.addEventListener('pointerup', end);
+ window.addEventListener('pointercancel', end);
+ window.addEventListener('blur', resetDrag);
+ cleanups.push(() => { mo.disconnect(); ro.disconnect(); window.removeEventListener('pointerup', end); window.removeEventListener('pointercancel', end); window.removeEventListener('blur', resetDrag); });
+}
+
+/** Attach every strip under `root`. Call after each render; returns a cleanup for the previous DOM. */
+export function initInstrumentStrips(root: Document | ShadowRoot): () => void {
+ const cleanups: (() => void)[] = [];
+ root.querySelectorAll<HTMLElement>('.ks-instrument-strip').forEach(strip => attach(strip, root, cleanups));
+ document.fonts?.ready.then(() => root.querySelectorAll<HTMLElement>('.ks-instrument-strip').forEach(place));
+ return () => cleanups.forEach(fn => fn());
+}
diff --git a/ui/component-review/kit.ts b/ui/component-review/kit.ts
new file mode 100644
index 000000000..d5928a06d
--- /dev/null
+++ b/ui/component-review/kit.ts
@@ -0,0 +1,8 @@
+/** The Impeccable design-system kit, vendored verbatim from impeccable-site (see vendor/ and
+ * scripts/sync-kinpaku-kit.mjs; the site is the source of truth). Shadow roots have no :root,
+ * so the token blocks also apply to :host. Class names are the kit's own. */
+import { tokens, kit, rail } from './vendor/kit-css';
+const hosted = (css: string) => css.replace(/^:root\s*\{/gm, ':root, :host {');
+export const ksKit = hosted(tokens) + '\n' + hosted(kit) + '\n' + rail;
+/** The kit's primary-button arrow (the site's .ks-button-arrow markup). */
+export const ksArrow = '<span class="ks-button-arrow" aria-hidden="true"><svg viewBox="0 0 16 8" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="square"><path d="M0 4h14M10 0l4 4-4 4"/></svg></span>';
diff --git a/ui/component-review/plan-model.test.ts b/ui/component-review/plan-model.test.ts
new file mode 100644
index 000000000..959a15951
--- /dev/null
+++ b/ui/component-review/plan-model.test.ts
@@ -0,0 +1,197 @@
+import { describe, expect, test } from 'bun:test';
+import { clearDecision, planView, decide, defaultAssetKind, extraRegions, flagMessage, isFlagged, isPlanPacket, itemState, medianColor, newPlanDraft, nextPending, pairLayout, planQueue, planSubmission, planSummary, ringSamples, setRegionReclassify, type PlanPacket } from './plan-model';
+
+const packet: PlanPacket = {
+ schemaVersion: 3, stage: 'components', id: 'review-1', revision: 'rev-1', title: 'Harbour', round: 1,
+ comp: { url: '/comp.png', width: 1440, height: 900 },
+ components: [
+ { id: 'figure', revision: 'f1', name: 'Hero figure', kind: 'plate', role: 'asset', box: { x: .52, y: .1, w: .4, h: .6 }, note: 'Illustrated fisherman', preview: { kind: 'image', url: '/files/r/figure.png' } },
+ { id: 'rule', revision: 'r1', name: 'Hairline', kind: 'chrome', role: 'plan', box: { x: 0, y: .6, w: 1, h: .01 }, note: 'Thin divider', preview: { kind: 'comp-crop' } },
+ { id: 'panel', revision: 'p1', name: 'Brushed panel', kind: 'chrome', role: 'plan', box: { x: 0, y: .7, w: 1, h: .1 }, note: 'Brushed steel band under the nav', preview: { kind: 'comp-crop' }, flags: [{ id: 'painted-pixels', message: 'The comp shows photographic shading here.' }] },
+ ],
+ codeRegions: [
+ { id: 'headline', name: 'Headline', kind: 'text', box: { x: .06, y: .2, w: .4, h: .2 }, note: 'A little closer to the sea.' },
+ { id: 'rule', name: 'Hairline', kind: 'chrome', box: { x: 0, y: .6, w: 1, h: .01 } },
+ ],
+};
+const [figure, rule, panel] = packet.components;
+
+describe('plan and asset review model', () => {
+ test('recognises only v3 component packets', () => {
+ expect(isPlanPacket(packet)).toBe(true);
+ expect(isPlanPacket({ ...packet, schemaVersion: 2 })).toBe(false);
+ expect(isPlanPacket({ ...packet, stage: 'hero' })).toBe(false);
+ });
+ test('queue puts flagged plan items first, then assets, then remaining plan items', () => {
+ expect(planQueue(packet).map(c => c.id)).toEqual(['panel', 'figure', 'rule']);
+ expect(isFlagged({ ...rule, codeDrawn: true })).toBe(true);
+ expect(isFlagged({ ...figure, flags: [{ id: 'x', message: 'y' }] })).toBe(false);
+ });
+ test('code regions already in the component list are not listed twice', () => {
+ expect(extraRegions(packet).map(r => r.id)).toEqual(['headline']);
+ });
+ test('approval requires every item approved and nothing changed; it confirms inventory', () => {
+ let draft = newPlanDraft(packet);
+ expect(planSummary(packet, draft)).toMatchObject({ pending: 3, canSubmit: false, mode: 'approve' });
+ for (const c of packet.components) draft = decide(draft, c, 'approve');
+ expect(planSummary(packet, draft)).toMatchObject({ approved: 3, canApprove: true, canSubmit: true });
+ const body = planSubmission(packet, draft);
+ expect(body).toMatchObject({ schemaVersion: 1, requestId: 'review-1', packetRevision: 'rev-1', inventoryConfirmed: true, missing: [] });
+ expect(body).not.toHaveProperty('reclassify');
+ expect(Object.keys(body.decisions).sort()).toEqual(['figure', 'panel', 'rule']);
+ });
+ test('reclassifying a plan item is a change, carries its kind, and never confirms inventory', () => {
+ let draft = newPlanDraft(packet);
+ draft = decide(draft, panel, 'reclassify', { feedback: ' keep it subtle ' });
+ expect(draft.decisions.panel).toEqual({ revision: 'p1', action: 'reclassify', feedback: 'keep it subtle', split: false, kind: 'texture' });
+ const summary = planSummary(packet, draft);
+ expect(summary).toMatchObject({ reclassify: 1, pending: 2, hasChanges: true, canSubmit: true, mode: 'changes' });
+ expect(planSubmission(packet, draft).inventoryConfirmed).toBe(false);
+ });
+ test('code regions without a component entry travel in submission.reclassify', () => {
+ let draft = setRegionReclassify(newPlanDraft(packet), 'headline', { kind: 'plate', feedback: 'hand lettered' });
+ draft = setRegionReclassify(draft, 'rule', { kind: 'texture' });
+ const body = planSubmission(packet, draft);
+ expect(body.reclassify).toEqual([{ id: 'headline', kind: 'plate', feedback: 'hand lettered' }]);
+ expect(body.decisions).toEqual({});
+ draft = setRegionReclassify(draft, 'headline', null);
+ expect(planSummary(packet, draft).hasChanges).toBe(false);
+ });
+ test('revise needs words on a plan item; reclassify is only for plan items', () => {
+ const draft = newPlanDraft(packet);
+ expect(() => decide(draft, rule, 'revise')).toThrow('feedback');
+ expect(decide(draft, rule, 'revise', { feedback: ' Extend the photo under it ' }).decisions.rule).toEqual({ revision: 'r1', action: 'revise', feedback: 'Extend the photo under it', split: false });
+ expect(() => decide(draft, figure, 'reclassify')).toThrow();
+ expect(itemState(figure, decide(draft, figure, 'revise', { feedback: 'Warmer' }))).toBe('revise');
+ });
+ test('missing marks need a name and a valid box; stale drafts cannot submit', () => {
+ const draft = newPlanDraft(packet);
+ draft.missing.push({ id: 'm1', name: 'Boat', box: { x: .1, y: .1, w: .1, h: .1 }, feedback: '' });
+ expect(planSummary(packet, draft)).toMatchObject({ hasChanges: true, canSubmit: true });
+ expect(planSubmission(packet, draft).inventoryConfirmed).toBe(false);
+ draft.missing[0].name = ' ';
+ expect(planSummary(packet, draft).canSubmit).toBe(false);
+ draft.missing[0].name = 'Boat';
+ expect(() => planSubmission({ ...packet, revision: 'rev-2' }, draft)).toThrow('stale');
+ });
+ test('a changed component revision reopens only that item', () => {
+ let draft = newPlanDraft(packet);
+ for (const c of packet.components) draft = decide(draft, c, 'approve');
+ const changed = { ...packet, components: packet.components.map(c => c.id === 'figure' ? { ...c, revision: 'f2' } : c) };
+ expect(planSummary(changed, draft)).toMatchObject({ approved: 2, pending: 1, canSubmit: false });
+ expect(Object.keys(planSubmission(packet, draft).decisions)).toHaveLength(3);
+ });
+ test('next pending follows queue order and wraps', () => {
+ let draft = newPlanDraft(packet);
+ expect(nextPending(packet, draft)).toBe('panel');
+ draft = decide(draft, panel, 'approve');
+ expect(nextPending(packet, draft, 'panel')).toBe('figure');
+ expect(nextPending(packet, draft, 'rule')).toBe('figure');
+ draft = decide(decide(draft, figure, 'approve'), rule, 'approve');
+ expect(nextPending(packet, draft, 'rule')).toBeUndefined();
+ expect(itemState(rule, clearDecision(draft, 'rule'))).toBe('pending');
+ });
+ test('default image kind follows the words that describe the region', () => {
+ expect(defaultAssetKind(panel)).toBe('texture');
+ expect(defaultAssetKind({ note: 'Fisherman mending a net', flags: [{ id: 'painted-pixels', message: 'photographic shading, soft gradients' }] })).toBe('plate');
+ expect(defaultAssetKind({ note: 'A photo of the harbour at dawn' })).toBe('image');
+ expect(defaultAssetKind({ note: 'Linen paper grain behind the menu' })).toBe('texture');
+ });
+ test('painted-pixel flags read as a plain statement', () => {
+ expect(flagMessage(panel.flags![0])).toBe(panel.flags![0].message);
+ expect(flagMessage({ id: 'other', message: 'Custom.' })).toBe('Custom.');
+ });
+ test('the backdrop colour is the median of the pixels around the box', () => {
+ const w = 10, h = 10, data = new Uint8ClampedArray(w * h * 4);
+ for (let i = 0; i < w * h; i++) data.set([240, 230, 220, 255], i * 4);
+ for (let y = 3; y < 7; y++) for (let x = 3; x < 7; x++) data.set([10, 10, 10, 255], (y * w + x) * 4);
+ expect(medianColor(ringSamples(data, w, h, { x: .3, y: .3, w: .4, h: .4 }, .1))).toBe('#f0e6dc');
+ expect(medianColor([])).toBeUndefined();
+ });
+ test('pair layout picks the larger of side by side and stacked', () => {
+ expect(pairLayout(1, 800, 500, 16, 24).direction).toBe('row');
+ const band = pairLayout(16, 800, 500, 16, 24);
+ expect(band.direction).toBe('column');
+ expect(band.w).toBeCloseTo(800);
+ const capped = pairLayout(1, 800, 500, 16, 24, 4, { w: 40, h: 40 });
+ expect(capped.w).toBe(160);
+ });
+ test('plan crops frame the region tightly and fill the pane width', () => {
+ const strip = planView({ x: 0, y: 0, w: 1, h: 102 / 900 }, 1440, 900, 590, 330);
+ expect(strip.width).toBeCloseTo(590);
+ expect(strip.view.h * 900).toBeLessThan(102 + 70);
+ expect(strip.view.y).toBe(0);
+ const card = planView({ x: .5, y: .5, w: .1, h: .1 }, 1440, 900, 590, 330);
+ expect(card.height).toBeCloseTo(330);
+ expect(card.view.w * 1440).toBeLessThan(144 + 40);
+ const tiny = planView({ x: .5, y: .5, w: .01, h: .01 }, 1440, 900, 590, 330);
+ expect(tiny.scale).toBe(4);
+ const hairline = planView({ x: 0, y: .5, w: 1, h: 2 / 900 }, 1440, 900, 590, 330);
+ expect(2 * hairline.scale).toBeGreaterThanOrEqual(8);
+ expect(hairline.width).toBeLessThanOrEqual(590.01);
+ const edge = planView({ x: 0, y: 0, w: .05, h: .002 }, 1440, 900, 590, 330);
+ expect(edge.view.x).toBe(0); expect(edge.view.y).toBe(0);
+ });
+});
+
+describe('stage flow helpers', () => {
+ test('the intro says how much there is to do, or what changed since last round', async () => {
+ const { introLine } = await import('./plan-model');
+ expect(introLine(packet, newPlanDraft(packet))).toBe('Three things to check before any page code is written. About one minute.');
+ const draft = decide(newPlanDraft(packet), rule, 'approve');
+ const history: any = { packet: { ...packet, round: 1 }, submitted: true, changes: { figure: { kind: 'changed', files: [], reasons: [] } }, feedback: { panel: { round: 1, decision: { action: 'revise', feedback: 'Moor the boats' } } } };
+ expect(introLine({ ...packet, round: 2 }, draft, history)).toBe('The agent worked on your notes for two items. One approval is kept.');
+ });
+ test('prior round quotes the user and keeps the old asset for before/after', async () => {
+ const { priorRound } = await import('./plan-model');
+ const old = { ...packet, components: packet.components.map(c => c.id === 'figure' ? { ...c, preview: { kind: 'image' as const, url: '/old.png' } } : c) };
+ const history: any = { packet: old, submitted: true, changes: { figure: { kind: 'changed', files: ['a.png'], reasons: [] } }, feedback: { figure: { round: 1, decision: { action: 'revise', feedback: ' Face the sea ' } } } };
+ expect(priorRound('figure', history)).toMatchObject({ round: 1, words: 'Face the sea', beforeUrl: '/old.png', wasCode: false });
+ expect(priorRound('rule', history)).toBeNull();
+ const reclassified: any = { packet: old, submitted: true, changes: {}, feedback: { headline: { round: 1, decision: { action: 'reclassify', kind: 'plate', feedback: '' } } } };
+ expect(priorRound('headline', reclassified)).toMatchObject({ wasCode: true, wasKind: 'text' });
+ });
+ test('figure layout keeps equal heights and stacks bands', async () => {
+ const { figureLayout } = await import('./plan-model');
+ const row = figureLayout([1, 1, 1], 900, 400, 16, 20);
+ expect(row.direction).toBe('row');
+ expect(new Set(row.sizes.map(s => Math.round(s.h))).size).toBe(1);
+ expect(row.sizes[0].w * 3 + 32).toBeLessThanOrEqual(900.01);
+ expect(figureLayout([10, 10], 900, 500, 16, 20).direction).toBe('column');
+ expect(figureLayout([1, 1], 900, 500, 16, 20, 2, { w: 50, h: 50 }).sizes[0].h).toBe(100);
+ });
+ test('loupe centres the pointed spot', async () => {
+ const { loupeOffset } = await import('./plan-model');
+ expect(loupeOffset(.5, .5, 200, 100, 80, 3)).toEqual({ x: 80 - 300, y: 80 - 150 });
+ });
+ test('send label counts what goes back', async () => {
+ const { sendLabel } = await import('./plan-model');
+ let draft = newPlanDraft(packet);
+ for (const c of packet.components) draft = decide(draft, c, 'approve');
+ expect(sendLabel(packet, draft)).toBe('Approve plan and assets');
+ draft = decide(draft, figure, 'revise', { feedback: 'x' });
+ draft = setRegionReclassify(draft, 'headline', { kind: 'plate' });
+ expect(sendLabel(packet, draft)).toBe('Send notes (1 note, 1 to become an image)');
+ });
+});
+
+describe('split into layers', () => {
+ test('only an asset revise splits, and the send label counts it apart from notes', async () => {
+ const { isSplit, sendLabel } = await import('./plan-model');
+ let draft = newPlanDraft(packet);
+ expect(() => decide(draft, rule, 'revise', { feedback: 'x', split: true })).toThrow('split');
+ expect(() => decide(draft, figure, 'approve', { split: true })).toThrow('split');
+ draft = decide(draft, figure, 'revise', { split: true, feedback: 'Frame and view apart' });
+ expect(draft.decisions.figure).toEqual({ revision: 'f1', action: 'revise', feedback: 'Frame and view apart', split: true });
+ expect(isSplit(draft.decisions.figure)).toBe(true);
+ expect(planSummary(packet, draft)).toMatchObject({ revise: 1, hasChanges: true });
+ for (const c of [rule, panel]) draft = decide(draft, c, 'approve');
+ expect(sendLabel(packet, draft)).toBe('Send notes (1 to split)');
+ });
+ test('layers of a split region are linked to the note that asked for them', async () => {
+ const { priorRound } = await import('./plan-model');
+ const history: any = { packet, submitted: true, changes: { 'figure-frame': { kind: 'added', files: [], reasons: [] } }, feedback: { figure: { round: 1, decision: { action: 'revise', split: true, feedback: 'Shutters apart' } } } };
+ expect(priorRound('figure-frame', history)).toMatchObject({ action: 'split', words: 'Shutters apart', splitFrom: 'Hero figure', round: 1 });
+ expect(priorRound('figurehead', history)).toBeNull();
+ });
+});
diff --git a/ui/component-review/plan-model.ts b/ui/component-review/plan-model.ts
new file mode 100644
index 000000000..0f0b3bc98
--- /dev/null
+++ b/ui/component-review/plan-model.ts
@@ -0,0 +1,305 @@
+/** Plan and asset review (packet schemaVersion 3). Pure logic; the view lives in plan-review.ts.
+ * Contract: docs/PLAN-REVIEW.md. */
+import { validBox, type Box, type Missing } from './model';
+
+export type AssetKind = 'plate' | 'image' | 'texture';
+export type Flag = { id: string; message: string };
+export type PlanItem = {
+ id: string; revision: string; name: string; kind: string; role: 'asset' | 'plan';
+ box: Box; note: string; medium?: string;
+ preview: { kind: 'image' | 'comp-crop' | 'page'; url?: string };
+ flags?: Flag[]; codeDrawn?: boolean;
+ material?: { format: string; width: number; height: number; alpha: 'transparent' | 'opaque' | 'unknown' };
+};
+export type CodeRegion = { id: string; name: string; kind: string; box: Box; note?: string; container?: boolean };
+export type PlanPacket = {
+ schemaVersion: 3; stage: 'components'; id: string; revision: string; title: string; round: number;
+ comp: { url: string; width: number; height: number; background?: string };
+ components: PlanItem[]; codeRegions?: CodeRegion[]; specSha256?: string;
+};
+export type PlanDecision = { revision: string; action: 'approve' | 'revise' | 'reclassify'; feedback: string; split: boolean; kind?: AssetKind };
+export type Reclassify = { id: string; kind: AssetKind; feedback: string };
+export type PlanDraft = { packetRevision: string; decisions: Record<string, PlanDecision>; missing: Missing[]; inventoryConfirmed: boolean; reclassify?: Reclassify[] };
+export type PlanHistory = {
+ packet: PlanPacket; submitted: boolean;
+ changes: Record<string, { kind: 'added' | 'changed' | 'unchanged'; files: string[]; reasons: string[]; carried?: boolean }>;
+ feedback?: Record<string, { round: number; decision: { action: string; feedback?: string; kind?: string; split?: boolean } }>;
+};
+export type ItemState = 'pending' | 'approved' | 'revise' | 'reclassify';
+
+export const ASSET_KINDS: { kind: AssetKind; label: string; hint: string }[] = [
+ { kind: 'plate', label: 'Illustration / plate', hint: 'Painted or drawn artwork' },
+ { kind: 'image', label: 'Photo / image', hint: 'A photograph' },
+ { kind: 'texture', label: 'Texture', hint: 'A surface or material' },
+];
+export const assetKindLabel = (kind: AssetKind) => ASSET_KINDS.find(k => k.kind === kind)!.label;
+
+export function isPlanPacket(packet: unknown): packet is PlanPacket {
+ const p = packet as Partial<PlanPacket> | null;
+ return !!p && p.schemaVersion === 3 && p.stage === 'components';
+}
+
+/** Plan items that need attention: the comp looks painted, or the plan draws artwork in code. */
+export function isFlagged(item: PlanItem) {
+ return item.role === 'plan' && (!!item.flags?.length || !!item.codeDrawn);
+}
+
+/** Flagged plan items first, then assets, then remaining plan items. Stable within groups. */
+export function planQueue(packet: PlanPacket): PlanItem[] {
+ const rank = (c: PlanItem) => isFlagged(c) ? 0 : c.role === 'asset' ? 1 : 2;
+ return packet.components.map((c, i) => ({ c, i })).sort((a, b) => rank(a.c) - rank(b.c) || a.i - b.i).map(x => x.c);
+}
+
+/** Code regions without a component entry; containers last so they never crowd the list. */
+export function extraRegions(packet: PlanPacket): CodeRegion[] {
+ const ids = new Set(packet.components.map(c => c.id));
+ return (packet.codeRegions ?? []).filter(r => !ids.has(r.id));
+}
+
+export function currentDecision(item: PlanItem, draft: PlanDraft): PlanDecision | undefined {
+ const d = draft.decisions[item.id];
+ return d?.revision === item.revision ? d : undefined;
+}
+
+export function itemState(item: PlanItem, draft: PlanDraft): ItemState {
+ const d = currentDecision(item, draft);
+ return d ? d.action === 'approve' ? 'approved' : d.action : 'pending';
+}
+
+export function regionReclassify(draft: PlanDraft, id: string) {
+ return draft.reclassify?.find(r => r.id === id);
+}
+
+/** Surface words suggest a texture; photographic words an image; otherwise a plate. */
+export function defaultAssetKind(item: { note?: string; name?: string; flags?: Flag[] }): AssetKind {
+ const text = [item.name, item.note, ...(item.flags ?? []).map(f => f.message)].join(' ');
+ if (/\b(textures?|surfaces?|grain|grainy|brushed|metal(lic)?|steel|brass|copper|paper|linen|canvas|fabric|cloth|wood(en)?|stone|marble|concrete|plaster|leather|noise|pattern(ed)?|weave|patina)\b/i.test(text)) return 'texture';
+ if (/\b(photo|photos|photograph|photographs|photographic|photography)\b/i.test(text) && !/\bphotographic shading\b/i.test(text)) return 'image';
+ return 'plate';
+}
+
+/** The plan statement shown for a code-planned item. */
+export function planStatement(item: { kind: string }) {
+ return `Drawn in code (${item.kind})`;
+}
+
+/** comp-spec writes each flag message as a reviewer-facing observation; show it as written. */
+export function flagMessage(flag: Flag) {
+ return flag.message;
+}
+
+export function planSummary(packet: PlanPacket, draft: PlanDraft) {
+ const states = packet.components.map(c => itemState(c, draft));
+ const approved = states.filter(s => s === 'approved').length;
+ const revise = states.filter(s => s === 'revise').length;
+ const extraIds = new Set(extraRegions(packet).map(r => r.id));
+ const regionReclassifications = (draft.reclassify ?? []).filter(r => extraIds.has(r.id)).length;
+ const reclassify = states.filter(s => s === 'reclassify').length + regionReclassifications;
+ const pending = states.filter(s => s === 'pending').length;
+ const missing = draft.missing.length;
+ const hasChanges = revise + reclassify + missing > 0;
+ const current = draft.packetRevision === packet.revision;
+ const missingValid = draft.missing.every(m => m.name.trim() && validBox(m.box));
+ const canApprove = current && !hasChanges && pending === 0;
+ return {
+ total: states.length, approved, revise, reclassify, pending, missing, hasChanges, canApprove,
+ mode: hasChanges ? 'changes' as const : 'approve' as const,
+ canSubmit: current && missingValid && (hasChanges || canApprove),
+ };
+}
+
+/** Pure decision update. Returns the next draft; callers keep the old one for undo. */
+export function decide(draft: PlanDraft, item: PlanItem, action: PlanDecision['action'], options: { feedback?: string; kind?: AssetKind; split?: boolean } = {}): PlanDraft {
+ // Split asks for a baked composite to come back as layers; only an asset's revise can carry it.
+ if (options.split && !(action === 'revise' && item.role === 'asset')) throw new Error('Only a generated asset can be split into layers');
+ // A plan item's revise is a region-map change in the reviewer's words, so it needs them.
+ if (action === 'revise' && item.role !== 'asset' && !(options.feedback ?? '').trim()) throw new Error('Revising a plan item needs feedback');
+ if (action === 'reclassify' && item.role !== 'plan') throw new Error('Only planned code can become an image');
+ const decision: PlanDecision = { revision: item.revision, action, feedback: action === 'approve' ? '' : (options.feedback ?? '').trim(), split: !!options.split };
+ if (action === 'reclassify') decision.kind = options.kind ?? defaultAssetKind(item);
+ return { ...draft, inventoryConfirmed: false, decisions: { ...draft.decisions, [item.id]: decision } };
+}
+export function clearDecision(draft: PlanDraft, id: string): PlanDraft {
+ const decisions = { ...draft.decisions };
+ delete decisions[id];
+ return { ...draft, inventoryConfirmed: false, decisions };
+}
+export function setRegionReclassify(draft: PlanDraft, id: string, value: { kind: AssetKind; feedback?: string } | null): PlanDraft {
+ const rest = (draft.reclassify ?? []).filter(r => r.id !== id);
+ return { ...draft, inventoryConfirmed: false, reclassify: value ? [...rest, { id, kind: value.kind, feedback: (value.feedback ?? '').trim() }] : rest };
+}
+
+/** Next undecided queue item after `after`, wrapping once. */
+export function nextPending(packet: PlanPacket, draft: PlanDraft, after?: string): string | undefined {
+ const queue = planQueue(packet);
+ const start = queue.findIndex(c => c.id === after);
+ for (let step = 1; step <= queue.length; step++) {
+ const item = queue[(start + step) % queue.length];
+ if (itemState(item, draft) === 'pending') return item.id;
+ }
+}
+
+/** Submission body. Approval (nothing changed, nothing missing) confirms the inventory;
+ * a changes submission never does. Region reclassifications travel separately. */
+export function planSubmission(packet: PlanPacket, draft: PlanDraft) {
+ const summary = planSummary(packet, draft);
+ if (!summary.canSubmit) throw new Error('Review is incomplete or stale');
+ const decisions: Record<string, PlanDecision> = {};
+ for (const c of packet.components) {
+ const d = currentDecision(c, draft);
+ if (d) decisions[c.id] = structuredClone(d);
+ }
+ const extraIds = new Set(extraRegions(packet).map(r => r.id));
+ const reclassify = (draft.reclassify ?? []).filter(r => extraIds.has(r.id)).map(r => ({ ...r }));
+ return {
+ schemaVersion: 1 as const, requestId: packet.id, packetRevision: draft.packetRevision,
+ decisions, missing: structuredClone(draft.missing), inventoryConfirmed: summary.mode === 'approve',
+ ...(reclassify.length ? { reclassify } : {}),
+ };
+}
+
+export function newPlanDraft(packet: PlanPacket): PlanDraft {
+ return { packetRevision: packet.revision, decisions: {}, missing: [], inventoryConfirmed: false, reclassify: [] };
+}
+
+/** Pixels around a box, as [r,g,b] samples, from RGBA image data of the whole comp. */
+export function ringSamples(data: ArrayLike<number>, width: number, height: number, box: Box, margin = 0.02): [number, number, number][] {
+ const x0 = Math.max(0, Math.floor((box.x - margin) * width)), x1 = Math.min(width - 1, Math.ceil((box.x + box.w + margin) * width));
+ const y0 = Math.max(0, Math.floor((box.y - margin) * height)), y1 = Math.min(height - 1, Math.ceil((box.y + box.h + margin) * height));
+ const ix0 = Math.floor(box.x * width), ix1 = Math.ceil((box.x + box.w) * width), iy0 = Math.floor(box.y * height), iy1 = Math.ceil((box.y + box.h) * height);
+ const out: [number, number, number][] = [];
+ const step = Math.max(1, Math.round(Math.max(x1 - x0, y1 - y0) / 80));
+ for (let y = y0; y <= y1; y += step) for (let x = x0; x <= x1; x += step) {
+ if (x >= ix0 && x < ix1 && y >= iy0 && y < iy1) continue;
+ const i = (y * width + x) * 4;
+ if (data[i + 3] < 200) continue;
+ out.push([data[i], data[i + 1], data[i + 2]]);
+ }
+ return out;
+}
+/** Per-channel median as a hex colour; undefined when nothing surrounds the box. */
+export function medianColor(samples: [number, number, number][]): string | undefined {
+ if (!samples.length) return undefined;
+ const channel = (n: number) => { const v = samples.map(s => s[n]).sort((a, b) => a - b); return v[v.length >> 1]; };
+ return '#' + [0, 1, 2].map(n => channel(n).toString(16).padStart(2, '0')).join('');
+}
+
+/** The comp crop for a plan region: the box plus a modest margin, scaled so the region fills the
+ * pane width (context lives on the comp map, not in this crop). A region so thin that it would
+ * render under `minHeight` px is scaled up to that height and shown as a centred segment. */
+export function planView(box: Box, compWidth: number, compHeight: number, width: number, height: number, maxScale = 4, minHeight = 24) {
+ const bw = box.w * compWidth, bh = box.h * compHeight;
+ const margin = Math.min(24, Math.max(8, 0.04 * Math.max(bw, bh)));
+ let vw = Math.min(compWidth, bw + margin * 2), vh = Math.min(compHeight, bh + margin * 2);
+ let scale = Math.min(maxScale, width / vw, height / vh);
+ if (bh * scale < minHeight && bh > 0) {
+ scale = Math.min(maxScale, minHeight / bh, height / vh);
+ vw = Math.min(vw, width / scale);
+ }
+ const cx = (box.x + box.w / 2) * compWidth, cy = (box.y + box.h / 2) * compHeight;
+ const x = Math.max(0, Math.min(compWidth - vw, cx - vw / 2)), y = Math.max(0, Math.min(compHeight - vh, cy - vh / 2));
+ return { scale, width: vw * scale, height: vh * scale, view: { x: x / compWidth, y: y / compHeight, w: vw / compWidth, h: vh / compHeight } };
+}
+
+/** Largest same-scale layout for two crops of aspect `ratio` (w/h): side by side or stacked. */
+export function pairLayout(ratio: number, width: number, height: number, gap: number, caption: number, maxScale = Infinity, natural?: { w: number; h: number }) {
+ const fit = (w: number, h: number) => {
+ let cw = Math.max(0, w), ch = cw / ratio;
+ if (ch > h) { ch = Math.max(0, h); cw = ch * ratio; }
+ if (natural && cw > natural.w * maxScale) { cw = natural.w * maxScale; ch = cw / ratio; }
+ return { w: cw, h: ch };
+ };
+ const side = fit((width - gap) / 2, height - caption);
+ const stacked = fit(width, (height - gap) / 2 - caption);
+ return side.w * side.h >= stacked.w * stacked.h ? { direction: 'row' as const, ...side } : { direction: 'column' as const, ...stacked };
+}
+
+// ---------------------------------------------------------------------------
+// Stage flow (intro, one item at a time, summary). Pure helpers for the view.
+
+const WORDS = ['no', 'one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine', 'ten', 'eleven', 'twelve'];
+const word = (n: number) => WORDS[n] ?? String(n);
+const Cap = (s: string) => s[0].toUpperCase() + s.slice(1);
+
+/** What the reviewer is about to do, in one sentence (the intro screen). */
+export function introLine(packet: PlanPacket, draft: PlanDraft, history?: PlanHistory | null) {
+ const pending = packet.components.filter(c => itemState(c, draft) === 'pending').length;
+ if (history && packet.round > 1) {
+ const worked = packet.components.filter(c => ['changed', 'added'].includes(history.changes[c.id]?.kind ?? '') || history.feedback?.[c.id]).length;
+ const kept = packet.components.filter(c => itemState(c, draft) === 'approved').length;
+ return `The agent worked on your notes for ${word(worked)} ${worked === 1 ? 'item' : 'items'}. ${Cap(word(kept))} ${kept === 1 ? 'approval is' : 'approvals are'} kept.`;
+ }
+ const minutes = Math.max(1, Math.round(pending * 15 / 60));
+ return `${Cap(word(pending))} ${pending === 1 ? 'thing' : 'things'} to check before any page code is written. About ${word(minutes)} ${minutes === 1 ? 'minute' : 'minutes'}.`;
+}
+
+/** The last round's request for this item, and what it looked like then. */
+/** Guidance prefilled when the reviewer asks for a composite to be split. */
+export const SPLIT_GUIDANCE = 'Frame, view and moving parts as separate pieces, e.g. the shutters.';
+/** Flags an asset carries (a baked composite, painted pixels): shown as a note on the stage. */
+export function assetFlags(item: PlanItem) { return item.role === 'asset' ? item.flags ?? [] : []; }
+export const isBakedComposite = (item: PlanItem) => assetFlags(item).some(f => f.id === 'baked-composite');
+export const isSplit = (d?: PlanDecision) => d?.action === 'revise' && d.split === true;
+
+export function priorRound(id: string, history?: PlanHistory | null) {
+ if (!history) return null;
+ // A split region comes back as new items (window-frame, window-view): link them to the
+ // region they came from by id prefix, so the reviewer sees their own note again.
+ const splitFrom = history.feedback?.[id] ? undefined : Object.entries(history.feedback ?? {})
+ .filter(([from, f]) => f.decision.action === 'revise' && f.decision.split && id.startsWith(`${from}-`))
+ .sort((a, b) => b[0].length - a[0].length)[0];
+ if (splitFrom) {
+ const [from, f] = splitFrom;
+ return { round: f.round, action: 'split', words: (f.decision.feedback ?? '').trim(), splitFrom: history.packet.components.find(c => c.id === from)?.name ?? from, beforeUrl: undefined, wasCode: false, wasKind: undefined, wasNote: '' };
+ }
+ const asked = history.feedback?.[id];
+ const before = history.packet.components.find(c => c.id === id);
+ const beforeRegion = history.packet.codeRegions?.find(r => r.id === id);
+ const change = history.changes[id]?.kind;
+ if (!asked && change !== 'changed') return null;
+ return {
+ round: asked?.round ?? history.packet.round,
+ action: asked?.decision.action,
+ words: (asked?.decision.feedback ?? '').trim(),
+ beforeUrl: before?.role === 'asset' ? before.preview.url : undefined,
+ // A region that was planned in code last round and is now an asset.
+ wasCode: (before?.role === 'plan' || (!before && !!beforeRegion)),
+ wasKind: before?.kind ?? beforeRegion?.kind,
+ wasNote: before?.note ?? beforeRegion?.note ?? '',
+ splitFrom: undefined as string | undefined,
+ };
+}
+
+/** Equal-height figures for aspect ratios (w/h): in a row, or stacked at equal width when
+ * that shows more. Each figure reserves `caption` px above it; `natural` caps the scale. */
+export function figureLayout(ratios: number[], width: number, height: number, gap: number, caption: number, maxScale = 4, natural?: { w: number; h: number }) {
+ const n = ratios.length;
+ let rowH = Math.max(0, Math.min(height - caption, (width - gap * (n - 1)) / ratios.reduce((a, r) => a + r, 0)));
+ let colW = Math.max(0, Math.min(width, (height - n * caption - gap * (n - 1)) / ratios.reduce((a, r) => a + 1 / r, 0)));
+ if (natural) { rowH = Math.min(rowH, natural.h * maxScale); colW = Math.min(colW, natural.w * maxScale); }
+ const rowArea = ratios.reduce((a, r) => a + r * rowH * rowH, 0);
+ const colArea = ratios.reduce((a, r) => a + colW * colW / r, 0);
+ return rowArea >= colArea
+ ? { direction: 'row' as const, sizes: ratios.map(r => ({ w: r * rowH, h: rowH })) }
+ : { direction: 'column' as const, sizes: ratios.map(r => ({ w: colW, h: colW / r })) };
+}
+
+/** Loupe: the translate that centres point (fx, fy) of a w x h image, scaled by zoom, in a lens of radius r. */
+export function loupeOffset(fx: number, fy: number, w: number, h: number, r: number, zoom: number) {
+ return { x: r - fx * w * zoom, y: r - fy * h * zoom };
+}
+
+/** Progress row: one light per item. */
+export function progressLights(packet: PlanPacket, draft: PlanDraft, current?: string) {
+ return planQueue(packet).map(c => ({ id: c.id, name: c.name, state: itemState(c, draft), current: c.id === current }));
+}
+
+/** The submit line on the summary: what will be sent, in counts. */
+export function sendLabel(packet: PlanPacket, draft: PlanDraft) {
+ const s = planSummary(packet, draft);
+ if (s.mode === 'approve') return 'Approve plan and assets';
+ const splits = packet.components.filter(c => isSplit(currentDecision(c, draft))).length;
+ const notes = s.revise - splits;
+ const parts = [notes ? `${notes} ${notes === 1 ? 'note' : 'notes'}` : '', splits ? `${splits} to split` : '', s.reclassify ? `${s.reclassify} to become ${s.reclassify === 1 ? 'an image' : 'images'}` : '', s.missing ? `${s.missing} missing` : ''].filter(Boolean);
+ return `Send notes (${parts.join(', ')})`;
+}
diff --git a/ui/component-review/plan-review.ts b/ui/component-review/plan-review.ts
new file mode 100644
index 000000000..4122be5b0
--- /dev/null
+++ b/ui/component-review/plan-review.ts
@@ -0,0 +1,631 @@
+/** Plan and asset review (packet schemaVersion 3, stage components). Contract: docs/PLAN-REVIEW.md;
+ * design brief: DESIGN-stage.md. An intro, then one item at a time on a full stage, then a summary
+ * with the coverage question and the single submit. The first-viewport stage keeps review.ts. */
+import {
+ ASSET_KINDS, clearDecision, currentDecision, decide, defaultAssetKind, extraRegions, figureLayout,
+ SPLIT_GUIDANCE, assetFlags, isBakedComposite, isSplit, flagMessage, introLine, isFlagged, itemState, loupeOffset, medianColor, newPlanDraft, planQueue, planStatement,
+ planSubmission, planSummary, planView, priorRound, progressLights, regionReclassify, ringSamples, sendLabel,
+ setRegionReclassify,
+ type AssetKind, type PlanDraft, type PlanHistory, type PlanItem, type PlanPacket,
+} from './plan-model';
+import type { Box } from './model';
+import { planStyles } from './plan-styles';
+import { ksArrow } from './kit';
+import { initInstrumentStrips } from './instrument-strip';
+
+const esc = (s: string) => s.replace(/[&<>"']/g, c => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;' }[c]!));
+const pct = (n: number) => `${n * 100}%`;
+// Only trusted adapter URLs may enter images. Never accept javascript: or executable data URLs.
+const url = (s: string) => {
+ const parsed = new URL(s, location.href);
+ if (!['http:', 'https:'].includes(parsed.protocol)) throw new Error('Unsupported preview URL');
+ return esc(parsed.href);
+};
+const boxStyle = (b: Box) => `left:${pct(b.x)};top:${pct(b.y)};width:${pct(b.w)};height:${pct(b.h)}`;
+const svg = (d: string) => `<svg viewBox="0 0 16 16" aria-hidden="true" focusable="false">${d}</svg>`;
+const ICON = {
+ check: svg('<path d="m3 8.5 3 3 7-7"/>'),
+ alert: svg('<path d="M8 2 1.5 13.5h13L8 2Z"/><path d="M8 6.5v3.2M8 11.6v.1"/>'),
+};
+const kbd = (k: string) => `<kbd class="cap">${k}</kbd>`;
+const KIND_WORD: Record<string, string> = { plate: 'illustration', image: 'photo', texture: 'texture' };
+
+/** The server's stale message is terse and ends in its own instruction; keep the fact, add one next step. */
+function staleDetail(status: string) {
+ const changed = status.match(/^review is stale:\s*(.+?)\s+changed\b/i);
+ if (changed) return `${changed[1]} changed after this round was prepared.`;
+ const text = status.replace(/;?\s*prepare a new round\.?\s*$/i, '').trim();
+ return text ? `${text[0].toUpperCase()}${text.slice(1)}${/[.!?]$/.test(text) ? '' : '.'}` : '';
+}
+const storage = {
+ get(key: string) { try { return localStorage.getItem(key); } catch { return null; } },
+ set(key: string, value: string) { try { localStorage.setItem(key, value); } catch { /* private mode */ } },
+};
+
+type View = 'intro' | 'stage' | 'summary';
+type Form = { type: 'revise' | 'reclassify'; id: string; region: boolean; text: string; kind: AssetKind; split?: boolean };
+type MountOptions = {
+ preview?: boolean; history?: PlanHistory | null; initialDraft?: PlanDraft; completed?: boolean; status?: string | null;
+ onDraftChange?: (draft: PlanDraft) => void; onSubmit: (value: ReturnType<typeof planSubmission>) => Promise<void>;
+};
+
+export function mountPlanReview(host: HTMLElement, packet: PlanPacket, options: MountOptions) {
+ const root = host.shadowRoot ?? host.attachShadow({ mode: 'open' });
+ let draft: PlanDraft = { ...newPlanDraft(packet), ...structuredClone(options.initialDraft ?? {}) } as PlanDraft;
+ draft.reclassify ??= [];
+ const queue = planQueue(packet);
+ const regions = extraRegions(packet);
+ const history = options.history ?? null;
+ const params = new URLSearchParams(location.search);
+ let submitted = !!options.completed;
+ let view: View = submitted ? 'summary' : (['intro', 'stage', 'summary'].includes(params.get('view') ?? '') ? params.get('view') as View : 'intro');
+ let current = (params.get('item') && queue.some(c => c.id === params.get('item')) ? params.get('item')! : undefined)
+ ?? queue.find(c => itemState(c, draft) === 'pending')?.id ?? queue[0]?.id;
+ let enter: 'next' | 'prev' | 'fade' | null = null;
+ let form: Form | null = null;
+ let panel: { type: 'region' | 'missing'; id: string } | null = null;
+ let marking = false;
+ let mapOpen = false;
+ let flipped = false;
+ const backdrop: Record<string, 'comp' | 'light' | 'dark'> = {};
+ let sending = false;
+ let justSent = false;
+ let error = '';
+ let toast: { label: string; before: PlanDraft; view: View; current?: string; timer: number } | null = null;
+ /** The last decision and its undo, shown in the caption slot above the decision bar (or the send row on the summary), never floating over the controls. */
+ const undoLine = () => toast ? `<p class="hint undo-line" role="status">${esc(toast.label)} <button type="button" class="text-action" id="undo">Undo${kbd('⌘Z')}</button></p>` : '';
+ let hintSeen = storage.get('impeccable.review.flipHint') === '1';
+ let resize: ResizeObserver | null = null;
+ let strips: (() => void) | null = null;
+ const transparency = new Map<string, boolean>();
+ const surround = new Map<string, string>();
+ let compPixels: { data: Uint8ClampedArray; width: number; height: number } | null = null;
+ const reduced = () => matchMedia('(prefers-reduced-motion: reduce)').matches;
+
+ const item = (id?: string) => packet.components.find(c => c.id === id);
+ const region = (id?: string) => regions.find(r => r.id === id);
+ const locked = () => submitted || sending || !!options.status;
+ const boxRatio = (b: Box) => (b.w * packet.comp.width) / (b.h * packet.comp.height);
+
+ // Comp pixels, once, for the backdrop colour under transparent assets.
+ const compImage = new Image();
+ compImage.onload = () => {
+ try {
+ const scale = Math.min(1, 480 / compImage.naturalWidth);
+ const canvas = document.createElement('canvas');
+ canvas.width = Math.max(1, Math.round(compImage.naturalWidth * scale));
+ canvas.height = Math.max(1, Math.round(compImage.naturalHeight * scale));
+ const ctx = canvas.getContext('2d', { willReadFrequently: true })!;
+ ctx.drawImage(compImage, 0, 0, canvas.width, canvas.height);
+ compPixels = { data: ctx.getImageData(0, 0, canvas.width, canvas.height).data, width: canvas.width, height: canvas.height };
+ if (view === 'stage') render();
+ } catch { /* A tainted or unreadable comp falls back to a neutral backdrop. */ }
+ };
+ compImage.src = new URL(packet.comp.url, location.href).href;
+ function compColour(c: PlanItem) {
+ if (!surround.has(c.id) && compPixels) surround.set(c.id, medianColor(ringSamples(compPixels.data, compPixels.width, compPixels.height, c.box)) ?? '');
+ return surround.get(c.id) || packet.comp.background || 'var(--ks-paper-deep)';
+ }
+ function isTransparent(c: PlanItem, src: string) {
+ if (c.material?.alpha === 'transparent') return true;
+ if (c.material?.alpha === 'opaque') return false;
+ if (transparency.has(src)) return transparency.get(src)!;
+ transparency.set(src, false);
+ if (!/\.(png|webp)(\?|$)/i.test(src)) return false;
+ const img = new Image();
+ img.onload = () => {
+ try {
+ const scale = Math.min(1, 160 / Math.max(img.naturalWidth, img.naturalHeight));
+ const canvas = document.createElement('canvas');
+ canvas.width = Math.max(1, Math.round(img.naturalWidth * scale)); canvas.height = Math.max(1, Math.round(img.naturalHeight * scale));
+ const ctx = canvas.getContext('2d', { willReadFrequently: true })!;
+ ctx.drawImage(img, 0, 0, canvas.width, canvas.height);
+ const data = ctx.getImageData(0, 0, canvas.width, canvas.height).data;
+ for (let i = 3; i < data.length; i += 4) if (data[i] < 250) { transparency.set(src, true); if (view === 'stage') render(); break; }
+ } catch { /* leave opaque */ }
+ };
+ img.src = new URL(src, location.href).href;
+ return false;
+ }
+
+ // ---------- actions ----------
+ function go(next: View, id?: string, how: typeof enter = 'fade') {
+ if (id) current = id;
+ enter = reduced() ? null : how;
+ view = next; form = null; flipped = false; mapOpen = false;
+ if (next !== 'summary') { panel = null; marking = false; }
+ render();
+ const focus = next === 'intro' ? 'start' : next === 'stage' ? 'decide-yes' : 'send';
+ root.getElementById(focus)?.focus({ preventScroll: true });
+ }
+ function move(delta: number) {
+ if (view !== 'stage' || !queue.length) return;
+ const next = queue.findIndex(c => c.id === current) + delta;
+ if (next >= queue.length) return go('summary', undefined, 'next');
+ if (next < 0) return;
+ go('stage', queue[next].id, delta > 0 ? 'next' : 'prev');
+ }
+ function showToast(label: string, before: PlanDraft) {
+ if (toast) clearTimeout(toast.timer);
+ toast = { label, before, view, current, timer: window.setTimeout(() => { toast = null; root.querySelector('.undo-line')?.classList.add('gone'); }, 6000) };
+ }
+ function commit(next: PlanDraft, label: string) {
+ const before = draft;
+ draft = next; form = null; error = '';
+ showToast(label, before);
+ }
+ function advance() {
+ const at = queue.findIndex(c => c.id === current);
+ const next = [...queue.slice(at + 1), ...queue.slice(0, at + 1)].find(c => itemState(c, draft) === 'pending');
+ if (next) go('stage', next.id, 'next'); else go('summary', undefined, 'next');
+ }
+ function approve() {
+ const c = item(current);
+ if (view !== 'stage' || !c || locked() || form) return;
+ commit(decide(draft, c, 'approve'), `${c.role === 'asset' ? 'Approved' : 'Kept in code'}: ${c.name}.`);
+ advance();
+ }
+ function openForm(type: Form['type'], regionId?: string, split = false) {
+ if (locked()) return;
+ const r = regionId ? region(regionId) : undefined;
+ const c = r ? undefined : item(current);
+ const target = c ?? r;
+ if (!target || (c && type === 'reclassify' && c.role !== 'plan')) return;
+ const saved = c ? currentDecision(c, draft) : undefined;
+ const savedRegion = r ? regionReclassify(draft, r.id) : undefined;
+ const keep = saved?.action === type && !!saved.split === split;
+ form = { type, split, id: target.id, region: !!r, text: keep ? saved!.feedback : split ? SPLIT_GUIDANCE : savedRegion?.feedback ?? '',
+ kind: saved?.kind ?? savedRegion?.kind ?? defaultAssetKind({ name: target.name, note: target.note ?? '', flags: c?.flags }) };
+ render();
+ root.getElementById('form-text')?.focus();
+ }
+ function saveForm() {
+ if (!form || locked()) return;
+ const f = form;
+ if (f.region) {
+ const r = region(f.id)!;
+ commit(setRegionReclassify(draft, r.id, { kind: f.kind, feedback: f.text }), `${r.name} will become ${KIND_WORD[f.kind]}.`);
+ render();
+ return;
+ }
+ const c = item(f.id)!;
+ if (f.type === 'revise' && c.role === 'plan' && !f.text.trim()) { root.getElementById('form-text')?.focus(); return; }
+ commit(decide(draft, c, f.type, { feedback: f.text, kind: f.kind, split: f.split }), f.split ? `Split into layers: ${c.name}.` : f.type === 'revise' ? `Noted: ${c.name}.` : `${c.name} will become ${KIND_WORD[f.kind]}.`);
+ advance();
+ }
+ function undo() {
+ if (!toast || locked()) return;
+ const t = toast; clearTimeout(t.timer); toast = null;
+ draft = t.before;
+ go(t.view, t.current, 'prev');
+ }
+ async function send() {
+ const summary = planSummary(packet, draft);
+ if (sending || submitted || form || !summary.canSubmit || options.status) return;
+ sending = true; error = ''; render();
+ try {
+ await options.onSubmit(planSubmission(packet, draft));
+ submitted = true; justSent = true; marking = false; toast = null;
+ } catch (e) { error = e instanceof Error ? e.message : 'The review could not be saved.'; }
+ finally { sending = false; render(); }
+ }
+ function addMissing(box: Box) {
+ const id = `missing-${crypto.randomUUID()}`;
+ draft = { ...draft, inventoryConfirmed: false, missing: [...draft.missing, { id, name: '', feedback: '', box }] };
+ marking = false; panel = { type: 'missing', id };
+ render();
+ root.getElementById('missing-name')?.focus();
+ }
+
+ // ---------- pieces ----------
+ const stateWord = (c: PlanItem) => {
+ const s = itemState(c, draft);
+ if (s === 'approved') return c.role === 'asset' ? 'Looks good' : 'Code is fine';
+ if (s === 'revise') return isSplit(currentDecision(c, draft)) ? 'Split into layers' : 'Needs work';
+ if (s === 'reclassify') return `Becomes ${KIND_WORD[currentDecision(c, draft)!.kind!]}`;
+ return submitted ? 'Not decided' : 'To decide';
+ };
+ const compLayer = (b: Box, cls = '') => `<span class="pic crop ${cls}"><img src="${url(packet.comp.url)}" alt="" draggable="false" style="width:${100 / b.w}%;left:${-100 * b.x / b.w}%;top:${-100 * b.y / b.h}%"></span>`;
+ const genLayer = (c: PlanItem, src: string, cls = 'gen') => {
+ const clear = isTransparent(c, src);
+ const bd = backdrop[c.id] ?? 'comp';
+ const bg = !clear ? '' : bd === 'light' ? 'var(--ks-paper-raised)' : bd === 'dark' ? 'var(--ks-instrument)' : compColour(c);
+ return `<span class="pic ${cls}" style="${bg ? `background:${esc(bg)}` : ''}"><img src="${url(src)}" alt="" draggable="false"></span>`;
+ };
+ function regionsOverlay(opts: { code: boolean; interactive: boolean }) {
+ type Shape = { kind: 'item' | 'region' | 'missing'; id: string; name: string; box: Box; cls: string };
+ const shapes: Shape[] = [
+ ...(opts.code ? regions.map(r => ({ kind: 'region' as const, id: r.id, name: r.name, box: r.box, cls: `code ${regionReclassify(draft, r.id) ? 'reclassify' : ''}` })) : []),
+ ...packet.components.map(c => ({ kind: 'item' as const, id: c.id, name: c.name, box: c.box, cls: `is-${c.role} ${isFlagged(c) || isBakedComposite(c) ? 'flagged' : ''} ${itemState(c, draft)}` })),
+ ...draft.missing.map(m => ({ kind: 'missing' as const, id: m.id, name: m.name || 'Missing', box: m.box, cls: 'missing' })),
+ ].sort((a, b) => b.box.w * b.box.h - a.box.w * a.box.h);
+ return shapes.map(s => {
+ const active = panel?.id === s.id || (mapOpen && view === 'stage' && s.id === current);
+ const tag = `<span class="tag">${esc(s.name)}</span>`;
+ return opts.interactive
+ ? `<button type="button" class="region ${s.cls} ${active ? 'selected' : ''} ${s.box.y < .06 ? 'tag-below' : ''} ${s.box.x > .7 ? 'tag-right' : ''}" style="${boxStyle(s.box)}" data-${s.kind}="${esc(s.id)}" aria-label="${esc(s.name)}">${tag}</button>`
+ : `<span class="region ${s.cls}" style="${boxStyle(s.box)}"></span>`;
+ }).join('');
+ }
+
+ function topBar() {
+ const lights = progressLights(packet, draft, view === 'stage' ? current : undefined);
+ const doneCount = lights.filter(l => l.state !== 'pending').length;
+ return `<header class="bar">
+ <div class="bar-title"><span class="bar-name">${esc(packet.title)}</span><span class="bar-round">Round ${packet.round}</span></div>
+ ${queue.length ? `<nav class="lights ${lights.length > 20 ? 'dense' : ''}" aria-label="Progress, ${doneCount} of ${lights.length} decided">${lights.map((l, i) => `<button type="button" class="light ${l.state === 'pending' ? '' : 'decided'} ${l.current ? 'current' : ''}" data-go="${esc(l.id)}" aria-label="${esc(`${i + 1}. ${l.name}: ${stateWord(item(l.id)!)}`)}" ${l.current ? 'aria-current="step"' : ''}><span class="tip">${esc(l.name)}${l.state === 'pending' ? '' : `<span class="tip-state"> · ${esc(stateWord(item(l.id)!))}</span>`}</span></button>`).join('')}<button type="button" class="lights-summary ${view === 'summary' ? 'current' : ''}" id="to-summary">Summary</button></nav>` : ''}
+ ${view === 'stage' ? `<button type="button" class="bar-locator" id="open-map-bar" aria-label="Open the comp">${compLayer({ x: 0, y: 0, w: 1, h: 1 })}</button>` : ''}
+ </header>`;
+ }
+ function banner() {
+ if (options.status) return `<div class="banner stale" role="alert">${ICON.alert}<div><strong>This review is out of date.</strong><p>${esc(staleDetail(options.status))} Ask the agent to prepare a new round, then reload this page.</p></div><button id="reload" class="ks-button ks-button-secondary">Reload</button></div>`;
+ if (error) return `<div class="banner error" role="alert">${ICON.alert}<div><strong>Your decisions were not sent.</strong><p>${esc(error)}</p></div><button id="retry" class="ks-button ks-button-secondary">Try again</button></div>`;
+ return '';
+ }
+
+ function intro() {
+ const round2 = !!history && packet.round > 1;
+ return `<div class="intro ${enter ? `enter-${enter}` : ''}">
+ <div class="intro-copy">
+ <p class="eyebrow">${round2 ? `Round ${packet.round}` : 'Before any page code'}</p>
+ <h1>${round2 ? 'Check what changed.' : 'Review the plan and assets.'}</h1>
+ <p class="lead">${esc(introLine(packet, draft, history))}</p>
+ <dl class="kinds-explained">
+ <div><dt><i class="swatch asset"></i>A generated image</dt><dd>Does it match the comp?</dd></div>
+ <div><dt><i class="swatch plan"></i>A region drawn in code</dt><dd>Can code do it justice, or should it be an image?</dd></div>
+ </dl>
+ <button type="button" class="ks-button ks-button-primary" id="start">Start${kbd('↵')}${ksArrow}</button>
+ </div>
+ <figure class="intro-comp"><div class="map" style="aspect-ratio:${packet.comp.width}/${packet.comp.height}"><img class="comp" src="${url(packet.comp.url)}" alt="The approved comp" draggable="false">${regionsOverlay({ code: false, interactive: false })}</div></figure>
+ </div>`;
+ }
+
+ function stageFigures(c: PlanItem) {
+ const prior = priorRound(c.id, history);
+ const ratio = boxRatio(c.box);
+ const natural = `${c.box.w * packet.comp.width}x${c.box.h * packet.comp.height}`;
+ if (c.role === 'asset' && c.preview.url) {
+ const src = c.preview.url;
+ const clear = isTransparent(c, src);
+ const bd = backdrop[c.id] ?? 'comp';
+ const switchMarkup = clear ? `<button type="button" class="ks-switch backdrop-switch" id="backdrop" aria-pressed="${bd !== 'comp'}" title="Backdrop behind the transparent image"><span class="ks-switch-track" aria-hidden="true"><span class="ks-switch-knob"></span></span><span class="ks-switch-label">${bd === 'comp' ? 'On comp colour' : bd === 'light' ? 'On light' : 'On dark'}</span></button>` : '';
+ const gen = `<figure class="fig" data-role="generated"><figcaption><span class="eyebrow">${flipped ? 'In the comp' : prior?.beforeUrl ? 'After' : 'Generated'}</span>${switchMarkup}</figcaption><div class="frame ${flipped ? 'flipped' : ''}">${genLayer(c, src)}${compLayer(c.box, 'flip')}</div></figure>`;
+ const comp = `<figure class="fig"><figcaption><span class="eyebrow">In the comp</span></figcaption><div class="frame">${compLayer(c.box)}</div></figure>`;
+ if (prior?.beforeUrl) {
+ const before = `<figure class="fig"><figcaption><span class="eyebrow">Before · round ${prior.round}</span></figcaption><div class="frame">${genLayer(c, prior.beforeUrl, 'gen before')}</div></figure>`;
+ return `<div class="figures" data-ratios="${ratio},${ratio},${ratio}" data-natural="${natural}">${before}${gen}${comp}</div>`;
+ }
+ return `<div class="figures" data-ratios="${ratio},${ratio}" data-natural="${natural}">${comp}${gen}</div>`;
+ }
+ if (c.role === 'asset') return `<div class="figures empty"><p>This image has no generated file.</p></div>`;
+ return `<div class="figures single" data-box="${esc(JSON.stringify(c.box))}"><figure class="fig"><figcaption><span class="eyebrow">In the comp</span></figcaption><div class="frame">${compLayer(c.box)}<span class="focus-box"></span></div></figure></div>`;
+ }
+
+ function decisionBar(c: PlanItem) {
+ if (submitted) return `<div class="decide-bar"><p class="record">${esc(stateWord(c))}${currentDecision(c, draft)?.feedback ? `: “${esc(currentDecision(c, draft)!.feedback)}”` : '.'}</p></div>`;
+ if (form && !form.region) {
+ const reclass = form.type === 'reclassify';
+ const planChange = !reclass && c.role === 'plan';
+ const split = !!form.split;
+ return `<form class="decide-bar form" id="decision-form">
+ ${reclass ? `<div class="form-row"><span class="eyebrow" id="kinds-label">Make it</span><div class="ks-instrument-strip is-paper" data-ks-strip="kind" role="group" aria-labelledby="kinds-label">${ASSET_KINDS.map(k => `<button type="button" class="ks-instrument-key" data-kind="${k.kind}" aria-pressed="${form!.kind === k.kind}">${k.label}</button>`).join('')}</div></div>` : ''}
+ <label class="field"><span class="eyebrow">${reclass ? 'Anything the image should keep? Optional' : split ? 'How should it come apart? Edit or keep' : planChange ? 'What should change?' : 'What needs to change? Optional'}</span><textarea id="form-text" rows="2" placeholder="${reclass ? 'For example: keep the brushed direction horizontal.' : planChange ? 'For example: extend the hero photo under the nav.' : 'For example: the figure should face the sea.'}">${esc(form.text)}</textarea></label>
+ <div class="form-actions"><button type="button" id="form-cancel" class="ks-button ks-button-ghost">Cancel${kbd('Esc')}</button><button type="submit" class="ks-button ks-button-primary">${reclass ? 'Make it an image' : split ? 'Split into layers' : 'Save note'}${kbd('⌘↵')}</button></div>
+ </form>`;
+ }
+ const d = currentDecision(c, draft);
+ const asset = c.role === 'asset';
+ return `<div class="decide-bar">
+ ${d ? `<p class="current-decision">${d.action === 'approve' ? ICON.check : ''}<span>${esc(stateWord(c))}${d.feedback ? `: “${esc(d.feedback)}”` : '.'}</span><button type="button" class="text-action" id="decision-clear">Clear</button></p>` : ''}
+ <div class="decisions">
+ <button type="button" id="decide-yes" class="ks-button ks-button-primary">${asset ? 'Looks good' : 'Code is fine'}${kbd('A')}</button>
+ <button type="button" id="decide-no" class="ks-button ks-button-secondary">${asset ? 'Needs work' : 'Make it an image'}${kbd('N')}</button>
+ ${asset ? `<button type="button" id="decide-split" class="ks-button ${isBakedComposite(c) ? 'ks-button-secondary' : 'ks-button-ghost'}">Split into layers${kbd('S')}</button>` : `<button type="button" id="decide-other" class="ks-button ks-button-ghost">Something else…${kbd('F')}</button>`}
+ </div>
+ </div>`;
+ }
+
+ function stage() {
+ const c = item(current);
+ if (!c) return '<div class="stage"><p>Nothing to review.</p></div>';
+ const index = queue.findIndex(q => q.id === c.id) + 1;
+ const prior = priorRound(c.id, history);
+ const flags = c.role === 'plan' ? [...(c.flags ?? []).map(flagMessage), ...(c.codeDrawn ? ['The plan draws this artwork in code.'] : [])] : assetFlags(c).map(flagMessage);
+ const note = (c.note ?? '').trim();
+ const sentence = c.role === 'plan'
+ ? `<p class="sentence"><strong>Will be drawn in code:</strong> ${esc(note || planStatement(c).toLowerCase())}</p>`
+ : prior?.wasCode ? `<p class="sentence"><s>Was going to be drawn in code: ${esc(prior.wasNote)}</s> Now a generated ${esc(KIND_WORD[c.kind] ?? c.kind)}.</p>`
+ : note ? `<p class="sentence muted">${esc(note)}</p>` : '';
+ return `<div class="stage ${c.role === 'plan' ? 'is-single' : ''} ${enter ? `enter-${enter}` : ''}">
+ <div class="stage-head">
+ <p class="eyebrow">${c.role === 'asset' ? `Generated ${esc(KIND_WORD[c.kind] ?? c.kind)}` : `Drawn in code · ${esc(c.kind)}`} · ${index} of ${queue.length}</p>
+ <h1>${esc(c.name)}</h1>
+ ${prior?.splitFrom ? `<blockquote class="asked"><span class="eyebrow">A layer of ${esc(prior.splitFrom)} · you asked to split it in round ${prior.round}</span>${prior.words ? `<p>“${esc(prior.words)}”</p>` : ''}</blockquote>`
+ : prior?.words ? `<blockquote class="asked"><span class="eyebrow">You asked in round ${prior.round}</span><p>“${esc(prior.words)}”</p></blockquote>` : ''}
+ </div>
+ ${stageFigures(c)}
+ <div class="stage-foot">
+ ${sentence}
+ ${flags.map(f => `<p class="flag">${esc(f)}</p>`).join('')}
+ ${toast ? undoLine() : c.role === 'asset' && !hintSeen && !submitted ? `<p class="hint">Hold ${kbd('Space')} to flip to the comp. Hover to magnify both.</p>` : ''}
+ </div>
+ <button type="button" class="locator" id="open-map" aria-label="Open the comp"><span class="locator-map" style="aspect-ratio:${packet.comp.width}/${packet.comp.height}"><img src="${url(packet.comp.url)}" alt="" draggable="false"><span class="locator-box" style="${boxStyle(c.box)}"></span></span><span class="locator-label">Comp ${kbd('C')}</span></button>
+ </div>
+ ${decisionBar(c)}`;
+ }
+
+ function sidePanel(): string {
+ if (panel?.type === 'missing') {
+ const m = draft.missing.find(x => x.id === panel!.id);
+ if (!m) return '';
+ return `<div class="side-panel"><p class="eyebrow missing">Missing from the review</p>
+ <label class="field"><span class="eyebrow">Name</span><input id="missing-name" value="${esc(m.name)}" placeholder="For example: harbour boat" ${locked() ? 'disabled' : ''}></label>
+ <label class="field"><span class="eyebrow">What is missing? Optional</span><textarea id="missing-feedback" rows="2" ${locked() ? 'disabled' : ''}>${esc(m.feedback)}</textarea></label>
+ <div class="form-actions start"><button type="button" id="panel-done" class="ks-button ks-button-secondary">Done</button>${locked() ? '' : '<button type="button" id="missing-remove" class="ks-button ks-button-ghost">Remove</button>'}</div></div>`;
+ }
+ if (panel?.type === 'region') {
+ const r = region(panel.id);
+ if (!r) return '';
+ const re = regionReclassify(draft, r.id);
+ const formHere = form?.region && form.id === r.id;
+ return `<div class="side-panel"><p class="eyebrow">Set in code · ${esc(r.kind)}</p><h3>${esc(r.name)}</h3>
+ <div class="panel-crop" style="aspect-ratio:${Math.max(.5, Math.min(6, boxRatio(r.box)))}">${compLayer(r.box)}</div>
+ ${formHere ? `<form id="decision-form" class="panel-form"><div class="ks-instrument-strip is-paper" data-ks-strip="region-kind" role="group" aria-label="Make it">${ASSET_KINDS.map(k => `<button type="button" class="ks-instrument-key" data-kind="${k.kind}" aria-pressed="${form!.kind === k.kind}">${KIND_WORD[k.kind][0].toUpperCase() + KIND_WORD[k.kind].slice(1)}</button>`).join('')}</div><textarea id="form-text" rows="2" placeholder="Anything the image should keep? Optional">${esc(form!.text)}</textarea><div class="form-actions start"><button type="submit" class="ks-button ks-button-primary">Make it an image</button><button type="button" id="form-cancel" class="ks-button ks-button-ghost">Cancel</button></div></form>`
+ : re ? `<p class="current-decision"><span>Becomes ${esc(KIND_WORD[re.kind])}${re.feedback ? `: “${esc(re.feedback)}”` : '.'}</span>${locked() ? '' : '<button type="button" class="text-action" id="region-keep">Keep in code</button>'}</p>`
+ : `<p class="muted">Checked in the first-viewport review, once the page is built.</p><div class="form-actions start">${locked() ? '' : `<button type="button" class="ks-button ks-button-secondary" id="region-image">Make it an image</button>`}<button type="button" id="panel-done" class="ks-button ks-button-ghost">Close</button></div>`}
+ </div>`;
+ }
+ return `<div class="side-panel quiet"><p>Every outlined region above was on your list. Hover the comp to see what is set in code; click a region to make it an image.</p>${locked() ? '' : `<button type="button" class="ks-button ks-button-secondary" id="mark" aria-pressed="${marking}">${marking ? 'Cancel marking' : 'Mark missing'}</button>`}${marking ? '<p class="marking-hint">Drag on the comp around what is missing.</p>' : ''}${draft.missing.length ? `<ul class="missing-list">${draft.missing.map(m => `<li><button type="button" class="text-action" data-missing="${esc(m.id)}">${esc(m.name || 'Unnamed missing piece')}</button></li>`).join('')}</ul>` : ''}</div>`;
+ }
+
+ function summary() {
+ const s = planSummary(packet, draft);
+ const helper = options.status ? 'This round can no longer be sent.'
+ : s.pending && !s.hasChanges ? `${s.pending} still to decide.`
+ : s.mode === 'approve' ? 'Approval confirms nothing is missing from the comp.'
+ : `${s.pending ? `${s.pending} undecided stay open. ` : ''}The agent applies your notes and opens a new round.`;
+ const card = (c: PlanItem) => {
+ const d = currentDecision(c, draft);
+ const st = itemState(c, draft);
+ let pic: string;
+ if (c.role === 'asset' && c.preview.url) {
+ const r = boxRatio(c.box);
+ pic = `<span class="card-pic" style="aspect-ratio:${r};width:min(100%, ${Math.round(118 * r)}px)">${genLayer(c, c.preview.url)}</span>`;
+ } else {
+ // A plan item's thumb is the same tight crop as its stage, sized to the card.
+ const fit = planView(c.box, packet.comp.width, packet.comp.height, 220, 118);
+ const v = fit.view;
+ pic = `<span class="card-pic" style="width:${Math.floor(fit.width)}px;height:${Math.floor(fit.height)}px"><span class="pic crop"><img src="${url(packet.comp.url)}" alt="" draggable="false" style="width:${100 / v.w}%;left:${-100 * v.x / v.w}%;top:${-100 * v.y / v.h}%"></span><span class="focus-box" style="${boxStyle({ x: (c.box.x - v.x) / v.w, y: (c.box.y - v.y) / v.h, w: c.box.w / v.w, h: c.box.h / v.h })}"></span></span>`;
+ }
+ return `<button type="button" class="card ${st}" data-go="${esc(c.id)}"><span class="card-thumb">${pic}</span><span class="card-text"><span class="card-name">${esc(c.name)}</span><span class="card-state">${st === 'approved' ? ICON.check : ''}${esc(stateWord(c))}</span>${d?.feedback ? `<span class="card-note">“${esc(d.feedback)}”</span>` : ''}</span></button>`;
+ };
+ return `<div class="summary ${enter ? `enter-${enter}` : ''}">
+ <div class="summary-head">
+ <p class="eyebrow">${submitted ? `Round ${packet.round} · sent` : 'Summary'}</p>
+ <h1>${submitted ? (s.hasChanges ? 'Notes sent.' : 'Plan and assets approved.') : s.pending ? 'Almost there.' : 'Your decisions.'}</h1>
+ ${submitted ? `<p class="lead">${s.hasChanges ? 'The agent applies them and opens a new round for anything that changed.' : 'The agent continues to the first viewport.'}${justSent ? '' : ' This round is read-only.'}</p>` : ''}
+ </div>
+ <div class="sheet">${queue.map(card).join('')}</div>
+ <section class="coverage" aria-label="Coverage">
+ <h2>Anything on the comp we didn't cover?</h2>
+ <div class="coverage-grid">
+ <div class="map-space"><div class="map ${marking ? 'marking' : ''} ${panel ? 'has-selection' : ''}" id="summary-map" style="aspect-ratio:${packet.comp.width}/${packet.comp.height}"><img class="comp" src="${url(packet.comp.url)}" alt="The approved comp" draggable="false">${regionsOverlay({ code: true, interactive: true })}<div class="draw-box" hidden></div></div></div>
+ ${sidePanel()}
+ </div>
+ </section>
+ </div>
+ ${submitted ? '' : `<div class="send-row"><div class="send-inner">${toast ? undoLine() : `<p>${esc(helper)}</p>`}<button type="button" class="ks-button ks-button-primary" id="send" ${!s.canSubmit || !!form || sending || !!options.status ? 'disabled' : ''}>${sending ? 'Sending…' : esc(sendLabel(packet, draft))}${sending ? '' : ksArrow}</button></div></div>`}`;
+ }
+
+ function mapOverlay() {
+ if (!mapOpen) return '';
+ return `<div class="overlay" role="dialog" aria-modal="true" aria-label="The comp"><div class="overlay-head"><span class="eyebrow">The comp · click a region to go to it</span><button type="button" class="ks-button ks-button-ghost" id="close-map">Close${kbd('Esc')}</button></div>
+ <div class="overlay-body"><div class="map has-selection" id="overlay-map" style="aspect-ratio:${packet.comp.width}/${packet.comp.height}"><img class="comp" src="${url(packet.comp.url)}" alt="The approved comp" draggable="false">${regionsOverlay({ code: true, interactive: true })}</div></div></div>`;
+ }
+
+ function render() {
+ resize?.disconnect(); strips?.();
+ const active = root.activeElement as HTMLElement | null;
+ const focusId = active?.id;
+ const scrollTop = view === 'summary' ? root.querySelector('.view-summary .screen')?.scrollTop ?? 0 : 0;
+ root.innerHTML = `<style>${planStyles}</style><section class="rv view-${view} ${submitted ? 'is-submitted' : ''}" aria-label="Plan and asset review">
+ ${topBar()}${banner()}
+ <main class="screen">${view === 'intro' ? intro() : view === 'stage' ? stage() : summary()}</main>
+ ${mapOverlay()}
+ </section>`;
+ enter = null;
+ const scr = root.querySelector('.screen'); if (scr && scrollTop) scr.scrollTop = scrollTop;
+ if (focusId) root.getElementById(focusId)?.focus({ preventScroll: true });
+ wire();
+ layout();
+ resize = new ResizeObserver(layout); resize.observe(root.querySelector('.screen')!);
+ strips = initInstrumentStrips(root);
+ if (!submitted) options.onDraftChange?.(structuredClone(draft));
+ }
+
+ function layout() {
+ const narrow = matchMedia('(max-width: 760px)').matches;
+ const figs = root.querySelector<HTMLElement>('.figures[data-ratios]');
+ if (figs && figs.clientWidth) {
+ const ratios = figs.dataset.ratios!.split(',').map(Number);
+ const [nw, nh] = (figs.dataset.natural ?? '0x0').split('x').map(Number);
+ const fit = narrow
+ ? { direction: 'column' as const, sizes: ratios.map(r => ({ w: Math.min(figs.clientWidth, 360 * r), h: Math.min(figs.clientWidth, 360 * r) / r })) }
+ : figureLayout(ratios, figs.clientWidth, figs.clientHeight, 28, 30, 4, { w: nw, h: nh });
+ figs.dataset.direction = fit.direction;
+ figs.querySelectorAll<HTMLElement>(':scope > .fig > .frame').forEach((f, i) => { f.style.width = `${Math.floor(fit.sizes[i].w)}px`; f.style.height = `${Math.floor(fit.sizes[i].h)}px`; });
+ buildLenses(figs);
+ }
+ const single = root.querySelector<HTMLElement>('.figures.single');
+ if (single?.clientWidth) {
+ const box = JSON.parse(single.dataset.box!) as Box;
+ const stageEl = single.closest<HTMLElement>('.stage')!;
+ const spare = stageEl.clientHeight - 36 - 28 - (stageEl.querySelector<HTMLElement>('.stage-head')?.offsetHeight ?? 0) - (stageEl.querySelector<HTMLElement>('.stage-foot')?.offsetHeight ?? 0) - 30 - 80;
+ const fit = planView(box, packet.comp.width, packet.comp.height, Math.min(single.clientWidth, 1120), narrow ? 320 : Math.max(80, spare));
+ const frame = single.querySelector<HTMLElement>('.frame')!, img = frame.querySelector<HTMLElement>('img')!, focus = frame.querySelector<HTMLElement>('.focus-box')!;
+ const v = fit.view;
+ frame.style.width = `${Math.floor(fit.width)}px`; frame.style.height = `${Math.floor(fit.height)}px`;
+ img.style.cssText = `width:${100 / v.w}%;left:${-100 * v.x / v.w}%;top:${-100 * v.y / v.h}%`;
+ focus.style.cssText = boxStyle({ x: (box.x - v.x) / v.w, y: (box.y - v.y) / v.h, w: box.w / v.w, h: box.h / v.h });
+ buildLenses(single);
+ }
+ for (const map of root.querySelectorAll<HTMLElement>('.overlay-body .map, .intro-comp .map')) {
+ const space = map.parentElement!;
+ const cs = getComputedStyle(space);
+ const w = space.clientWidth - parseFloat(cs.paddingLeft) - parseFloat(cs.paddingRight), h = space.clientHeight - parseFloat(cs.paddingTop) - parseFloat(cs.paddingBottom);
+ if (!w || !h) continue;
+ const scale = Math.min(w / packet.comp.width, h / packet.comp.height);
+ map.style.width = `${packet.comp.width * scale}px`; map.style.height = `${packet.comp.height * scale}px`;
+ }
+ }
+
+ // Loupe: a lens in each frame shows the same relative spot, magnified.
+ const LENS = 78, ZOOM = 3;
+ function buildLenses(scope: HTMLElement) {
+ scope.querySelectorAll<HTMLElement>('.frame').forEach(frame => {
+ frame.querySelector('.lens')?.remove();
+ const lens = document.createElement('span');
+ lens.className = 'lens'; lens.setAttribute('aria-hidden', 'true');
+ const inner = document.createElement('span');
+ inner.className = 'lens-inner';
+ inner.style.width = `${frame.clientWidth}px`; inner.style.height = `${frame.clientHeight}px`;
+ frame.querySelectorAll(':scope > .pic, :scope > .focus-box').forEach(p => inner.append(p.cloneNode(true)));
+ lens.append(inner);
+ frame.append(lens);
+ });
+ }
+ function moveLens(fx: number, fy: number) {
+ root.querySelectorAll<HTMLElement>('.figures .frame').forEach(frame => {
+ const lens = frame.querySelector<HTMLElement>('.lens'), inner = lens?.querySelector<HTMLElement>('.lens-inner');
+ if (!lens || !inner) return;
+ const w = frame.clientWidth, h = frame.clientHeight;
+ lens.style.transform = `translate(${fx * w - LENS}px, ${fy * h - LENS}px)`;
+ const o = loupeOffset(fx, fy, w, h, LENS, ZOOM);
+ inner.style.transform = `translate(${o.x}px, ${o.y}px) scale(${ZOOM})`;
+ });
+ }
+
+ function wire() {
+ const on = (id: string, fn: () => void) => root.getElementById(id)?.addEventListener('click', fn);
+ on('start', () => { const first = queue.find(c => itemState(c, draft) === 'pending') ?? queue[0]; if (first) go('stage', first.id, 'next'); else go('summary'); });
+ root.querySelectorAll<HTMLElement>('[data-go]').forEach(el => el.addEventListener('click', () => {
+ const id = el.dataset.go!; const at = queue.findIndex(c => c.id === current);
+ go('stage', id, view !== 'stage' ? 'fade' : queue.findIndex(c => c.id === id) >= at ? 'next' : 'prev');
+ }));
+ on('to-summary', () => go('summary', undefined, 'next'));
+ on('decide-yes', approve);
+ on('decide-no', () => openForm(item(current)?.role === 'asset' ? 'revise' : 'reclassify'));
+ on('decide-other', () => openForm('revise'));
+ on('decide-split', () => openForm('revise', undefined, true));
+ on('decision-clear', () => { const c = item(current); if (c && !locked()) { commit(clearDecision(draft, c.id), `Cleared: ${c.name}.`); render(); } });
+ on('form-cancel', () => { form = null; render(); });
+ root.getElementById('decision-form')?.addEventListener('submit', e => { e.preventDefault(); saveForm(); });
+ root.getElementById('form-text')?.addEventListener('input', e => { if (form) form.text = (e.target as HTMLTextAreaElement).value; });
+ root.querySelectorAll<HTMLElement>('[data-kind]').forEach(el => el.addEventListener('click', () => {
+ if (!form) return;
+ form.kind = el.dataset.kind as AssetKind;
+ root.querySelectorAll<HTMLElement>('[data-kind]').forEach(k => k.setAttribute('aria-pressed', String(k === el)));
+ }));
+ on('backdrop', () => { const c = item(current); if (!c) return; const order = ['comp', 'light', 'dark'] as const; backdrop[c.id] = order[(order.indexOf(backdrop[c.id] ?? 'comp') + 1) % 3]; render(); });
+ on('undo', undo);
+ on('send', () => void send());
+ on('retry', () => void send());
+ on('reload', () => location.reload());
+ const openMap = () => { mapOpen = true; render(); root.getElementById('close-map')?.focus(); };
+ on('open-map', openMap);
+ on('open-map-bar', openMap);
+ on('close-map', () => { mapOpen = false; render(); });
+ on('mark', () => { if (locked()) return; marking = !marking; panel = null; form = null; render(); });
+ on('panel-done', () => { panel = null; form = null; render(); });
+ on('region-image', () => { if (panel?.type === 'region') openForm('reclassify', panel.id); });
+ on('region-keep', () => { const r = panel?.type === 'region' ? region(panel.id) : undefined; if (r && !locked()) { commit(setRegionReclassify(draft, r.id, null), `${r.name} stays in code.`); render(); } });
+ on('missing-remove', () => { if (panel?.type !== 'missing') return; const id = panel.id; draft = { ...draft, missing: draft.missing.filter(x => x.id !== id) }; panel = null; render(); });
+ root.getElementById('missing-name')?.addEventListener('input', e => { const m = draft.missing.find(x => x.id === panel?.id); if (m) { m.name = (e.target as HTMLInputElement).value; const b = root.getElementById('send') as HTMLButtonElement | null; if (b) b.disabled = !planSummary(packet, draft).canSubmit || sending || !!options.status; options.onDraftChange?.(structuredClone(draft)); } });
+ root.getElementById('missing-feedback')?.addEventListener('input', e => { const m = draft.missing.find(x => x.id === panel?.id); if (m) { m.feedback = (e.target as HTMLTextAreaElement).value; options.onDraftChange?.(structuredClone(draft)); } });
+ if (locked()) root.querySelectorAll<HTMLButtonElement>('#decide-yes,#decide-no,#decide-other,#decide-split,#decision-clear,#mark,#region-image').forEach(b => b.disabled = true);
+
+ // Regions on a map: items open their stage, code regions and missing marks open the side panel.
+ root.querySelectorAll<HTMLElement>('.map [data-item]').forEach(el => el.addEventListener('click', () => { if (!marking) go('stage', el.dataset.item!, 'fade'); }));
+ const toPanel = (next: NonNullable<typeof panel>) => { if (marking) return; panel = next; form = null; if (view !== 'summary') { view = 'summary'; mapOpen = false; enter = reduced() ? null : 'fade'; } render(); root.querySelector('.coverage')?.scrollIntoView({ block: 'start' }); };
+ root.querySelectorAll<HTMLElement>('[data-region]').forEach(el => el.addEventListener('click', () => toPanel({ type: 'region', id: el.dataset.region! })));
+ root.querySelectorAll<HTMLElement>('[data-missing]').forEach(el => el.addEventListener('click', () => toPanel({ type: 'missing', id: el.dataset.missing! })));
+
+ // Loupe on the stage.
+ const figs = root.querySelector<HTMLElement>('.figures');
+ figs?.querySelectorAll<HTMLElement>(':scope > .fig > .frame').forEach(frame => {
+ frame.addEventListener('pointerenter', e => { if ((e as PointerEvent).pointerType === 'mouse') figs.classList.add('looking'); });
+ frame.addEventListener('pointerleave', () => figs.classList.remove('looking'));
+ frame.addEventListener('pointermove', e => { const r = frame.getBoundingClientRect(); moveLens((e.clientX - r.left) / r.width, (e.clientY - r.top) / r.height); });
+ });
+
+ // Drawing a missing mark on the summary map.
+ const map = root.getElementById('summary-map');
+ if (map) {
+ const point = (e: PointerEvent) => { const r = map.getBoundingClientRect(); return { x: Math.max(0, Math.min(1, (e.clientX - r.left) / r.width)), y: Math.max(0, Math.min(1, (e.clientY - r.top) / r.height)) }; };
+ let start: { x: number; y: number } | null = null, box: Box | null = null;
+ map.addEventListener('pointerdown', e => { if (!marking) return; start = point(e); box = null; map.setPointerCapture(e.pointerId); e.preventDefault(); });
+ map.addEventListener('pointermove', e => {
+ if (!start) return;
+ const p = point(e);
+ box = { x: Math.min(start.x, p.x), y: Math.min(start.y, p.y), w: Math.abs(p.x - start.x), h: Math.abs(p.y - start.y) };
+ const outline = root.querySelector<HTMLElement>('.draw-box')!; outline.hidden = false; outline.style.cssText = boxStyle(box);
+ });
+ map.addEventListener('pointerup', () => { if (box && box.w > .01 && box.h > .01) addMissing(box); start = null; box = null; });
+ map.addEventListener('pointercancel', () => { start = null; box = null; render(); });
+ }
+ }
+
+ function setFlip(on: boolean) {
+ if (flipped === on) return;
+ flipped = on;
+ root.querySelectorAll<HTMLElement>('[data-role="generated"] .frame').forEach(f => f.classList.toggle('flipped', on));
+ const cap = root.querySelector<HTMLElement>('[data-role="generated"] figcaption .eyebrow');
+ if (cap) cap.textContent = on ? 'In the comp' : priorRound(current ?? '', history)?.beforeUrl ? 'After' : 'Generated';
+ if (on && !hintSeen) { hintSeen = true; storage.set('impeccable.review.flipHint', '1'); root.querySelector('.hint')?.classList.add('gone'); }
+ }
+
+ const onKey = (event: Event) => {
+ const e = event as KeyboardEvent;
+ if (!host.isConnected || e.defaultPrevented) return;
+ const target = e.composedPath()[0] as HTMLElement;
+ const typing = target instanceof HTMLTextAreaElement || target instanceof HTMLInputElement;
+ if (e.key === 'Escape') {
+ if (mapOpen) { e.preventDefault(); mapOpen = false; render(); }
+ else if (form) { e.preventDefault(); form = null; render(); }
+ else if (marking) { e.preventDefault(); marking = false; render(); }
+ else if (panel) { e.preventDefault(); panel = null; render(); }
+ return;
+ }
+ if (e.key === 'Enter' && (e.metaKey || e.ctrlKey) && form) { e.preventDefault(); saveForm(); return; }
+ if (typing || e.altKey || e.isComposing) return;
+ if ((e.metaKey || e.ctrlKey) && e.key.toLowerCase() === 'z') { if (toast) { e.preventDefault(); undo(); } return; }
+ if (e.metaKey || e.ctrlKey) return;
+ if (view === 'intro' && e.key === 'Enter' && target?.tagName !== 'BUTTON') { e.preventDefault(); root.getElementById('start')?.click(); return; }
+ if (mapOpen || form) return;
+ const key = e.key.toLowerCase();
+ if (e.key === ' ' && view === 'stage' && item(current)?.role === 'asset' && target?.tagName !== 'BUTTON' && target?.tagName !== 'A') { e.preventDefault(); if (!e.repeat) setFlip(true); return; }
+ if (e.key === ' ' && view === 'stage' && item(current)?.role === 'asset') { e.preventDefault(); if (!e.repeat) setFlip(true); return; }
+ if (key === 'c' && view !== 'intro') { e.preventDefault(); mapOpen = true; render(); return; }
+ if (view !== 'stage' || locked()) {
+ if (view === 'summary' && (key === 'k' || e.key === 'ArrowLeft') && queue.length && !locked()) { e.preventDefault(); go('stage', queue[queue.length - 1].id, 'prev'); }
+ return;
+ }
+ if (key === 'a') { e.preventDefault(); approve(); }
+ else if (key === 'n') { e.preventDefault(); root.getElementById('decide-no')?.click(); }
+ else if (key === 'f' && item(current)?.role === 'plan') { e.preventDefault(); openForm('revise'); }
+ else if (key === 's' && item(current)?.role === 'asset') { e.preventDefault(); openForm('revise', undefined, true); }
+ else if (key === 'j' || e.key === 'ArrowRight') { e.preventDefault(); move(1); }
+ else if (key === 'k' || e.key === 'ArrowLeft') { e.preventDefault(); move(-1); }
+ };
+ const onKeyUp = (event: Event) => { if ((event as KeyboardEvent).key === ' ' && flipped) { event.preventDefault(); setFlip(false); } };
+ const onBlur = () => setFlip(false);
+ document.addEventListener('keydown', onKey);
+ document.addEventListener('keyup', onKeyUp);
+ window.addEventListener('blur', onBlur);
+
+ render();
+ return {
+ destroy() { resize?.disconnect(); strips?.(); document.removeEventListener('keydown', onKey); document.removeEventListener('keyup', onKeyUp); window.removeEventListener('blur', onBlur); root.replaceChildren(); },
+ getDraft(): PlanDraft { return structuredClone(draft); },
+ };
+}
diff --git a/ui/component-review/plan-styles.ts b/ui/component-review/plan-styles.ts
new file mode 100644
index 000000000..6de80d419
--- /dev/null
+++ b/ui/component-review/plan-styles.ts
@@ -0,0 +1,240 @@
+/** Plan and asset review: the stage. Only the vendored site kit and its tokens (kit.ts). One paper
+ * plane, one hairline per boundary, images outlined by --ks-rule with no card, eyebrows for labels,
+ * Alumni Sans for the one title per screen. Motion on --ks-ease; none when reduced motion is asked. */
+import { ksKit } from './kit';
+export const planStyles = ksKit + `
+:host{display:block;height:var(--component-review-height,100dvh);min-height:0;overflow:hidden;color:var(--ks-text);font:400 var(--ks-type-small-size)/1.5 var(--ks-font);
+ --asset:var(--ks-patina);--plan:var(--ks-ink);--flag:var(--ks-vermilion);--missing:var(--ks-vermilion);--stage-ease:var(--ks-ease)}
+*{box-sizing:border-box}
+h1,h2,h3,p,figure,blockquote,dl,dd{margin:0}
+button,input,textarea{font:inherit;color:inherit}
+button{cursor:pointer}
+button:disabled{cursor:not-allowed}
+svg{width:16px;height:16px;flex-shrink:0;fill:none;stroke:currentColor;stroke-width:1.6;stroke-linecap:round;stroke-linejoin:round}
+:focus-visible{outline:2px solid var(--ks-focus-ring);outline-offset:3px}
+.eyebrow{font:400 var(--ks-type-eyebrow-size)/1.3 var(--ks-mono);letter-spacing:var(--ks-type-eyebrow-track);text-transform:uppercase;color:var(--ks-text-muted)}
+.muted{color:var(--ks-text-muted)}
+.cap{display:inline-flex;align-items:center;justify-content:center;min-width:20px;height:20px;padding:0 5px;margin:0 -8px 0 2px;border:1px solid currentColor;border-radius:var(--ks-radius-sm);font:500 var(--ks-type-micro-size)/1 var(--ks-mono);letter-spacing:0;opacity:.5}
+.ks-button-primary .cap{opacity:.55}
+.ks-button[disabled] .ks-button-arrow{color:currentColor}
+.text-action{border:0;background:none;padding:0 2px;min-height:0;color:var(--ks-link-on-paper);font:inherit;text-decoration:underline;text-decoration-color:var(--ks-link-on-paper-line);text-underline-offset:3px;transition:text-decoration-color var(--ks-quick) var(--ks-ease)}
+.text-action:hover:not(:disabled){text-decoration-color:var(--ks-link-on-paper-line-hover)}
+.text-action .cap{margin:0 0 0 8px;height:18px;min-width:18px}
+textarea,input{width:100%;display:block;background:var(--ks-paper-raised);color:var(--ks-ink);border:1px solid var(--ks-edge);border-radius:var(--ks-radius-sm);padding:10px 14px;line-height:1.45}
+textarea{resize:vertical;min-height:64px}
+textarea:focus,input:focus{outline:none;border-color:var(--ks-patina);box-shadow:0 0 0 1px var(--ks-patina)}
+.field{display:flex;flex-direction:column;gap:8px}
+
+.rv{height:100%;display:flex;flex-direction:column;min-height:0;background:var(--ks-paper);position:relative;isolation:isolate}
+.rv::before{content:"";position:fixed;inset:0;z-index:-1;pointer-events:none;opacity:0.055;mix-blend-mode:multiply;background-image:var(--ks-grain);background-size:160px 160px}
+
+/* Top bar: title, round, a light per item. */
+.bar{flex-shrink:0;height:56px;display:grid;grid-template-columns:1fr auto 1fr;align-items:center;gap:20px;padding:0 28px;border-bottom:1px solid var(--ks-rule)}
+.bar-title{display:flex;align-items:baseline;gap:12px;min-width:0}
+.bar-name{font-size:var(--ks-type-ui-size);font-weight:500;color:var(--ks-ink);white-space:nowrap;overflow:hidden;text-overflow:ellipsis}
+.bar-round{font:400 var(--ks-type-eyebrow-size)/1 var(--ks-mono);letter-spacing:var(--ks-type-eyebrow-track);text-transform:uppercase;color:var(--ks-text-muted);white-space:nowrap}
+.lights{display:flex;align-items:center;gap:4px}
+.light{position:relative;width:20px;height:24px;padding:0;border:0;background:transparent;display:grid;place-items:center}
+.light::before{content:"";width:8px;height:8px;border-radius:50%;background:var(--ks-gray-2);box-shadow:inset 0 1px 1px oklch(13% 0 0 / 0.18);transition:background-color 160ms var(--ks-ease),box-shadow 160ms var(--ks-ease),transform 160ms var(--ks-ease)}
+.lights.dense{gap:0}.lights.dense .light{width:14px}.lights.dense .light::before{width:7px;height:7px}
+.light.decided::before{background:var(--ks-kinpaku);box-shadow:var(--ks-led)}
+.light.current::before{transform:scale(1.35);background:var(--ks-patina);box-shadow:0 0 0 1px oklch(13% 0 0 / 0.12),0 0 4px color-mix(in oklch,var(--ks-patina) 60%,transparent)}
+.light:hover::before{transform:scale(1.25)}
+.light.current:hover::before{transform:scale(1.35)}
+.light:focus-visible{outline-offset:0;border-radius:var(--ks-radius-sm)}
+.tip{position:absolute;top:calc(100% + 6px);left:50%;transform:translate(-50%,-2px);padding:5px 8px;border:1px solid var(--ks-rule);border-radius:var(--ks-radius-sm);background:var(--ks-paper-deep);color:var(--ks-ink);font-size:var(--ks-type-label-size);white-space:nowrap;opacity:0;pointer-events:none;transition:opacity var(--ks-quick) var(--ks-ease),transform var(--ks-quick) var(--ks-ease);z-index:20}
+.tip-state{color:var(--ks-text-muted)}
+.light:hover .tip,.light:focus-visible .tip{opacity:1;transform:translate(-50%,0)}
+.lights-summary{margin-left:14px;padding:4px 2px;border:0;background:none;border-bottom:2px solid transparent;font-size:var(--ks-type-label-size);color:var(--ks-text-muted);transition:color 180ms var(--ks-ease),border-color 180ms var(--ks-ease)}
+.lights-summary:hover{color:var(--ks-ink)}
+.lights-summary.current{color:var(--ks-ink);border-bottom-color:var(--ks-kinpaku)}
+.bar-locator{display:none;justify-self:end;position:relative;width:52px;height:34px;padding:0;border:0;overflow:hidden;background:var(--ks-paper-deep);box-shadow:0 0 0 1px var(--ks-rule)}
+
+.banner{flex-shrink:0;display:flex;align-items:center;gap:14px;padding:12px 28px;border-bottom:1px solid var(--ks-rule)}
+.banner>svg{width:18px;height:18px;color:var(--ks-vermilion)}
+.banner>div{flex:1;min-width:0}
+.banner strong{display:block;color:var(--ks-ink);font-weight:500}
+.banner p{color:var(--ks-text-muted);font-size:var(--ks-type-ui-size)}
+
+.screen{flex:1;min-height:0;display:flex;flex-direction:column;overflow:hidden;position:relative}
+.view-summary .screen{overflow:auto}
+
+/* Arrivals. */
+@keyframes enter-next{from{opacity:0;transform:translateX(28px)}to{opacity:1;transform:none}}
+@keyframes enter-prev{from{opacity:0;transform:translateX(-28px)}to{opacity:1;transform:none}}
+@keyframes enter-fade{from{opacity:0}to{opacity:1}}
+.enter-next{animation:enter-next 240ms var(--stage-ease) both}
+.enter-prev{animation:enter-prev 240ms var(--stage-ease) both}
+.enter-fade{animation:enter-fade 200ms var(--stage-ease) both}
+
+/* Intro. */
+.intro{flex:1;min-height:0;display:grid;grid-template-columns:minmax(320px,440px) minmax(0,1fr);gap:56px;align-items:center;padding:40px 56px}
+.intro-copy{display:flex;flex-direction:column;align-items:flex-start;gap:18px}
+.intro h1{font:300 clamp(2.6rem,4.4vw,3.6rem)/1.02 var(--ks-font-display);font-variation-settings:'wght' 300;color:var(--ks-ink)}
+.lead{font-size:var(--ks-type-lead-size,1.125rem);line-height:1.5;color:var(--ks-text);max-width:34ch}
+.kinds-explained{display:flex;flex-direction:column;gap:12px;margin-top:6px;padding-top:18px;border-top:1px solid var(--ks-rule);width:100%}
+.kinds-explained dt{display:flex;align-items:center;gap:10px;color:var(--ks-ink);font-weight:500}
+.kinds-explained dd{margin-left:24px;color:var(--ks-text-muted);font-size:var(--ks-type-ui-size)}
+.swatch{display:inline-block;width:14px;height:10px}
+.swatch.asset{border:2px solid var(--asset)}.swatch.plan{border:1.5px dashed var(--plan)}
+.intro-copy .ks-button{margin-top:14px}
+.intro-comp{min-height:0;height:100%;display:flex;align-items:center;justify-content:center}
+
+/* The comp with regions (intro, summary, overlay). */
+.map{position:relative;overflow:hidden;background:var(--ks-paper-deep);box-shadow:0 0 0 1px var(--ks-rule)}
+.map .comp{display:block;width:100%;height:100%;user-select:none;pointer-events:none}
+.region{position:absolute;padding:0;min-height:0;border:0;border-radius:0;background:transparent;outline:2px solid transparent;outline-offset:-1px}
+.region.is-asset{outline:2px solid var(--asset);box-shadow:0 0 0 1px oklch(99.5% 0 0 / .7),inset 0 0 0 1px oklch(99.5% 0 0 / .7)}
+.region.is-plan{outline:1.5px dashed var(--plan);box-shadow:0 0 0 1px oklch(99.5% 0 0 / .6),inset 0 0 0 1px oklch(99.5% 0 0 / .6)}
+.region.flagged{outline:2px solid var(--flag);background:oklch(52% 0.16 35 / .1);box-shadow:0 0 0 1px var(--ks-paper-raised),inset 0 0 0 1px var(--ks-paper-raised)}
+.region.code:hover,.region.code:focus-visible,.region.code.selected{outline:1.5px dotted var(--ks-ink);background:oklch(99.5% 0 0 / .15);box-shadow:0 0 0 1px oklch(99.5% 0 0 / .6)}
+.region.code.reclassify{outline:2px solid var(--ks-ink);background:oklch(13% 0 0 / .06)}
+.region.missing{outline:2px dashed var(--missing);background:oklch(52% 0.16 35 / .12);box-shadow:0 0 0 1px oklch(99.5% 0 0 / .7)}
+.region.approved{opacity:.55}
+.region.revise,.region.reclassify{outline-color:var(--ks-ink);outline-style:solid}
+button.region{cursor:pointer}
+button.region:hover{opacity:1;background-color:oklch(99.5% 0 0 / .14);z-index:4}
+.map.has-selection .region.selected{z-index:5;opacity:1;outline:2px solid var(--ks-paper-raised);box-shadow:0 0 0 1.5px var(--ks-ink),0 0 0 100vmax oklch(13% 0 0 / .22)}
+.tag{position:absolute;left:-2px;bottom:calc(100% + 4px);padding:3px 7px;border-radius:var(--ks-radius-sm);background:var(--ks-ink);color:var(--ks-paper-raised);font:500 var(--ks-type-micro-size)/1.25 var(--ks-font);white-space:nowrap;pointer-events:none;opacity:0;transform:translateY(2px);transition:opacity var(--ks-quick) var(--ks-ease),transform var(--ks-quick) var(--ks-ease);z-index:6}
+.region.tag-below .tag{bottom:auto;top:calc(100% + 4px)}
+.region.tag-right .tag{left:auto;right:-2px}
+.region:hover .tag,.region:focus-visible .tag,.region.selected .tag{opacity:1;transform:none}
+.map.marking{cursor:crosshair;touch-action:none}
+.map.marking .region{pointer-events:none;opacity:.35}
+.draw-box{position:absolute;outline:2px dashed var(--missing);background:oklch(52% 0.16 35 / .15);pointer-events:none;z-index:7}
+
+/* Stage: one item. */
+.stage{flex:1;min-height:0;display:flex;flex-direction:column;align-items:center;gap:14px;padding:22px 48px 12px;position:relative}
+.stage-head{flex-shrink:0;display:flex;flex-direction:column;align-items:center;gap:8px;text-align:center;max-width:760px}
+.stage h1{font:300 clamp(2rem,3vw,2.75rem)/1.04 var(--ks-font-display);font-variation-settings:'wght' 300;color:var(--ks-ink)}
+.asked{margin-top:6px;display:flex;flex-direction:column;align-items:center;gap:6px;padding:12px 18px 0;border-top:1px solid var(--ks-rule)}
+.asked p{font-size:var(--ks-type-lead-size,1.125rem);line-height:1.45;color:var(--ks-ink);max-width:58ch}
+.figures{flex:1 1 0;min-height:0;width:100%;display:flex;justify-content:center;align-items:center;gap:28px}
+.figures[data-direction=column]{flex-direction:column;gap:14px}
+.stage.is-single{justify-content:center}
+.figures.single{flex:none;align-items:center}
+.figures.empty{color:var(--ks-text-muted)}
+.fig{display:flex;flex-direction:column;gap:10px;min-width:0}
+.fig figcaption{height:20px;display:flex;align-items:center;justify-content:space-between;gap:12px}
+.frame{position:relative;overflow:hidden;background:var(--ks-paper-deep);box-shadow:0 0 0 1px var(--ks-rule)}
+.pic{position:absolute;inset:0;display:block;overflow:hidden}
+.pic.crop img{position:absolute;max-width:none;height:auto;user-select:none}
+.pic.gen img{display:block;width:100%;height:100%;object-fit:contain;user-select:none}
+.frame .flip{visibility:hidden}
+.frame.flipped .flip{visibility:visible}
+.frame.flipped .gen:not(.before){visibility:hidden}
+.focus-box{position:absolute;outline:2px solid var(--ks-paper-raised);box-shadow:0 0 0 1.5px var(--ks-ink),0 0 0 100vmax oklch(13% 0 0 / .35);pointer-events:none}
+.figures.looking .frame{cursor:none}
+.lens{position:absolute;top:0;left:0;width:156px;height:156px;border-radius:50%;overflow:hidden;pointer-events:none;opacity:0;z-index:3;background:var(--ks-paper-deep);box-shadow:0 0 0 2px var(--ks-paper-raised),0 0 0 3px oklch(13% 0 0 / .35),var(--ks-lift-2);transition:opacity var(--ks-quick) var(--ks-ease)}
+.figures.looking .lens{opacity:1}
+.lens-inner{position:absolute;top:0;left:0;transform-origin:0 0}
+.lens-inner .focus-box{box-shadow:0 0 0 1.5px var(--ks-ink)}
+.backdrop-switch{font-size:var(--ks-type-label-size)}
+.backdrop-switch .ks-switch-track{transform:scale(.8);transform-origin:right center;margin-right:-6px}
+.stage-foot{flex-shrink:0;display:flex;flex-direction:column;align-items:center;gap:6px;text-align:center;max-width:720px;min-height:22px}
+.sentence{font-size:var(--ks-type-ui-lead);color:var(--ks-ink)}
+.sentence.muted{color:var(--ks-text-muted);font-size:var(--ks-type-small-size)}
+.sentence strong{font-weight:600}
+.sentence s{color:var(--ks-text-muted);text-decoration-color:var(--ks-text-muted);margin-right:4px}
+.flag{display:flex;align-items:baseline;gap:8px;text-align:left;font-size:var(--ks-type-ui-size);color:var(--ks-vermilion);max-width:64ch}
+.flag::before{content:"";flex-shrink:0;width:6px;height:6px;border-radius:50%;background:var(--ks-vermilion);transform:translateY(-1px)}
+.undo-line{color:var(--ks-text-muted);animation:toast-in 240ms var(--ks-ease)}.undo-line .text-action{margin-left:6px}.undo-line .text-action .cap{margin-left:6px}.hint{font-size:var(--ks-type-label-size);color:var(--ks-text-faint);transition:opacity 400ms var(--ks-ease)}
+.hint .cap{margin:0 2px;height:18px}
+.hint.gone,.undo-line.gone{opacity:0;pointer-events:none}
+.locator{position:absolute;left:28px;bottom:14px;display:flex;flex-direction:column;align-items:flex-start;gap:6px;padding:0;border:0;background:none;color:var(--ks-text-muted)}
+.locator-map{position:relative;display:block;width:128px;overflow:hidden;box-shadow:0 0 0 1px var(--ks-rule);transition:box-shadow var(--ks-quick) var(--ks-ease)}
+.locator-map img{display:block;width:100%;height:100%}
+.locator-box{position:absolute;outline:1.5px solid var(--ks-paper-raised);box-shadow:0 0 0 1px var(--ks-ink),0 0 0 100vmax oklch(13% 0 0 / .3)}
+.locator:hover .locator-map{box-shadow:0 0 0 1px var(--ks-edge),var(--ks-lift-1)}
+.locator-label{font:400 var(--ks-type-eyebrow-size)/1 var(--ks-mono);letter-spacing:var(--ks-type-eyebrow-track);text-transform:uppercase;display:inline-flex;align-items:center}
+.locator-label .cap{margin:0 0 0 8px;height:18px;min-width:18px}
+.locator:hover{color:var(--ks-ink)}
+
+/* Decision bar. */
+.decide-bar{flex-shrink:0;display:flex;flex-direction:column;align-items:center;gap:10px;padding:16px 28px 22px;border-top:1px solid var(--ks-rule);background:var(--ks-paper)}
+.decisions{display:flex;justify-content:center;gap:12px}
+.decisions .ks-button{min-width:210px}
+.decisions .ks-button-ghost{min-width:0}
+.current-decision{display:inline-flex;align-items:center;gap:8px;font-size:var(--ks-type-ui-size);color:var(--ks-text-muted);max-width:720px}
+.current-decision svg{color:var(--ks-state-ink)}
+.current-decision span{color:var(--ks-ink)}
+.record{font-size:var(--ks-type-ui-lead);color:var(--ks-ink)}
+.decide-bar.form{align-items:stretch;width:100%}
+.decide-bar.form>*{width:100%;max-width:720px;margin:0 auto}
+.form-row{display:flex;align-items:center;gap:14px}
+.form-actions{display:flex;justify-content:flex-end;gap:8px}
+.form-actions.start{justify-content:flex-start}
+
+/* Toast. */
+@keyframes toast-in{from{opacity:0;transform:translateY(8px)}to{opacity:1;transform:none}}
+
+
+
+.view-summary
+
+/* Summary. */
+.summary{width:100%;max-width:1240px;margin:0 auto;padding:36px 48px 0;display:flex;flex-direction:column;gap:36px}
+.summary-head{display:flex;flex-direction:column;gap:10px}
+.summary h1{font:300 clamp(2.4rem,4vw,3.4rem)/1.02 var(--ks-font-display);font-variation-settings:'wght' 300;color:var(--ks-ink)}
+.sheet{display:grid;grid-template-columns:repeat(auto-fill,minmax(200px,1fr));gap:28px 24px}
+.card{display:flex;flex-direction:column;gap:10px;padding:0;border:0;background:none;text-align:left;color:inherit;min-width:0}
+.card-thumb .focus-box{box-shadow:0 0 0 1px var(--ks-ink),0 0 0 100vmax oklch(13% 0 0 / .3);outline-width:1.5px}
+.card-thumb{height:118px;display:flex;align-items:center;justify-content:center;background:var(--ks-paper-deep);box-shadow:0 0 0 1px var(--ks-rule);overflow:hidden;transition:box-shadow var(--ks-quick) var(--ks-ease)}
+.card:hover .card-thumb{box-shadow:0 0 0 1px var(--ks-edge)}
+.card-pic{position:relative;display:block;max-height:100%;overflow:hidden}
+.card-text{display:flex;flex-direction:column;gap:2px;min-width:0}
+.card-name{font-weight:500;color:var(--ks-ink);white-space:nowrap;overflow:hidden;text-overflow:ellipsis}
+.card-state{display:inline-flex;align-items:center;gap:5px;font-size:var(--ks-type-label-size);color:var(--ks-text-muted)}
+.card-state svg{width:13px;height:13px;stroke-width:2}
+.card.approved .card-state{color:var(--ks-state-ink)}
+.card.revise .card-state,.card.reclassify .card-state{color:var(--ks-ink);font-weight:500}
+.card.pending .card-state{color:var(--ks-vermilion)}
+.card-note{font-size:var(--ks-type-label-size);color:var(--ks-text-muted);display:-webkit-box;-webkit-line-clamp:2;-webkit-box-orient:vertical;overflow:hidden}
+.coverage{display:flex;flex-direction:column;gap:18px;padding-top:32px;border-top:1px solid var(--ks-rule)}
+.coverage h2{font:300 clamp(1.8rem,2.6vw,2.3rem)/1.05 var(--ks-font-display);font-variation-settings:'wght' 300;color:var(--ks-ink)}
+.coverage-grid{display:grid;grid-template-columns:minmax(0,1fr) 300px;gap:32px;align-items:start}
+.map-space .map{width:100%}
+.side-panel{display:flex;flex-direction:column;gap:14px;align-items:stretch}
+.side-panel.quiet p{color:var(--ks-text-muted);font-size:var(--ks-type-ui-size)}
+.side-panel.quiet .ks-button{align-self:flex-start}
+.side-panel h3{font-size:var(--ks-type-subhead-size,1.25rem);font-weight:500;color:var(--ks-ink)}
+.side-panel .eyebrow.missing{color:var(--ks-vermilion)}
+.panel-crop{position:relative;width:100%;max-height:180px;overflow:hidden;box-shadow:0 0 0 1px var(--ks-rule);background:var(--ks-paper-deep)}
+.panel-form{display:flex;flex-direction:column;gap:12px}
+.marking-hint{color:var(--ks-ink)!important;font-weight:500}
+.missing-list{list-style:none;margin:0;padding:0;display:flex;flex-direction:column;gap:6px;font-size:var(--ks-type-ui-size)}
+.summary{padding-bottom:40px}
+.send-row{position:sticky;bottom:0;z-index:10;margin-top:auto;background:var(--ks-paper-raised);border-top:1px solid var(--ks-rule)}
+.send-inner{max-width:1240px;margin:0 auto;display:flex;align-items:center;justify-content:flex-end;gap:20px;padding:14px 48px 18px}
+.send-row p{font-size:var(--ks-type-ui-size);color:var(--ks-text-muted);text-align:right}
+
+/* The comp overlay (C). */
+@keyframes overlay-in{from{opacity:0;transform:scale(.985)}to{opacity:1;transform:none}}
+.overlay{position:absolute;inset:0;z-index:40;display:flex;flex-direction:column;background:var(--ks-paper);animation:overlay-in 200ms var(--ks-ease) both}
+.overlay-head{flex-shrink:0;height:56px;display:flex;align-items:center;justify-content:space-between;padding:0 16px 0 28px;border-bottom:1px solid var(--ks-rule)}
+.overlay-body{flex:1;min-height:0;display:flex;align-items:center;justify-content:center;padding:28px}
+
+@media (max-width:1100px){.intro{grid-template-columns:1fr;gap:28px;overflow:auto;align-content:start}.intro-comp{height:auto}.intro-comp .map{width:100%!important;height:auto!important}.coverage-grid{grid-template-columns:1fr}}
+@media (max-width:760px){
+ :host{height:auto;overflow:visible}
+ .rv{height:auto;min-height:100dvh}
+ .bar{grid-template-columns:1fr auto;grid-template-rows:auto auto;height:auto;gap:8px 12px;padding:10px 16px}
+ .bar-title{grid-column:1}
+ .bar-locator{display:block;grid-column:2;grid-row:1}
+ .lights{grid-column:1/-1;flex-wrap:wrap}
+ .screen{overflow:visible}
+ .intro{padding:24px 16px}
+ .stage{padding:18px 16px 8px}
+ .figures{flex:none}
+ .locator{display:none}
+ .decide-bar{position:sticky;bottom:0;z-index:10;padding:12px 16px calc(12px + env(safe-area-inset-bottom))}
+ .decisions{flex-wrap:wrap;width:100%}
+ .decisions .ks-button{flex:1 1 40%;min-width:0}
+ .cap{display:none}
+
+ .summary{padding:24px 16px 0}
+ .send-inner{padding:12px 16px;flex-wrap:wrap}
+ .send-row p{text-align:left}
+}
+@media (prefers-reduced-motion:reduce){*,*::before{animation:none!important;transition:none!important}}
+`;
diff --git a/ui/component-review/review.ts b/ui/component-review/review.ts
index 952499fcc..a15e2a4a3 100644
--- a/ui/component-review/review.ts
+++ b/ui/component-review/review.ts
@@ -2,6 +2,10 @@ import { reviewScope, type Component, reviewUnits, reviewPeers, decisionTargets,
import { comparisonSize, hoverPan } from './viewport';
import { styles } from './styles';
import { icon } from './icons';
+import { isPlanPacket, type PlanDraft, type PlanHistory } from './plan-model';
+import { mountPlanReview } from './plan-review';
+import { ksArrow } from './kit';
+import { initInstrumentStrips } from './instrument-strip';
const esc = (s: string) => s.replace(/[&<>"']/g, c => ({'&':'&amp;','<':'&lt;','>':'&gt;','"':'&quot;',"'":'&#39;'}[c]!));
const pct = (n: number) => `${n * 100}%`;
@@ -12,8 +16,14 @@ const url = (s: string) => {
return esc(parsed.href);
};
export function mountComponentReview(host: HTMLElement, packet: ReviewPacket, options: {
- preview?: boolean; history?: ReviewHistory | null; initialDraft?: Draft; completed?: boolean; onDraftChange?: (draft: Draft) => void; onSubmit: (value: ReturnType<typeof submission>) => Promise<void>;
+ preview?: boolean; history?: ReviewHistory | null; initialDraft?: Draft; completed?: boolean; status?: string | null; onDraftChange?: (draft: Draft) => void; onSubmit: (value: ReturnType<typeof submission>) => Promise<void>;
}) {
+ // Plan and asset review (schemaVersion 3) has its own view; the first-viewport stage keeps this one.
+ if (isPlanPacket(packet)) return mountPlanReview(host, packet, {
+ ...options, history: options.history as unknown as PlanHistory | null, initialDraft: options.initialDraft as PlanDraft | undefined,
+ onDraftChange: options.onDraftChange as ((draft: PlanDraft) => void) | undefined,
+ onSubmit: options.onSubmit as unknown as (value: unknown) => Promise<void>,
+ }) as unknown as { destroy(): void; getDraft(): Draft };
const root = host.attachShadow({mode: 'open'});
let draft = structuredClone(options.initialDraft ?? newDraft(packet));
// Legacy packets with several regions or marked omissions retain the inventory UI.
@@ -48,6 +58,7 @@ export function mountComponentReview(host: HTMLElement, packet: ReviewPacket, op
let drag: { x: number; y: number } | null = null;
let dragBox: Box | null = null;
let resize: ResizeObserver | null = null;
+ let strips: (() => void) | null = null;
const checkIcon = '<svg viewBox="0 0 16 16" aria-hidden="true"><path d="m3 8 3 3 7-7"/></svg>';
const feedbackIcon = '<svg viewBox="0 0 16 16" aria-hidden="true"><path d="m3 11 1 2 2-1 7-7-3-3-7 7v2Z"/></svg>';
const scopeMarkup = (p: ReviewPacket, item: Component) => {
@@ -130,6 +141,7 @@ export function mountComponentReview(host: HTMLElement, packet: ReviewPacket, op
}
function render() {
resize?.disconnect();
+ strips?.();
if (submitted || (finished && !assembled)) expandedComparison = false;
const active = root.activeElement as HTMLElement | null;
const focusId = active?.id;
@@ -160,7 +172,7 @@ export function mountComponentReview(host: HTMLElement, packet: ReviewPacket, op
const peers = c ? reviewPeers(packet,c) : [];
const targets = c ? decisionTargets(packet,draft,c,applyGroup,Object.keys(edits)) : [];
const isLast = c ? !packet.components.some(item=>!targets.some(t=>t.id===item.id) && componentState(item,draft).kind==='pending') : false;
- const notice = lastDecision && !submitted ? `<div class="decision-notice"><span role="status">${esc(lastDecision.name)} ${lastDecision.action==='approve'?'approved':'flagged for repair'}.</span><button id="undo-decision" class="quiet">Undo</button></div>` : '';
+ const notice = lastDecision && !submitted ? `<div class="decision-notice"><span role="status">${esc(lastDecision.name)} ${lastDecision.action==='approve'?'approved':'flagged for repair'}.</span><button id="undo-decision" class="text-action">Undo</button></div>` : '';
const stats = summarize(packet, draft);
const history = options.history;
const repair = c ? repairStatus(c.id, history) : undefined;
@@ -200,11 +212,11 @@ export function mountComponentReview(host: HTMLElement, packet: ReviewPacket, op
root.innerHTML = `<style>${styles}</style><section class="review ${assembled?'assembled-review':''}" aria-label="${assembled?'Assembled page review':'Component review'}" style="--comp-background:${/^#[0-9a-f]{6}$/i.test(packet.comp.background ?? '') ? packet.comp.background : '#eeeeee'}">
<header><div><h1>${submitted?'Review record.':assembled?'Review the assembled page.':'Review the components.'}</h1><p>${esc(packet.title)} <span>· Round ${packet.round}</span></p></div>${submitted ? '<span class="badge">Submitted · read-only</span>' : options.preview ? '<span class="badge">Interactive preview</span>' : ''}</header>
${options.preview ? '<p class="preview-note">Historical hotel artwork for testing this interface. Decisions stay in this preview; no run is changed.</p>' : ''}
- ${history && !assembled ? `<section class="round-summary" aria-label="Changes since previous round"><p><strong>${pendingUnits} ${pendingUnits===1?'item':'items'} to review</strong><span>${summaryDetails}</span></p>${stats.pending?`<button id="review-changes" class="icon-button" aria-label="Next to review" title="Next to review">${icon('next')}</button>`:''}${history.removed.length?`<details><summary>Removed from the map</summary><p>${history.removed.map(item=>esc(item.name)).join(' · ')}. Confirm these omissions are intentional before accepting the map.</p></details>`:''}</section>`:''}
- ${!assembled?`<div class="mobile-panes" role="group" aria-label="Inspection view"><button id="show-comp" aria-pressed="${mobilePane==='comp'}">Approved comp</button><button id="show-component" aria-pressed="${mobilePane==='component'}">Component ${index}</button></div>`:''}
+ ${history && !assembled ? `<section class="round-summary" aria-label="Changes since previous round"><p><strong>${pendingUnits} ${pendingUnits===1?'item':'items'} to review</strong><span>${summaryDetails}</span></p>${stats.pending?`<button id="review-changes" class="ks-icon-button" aria-label="Next to review" title="Next to review">${icon('next')}</button>`:''}${history.removed.length?`<details><summary>Removed from the map</summary><p>${history.removed.map(item=>esc(item.name)).join(' · ')}. Confirm these omissions are intentional before accepting the map.</p></details>`:''}</section>`:''}
+ ${!assembled?`<div class="mobile-panes"><div class="ks-instrument-strip is-paper" data-ks-strip="pane" role="group" aria-label="Inspection view"><button type="button" class="ks-instrument-key" id="show-comp" aria-pressed="${mobilePane==='comp'}">Approved comp</button><button type="button" class="ks-instrument-key" id="show-component" aria-pressed="${mobilePane==='component'}">Component ${index}</button></div></div>`:''}
<div class="workbench" data-mobile-pane="${mobilePane}">${!assembled?`<svg class="connector" aria-hidden="true"><path /></svg>
<section class="reference" aria-label="Approved composition">
- <div class="section-head"><h2>Approved comp</h2>${!submitted?`<button id="mark" class="label-icon" aria-pressed="${marking}">${icon(marking?'close':'mark')}${marking ? 'Cancel' : 'Mark missing'}</button>`:''}</div>
+ <div class="section-head"><h2>Approved comp</h2>${!submitted?`<button id="mark" class="ks-button ks-button-ghost" aria-pressed="${marking}">${marking ? 'Cancel' : 'Mark missing'}</button>`:''}</div>
<div class="map-space"><div class="map ${marking ? 'marking' : ''}" style="aspect-ratio:${packet.comp.width}/${packet.comp.height}">
<img class="comp" src="${url(packet.comp.url)}" alt="Approved composition for ${esc(packet.title)}" draggable="false">
${box && !finished ? `<div class="region" style="${boxStyle(box)}"></div>` : ''}
@@ -225,23 +237,23 @@ export function mountComponentReview(host: HTMLElement, packet: ReviewPacket, op
${repair?.change?.kind==='changed'?`<details class="changed-files" ${filesOpen?'open':''}><summary>${repair.change.files.length?`${repair.change.files.length} changed ${repair.change.files.length===1?'file':'files'}`:repair.change.reasons.includes('region')?'Region changed':priorComponent?.note!==c.note?'Description changed · files unchanged':'Component definition changed · files unchanged'}</summary>${repair.change.files.length?`<ul>${repair.change.files.map(path=>`<li>${esc(path)}</li>`).join('')}</ul>`:''}${priorComponent&&priorComponent.note!==c.note?`<dl class="description-diff"><dt>Previous description</dt><dd>${esc(priorComponent.note)}</dd><dt>Current description</dt><dd>${esc(c.note)}</dd></dl>`:''}</details>`:''}
</div>`:''}
- <div class="comparison-slot"><div class="comparison-panel ${groupOverview?'group-overview':''}"><h2 class="expanded-title">${esc(groupOverview?unit!.label:v!.name)}</h2>${peers.length>1?`<div class="review-peers"><strong>${peers.length} instances</strong>${!groupOverview?'<button id="all-instances" class="quiet">All instances</button>':'<span class="group-hint">Select to inspect</span>'}</div>`:''}<div class="compare-toolbar">${priorComponent?`<div class="round-switch" role="group" aria-label="Preview version"><button id="current-round" aria-label="Current · round ${packet.round}" title="Current · round ${packet.round}" aria-pressed="${!viewingPrevious}">Current</button><button id="previous-round" aria-label="Previous · round ${history!.packet.round}" title="Previous · round ${history!.packet.round}" aria-pressed="${viewingPrevious}">Previous</button></div>`:''}<label class="zoom-control" title="Comparison zoom · based on comp pixels">${icon('zoom')}<select id="zoom" aria-label="Comparison zoom">${[['fit','Fit'],['1','100%'],['2','200%'],['4','400%']].map(([value,label])=>`<option value="${value}" ${String(zoom)===value?'selected':''}>${label}</option>`).join('')}</select>${icon('chevronDown')}</label><button id="overlay" class="overlay-control" aria-label="Overlay comp" title="Overlay approved comp" aria-pressed="${overlay}"><svg viewBox="0 0 20 20" aria-hidden="true"><rect x="3" y="3" width="10" height="10"/><rect x="7" y="7" width="10" height="10"/></svg><span class="overlay-label">Overlay</span></button><div class="comparison-actions" role="group" aria-label="Comparison view actions"><button id="expand-comparison" class="icon-button" aria-label="${expandedComparison?'Restore comparison':'Enlarge comparison'}" title="${expandedComparison?'Restore comparison (Esc)':'Enlarge comparison'}" aria-expanded="${expandedComparison}">${icon(expandedComparison?'compact':'expand')}</button>${v?.preview.kind==='image'?`<a class="icon-button source-link" href="${url(sourceUrl!)}" target="_blank" rel="noopener" aria-label="${useContext?'Open context capture':presentation!.fileLabel}" title="${useContext?'Open context capture':presentation!.fileLabel}">${icon('external')}</a>`:''}</div></div>
+ <div class="comparison-slot"><div class="comparison-panel ${groupOverview?'group-overview':''}"><h2 class="expanded-title">${esc(groupOverview?unit!.label:v!.name)}</h2>${peers.length>1?`<div class="review-peers"><strong>${peers.length} instances</strong>${!groupOverview?'<button id="all-instances" class="quiet">All instances</button>':'<span class="group-hint">Select to inspect</span>'}</div>`:''}<div class="compare-toolbar">${priorComponent?`<div class="round-switch ks-instrument-strip is-paper" data-ks-strip="round" role="group" aria-label="Preview version"><button type="button" class="ks-instrument-key" id="current-round" aria-label="Current · round ${packet.round}" title="Current · round ${packet.round}" aria-pressed="${!viewingPrevious}">Current</button><button type="button" class="ks-instrument-key" id="previous-round" aria-label="Previous · round ${history!.packet.round}" title="Previous · round ${history!.packet.round}" aria-pressed="${viewingPrevious}">Previous</button></div>`:''}<div class="ks-instrument-strip is-paper zoom-strip" data-ks-strip="zoom" role="group" aria-label="Comparison zoom">${[['fit','Fit'],['1','100%'],['2','200%'],['4','400%']].map(([value,label])=>`<button type="button" class="ks-instrument-key" data-zoom="${value}" aria-pressed="${String(zoom)===value}">${label}</button>`).join('')}</div><button id="overlay" type="button" class="ks-switch" title="Overlay the approved comp" aria-pressed="${overlay}"><span class="ks-switch-track" aria-hidden="true"><span class="ks-switch-knob"></span></span><span class="ks-switch-label">Overlay</span></button><div class="comparison-actions" role="group" aria-label="Comparison view actions"><button id="expand-comparison" class="ks-icon-button" aria-label="${expandedComparison?'Restore comparison':'Enlarge comparison'}" title="${expandedComparison?'Restore comparison (Esc)':'Enlarge comparison'}" aria-expanded="${expandedComparison}">${icon(expandedComparison?'compact':'expand')}</button>${v?.preview.kind==='image'?`<a class="ks-icon-button source-link" href="${url(sourceUrl!)}" target="_blank" rel="noopener" aria-label="${useContext?'Open context capture':presentation!.fileLabel}" title="${useContext?'Open context capture':presentation!.fileLabel}">${icon('external')}</a>`:''}</div></div>
${groupOverview?`<div class="instance-grid" aria-label="All instances of ${esc(unit!.label)}"><div class="instance-grid-labels"><span>Full comp crop</span><span>Component preview</span></div>${unit!.members.map((m,n)=>{const st=stateFor(m);return `<button class="instance-row ${st.kind}" data-instance="${esc(m.id)}" aria-label="Inspect instance ${n+1}: ${esc(m.name)} — ${esc(st.label)}"><span class="instance-caption"><strong>${esc(m.name)}</strong><span>${esc(st.label)}</span></span><span class="instance-pair"><span class="instance-reference" style="width:min(100%,${m.box.w*packet.comp.width}px,${180*m.box.w*packet.comp.width/(m.box.h*packet.comp.height)}px);aspect-ratio:${m.box.w*packet.comp.width}/${m.box.h*packet.comp.height}"><img src="${url(packet.comp.url)}" alt="Comp: ${esc(m.name)}" loading="lazy" style="width:${100/m.box.w}%;left:${-100*m.box.x/m.box.w}%;top:${-100*m.box.y/m.box.h}%">${referenceLayers(packet,m)}</span><span class="instance-produced" style="width:min(100%,${m.box.w*packet.comp.width}px,${180*m.box.w*packet.comp.width/(m.box.h*packet.comp.height)}px);aspect-ratio:${m.box.w*packet.comp.width}/${m.box.h*packet.comp.height}">${m.preview.kind==='image'?`<img src="${url(m.preview.url)}" alt="Produced: ${esc(m.name)}" loading="lazy">`:m.thumbnail?`<img src="${url(m.thumbnail.url)}" alt="Preview: ${esc(m.name)}" loading="lazy">`:'Open live component'}</span></span>${scopeMarkup(packet,m)}</button>`;}).join('')}</div>`:''}
${!groupOverview&&v?scopeMarkup(vp,v):''}<div class="compare">
<figure><figcaption>${viewingPrevious ? `Comp · Round ${history!.packet.round}` : assembled ? 'Approved comp' : visibleScope?.related.length ? 'Full comp crop' : 'In the comp'}</figcaption><div class="pan-viewport" aria-label="Reference comparison canvas" tabindex="0"><div class="crop-stage"><img class="crop-image" src="${url(vp.comp.url)}" alt="Reference region for ${esc(v!.name)}" style="width:${100/v!.box.w}%;left:${-100*v!.box.x/v!.box.w}%;top:${-100*v!.box.y/v!.box.h}%">${referenceLayers(vp,v!)}</div></div></figure>
<figure><figcaption>${viewingPrevious ? `Previous · Round ${history!.packet.round}` : assembled ? 'Assembled page' : useContext ? 'In context' : history ? `${presentation!.caption} · Round ${packet.round}` : presentation!.caption}</figcaption><div class="pan-viewport" aria-label="Produced comparison canvas" tabindex="0"><div class="output crop-stage ${hasTransparency&&!useContext&&!useFrame&&backdrop==='checker'?'checker':''}">${!useFrame ? `<img class="asset" src="${url(sourceUrl!)}" alt="Produced ${esc(v!.name)}" style="object-position:${esc(v!.preview.position ?? 'center')}">` : `<iframe aria-hidden="true" title="Rendered ${esc(v!.name)}" src="${url(sourceUrl!)}" sandbox="" tabindex="-1" width="${vp.comp.width}" height="${vp.comp.height}"></iframe>`}${overlay ? `<img class="crop-image overlay-image" src="${url(vp.comp.url)}" alt="Reference overlay" style="width:${100/v!.box.w}%;left:${-100*v!.box.x/v!.box.w}%;top:${-100*v!.box.y/v!.box.h}%">` : ''}</div></div></figure>
</div>
- ${hasTransparency || v!.context ? `<div class="view-controls">${v!.context ? `<div role="group" aria-label="Component view"><button id="isolated" aria-pressed="${!useContext}">${isRaster?'Asset only':'Component only'}</button><button id="context" aria-pressed="${useContext}">In context</button></div>` : ''}${hasTransparency?`<div class="background-options" role="group" aria-label="Asset preview background"><button id="background-checker" class="swatch-button" aria-label="Checkerboard background" title="Checkerboard background" aria-pressed="${backdrop==='checker'}" ${useContext?'disabled':''}><span class="background-swatch checker"></span></button><button id="background-page" class="swatch-button" aria-label="${vp.comp.background?'Page color':'Neutral'} background" title="${vp.comp.background?'Page color':'Neutral'} background" aria-pressed="${backdrop==='page'}" ${useContext?'disabled':''}><span class="background-swatch page-swatch"></span></button></div>`:''}</div>` : ''}
+ ${hasTransparency || v!.context ? `<div class="view-controls">${v!.context ? `<div class="ks-instrument-strip is-paper" data-ks-strip="view" role="group" aria-label="Component view"><button type="button" class="ks-instrument-key" id="isolated" aria-pressed="${!useContext}">${isRaster?'Asset only':'Component only'}</button><button type="button" class="ks-instrument-key" id="context" aria-pressed="${useContext}">In context</button></div>` : ''}${hasTransparency?`<div class="background-options ks-instrument-strip is-paper" data-ks-strip="background" role="group" aria-label="Asset preview background"><button type="button" id="background-checker" class="ks-instrument-key" aria-label="Checkerboard background" title="Checkerboard background" aria-pressed="${backdrop==='checker'}" ${useContext?'disabled':''}>Checker</button><button type="button" id="background-page" class="ks-instrument-key" aria-label="${vp.comp.background?'Page color':'Neutral'} background" title="${vp.comp.background?'Page color':'Neutral'} background" aria-pressed="${backdrop==='page'}" ${useContext?'disabled':''}>Page</button></div>`:''}</div>` : ''}
</div></div>${!assembled&&!groupOverview?`<div class="component-details"><div class="material">${icon(presentation!.code ? 'code' : 'image')}<strong>${esc(materialLabel)}</strong><span>${v?.material ? `${v.material.width} × ${v.material.height} px` : ''}</span></div>${vp.stage==='components'&&presentation?.captured&&!v?.preview.isolation?'<p class="layering">Legacy region capture · may include overlapping components.</p>':''}${v?.context?.layering&&(isRaster||useContext)?`<p class="layering">${esc(v.context.layering)}</p>`:''}
<p class="component-note">${!visibleScope?.related.length?esc(v!.note):''}</p>
- </div>`:''}</div><div class="review-form">${notice}${viewingPrevious?'<p class="previous-notice">Viewing the previous round. Return to Current to make a decision.</p>':''}${submitted?`<div class="record-verdict"><strong>${d?.action==='approve'?'Approved':d?.action==='revise'?'Changes requested':'Not reviewed'}</strong><span>Submitted in round ${packet.round} · read-only</span></div>`:`<div class="decisions" role="group" aria-label="Decision for ${esc(c.name)}">${!assembled?`<div class="decision-title"><strong>Your review <span>Round ${packet.round}</span></strong>${viewingPrevious?'<p>Return to Current to review this round.</p>':''}</div>`:''}<button id="approve" ${!targets.length?'disabled':''} class="decision-approve ${d?.action === 'approve' ? 'approved' : ''}" aria-pressed="${d?.action === 'approve'}">${assembled?(sending?'Sending…':'Approve & continue'):targets.length>1?`Approve ${targets.length} instances`:'Looks good'}</button><button id="revise" ${!targets.length?'disabled':''} class="decision-revise ${d?.action === 'revise' ? 'revise' : ''}" aria-pressed="${d?.action === 'revise'}">${targets.length>1?`Revise ${targets.length} instances`:'Needs work'}</button>${d && !assembled && !groupOverview ? `<button id="clear" class="quiet icon-button" aria-label="Clear decision" title="Clear decision">${icon('undo')}</button>` : ''}</div>`}
- ${edit ? `<form id="feedback-form"><div class="feedback-fields"><label class="feedback-field">What needs to change?<textarea id="feedback" aria-describedby="feedback-hint">${esc(edit.feedback)}</textarea></label><p id="feedback-hint" class="feedback-hint">Optional — leave blank for the agent to diagnose.</p>${!assembled?`<label class="check"><input id="split" type="checkbox" ${edit.split ? 'checked' : ''}> Split into separately reviewable components</label>`:''}</div><div class="feedback-actions"><button id="cancel-feedback" type="button" class="quiet">Cancel</button><button id="save-feedback" type="submit" class="primary">${assembled?'Send feedback':isLast?'Save & finish review':'Save & next'} <svg viewBox="0 0 24 24" aria-hidden="true"><path d="M4 12h15m-6-6 6 6-6 6"/></svg></button><span class="shortcut-hint">${shortcutLabel}</span></div></form>` : d?.action==='revise' ? `<p class="saved-feedback">${esc(d.feedback || 'No note — agent will diagnose.')}</p>` : ''}
+ </div>`:''}</div><div class="review-form">${notice}${viewingPrevious?'<p class="previous-notice">Viewing the previous round. Return to Current to make a decision.</p>':''}${submitted?`<div class="record-verdict"><strong>${d?.action==='approve'?'Approved':d?.action==='revise'?'Changes requested':'Not reviewed'}</strong><span>Submitted in round ${packet.round} · read-only</span></div>`:`<div class="decisions" role="group" aria-label="Decision for ${esc(c.name)}">${!assembled?`<div class="decision-title"><strong>Your review <span>Round ${packet.round}</span></strong>${viewingPrevious?'<p>Return to Current to review this round.</p>':''}</div>`:''}<button id="approve" ${!targets.length?'disabled':''} class="ks-button ks-button-primary decision-approve ${d?.action === 'approve' ? 'approved' : ''}" aria-pressed="${d?.action === 'approve'}">${assembled?(sending?'Sending…':`Approve & continue${ksArrow}`):targets.length>1?`Approve ${targets.length} instances`:'Looks good'}</button><button id="revise" ${!targets.length?'disabled':''} class="ks-button ks-button-secondary decision-revise ${d?.action === 'revise' ? 'revise' : ''}" aria-pressed="${d?.action === 'revise'}">${targets.length>1?`Revise ${targets.length} instances`:'Needs work'}</button>${d && !assembled && !groupOverview ? `<button id="clear" class="ks-icon-button" aria-label="Clear decision" title="Clear decision">${icon('undo')}</button>` : ''}</div>`}
+ ${edit ? `<form id="feedback-form"><div class="feedback-fields"><label class="feedback-field">What needs to change?<textarea id="feedback" aria-describedby="feedback-hint">${esc(edit.feedback)}</textarea></label><p id="feedback-hint" class="feedback-hint">Optional — leave blank for the agent to diagnose.</p>${!assembled?`<label class="check"><input id="split" type="checkbox" ${edit.split ? 'checked' : ''}> Split into separately reviewable components</label>`:''}</div><div class="feedback-actions"><button id="cancel-feedback" type="button" class="ks-button ks-button-ghost">Cancel</button><button id="save-feedback" type="submit" class="ks-button ks-button-primary">${assembled?'Send feedback':isLast?'Save & finish review':'Save & next'}${ksArrow}</button><span class="shortcut-hint">${shortcutLabel}</span></div></form>` : d?.action==='revise' ? `<p class="saved-feedback">${esc(d.feedback || 'No note — agent will diagnose.')}</p>` : ''}
${assembled?`<p class="page-review-status" role="status">${esc(error || (submitted?'Your decision is saved.':sending?'Sending…':edit?'':'Approval confirms the composition and that nothing is missing.'))}</p>`:''}</div>` : missing ? `<p>This piece will be added to the unresolved inventory.</p><label class="feedback-field">Name<input id="missing-name" value="${esc(missing.name)}"></label><label class="feedback-field">What is missing?<textarea id="missing-feedback">${esc(missing.feedback)}</textarea></label><div class="coordinates">${(['x','y','w','h'] as const).map(k=>`<label>${{x:'Left',y:'Top',w:'Width',h:'Height'}[k]} %<input type="number" data-coordinate="${k}" value="${Math.round(missing.box[k]*1000)/10}" min="0" max="100" step="0.1"></label>`).join('')}</div><button id="remove-missing">Remove this mark</button></div>` : '<p>No components supplied.</p></div>'}
</section>
</div>
- ${!assembled?`<section class="inventory-section ${trayOpen?'':'tray-collapsed'} ${showAll&&trayOpen?'tray-expanded':''}" aria-label="Component inventory"><div class="section-head"><h2>Components</h2><div class="inventory-filters" role="group" aria-label="Filter components"><button data-filter="pending" aria-pressed="${inventoryFilter==='pending'}">To review <b>${pendingUnits}</b></button><button data-filter="reviewed" aria-pressed="${inventoryFilter==='reviewed'}">Reviewed <b>${reviewedCount}</b></button><button data-filter="all" aria-pressed="${inventoryFilter==='all'}">All <b>${units.length+draft.missing.length}</b></button></div><div class="tray-actions"><button id="show-all" class="icon-button" aria-pressed="${showAll}" aria-controls="component-tray" aria-label="${showAll?'Compact':'Expand'} tray" title="${showAll?'Compact':'Expand'} tray">${icon(showAll?'compact':'expand')}</button><button id="toggle-tray" class="icon-button" aria-expanded="${trayOpen}" aria-controls="component-tray" aria-label="${trayOpen?'Hide':'Show'} component tray" title="${trayOpen?'Hide':'Show'} component tray">${icon(trayOpen?'hideTray':'showTray')}</button></div></div>
+ ${!assembled?`<section class="inventory-section ${trayOpen?'':'tray-collapsed'} ${showAll&&trayOpen?'tray-expanded':''}" aria-label="Component inventory"><div class="section-head"><h2>Components</h2><div class="inventory-filters ks-instrument-strip is-paper" data-ks-strip="filter" role="group" aria-label="Filter components"><button type="button" class="ks-instrument-key" data-filter="pending" aria-pressed="${inventoryFilter==='pending'}">To review <b>${pendingUnits}</b></button><button type="button" class="ks-instrument-key" data-filter="reviewed" aria-pressed="${inventoryFilter==='reviewed'}">Reviewed <b>${reviewedCount}</b></button><button type="button" class="ks-instrument-key" data-filter="all" aria-pressed="${inventoryFilter==='all'}">All <b>${units.length+draft.missing.length}</b></button></div><div class="tray-actions"><button id="show-all" class="ks-icon-button" aria-pressed="${showAll}" aria-controls="component-tray" aria-label="${showAll?'Compact':'Expand'} tray" title="${showAll?'Compact':'Expand'} tray">${icon(showAll?'compact':'expand')}</button><button id="toggle-tray" class="ks-icon-button" aria-expanded="${trayOpen}" aria-controls="component-tray" aria-label="${trayOpen?'Hide':'Show'} component tray" title="${trayOpen?'Hide':'Show'} component tray">${icon(trayOpen?'hideTray':'showTray')}</button></div></div>
<div id="component-tray" class="inventory ${showAll ? 'all' : ''}">${shownComponents.map(item=>{const u=units.find(u=>u.members.some(m=>m.id===item.id))!;const i=units.indexOf(u);const state={kind:u.kind,label:u.stateLabel}; return `<button class="item ${state.kind} ${!finished && unit?.id === u.id ? 'active' : ''}" data-select="${esc(item.id)}" aria-pressed="${!finished && unit?.id === u.id}">${item.thumbnail ? `<span class="item-thumb">${item.thumbnail.box ? `<span class="thumb-crop" style="width:min(100%,${76*item.thumbnail.box.w*packet.comp.width/(item.thumbnail.box.h*packet.comp.height)}px);aspect-ratio:${item.thumbnail.box.w*packet.comp.width}/${item.thumbnail.box.h*packet.comp.height}"><img alt="" loading="lazy" src="${url(item.thumbnail.url)}" style="position:absolute;width:${100/item.thumbnail.box.w}%;max-width:none;left:${-100*item.thumbnail.box.x/item.thumbnail.box.w}%;top:${-100*item.thumbnail.box.y/item.thumbnail.box.h}%;"></span>` : `<img alt="" loading="lazy" src="${url(item.thumbnail.url)}">`}</span>` : ''}<span class="item-number">${state.kind==='approved'?checkIcon:state.kind==='feedback'?feedbackIcon:''}${i+1}<span class="item-medium">${icon(componentPresentation(item).code ? 'code' : 'image')}${esc(componentPresentation(item).label)}</span></span><strong>${esc(displayName(item.id))}${u.members.length>1?` <small>×${u.members.length}</small>`:''}</strong><span class="state ${state.kind}">${esc(state.label)}</span></button>`}).join('')}${(inventoryFilter==='pending'?[]:draft.missing).map((m,i)=>`<button class="item feedback ${selected===m.id?'active':''}" data-select="${esc(m.id)}"><span class="item-number">${units.length+i+1}</span><strong>${esc(m.name)}</strong><span class="state revise">Missing</span></button>`).join('')}${!shownComponents.length&&(inventoryFilter==='pending'||!draft.missing.length)?`<p class="inventory-empty">${inventoryFilter==='pending'?'Nothing left to review. Your decisions are ready.':'No components reviewed yet.'}</p>`:''}</div></section>`:''}
- ${assembled?'':submitted?`<footer class="record-footer"><span>Round ${packet.round} submitted · read-only</span><span>${stats.approved} approved · ${stats.revisions} changes requested</span></footer>`:`<footer class="${!stats.pending&&!uncommitted?'queue-complete':''}"><div>${!stats.pending&&!uncommitted ? `<button id="show-summary" class="completion-link">${checkIcon}${submitted?'Review sent':'All components reviewed'}</button>` : ''}<button id="approve-rest" ${!stats.pending?'hidden':''} ${!stats.pending || uncommitted ? 'disabled' : ''}>Approve ${stats.approved || stats.revisions ? 'remaining' : 'all'}</button><label class="check"><input id="inventory-confirm" type="checkbox" ${draft.inventoryConfirmed?'checked':''}> Nothing missing from the comp</label></div><div class="submit-area"><p role="status">${esc(statusMessage)}</p><button id="submit" class="primary" ${!stats.canSubmit || uncommitted || sending || submitted?'disabled':''}>${sending?'Sending…':submitted?'Review sent':stats.hasFeedback?'Send feedback':'Approve & continue'}</button></div></footer>`}
+ ${assembled?'':submitted?`<footer class="record-footer"><span>Round ${packet.round} submitted · read-only</span><span>${stats.approved} approved · ${stats.revisions} changes requested</span></footer>`:`<footer class="${!stats.pending&&!uncommitted?'queue-complete':''}"><div>${!stats.pending&&!uncommitted ? `<button id="show-summary" class="completion-link">${checkIcon}${submitted?'Review sent':'All components reviewed'}</button>` : ''}<button id="approve-rest" class="ks-button ks-button-secondary" ${!stats.pending?'hidden':''} ${!stats.pending || uncommitted ? 'disabled' : ''}>Approve ${stats.approved || stats.revisions ? 'remaining' : 'all'}</button><label class="check ks-checkbox"><input id="inventory-confirm" type="checkbox" ${draft.inventoryConfirmed?'checked':''}> Nothing missing from the comp</label></div><div class="submit-area"><p role="status">${esc(statusMessage)}</p><button id="submit" class="ks-button ks-button-primary" ${!stats.canSubmit || uncommitted || sending || submitted?'disabled':''}>${sending?'Sending…':submitted?'Review sent':stats.hasFeedback?'Send feedback':'Approve & continue'}${sending||submitted?'':ksArrow}</button></div></footer>`}
</section><dialog id="comparison-dialog" aria-label="${assembled?'Enlarged page comparison':'Enlarged component comparison'}"></dialog>`;
const comparisonDialog=root.querySelector<HTMLDialogElement>('#comparison-dialog')!;
const comparisonPanel=root.querySelector<HTMLElement>('.comparison-panel');
@@ -304,7 +316,7 @@ export function mountComponentReview(host: HTMLElement, packet: ReviewPacket, op
on('overlay',()=>{overlay=!overlay; render();});
on('isolated',()=>{outputMode='isolated';render();});
on('context',()=>{outputMode='context';render();});
- root.querySelector('#zoom')?.addEventListener('change',e=>{const value=(e.target as HTMLSelectElement).value;zoom=value==='fit'?'fit':Number(value);render();});
+ root.querySelectorAll<HTMLElement>('[data-zoom]').forEach(el=>el.addEventListener('click',()=>{const value=el.dataset.zoom!;zoom=value==='fit'?'fit':Number(value);render();}));
on('background-checker',()=>{backdrop='checker';render();});
on('background-page',()=>{backdrop='page';render();});
on('show-all',()=>{showAll=!showAll;trayOpen=true;render();});
@@ -419,7 +431,7 @@ export function mountComponentReview(host: HTMLElement, packet: ReviewPacket, op
on('expand-comparison',()=>setComparisonExpanded(!expandedComparison));
comparisonDialog.addEventListener('cancel',e=>{e.preventDefault();e.stopPropagation();setComparisonExpanded(false);});
comparisonDialog.addEventListener('keydown',e=>{if(e.key==='Escape'){e.preventDefault();e.stopPropagation();setComparisonExpanded(false);}});
- resize=new ResizeObserver(()=>{resizePreview();updateScrollEdges();});resize.observe(workbench);resize.observe(comparisonDialog);if(reviewForm)resize.observe(reviewForm);const content=root.querySelector('.inspection-content');if(content)resize.observe(content);const feedback=root.querySelector('.repair-context');if(feedback)resize.observe(feedback);const toolbar=comparisonPanel?.querySelector('.compare-toolbar');if(toolbar)resize.observe(toolbar);resizePreview();
+ strips=initInstrumentStrips(root);resize=new ResizeObserver(()=>{resizePreview();updateScrollEdges();});resize.observe(workbench);resize.observe(comparisonDialog);if(reviewForm)resize.observe(reviewForm);const content=root.querySelector('.inspection-content');if(content)resize.observe(content);const feedback=root.querySelector('.repair-context');if(feedback)resize.observe(feedback);const toolbar=comparisonPanel?.querySelector('.compare-toolbar');if(toolbar)resize.observe(toolbar);resizePreview();
const panes=Array.from(root.querySelectorAll<HTMLElement>('.pan-viewport'));
panes.forEach(pane=>{pane.scrollLeft=panLeft;pane.scrollTop=panTop;});
panes.forEach(pane=>{
@@ -444,5 +456,5 @@ export function mountComponentReview(host: HTMLElement, packet: ReviewPacket, op
if(!submitted) options.onDraftChange?.(structuredClone(draft));
}
render();
- return {destroy(){resize?.disconnect();root.replaceChildren();},getDraft():Draft{return structuredClone(draft);}};
+ return {destroy(){resize?.disconnect();strips?.();root.replaceChildren();},getDraft():Draft{return structuredClone(draft);}};
}
diff --git a/ui/component-review/styles.ts b/ui/component-review/styles.ts
index 8e95638c0..f805d85c0 100644
--- a/ui/component-review/styles.ts
+++ b/ui/component-review/styles.ts
@@ -1,45 +1,43 @@
import { appLayout } from './app-layout';
+import { ksKit } from './kit';
export const styles = `
.review-peers{display:grid;gap:8px;padding:8px 0 12px;font-size:12px}
.review-peers strong span{font-weight:400}.review-peers>div{display:flex;flex-wrap:wrap;gap:4px}
.review-peers button{min-width:28px;min-height:28px;padding:3px;border:1px solid var(--line);border-radius:4px;background:var(--paper);color:inherit}
-.review-peers button[aria-pressed="true"]{background:var(--teal);color:white}
+.review-peers button[aria-pressed="true"]{background:var(--teal);color:var(--ks-paper-raised)}
.review-peers label{display:flex;align-items:center;gap:6px}
-:host{display:block;color:var(--color-text,#292929);font:14px/1.45 var(--font-sans,Arial,sans-serif);--line:var(--color-border,#ddd);--paper:var(--color-panel,#fff);--muted:var(--color-muted,#666);--teal:var(--color-patina,#28625e);--warn:var(--color-warn,#8a5b30);--selection:#43897f}
-*{box-sizing:border-box}h1,h2,p,figure{margin:0}button,input,textarea{font:inherit}button{cursor:pointer;border:1px solid var(--line);border-radius:4px;background:var(--paper);color:inherit;padding:8px 12px;min-height:36px}button:hover{border-color:var(--teal);color:var(--teal)}button:disabled{cursor:default;opacity:.45}button:focus-visible,input:focus-visible,textarea:focus-visible{outline:2px solid var(--teal);outline-offset:3px}button[aria-pressed=true]{box-shadow:inset 0 0 0 1px var(--teal)}input[type=checkbox]{accent-color:var(--teal);width:16px;height:16px;flex-shrink:0}textarea,input:not([type=checkbox]){width:100%;background:var(--paper);color:inherit;border:1px solid #999;border-radius:4px;padding:9px 10px}textarea{resize:vertical;min-height:80px}::selection{background:#c7ddd8}a{color:var(--teal)}
+:host{display:block;color:var(--ks-text);font:14px/1.45 var(--ks-font);--line:var(--ks-rule);--paper:var(--ks-paper-raised);--muted:var(--ks-text-muted);--teal:var(--ks-patina-deep);--warn:var(--ks-vermilion);--selection:var(--ks-patina)}
+*{box-sizing:border-box}h1,h2,p,figure{margin:0}button,input,textarea{font:inherit}button{cursor:pointer;border:1px solid var(--line);border-radius:4px;background:var(--paper);color:inherit;padding:8px 12px;min-height:36px}button:hover{border-color:var(--teal);color:var(--teal)}button:disabled{cursor:default;opacity:.45}button:focus-visible,input:focus-visible,textarea:focus-visible{outline:2px solid var(--teal);outline-offset:3px}button[aria-pressed=true]{box-shadow:inset 0 0 0 1px var(--teal)}input[type=checkbox]{accent-color:var(--teal);width:16px;height:16px;flex-shrink:0}textarea,input:not([type=checkbox]){width:100%;background:var(--paper);color:inherit;border:1px solid var(--ks-edge);border-radius:4px;padding:9px 10px}textarea{resize:vertical;min-height:80px}::selection{background:var(--ks-patina-pale)}a{color:var(--teal)}
.review{max-width:1600px;margin:auto;padding:24px 28px 0}header{display:flex;align-items:center;justify-content:space-between;gap:20px;margin-bottom:16px}h1{font:400 40px/1.05 var(--font-display,Arial,sans-serif);letter-spacing:-.02em}header p{margin-top:8px;font-size:15px}header p span,.medium{color:var(--muted)}.badge{border:1px solid var(--line);padding:5px 10px;font-size:12px;white-space:nowrap}.preview-note{color:var(--muted);font-size:12px;border-bottom:1px solid var(--line);padding-bottom:16px;margin-bottom:24px}
.connector{position:absolute;inset:0;width:100%;height:100%;pointer-events:none;z-index:5;overflow:visible}.connector path{fill:none;stroke:var(--selection);stroke-width:2}.workbench{align-items:start;display:grid;grid-template-columns:minmax(0,1.18fr) minmax(0,1fr);gap:40px;position:relative}.section-head{display:flex;align-items:center;justify-content:space-between;gap:12px;margin-bottom:14px;min-height:36px}.section-head h2{font-size:17px;font-weight:500;line-height:1.2}.section-head>span,.section-head h2>span:not(.number){font-size:12px;color:var(--muted)}.section-head button{font-size:12px}.number{display:inline-flex;align-items:center;justify-content:center;width:27px;height:27px;border:1px solid var(--teal);color:var(--teal);margin-right:7px;font:12px var(--font-mono,monospace)}
-.map{position:relative;background:#eaeaea;isolation:isolate}.comp{width:100%;height:100%;display:block;user-select:none}.map.marking{touch-action:none;cursor:crosshair}.map.marking .pin{pointer-events:none;opacity:.25}.pin{position:absolute;transform:translate(-50%,-50%);padding:0;min-height:25px;width:25px;height:25px;border-radius:50%;border:1px solid #fff;background:#fff;color:#292929;font:11px var(--font-mono,monospace);box-shadow:0 1px 4px #0006;z-index:2}.pin.selected{background:var(--teal);color:#fff;border-color:var(--teal);box-shadow:none;outline:none;z-index:3}.pin:focus-visible{outline:2px solid white;outline-offset:3px}.region,.draw-box{position:absolute;pointer-events:none;outline:2px solid var(--selection);z-index:1}.draw-box{background:#28625e33;z-index:4}.map-caption{font-size:12px;color:var(--muted);padding-top:12px;min-height:40px}.map-caption button{display:block;margin-top:10px}.compare{display:grid;grid-template-columns:1fr 1fr;gap:12px}.compare figure{min-width:0}.compare figcaption{height:24px;min-height:0;font-size:12px;margin-bottom:9px}.compare figcaption span{display:block;color:var(--muted);font-size:11px}.crop-stage{position:relative;overflow:hidden;background:var(--comp-background,#eee);min-width:0}.crop-image{position:absolute;max-width:none;height:auto}.asset{display:block;width:100%;height:100%;object-fit:contain}.crop-stage iframe{position:absolute;max-width:none;border:0;transform-origin:top left;pointer-events:none}.overlay-image{opacity:.5;pointer-events:none}.component-note{font-size:12px;line-height:1.5;color:var(--muted);margin:6px 0 0}.decisions{display:flex;gap:10px;padding:10px 0;background:var(--paper);position:sticky;bottom:0;z-index:6}.decisions>button{flex:1;min-height:48px;font-weight:600;font-size:15px;border-color:var(--teal)}.decision-approve{background:var(--teal);color:white}.decision-approve:hover{background:#224e4b;color:white}.decision-revise{color:var(--teal);background:var(--paper)}.decisions>.quiet{flex:0;border:0;background:transparent;font-size:12px}.decisions .approved{color:var(--teal);background:#e9f0ed;border-color:var(--teal)}.decisions .revise{color:var(--warn);background:#f7f0e6;border-color:var(--warn)}.feedback-field{display:block;margin-top:16px;font-size:13px}.feedback-field>span{float:right;color:var(--muted);font-size:12px}.feedback-field textarea,.feedback-field input{display:block;margin-top:7px}.check{display:flex;align-items:center;gap:7px;font-size:12px;line-height:1.5;margin-top:12px}.coordinates{display:grid;grid-template-columns:repeat(4,1fr);gap:8px;margin:16px 0}.coordinates label{font-size:12px}.coordinates input{margin-top:5px}
-.inventory-section{margin-top:28px;border-top:1px solid var(--line);padding-top:16px}.inventory-section .section-head{margin-bottom:10px}.inventory{display:flex;gap:8px;overflow-x:auto;padding:3px 3px 14px;scrollbar-color:#a6bcb8 #eee;scrollbar-width:thin}.item{position:relative;flex:0 0 134px;display:grid;grid-template-columns:20px 1fr;column-gap:8px;row-gap:3px;padding:10px;text-align:left;background:transparent}.item strong{grid-column:2;font-size:12px;font-weight:500;white-space:nowrap;overflow:hidden;text-overflow:ellipsis}.item.active{background:var(--paper);border-color:var(--teal)}.thumb-crop{position:relative;display:block;overflow:hidden}.item-thumb{display:flex;align-items:center;justify-content:center;grid-column:1/-1;position:relative;overflow:hidden;width:100%;height:76px;background:var(--comp-background,#eee);margin-bottom:7px}.item-thumb img{width:100%;height:100%;object-fit:contain}.item-thumb img[style]{height:auto}.inventory.all{display:grid;grid-template-columns:repeat(auto-fill,minmax(128px,1fr));overflow:visible}.item-number{grid-row:2/4;font:12px var(--font-mono,monospace);color:var(--muted);padding-top:2px}.state{grid-column:2;font-size:11px;color:var(--muted)}.state.approve{color:var(--teal)}.state.revise{color:var(--warn)}footer{display:flex;justify-content:space-between;gap:24px;padding:20px 0 24px;border-top:1px solid var(--line);margin-top:8px}.submit-area{display:flex;align-items:center;gap:20px}.submit-area p{font-size:12px;color:var(--muted);max-width:28ch}.primary{min-height:46px;font-weight:600;background:var(--teal);border-color:var(--teal);color:white;white-space:nowrap}.primary:hover{color:white;background:#224e4b}.primary:disabled{opacity:.45}.inspector>p{margin:12px 0}
+.map{position:relative;background:var(--ks-paper-deep);isolation:isolate}.comp{width:100%;height:100%;display:block;user-select:none}.map.marking{touch-action:none;cursor:crosshair}.map.marking .pin{pointer-events:none;opacity:.25}.pin{position:absolute;transform:translate(-50%,-50%);padding:0;min-height:25px;width:25px;height:25px;border-radius:50%;border:1px solid var(--ks-paper-raised);background:var(--ks-paper-raised);color:var(--ks-text);font:11px var(--font-mono,monospace);box-shadow:0 1px 4px oklch(13% 0 0 / .4);z-index:2}.pin.selected{background:var(--teal);color:var(--ks-paper-raised);border-color:var(--teal);box-shadow:none;outline:none;z-index:3}.pin:focus-visible{outline:2px solid var(--ks-paper-raised);outline-offset:3px}.region,.draw-box{position:absolute;pointer-events:none;outline:2px solid var(--selection);z-index:1}.draw-box{background:oklch(45% 0.10 190 / .2);z-index:4}.map-caption{font-size:12px;color:var(--muted);padding-top:12px;min-height:40px}.map-caption button{display:block;margin-top:10px}.compare{display:grid;grid-template-columns:1fr 1fr;gap:12px}.compare figure{min-width:0}.compare figcaption{height:24px;min-height:0;font-size:12px;margin-bottom:9px}.compare figcaption span{display:block;color:var(--muted);font-size:11px}.crop-stage{position:relative;overflow:hidden;background:var(--comp-background,var(--ks-paper-deep));min-width:0}.crop-image{position:absolute;max-width:none;height:auto}.asset{display:block;width:100%;height:100%;object-fit:contain}.crop-stage iframe{position:absolute;max-width:none;border:0;transform-origin:top left;pointer-events:none}.overlay-image{opacity:.5;pointer-events:none}.component-note{font-size:12px;line-height:1.5;color:var(--muted);margin:6px 0 0}.decisions{display:flex;gap:10px;padding:10px 0;background:var(--paper);position:sticky;bottom:0;z-index:6}.feedback-field{display:block;margin-top:16px;font-size:13px}.feedback-field>span{float:right;color:var(--muted);font-size:12px}.feedback-field textarea,.feedback-field input{display:block;margin-top:7px}.check{display:flex;align-items:center;gap:7px;font-size:12px;line-height:1.5;margin-top:12px}.coordinates{display:grid;grid-template-columns:repeat(4,1fr);gap:8px;margin:16px 0}.coordinates label{font-size:12px}.coordinates input{margin-top:5px}
+.inventory-section{margin-top:28px;border-top:1px solid var(--line);padding-top:16px}.inventory-section .section-head{margin-bottom:10px}.inventory{display:flex;gap:8px;overflow-x:auto;padding:3px 3px 14px;scrollbar-color:var(--ks-gray-2) var(--ks-paper-deep);scrollbar-width:thin}.item{position:relative;flex:0 0 134px;display:grid;grid-template-columns:20px 1fr;column-gap:8px;row-gap:3px;padding:10px;text-align:left;background:transparent}.item strong{grid-column:2;font-size:12px;font-weight:500;white-space:nowrap;overflow:hidden;text-overflow:ellipsis}.item.active{background:var(--paper);border-color:var(--teal)}.thumb-crop{position:relative;display:block;overflow:hidden}.item-thumb{display:flex;align-items:center;justify-content:center;grid-column:1/-1;position:relative;overflow:hidden;width:100%;height:76px;background:var(--comp-background,var(--ks-paper-deep));margin-bottom:7px}.item-thumb img{width:100%;height:100%;object-fit:contain}.item-thumb img[style]{height:auto}.inventory.all{display:grid;grid-template-columns:repeat(auto-fill,minmax(128px,1fr));overflow:visible}.item-number{grid-row:2/4;font:12px var(--font-mono,monospace);color:var(--muted);padding-top:2px}.state{grid-column:2;font-size:11px;color:var(--muted)}.state.approve{color:var(--teal)}.state.revise{color:var(--warn)}footer{display:flex;justify-content:space-between;gap:24px;padding:20px 0 24px;border-top:1px solid var(--line);margin-top:8px}.submit-area{display:flex;align-items:center;gap:20px}.submit-area p{font-size:12px;color:var(--muted);max-width:28ch}.inspector>p{margin:12px 0}
@media(min-width:1300px){.workbench{gap:56px}.review{padding-top:32px}.component-note{max-width:62ch}}
@media(max-width:800px){.connector{display:none}.review{padding:20px 16px 0}.workbench{grid-template-columns:1fr;gap:24px}.reference{max-width:640px;margin:auto;width:100%}.inspector{border-top:1px solid var(--line);padding-top:16px}.compare{max-width:640px}.inventory-section .section-head{align-items:flex-start;flex-direction:column;gap:4px}footer{flex-direction:column}.submit-area{justify-content:space-between}.badge{font-size:11px}.section-head{gap:8px}h1{font-size:34px}header{align-items:flex-start}.section-head h2{font-size:16px}}
.inspector{height:690px;overflow-y:auto;scrollbar-gutter:stable;scrollbar-width:thin;padding:0 5px 0 1px;overflow-anchor:none}
.material{display:flex;align-items:baseline;flex-wrap:wrap;gap:5px 12px;min-height:34px;margin-bottom:6px}.material strong{font-size:14px;font-weight:600}.material span{font:11px var(--font-mono,monospace);color:var(--muted)}
-.compare-toolbar{display:flex;align-items:center;justify-content:space-between;gap:10px;margin-bottom:16px}.compare-toolbar label{font-size:12px;display:flex;align-items:center;gap:8px}select{font:inherit;color:inherit;background:var(--paper);border:1px solid #999;border-radius:4px;padding:7px 9px;min-height:36px}select:focus-visible,.pan-viewport:focus-visible{outline:2px solid var(--teal);outline-offset:2px}
-.overlay-control{display:flex;align-items:center;gap:8px;border-color:var(--teal);color:var(--teal);font-weight:500}.overlay-control[aria-pressed=true]{background:#e9f0ed}.overlay-control svg{width:18px;height:18px;fill:none;stroke:currentColor;stroke-width:1.3}
-.pan-viewport{height:248px;overflow:auto;display:flex;background:#efefef;scrollbar-width:thin;scrollbar-color:#829b98 #eee;overscroll-behavior:contain}.crop-stage{flex-shrink:0;margin:auto}.checker{background-color:#eee;background-image:conic-gradient(#c7c7c7 25%,transparent 0 50%,#c7c7c7 0 75%,transparent 0);background-size:16px 16px}
-.view-controls{display:flex;justify-content:space-between;align-items:center;flex-wrap:wrap;gap:8px;margin-top:12px;min-height:36px}.view-controls>div{display:flex;background:#eee;border:1px solid var(--line);padding:2px;border-radius:4px}.view-controls button{border:0;background:transparent;font-size:12px;min-height:30px;padding:5px 9px}.view-controls button[aria-pressed=true]{background:var(--paper);box-shadow:0 1px 2px #0002}.view-controls label{font-size:11px;display:flex;gap:6px;align-items:center}.view-controls select{font-size:11px;min-height:32px;padding:5px}.view-controls>span{font-size:12px;color:var(--muted)}.scale-note{font-size:11px;color:var(--muted);margin:10px 0 0;min-height:18px}.scale-note a{white-space:nowrap}
+.compare-toolbar{display:flex;align-items:center;justify-content:space-between;gap:10px;margin-bottom:16px}.compare-toolbar label{font-size:12px;display:flex;align-items:center;gap:8px}select{font:inherit;color:inherit;background:var(--paper);border:1px solid var(--ks-edge);border-radius:4px;padding:7px 9px;min-height:36px}select:focus-visible,.pan-viewport:focus-visible{outline:2px solid var(--teal);outline-offset:2px}
+.pan-viewport{height:248px;overflow:auto;display:flex;background:var(--ks-paper-deep);scrollbar-width:thin;scrollbar-color:var(--ks-gray-2) var(--ks-paper-deep);overscroll-behavior:contain}.crop-stage{flex-shrink:0;margin:auto}.checker{background-color:var(--ks-paper-deep);background-image:conic-gradient(var(--ks-gray-2) 25%,transparent 0 50%,var(--ks-gray-2) 0 75%,transparent 0);background-size:16px 16px}
+.view-controls{display:flex;justify-content:space-between;align-items:center;flex-wrap:wrap;gap:8px;margin-top:12px;min-height:36px}.view-controls label{font-size:11px;display:flex;gap:6px;align-items:center}.view-controls select{font-size:11px;min-height:32px;padding:5px}.view-controls>span{font-size:12px;color:var(--muted)}.scale-note{font-size:11px;color:var(--muted);margin:10px 0 0;min-height:18px}.scale-note a{white-space:nowrap}
.component-details{height:78px;overflow:auto;margin-top:12px;padding-right:4px;scrollbar-width:thin}.layering{font-size:12px;line-height:1.5}.component-details .component-note{margin-top:6px}
-#approve-rest{min-height:44px;font-weight:600;border-color:var(--teal);color:var(--teal)}
@media(max-width:800px){.inspector{height:720px}.pan-viewport{height:248px}.component-details{height:92px}.view-controls label{font-size:11px}.review header{align-items:flex-start}}
.round-summary{display:flex;flex-wrap:wrap;align-items:center;justify-content:space-between;gap:10px 20px;padding:14px 0;margin-bottom:22px;border-block:1px solid var(--line)}.round-summary p{display:flex;flex-wrap:wrap;gap:5px 18px;font-size:13px}.round-summary p>span{color:var(--muted)}.round-summary details{flex-basis:100%;font-size:12px}.round-summary details p{font-size:12px;margin-top:8px;max-width:80ch}
.repair-context{display:grid;grid-template-columns:minmax(0,1fr) auto;gap:4px 12px;margin:0 0 10px;font-size:12px}.previous-feedback{display:contents;overflow-wrap:anywhere}.previous-feedback h3{grid-column:1;grid-row:1;margin:0;font-size:11px;font-weight:500;color:var(--muted);align-self:center}.previous-feedback h3 span{font-weight:400;white-space:nowrap}.previous-feedback blockquote{grid-column:1/-1;grid-row:2;margin:0;white-space:pre-wrap;font-size:13px;line-height:1.45;max-height:5.8em;overflow:auto}.previous-feedback>p{grid-column:1/-1;margin:0;font-size:12px}.kept-approval{color:var(--teal);font-size:12px;align-self:center}
-.round-switch{display:flex;gap:1px;border:1px solid var(--line);border-radius:4px;padding:2px;background:#eee;flex-shrink:0}.round-switch button{min-height:28px;font-size:11px;padding:4px 7px;border:0;background:transparent}.round-switch button[aria-pressed=true]{background:var(--paper);color:var(--teal);box-shadow:0 1px 2px #0002}
-.changed-files{grid-column:2;grid-row:1;margin:0;color:var(--muted);font-size:11px}.changed-files summary{padding:2px 0;min-height:24px}.changed-files[open]{grid-column:1/-1;grid-row:auto}.changed-files[open] summary{font-weight:500}summary{cursor:pointer;padding:5px 0;min-height:30px}summary:focus-visible{outline:2px solid var(--teal);outline-offset:2px}.changed-files ul{padding-left:18px;margin:6px 0;overflow-wrap:anywhere;font:11px/1.6 var(--font-mono,monospace)}.description-diff{margin:6px 0 12px}.description-diff dt{font-weight:600;font-size:11px;margin-top:10px}.description-diff dd{margin:4px 0 0;white-space:pre-wrap;overflow-wrap:anywhere;color:var(--color-text,#292929)}.previous-notice{font-size:12px;color:var(--muted);margin-top:8px}.inspector .previous-notice{display:none}
-.decisions{display:grid;grid-template-columns:minmax(0,1fr) minmax(0,1fr) auto;gap:8px 10px;padding-top:12px}.decision-title{grid-column:1/-1}.decision-title strong{font-size:14px;font-weight:600;display:flex;justify-content:space-between;gap:12px}.decision-title strong span{font-size:11px;color:var(--muted);font-weight:400}.decision-title p{font-size:12px;font-weight:400;color:var(--muted);margin-top:4px}.decisions>.quiet{align-self:center;padding-inline:4px}.decisions:not(:has(.quiet)){grid-template-columns:1fr 1fr}
+.changed-files{grid-column:2;grid-row:1;margin:0;color:var(--muted);font-size:11px}.changed-files summary{padding:2px 0;min-height:24px}.changed-files[open]{grid-column:1/-1;grid-row:auto}.changed-files[open] summary{font-weight:500}summary{cursor:pointer;padding:5px 0;min-height:30px}summary:focus-visible{outline:2px solid var(--teal);outline-offset:2px}.changed-files ul{padding-left:18px;margin:6px 0;overflow-wrap:anywhere;font:11px/1.6 var(--font-mono,monospace)}.description-diff{margin:6px 0 12px}.description-diff dt{font-weight:600;font-size:11px;margin-top:10px}.description-diff dd{margin:4px 0 0;white-space:pre-wrap;overflow-wrap:anywhere;color:var(--color-text,var(--ks-text))}.previous-notice{font-size:12px;color:var(--muted);margin-top:8px}.inspector .previous-notice{display:none}
+.decisions{display:grid;grid-template-columns:minmax(0,1fr) minmax(0,1fr) auto;gap:8px 10px;padding-top:12px}.decision-title{grid-column:1/-1}.decision-title strong{font-size:14px;font-weight:600;display:flex;justify-content:space-between;gap:12px}.decision-title strong span{font-size:11px;color:var(--muted);font-weight:400}.decision-title p{font-size:12px;font-weight:400;color:var(--muted);margin-top:4px}.decisions:not(:has(.quiet)){grid-template-columns:1fr 1fr}
.inspector{display:flex;flex-direction:column;overflow:hidden;padding:0}.inspection-content{flex:1;min-height:0;overflow:auto;scrollbar-width:thin;scrollbar-gutter:stable;overscroll-behavior:contain;padding:0 5px 10px 1px}.review-form{flex-shrink:0;padding:12px 5px 0 1px;border-top:1px solid var(--line);background:var(--paper)}.review-form .decisions{position:static;padding:0 0 8px;background:transparent}.review-form .feedback{margin-top:8px}.review-form .feedback textarea{min-height:72px;max-height:120px}.review-form .check{margin:8px 0;font-size:11px}
.inspection-content:focus-visible{outline:2px solid var(--teal);outline-offset:-2px}
.inspector>.section-head{flex-shrink:0;padding:0 5px 0 1px}
-.pin{display:flex;align-items:center;justify-content:center;gap:3px;font-size:12px;font-weight:600;width:30px;height:30px;min-height:30px}.pin svg,.map-legend svg,.item-number svg{width:13px;height:13px;fill:none;stroke:currentColor;stroke-width:1.8;stroke-linecap:round;stroke-linejoin:round;flex-shrink:0}.pin.pending,.pin.pending.selected{background:#f4cd68;border-color:#f4cd68;color:#3c300f}.pin.approved,.pin.approved.selected{width:38px;min-height:24px;height:24px;background:#edf3ef;border-color:#edf3ef;color:#326258;border-radius:4px}.pin.approved:not(.selected){opacity:.55;box-shadow:none}.pin.approved:hover,.pin.approved:focus-visible{opacity:1}.pin.feedback,.pin.feedback.selected{width:38px;background:#964b2f;border-color:#fff;color:#fff;border-radius:4px}.pin.selected{outline:none;border:3px solid #fff;box-shadow:none;z-index:3}.pin:focus-visible{outline:2px solid #fff;outline-offset:3px}
-.map-legend{display:flex;flex-wrap:wrap;gap:9px 18px;margin-top:14px;font-size:11px;color:var(--muted)}.map-legend>span{display:flex;align-items:center;gap:6px}.map-legend i{display:inline-flex;align-items:center;justify-content:center;min-width:21px;height:21px;font-style:normal}.legend-pending{background:#f4cd68;color:#3c300f;border-radius:50%}.legend-feedback{background:#964b2f;color:#fff;border-radius:3px}.legend-approved{background:#edf3ef;color:#326258;border-radius:3px}.map-caption{font-size:11px}
-.inventory-section .section-head{flex-wrap:wrap}.inventory-filters{display:flex;gap:3px;padding:3px;background:#eee;border-radius:5px}.inventory-filters button{border:0;background:transparent;min-height:34px;padding:7px 10px;font-size:12px;white-space:nowrap}.inventory-filters button[aria-pressed=true]{background:var(--paper);color:var(--teal);box-shadow:0 1px 2px #0002}.inventory-filters b{margin-left:5px;font-weight:600;font-variant-numeric:tabular-nums}.item.pending{border-color:#b18a2f;background:#fffbef}.item.feedback{border-color:#964b2f;background:#fcf1eb}.item.approved{background:#f1f4f2;border-color:#ccd8d1}.item.approved .item-thumb{opacity:.65}.item.active{outline:2px solid var(--teal);outline-offset:0;box-shadow:none}.item-number{display:flex;align-items:center;gap:3px;grid-column:1/-1;grid-row:auto;min-height:20px;font-weight:600}.item strong{grid-column:1/-1;font-size:13px;white-space:normal;min-height:36px;line-height:1.35}.state{grid-column:1/-1;font-size:12px;font-weight:600;padding-top:6px;border-top:1px solid #0002}.state.pending{color:#725819}.state.feedback{color:#914429}.state.approved{color:#326258}.inventory-empty{padding:20px 0;font-size:13px;color:var(--muted)}
-@media(max-width:800px){.inventory-section .section-head{gap:10px}.inventory-filters{width:100%}.inventory-filters button{padding-inline:7px;font-size:11px;flex:1}.inventory-filters b{margin-left:3px}}
+.pin{display:flex;align-items:center;justify-content:center;gap:3px;font-size:12px;font-weight:600;width:30px;height:30px;min-height:30px}.pin svg,.map-legend svg,.item-number svg{width:13px;height:13px;fill:none;stroke:currentColor;stroke-width:1.8;stroke-linecap:round;stroke-linejoin:round;flex-shrink:0}.pin.pending,.pin.pending.selected{background:var(--ks-kinpaku);border-color:var(--ks-kinpaku);color:var(--ks-on-gold)}.pin.approved,.pin.approved.selected{width:38px;min-height:24px;height:24px;background:var(--ks-paper-raised);border-color:var(--ks-paper-raised);color:var(--ks-state-ink);border-radius:4px}.pin.approved:not(.selected){opacity:.55;box-shadow:none}.pin.approved:hover,.pin.approved:focus-visible{opacity:1}.pin.feedback,.pin.feedback.selected{width:38px;background:var(--ks-ink);border-color:var(--ks-paper-raised);color:var(--ks-paper-raised);border-radius:4px}.pin.selected{outline:none;border:3px solid var(--ks-paper-raised);box-shadow:none;z-index:3}.pin:focus-visible{outline:2px solid var(--ks-paper-raised);outline-offset:3px}
+.map-legend{display:flex;flex-wrap:wrap;gap:9px 18px;margin-top:14px;font-size:11px;color:var(--muted)}.map-legend>span{display:flex;align-items:center;gap:6px}.map-legend i{display:inline-flex;align-items:center;justify-content:center;min-width:21px;height:21px;font-style:normal}.legend-pending{background:var(--ks-kinpaku);color:var(--ks-on-gold);border-radius:50%}.legend-feedback{background:var(--ks-ink);color:var(--ks-paper-raised);border-radius:3px}.legend-approved{background:var(--ks-paper-raised);color:var(--ks-state-ink);border-radius:3px}.map-caption{font-size:11px}
+.inventory-section .section-head{flex-wrap:wrap}.item.pending{border-color:var(--ks-kinpaku-deep);background:var(--ks-paper-raised)}.item.feedback{border-color:var(--ks-ink);background:var(--ks-paper-raised)}.item.approved{background:var(--ks-paper);border-color:var(--ks-rule)}.item.approved .item-thumb{opacity:.65}.item.active{outline:2px solid var(--teal);outline-offset:0;box-shadow:none}.item-number{display:flex;align-items:center;gap:3px;grid-column:1/-1;grid-row:auto;min-height:20px;font-weight:600}.item strong{grid-column:1/-1;font-size:13px;white-space:normal;min-height:36px;line-height:1.35}.state{grid-column:1/-1;font-size:12px;font-weight:600;padding-top:6px;border-top:1px solid var(--ks-rule)}.state.pending{color:var(--ks-ink)}.state.feedback{color:var(--ks-ink)}.state.approved{color:var(--ks-state-ink)}.inventory-empty{padding:20px 0;font-size:13px;color:var(--muted)}
+@media(max-width:800px){.inventory-section .section-head{gap:10px}}
@media(prefers-reduced-motion:reduce){*{scroll-behavior:auto}}
.item-medium{margin-left:auto;font-weight:400;display:flex;align-items:center;gap:4px;font-size:10px;color:var(--muted);min-height:16px}.item-medium .utility-icon{width:14px;height:14px;flex-shrink:0}.material>.utility-icon{width:18px;height:18px;align-self:center;color:var(--teal)}
-.feedback-actions{display:flex;align-items:center;gap:10px;margin-top:12px;flex-wrap:wrap}.feedback-actions .primary{margin-left:auto;display:inline-flex;align-items:center;gap:10px}.feedback-actions svg{width:18px;height:18px;fill:none;stroke:currentColor;stroke-width:1.5}.feedback-hint,.shortcut-hint{font-size:12px;color:var(--muted)}.feedback-hint{margin-top:6px}.shortcut-hint{flex-basis:100%;text-align:right}.record-verdict{display:flex;flex-wrap:wrap;align-items:baseline;gap:5px 12px;font-size:13px}.record-verdict span{font-size:11px;color:var(--muted)}.review>.record-footer{font-size:12px;color:var(--muted);flex-wrap:wrap;gap:6px 16px}.saved-feedback{font-size:13px;white-space:pre-wrap;overflow-wrap:anywhere;margin:8px 0}.decision-notice{display:flex;align-items:center;gap:12px;font-size:12px;margin-bottom:10px}.decision-notice>span{flex:1;overflow-wrap:anywhere}.decision-notice button{color:var(--teal);flex-shrink:0}.review-summary{padding:4px 2px}.completion-mark{display:flex;align-items:center;justify-content:center;width:32px;height:32px;border-radius:50%;background:#e6efe8;color:#28625e;float:left;margin:0 10px 8px 0}.completion-mark svg{width:24px;height:24px;fill:none;stroke:currentColor;stroke-width:1.6}.completion-link{display:inline-flex;align-items:center;gap:8px;color:var(--teal);border:0;background:transparent;padding:0;font-size:12px;text-align:left}.completion-link svg{width:18px;height:18px;fill:none;stroke:currentColor;stroke-width:1.8;flex-shrink:0}.queue-complete #approve-rest{display:none}.review-summary h2{font-size:22px;line-height:32px}.review-summary p{clear:both;margin-top:8px;color:var(--muted)}.summary-decisions{margin-top:24px;display:grid}.summary-decisions button{display:grid;grid-template-columns:1fr auto;gap:6px 16px;text-align:left;border:0;border-bottom:1px solid var(--line);border-radius:0;padding:12px 0;background:transparent}.summary-decisions strong{font-size:13px;font-weight:500}.summary-decisions span{font-size:12px;color:var(--teal)}.summary-decisions small{grid-column:1/-1;font-size:12px;color:var(--muted);white-space:pre-wrap;overflow-wrap:anywhere}
+.feedback-actions{display:flex;align-items:center;gap:10px;margin-top:12px;flex-wrap:wrap}.feedback-actions svg{width:18px;height:18px;fill:none;stroke:currentColor;stroke-width:1.5}.feedback-hint,.shortcut-hint{font-size:12px;color:var(--muted)}.feedback-hint{margin-top:6px}.shortcut-hint{flex-basis:100%;text-align:right}.record-verdict{display:flex;flex-wrap:wrap;align-items:baseline;gap:5px 12px;font-size:13px}.record-verdict span{font-size:11px;color:var(--muted)}.review>.record-footer{font-size:12px;color:var(--muted);flex-wrap:wrap;gap:6px 16px}.saved-feedback{font-size:13px;white-space:pre-wrap;overflow-wrap:anywhere;margin:8px 0}.decision-notice{display:flex;align-items:center;gap:12px;font-size:12px;margin-bottom:10px}.decision-notice>span{flex:1;overflow-wrap:anywhere}.decision-notice button{color:var(--teal);flex-shrink:0}.review-summary{padding:4px 2px}.completion-mark{display:flex;align-items:center;justify-content:center;width:32px;height:32px;border-radius:50%;background:var(--ks-gray);color:var(--ks-patina-deep);float:left;margin:0 10px 8px 0}.completion-mark svg{width:24px;height:24px;fill:none;stroke:currentColor;stroke-width:1.6}.completion-link{display:inline-flex;align-items:center;gap:8px;color:var(--teal);border:0;background:transparent;padding:0;font-size:12px;text-align:left}.completion-link svg{width:18px;height:18px;fill:none;stroke:currentColor;stroke-width:1.8;flex-shrink:0}.review-summary h2{font-size:22px;line-height:32px}.review-summary p{clear:both;margin-top:8px;color:var(--muted)}.summary-decisions{margin-top:24px;display:grid}.summary-decisions button{display:grid;grid-template-columns:1fr auto;gap:6px 16px;text-align:left;border:0;border-bottom:1px solid var(--line);border-radius:0;padding:12px 0;background:transparent}.summary-decisions strong{font-size:13px;font-weight:500}.summary-decisions span{font-size:12px;color:var(--teal)}.summary-decisions small{grid-column:1/-1;font-size:12px;color:var(--muted);white-space:pre-wrap;overflow-wrap:anywhere}
` + appLayout + `
.review-form:has(#feedback-form){max-height:75%;min-height:0;flex-shrink:1;display:flex;flex-direction:column;overflow:hidden;padding-top:8px}
#feedback-form{display:flex;flex-direction:column;flex:1;min-height:0}
@@ -47,48 +45,39 @@ export const styles = `
.feedback-fields{flex:1;min-height:0;overflow:auto;padding:6px}
.review-form:has(#feedback-form) .decision-notice{flex-shrink:0}
.review-form:has(#feedback-form) .decisions{display:none}
-.feedback-actions{flex-shrink:0;position:static;background:var(--surface,var(--paper));padding:8px 0;margin-top:8px;box-shadow:0 -5px 8px -6px #24332838}
+.feedback-actions{flex-shrink:0;position:static;background:var(--surface,var(--paper));padding:8px 0;margin-top:8px;box-shadow:0 -5px 8px -6px oklch(13% 0 0 / 0.22)}
.feedback-actions .shortcut-hint{flex-basis:auto;order:-1;margin-right:auto}
-.feedback-actions .primary{margin-left:0}
-@media(max-height:800px),(max-width:800px){.feedback-actions .shortcut-hint{display:none}.feedback-actions .primary{margin-left:auto}.review-form .feedback textarea{min-height:56px}.review-form:has(#feedback-form) .decision-notice{margin-bottom:4px}}
+@media(max-height:800px),(max-width:800px){.feedback-actions .shortcut-hint{display:none}.review-form .feedback textarea{min-height:56px}.review-form:has(#feedback-form) .decision-notice{margin-bottom:4px}}
-.comparison-panel{min-width:0;container-type:inline-size}.comparison-panel .expanded-title{display:none}.comparison-panel .compare-toolbar{justify-content:flex-start}.comparison-panel .overlay-control{margin-left:0}.comparison-panel #expand-comparison{flex-shrink:0}.pan-viewport.pannable{cursor:move}.pan-viewport img{user-select:none;-webkit-user-drag:none}
-#comparison-dialog{position:fixed;inset:16px;width:calc(100vw - 32px);height:calc(100dvh - 32px);max-width:none;max-height:none;margin:0;padding:24px;background:var(--paper);color:inherit;border:1px solid var(--line);border-radius:8px;box-shadow:0 20px 60px #14292340;overflow:hidden;transform-origin:top left}
+.comparison-panel{min-width:0;container-type:inline-size}.comparison-panel .expanded-title{display:none}.comparison-panel .compare-toolbar{justify-content:flex-start}.comparison-panel #expand-comparison{flex-shrink:0}.pan-viewport.pannable{cursor:move}.pan-viewport img{user-select:none;-webkit-user-drag:none}
+#comparison-dialog{position:fixed;inset:16px;width:calc(100vw - 32px);height:calc(100dvh - 32px);max-width:none;max-height:none;margin:0;padding:24px;background:var(--paper);color:inherit;border:1px solid var(--line);border-radius:8px;box-shadow:0 20px 60px oklch(13% 0 0 / .25);overflow:hidden;transform-origin:top left}
#comparison-dialog[open]{display:flex;flex-direction:column;gap:12px}
#comparison-dialog>.review-form{width:100%;max-width:900px;align-self:center;max-height:55%;padding:12px 4px 0}
#comparison-dialog>.review-form .decision-title{display:none}
-#comparison-dialog::backdrop{background:#172821a6}
+#comparison-dialog::backdrop{background:oklch(13% 0 0 / .6)}
#comparison-dialog .comparison-panel{flex:1;min-height:0;display:flex;flex-direction:column;gap:12px}
#comparison-dialog .expanded-title{display:block;font-size:20px;line-height:1.3;margin:0;font-weight:500}
#comparison-dialog .compare-toolbar{flex-shrink:0;margin:0}
#comparison-dialog .compare{flex:1;min-height:0;max-width:none;grid-template-columns:minmax(0,1fr) minmax(0,1fr)}
#comparison-dialog .compare figure{display:flex;flex-direction:column;min-height:0}#comparison-dialog .pan-viewport{flex:1;min-height:0}#comparison-dialog .compare figcaption{flex-shrink:0}
#comparison-dialog .view-controls{flex-shrink:0;margin:0}
-@media(max-width:600px){#comparison-dialog{inset:6px;width:calc(100vw - 12px);height:calc(100dvh - 12px);padding:14px}.comparison-panel .compare-toolbar{gap:6px}.comparison-panel .overlay-control{padding-inline:8px;font-size:12px}#comparison-dialog .compare{gap:8px}#comparison-dialog .compare figcaption{font-size:11px}}
+@media(max-width:600px){#comparison-dialog{inset:6px;width:calc(100vw - 12px);height:calc(100dvh - 12px);padding:14px}.comparison-panel .compare-toolbar{gap:6px}#comparison-dialog .compare{gap:8px}#comparison-dialog .compare figcaption{font-size:11px}}
.comparison-panel .compare-toolbar{gap:6px;padding:0;min-width:0;flex-wrap:wrap;margin-bottom:8px}
.comparison-actions{display:flex;align-items:center;gap:2px;margin-left:auto;flex-shrink:0}
-.comparison-panel .zoom-control{position:relative;display:block;flex-shrink:0}
-.zoom-control select{appearance:none;-webkit-appearance:none;width:104px;height:36px;min-height:36px;padding:6px 30px 6px 32px;font-size:12px;line-height:1.4;border-color:var(--line);background:var(--paper);cursor:pointer}
-.zoom-control>.utility-icon{position:absolute;top:50%;transform:translateY(-50%);pointer-events:none}
-.zoom-control>.utility-icon:first-child{left:10px;width:15px;height:15px;color:var(--muted)}
-.zoom-control>.utility-icon:last-child{right:10px;width:13px;height:13px;color:var(--muted)}
-.comparison-panel .overlay-control{height:36px;min-height:36px;font-size:12px;padding:6px 10px;gap:6px}
-.comparison-panel .overlay-control svg{width:18px;height:18px;stroke-width:1.6}
.comparison-actions .source-link{color:var(--muted)}
.component-details .material{min-height:0;margin:12px 0 5px;gap:5px 8px}.component-details .material strong{font-size:11px;font-weight:500;color:var(--muted)}.component-details .material>.utility-icon{width:15px;height:15px}.component-details .material span{font-size:10px}
-@container(max-width:460px){.compare-toolbar .overlay-label{display:none}.compare-toolbar .overlay-control{width:34px;padding:7px}.compare-toolbar .zoom-control select{width:86px;padding-left:27px;padding-right:24px}.compare-toolbar .zoom-control>.utility-icon:first-child{left:8px}.compare-toolbar .zoom-control>.utility-icon:last-child{right:7px}}
-@media(forced-colors:active){.zoom-control select{appearance:auto;padding:6px 8px}.zoom-control>.utility-icon{display:none}}
+@container(max-width:460px){}
+@media(forced-colors:active){}
/* A full-page checkpoint is one comparison, not a component inventory. */
.assembled-review>.workbench{grid-template-columns:minmax(0,1fr);gap:0}
.assembled-review .workbench>.inspector{display:flex}
.assembled-review .inspection-content{padding:16px 20px;scrollbar-gutter:auto}
.assembled-review .compare{max-width:none;gap:20px}
-.assembled-review .pan-viewport{background:var(--canvas);border:1px solid #bdc6bd;box-shadow:inset 0 2px 7px #263d2a12}
+.assembled-review .pan-viewport{background:var(--canvas);border:1px solid var(--ks-rule);box-shadow:inset 0 2px 7px oklch(13% 0 0 / 0.07)}
.assembled-review .inspector>.review-form{padding:12px 20px;max-height:55%}
.assembled-review .decisions{display:flex;justify-content:flex-end;gap:10px}
-.assembled-review #approve{order:2;min-width:180px}
.assembled-review .page-review-status{font-size:11px;color:var(--muted);text-align:right;line-height:1.4;overflow-wrap:anywhere}
.assembled-review .page-review-status:empty{display:none}
.assembled-review .review-form:has(#feedback-form){max-height:55%}
@@ -99,7 +88,6 @@ export const styles = `
.assembled-review .inspection-content{padding:10px}
.assembled-review .compare{grid-template-columns:minmax(0,1fr) minmax(0,1fr);gap:8px}
.assembled-review .inspector>.review-form{padding:10px}
- .assembled-review .decisions>button{flex:1;min-width:0}
.assembled-review .page-review-status{text-align:left}
}
@@ -115,7 +103,7 @@ export const styles = `
.instance-grid{display:grid;gap:0;flex:none;grid-auto-rows:max-content}
.instance-grid-labels{display:grid;grid-template-columns:1fr 1fr;gap:16px;color:var(--muted);font-size:12px;padding:8px 0}
.instance-row{display:block;height:auto;width:100%;text-align:left;padding:12px 0;border:0;border-top:1px solid var(--line);border-radius:0;background:transparent;color:inherit}
-.instance-row:hover{background:#eef3f1}
+.instance-row:hover{background:var(--ks-paper-deep)}
.instance-caption{display:flex;justify-content:space-between;align-items:baseline;gap:12px;font-size:12px;margin-bottom:8px}
.instance-caption>span{color:var(--muted);font-size:11px}
.instance-pair{display:grid;grid-template-columns:1fr 1fr;align-items:center;gap:16px}
@@ -129,11 +117,71 @@ export const styles = `
#comparison-dialog .group-overview>.compare-toolbar{top:0}
#comparison-dialog .group-overview>.expanded-title{padding-right:44px}
-.review-scope{font-size:12px;line-height:1.5;margin:8px 0 12px;color:var(--color-text,#292929);text-align:left;white-space:normal}
+.review-scope{font-size:12px;line-height:1.5;margin:8px 0 12px;color:var(--color-text,var(--ks-text));text-align:left;white-space:normal}
.review-scope p{margin:4px 0;overflow-wrap:anywhere}.review-scope strong{font-weight:600;margin-right:5px}
.review-scope .separate-reviews,.review-scope .scope-excluded{font-size:11px;color:var(--muted)}
.instance-row .review-scope{margin:12px 0 0}
#comparison-dialog .review-scope{flex:none}
-.reference-layer{position:absolute;box-sizing:border-box;border:1px dashed #fff;outline:1px solid #173e43;pointer-events:none;z-index:2}.reference-layer>span{position:absolute;top:0;left:0;max-width:100%;padding:1px 4px;background:#173e43;color:white;font:10px/1.4 var(--font-sans,sans-serif);white-space:nowrap;overflow:hidden;text-overflow:ellipsis;opacity:0;transition:opacity .12s}.instance-row:hover .reference-layer>span,.instance-row:focus-visible .reference-layer>span,.pan-viewport:hover .reference-layer>span,.pan-viewport:focus .reference-layer>span{opacity:1}
+.reference-layer{position:absolute;box-sizing:border-box;border:1px dashed var(--ks-paper-raised);outline:1px solid var(--ks-ink);pointer-events:none;z-index:2}.reference-layer>span{position:absolute;top:0;left:0;max-width:100%;padding:1px 4px;background:var(--ks-ink);color:var(--ks-paper-raised);font:10px/1.4 var(--font-sans,sans-serif);white-space:nowrap;overflow:hidden;text-overflow:ellipsis;opacity:0;transition:opacity .12s}.instance-row:hover .reference-layer>span,.instance-row:focus-visible .reference-layer>span,.pan-viewport:hover .reference-layer>span,.pan-viewport:focus .reference-layer>span{opacity:1}
+
+/* Design-system pass (tokens.ts mirrors kinpaku-tokens.css). One paper plane, hairline rules
+ instead of nested panels, ink for the primary action, patina for state, gold as a line. */
+.review,.review>.workbench,.review>.inventory-section,.review>.round-summary,.review>.preview-note,.mobile-panes{--workspace:var(--ks-paper);--canvas:var(--ks-paper-deep);--dock:var(--ks-paper);--surface:var(--ks-paper);background:var(--ks-paper)}
+.review{color:var(--ks-text)}
+.review h1{font:300 34px/1.04 var(--ks-font-display);font-variation-settings:'wght' 300;color:var(--ks-ink);letter-spacing:0}
+.review>header{background:var(--ks-paper);border-bottom:1px solid var(--ks-rule);box-shadow:none}
+.review>header p,.review>header p span{color:var(--ks-text-muted)}
+.review>.round-summary,.review>.preview-note,.mobile-panes{box-shadow:none;border-bottom:1px solid var(--ks-rule)}
+.section-head h2,.inventory-section h2{font:400 var(--ks-type-eyebrow-size)/1.3 var(--ks-mono);letter-spacing:var(--ks-type-eyebrow-track);text-transform:uppercase;color:var(--ks-text-muted)}
+.compare figcaption,.instance-grid-labels{font:400 var(--ks-type-eyebrow-size)/1.4 var(--ks-mono);letter-spacing:var(--ks-type-eyebrow-track);text-transform:uppercase;color:var(--ks-text-muted)}
+.map-space{background:transparent;border:0;box-shadow:none;border-radius:0}
+.map{box-shadow:0 0 0 1px var(--ks-rule)}
+.workbench>.inspector{background:transparent;border-radius:0;box-shadow:none;border-left:1px solid var(--ks-rule)}
+.inspector>.section-head{background:transparent;border-bottom:1px solid var(--ks-rule);box-shadow:none!important}
+.inspection-content{background:transparent}
+.inspector>.review-form{background:transparent;border-top:1px solid var(--ks-rule);box-shadow:none!important}
+.pan-viewport,.crop-stage{background:transparent}
+.pan-viewport{border:0;box-shadow:none;border-radius:0}
+.crop-stage{box-shadow:0 0 0 1px var(--ks-rule)}
+.review>.inventory-section{box-shadow:none;border-top:1px solid var(--ks-rule)}
+.inventory-section>.section-head{border-bottom:1px solid var(--ks-rule)}
+.inventory .item,.inventory .item.active{background:var(--ks-paper-raised)}
+.item.active{box-shadow:inset 0 -2px 0 var(--ks-kinpaku)}
+.review>footer{background:var(--ks-paper-raised);border-top:1px solid var(--ks-rule);box-shadow:none}
+button:focus-visible,input:focus-visible,textarea:focus-visible{outline-color:var(--ks-focus-ring)}
+textarea,input:not([type=checkbox]),select{border-color:var(--ks-edge);border-radius:var(--ks-radius-sm);background:var(--ks-paper-raised)}
+input[type=checkbox]{accent-color:var(--ks-ink)}
+.decisions{background:transparent}
+.badge{border:0;border-radius:var(--ks-radius-sm);background:var(--ks-gray);color:var(--ks-text-muted);font:600 var(--ks-type-eyebrow-size)/1 var(--ks-mono);letter-spacing:.02em;text-transform:uppercase;padding:5px 7px}
+#comparison-dialog{background:var(--ks-paper);border-color:var(--ks-rule);border-radius:var(--ks-radius-md);box-shadow:var(--ks-lift-2)}
+/* The first-viewport review: two figures on the paper, a small toolbar, two buttons. */
+.assembled-review>.workbench{padding:20px 28px 0}
+.assembled-review .workbench>.inspector{border-left:0}
+.assembled-review .inspection-content{padding:0}
+.assembled-review .compare{gap:28px}
+.assembled-review .pan-viewport{background:transparent;border:0;box-shadow:none}
+.assembled-review .inspector>.review-form{padding:14px 0 18px;margin-top:8px}
+.assembled-review .decisions{padding:0}
+.assembled-review .page-review-status{color:var(--ks-text-muted);font-size:var(--ks-type-label-size)}
+@media(max-width:800px){.assembled-review>.workbench{padding:12px 16px 0}.assembled-review .compare{gap:12px}}
+`+ ksKit + `
+/* Local fit for the vendored kit: sizes the legacy layout expects, the link-style text action,
+ and the paper grain the site puts on its page ground (kit body::before, here on the review root). */
+.review{position:relative;isolation:isolate}
+.review::before{content:"";position:fixed;inset:0;z-index:-1;pointer-events:none;opacity:0.055;mix-blend-mode:multiply;background-image:var(--ks-grain);background-size:160px 160px}
+.decisions>.ks-button{flex:1}
+.assembled-review .decisions{display:flex;justify-content:flex-end;gap:12px}
+.assembled-review .decisions>.ks-button{flex:0 0 auto;min-width:200px}
+.assembled-review #approve{order:2}
+.ks-button[disabled] .ks-button-arrow{color:currentColor}
+.text-action{border:0;background:none;padding:0 2px;min-height:0;color:var(--ks-link-on-paper);font:inherit;font-size:var(--ks-type-label-size);text-decoration:underline;text-decoration-color:var(--ks-link-on-paper-line);text-underline-offset:3px;cursor:pointer}
+.text-action:hover{text-decoration-color:var(--ks-link-on-paper-line-hover)}
+.compare-toolbar{align-items:center;gap:16px}
+.comparison-actions{display:flex;gap:8px;margin-left:auto}
+.ks-icon-button{padding:0;min-height:0}
+.ks-icon-button .utility-icon{width:16px;height:16px}
+.mobile-panes{padding:8px 14px}
+.ks-checkbox input{margin:0}
+.review .ks-switch,.review .ks-switch[aria-pressed=true],.review .ks-instrument-key[aria-pressed=true]{box-shadow:none}
`;
diff --git a/ui/component-review/vendor.d.ts b/ui/component-review/vendor.d.ts
new file mode 100644
index 000000000..0510a9a56
--- /dev/null
+++ b/ui/component-review/vendor.d.ts
@@ -0,0 +1 @@
+declare module '*.css' { const text: string; export default text; }
diff --git a/ui/component-review/vendor/docs-rail.css b/ui/component-review/vendor/docs-rail.css
new file mode 100644
index 000000000..fc6110389
--- /dev/null
+++ b/ui/component-review/vendor/docs-rail.css
@@ -0,0 +1,50 @@
+/* VENDORED from impeccable-site/site/styles/docs-kinpaku.css (the command rail list: the site's selected-row pattern) (the source of truth).
+ Do not edit here: change the site, then run node scripts/sync-kinpaku-kit.mjs. */
+/* Group headings are ink and bold, so they read as headings over their
+ links rather than as meta beside them; the links are muted and a step
+ smaller, ink on hover and on the current page. */
+.docs-kinpaku .skills-sidebar-category {
+ display: block;
+ font-family: var(--ks-font);
+ font-size: 0.8125rem;
+ font-weight: 650;
+ letter-spacing: 0.01em;
+ text-transform: none;
+ color: var(--ks-ink);
+ margin-bottom: 6px;
+ padding: 0 0 0 14px;
+}
+
+.docs-kinpaku .skills-sidebar-list {
+ list-style: none;
+ padding: 0;
+ margin: 0;
+}
+
+.docs-kinpaku .skills-sidebar-list li {
+ margin: 0;
+}
+
+.docs-kinpaku .skills-sidebar-list a {
+ display: block;
+ padding: 4px 0 4px 12px;
+ border-left: 2px solid transparent;
+ font-family: var(--ks-font);
+ font-size: 0.875rem;
+ font-weight: 400;
+ line-height: 1.5;
+ color: var(--ks-text-muted);
+ text-decoration: none;
+ transition: color 160ms var(--ks-ease),
+ border-color 160ms var(--ks-ease);
+}
+
+.docs-kinpaku .skills-sidebar-list a:hover {
+ color: var(--ks-ink);
+}
+
+.docs-kinpaku .skills-sidebar-list a[aria-current="page"] {
+ color: var(--ks-ink);
+ font-weight: 600;
+ border-left-color: var(--ks-gold-line);
+}
diff --git a/ui/component-review/vendor/instrument-strip.js b/ui/component-review/vendor/instrument-strip.js
new file mode 100644
index 000000000..a0d47c5f9
--- /dev/null
+++ b/ui/component-review/vendor/instrument-strip.js
@@ -0,0 +1,115 @@
+// VENDORED from impeccable-site/site/scripts/instrument-strip.js (the source of truth).
+// Do not edit here: change the site, then run node scripts/sync-kinpaku-kit.mjs.
+// Instrument strip: the sliding thumb.
+//
+// Every .ks-instrument-strip gets one raised cap that slides between keys.
+// The page's own handlers still toggle is-active / aria-selected /
+// aria-pressed on the keys; this script only measures the active key and
+// writes --thumb-x / --thumb-w on the strip, on load, on any class or aria
+// change, and on resize. Dragging the thumb selects the nearest key by
+// clicking it, so the page's handler runs unchanged.
+
+const ACTIVE = '.is-active, [aria-selected="true"], [aria-pressed="true"]';
+
+// Writes only when a value changes: the observer below watches class
+// changes on the strip's subtree, and an unconditional classList.add would
+// re-trigger it forever.
+function place(strip) {
+ const key = strip.querySelector(`.ks-instrument-key:is(${ACTIVE})`);
+ if (!key) {
+ if (strip.classList.contains('has-thumb')) strip.classList.remove('has-thumb');
+ return;
+ }
+ const s = strip.getBoundingClientRect();
+ const k = key.getBoundingClientRect();
+ const styles = getComputedStyle(strip);
+ // Rects include CSS zoom; the thumb's CSS dimensions use layout pixels.
+ const scale = s.width / parseFloat(styles.width) || 1;
+ const border = parseFloat(styles.borderLeftWidth) || 0;
+ const x = Math.round(((k.left - s.left) / scale - border + strip.scrollLeft) * 100) / 100;
+ const w = Math.round(k.width / scale * 100) / 100;
+ let thumb = strip.querySelector(':scope > .ks-thumb');
+ if (!thumb) {
+ thumb = document.createElement('span');
+ thumb.className = 'ks-thumb';
+ thumb.setAttribute('aria-hidden', 'true');
+ strip.appendChild(thumb);
+ }
+ if (thumb.style.width !== `${w}px`) thumb.style.width = `${w}px`;
+ const t = `translateX(${x}px)`;
+ if (thumb.style.transform !== t) thumb.style.transform = t;
+ if (!strip.classList.contains('has-thumb')) strip.classList.add('has-thumb');
+}
+
+function attach(strip) {
+ if (strip.dataset.thumb) return;
+ strip.dataset.thumb = '1';
+ place(strip);
+ // Observe the keys, not the strip itself, so the strip's own class and
+ // style writes never feed back into the observer.
+ const mo = new MutationObserver((records) => {
+ if (records.some((r) => r.target !== strip && !r.target.classList?.contains('ks-thumb'))) place(strip);
+ });
+ mo.observe(strip, { subtree: true, attributes: true, attributeFilter: ['class', 'aria-selected', 'aria-pressed'], childList: true });
+ if (typeof ResizeObserver !== 'undefined') new ResizeObserver(() => place(strip)).observe(strip);
+
+ // Mouse and pen can scrub between keys. Touch keeps native taps and
+ // scrolling, including sideways drift before the browser starts a pan.
+ // No pointer capture: a plain press and release stays a normal click.
+ let pointerId = null;
+ let dragging = false;
+ let startX = 0;
+ let last = null;
+ const keyAt = (x, y) => document.elementFromPoint(x, y)?.closest('.ks-instrument-key');
+ strip.addEventListener('pointerdown', (e) => {
+ if (!['mouse', 'pen'].includes(e.pointerType) || !e.isPrimary || e.button !== 0 || pointerId !== null) return;
+ pointerId = e.pointerId;
+ dragging = false;
+ startX = e.clientX;
+ last = keyAt(e.clientX, e.clientY);
+ });
+ strip.addEventListener('pointermove', (e) => {
+ if (e.pointerId !== pointerId) return;
+ if (!dragging && Math.abs(e.clientX - startX) < 6) return;
+ dragging = true;
+ const key = keyAt(e.clientX, e.clientY);
+ if (key && key !== last && strip.contains(key)) {
+ last = key;
+ key.click();
+ }
+ });
+ const resetDrag = () => {
+ pointerId = null;
+ dragging = false;
+ last = null;
+ };
+ const end = (e) => {
+ if (e.pointerId === pointerId) resetDrag();
+ };
+ window.addEventListener('pointerup', end);
+ window.addEventListener('pointercancel', end);
+ // A release outside the focused window may never send either event.
+ window.addEventListener('blur', resetDrag);
+}
+
+export function initInstrumentStrips(root = document) {
+ root.querySelectorAll('.ks-instrument-strip').forEach(attach);
+ // Strips rendered later (the command palette, the mobile picker).
+ const mo = new MutationObserver((records) => {
+ for (const r of records) {
+ for (const n of r.addedNodes) {
+ if (!(n instanceof Element)) continue;
+ if (n.matches('.ks-instrument-strip')) attach(n);
+ n.querySelectorAll?.('.ks-instrument-strip').forEach(attach);
+ }
+ }
+ });
+ mo.observe(root.body || root, { childList: true, subtree: true });
+ window.addEventListener('resize', () => root.querySelectorAll('.ks-instrument-strip').forEach(place));
+ if (document.fonts?.ready) document.fonts.ready.then(() => root.querySelectorAll('.ks-instrument-strip').forEach(place));
+}
+
+if (typeof document !== 'undefined') {
+ if (document.readyState === 'loading') document.addEventListener('DOMContentLoaded', () => initInstrumentStrips());
+ else initInstrumentStrips();
+}
diff --git a/ui/component-review/vendor/kinpaku-kit.css b/ui/component-review/vendor/kinpaku-kit.css
new file mode 100644
index 000000000..9d9dc27d3
--- /dev/null
+++ b/ui/component-review/vendor/kinpaku-kit.css
@@ -0,0 +1,728 @@
+/* VENDORED from impeccable-site/site/styles/kinpaku-kit.css (buttons, tabs, select, icon button, instrument strip, grain, switch, paper strip, thumb) (the source of truth).
+ Do not edit here: change the site, then run node scripts/sync-kinpaku-kit.mjs. */
+/* ============================================================
+ Buttons: primary, secondary, ghost, disabled
+
+ The primary action is ink on paper. Gold does not fill a button on this
+ site: a gold slab on paper is the hotel-lobby read. The brand is present
+ on the primary as the gold arrow, not as the fill.
+
+ Variants chain on .ks-button so specificity (0,2,0) wins over generic page
+ anchor resets like `.kinpaku-system-page a { color: inherit }` (0,1,1).
+ Use class="ks-button ks-button-primary", both classes required.
+ ============================================================ */
+
+.ks-button {
+ position: relative;
+ min-height: var(--ks-control-lg);
+ display: inline-flex;
+ align-items: center;
+ justify-content: center;
+ gap: 12px;
+ padding: 0 22px;
+ border-radius: var(--ks-radius-sm);
+ font-family: var(--ks-font);
+ font-size: 0.9375rem;
+ font-weight: 500;
+ line-height: 1;
+ letter-spacing: -0.005em;
+ text-decoration: none;
+ border: 1px solid transparent;
+ cursor: pointer;
+ transition: background-color var(--ks-quick) var(--ks-ease), border-color var(--ks-quick) var(--ks-ease), color var(--ks-quick) var(--ks-ease);
+}
+
+.ks-button .ks-button-arrow {
+ width: 16px;
+ height: 8px;
+ display: inline-block;
+ flex: none;
+}
+
+.ks-button-arrow svg { width: 100%; height: 100%; display: block; overflow: visible; }
+
+/* The arrow says where the button goes. On a button whose target is further
+ down the page (an in-page anchor, or .is-down on the arrow) it curves and
+ points downward on hover, and straightens again on leave. The rest shape
+ is set here too, as the same command list, so the two interpolate. */
+.ks-button-arrow path {
+ d: path("M0 4C5 4 9 4 14 4M10 0L14 4L10 8");
+ transition: d 420ms var(--ks-ease);
+}
+
+.ks-button[href^="#"]:hover .ks-button-arrow path,
+.ks-button:hover .ks-button-arrow.is-down path {
+ d: path("M0 4C7 4 11 4 11 11M7 7L11 11L15 7");
+}
+
+@media (prefers-reduced-motion: reduce) {
+ .ks-button-arrow path { transition: none; }
+}
+
+.ks-button.ks-button-primary {
+ color: var(--ks-paper-raised);
+ background: var(--ks-ink);
+ border-color: var(--ks-ink);
+}
+
+.ks-button.ks-button-primary .ks-button-arrow {
+ color: var(--ks-kinpaku);
+}
+
+.ks-button.ks-button-primary:hover {
+ color: var(--ks-paper-raised);
+ background: var(--ks-text);
+ border-color: var(--ks-text);
+}
+
+.ks-button.ks-button-primary:active {
+ background: oklch(8% 0 0);
+ border-color: oklch(8% 0 0);
+}
+
+.ks-button.ks-button-secondary {
+ color: var(--ks-ink);
+ background: var(--ks-paper-raised);
+ border-color: var(--ks-edge);
+}
+
+.ks-button.ks-button-secondary:hover {
+ color: var(--ks-ink);
+ border-color: var(--ks-ink);
+}
+
+.ks-button.ks-button-secondary:active {
+ background: var(--ks-gray);
+}
+
+.ks-button.ks-button-ghost {
+ color: var(--ks-ink);
+ background: transparent;
+ border-color: transparent;
+ padding: 0 12px;
+}
+
+.ks-button.ks-button-ghost:hover {
+ color: var(--ks-accent-ink);
+}
+
+.ks-button[disabled],
+.ks-button.ks-button-disabled {
+ color: var(--ks-text-mute-deep);
+ background: transparent;
+ border-color: var(--ks-rule);
+ cursor: not-allowed;
+ transform: none !important;
+}
+
+.ks-button:focus-visible {
+ outline: 2px solid var(--ks-focus-ring);
+ outline-offset: 3px;
+}
+
+.ks-button-row {
+ display: flex;
+ flex-wrap: wrap;
+ align-items: center;
+ gap: 18px;
+}
+
+/* ============================================================
+ Tabs
+ ============================================================ */
+
+.ks-tabs { max-width: 460px; }
+
+.ks-tab-list { display: flex; border-bottom: 1px solid var(--ks-rule); }
+
+.ks-tab-list button {
+ flex: 1;
+ min-height: 42px;
+ border: 0;
+ border-bottom: 2px solid transparent;
+ background: transparent;
+ color: var(--ks-text-muted);
+ cursor: pointer;
+ font-size: 0.92rem;
+ transition: color 180ms var(--ks-ease), border-color 180ms var(--ks-ease);
+}
+
+.ks-tab-list button:hover { color: var(--ks-ink); }
+
+.ks-tab-list button[aria-selected="true"] {
+ color: var(--ks-accent-ink);
+ border-bottom-color: var(--ks-kinpaku);
+}
+
+.ks-tab-panel {
+ padding: 22px 4px 0;
+ color: var(--ks-ink);
+ font-size: 0.92rem;
+ line-height: 1.6;
+}
+
+/* ============================================================
+ Form controls — input, toggle, checkbox, select
+ ============================================================ */
+
+.ks-form-sample {
+ display: grid;
+ gap: 22px;
+ max-width: 360px;
+}
+
+.ks-form-sample label {
+ display: grid;
+ gap: 8px;
+ color: var(--ks-text-muted);
+ font-size: 0.82rem;
+ letter-spacing: 0.04em;
+}
+
+.ks-form-sample input[type="search"],
+.ks-form-sample input[type="text"] {
+ min-height: 46px;
+ padding: 0 14px;
+ border: 1px solid var(--ks-rule);
+ border-radius: var(--ks-radius-sm);
+ background: var(--ks-paper-raised);
+ color: var(--ks-ink);
+ font-size: 0.92rem;
+}
+
+.ks-form-sample input[type="search"]:focus,
+.ks-form-sample input[type="text"]:focus {
+ outline: none;
+ border-color: var(--ks-patina);
+}
+
+.ks-toggle {
+ display: flex !important;
+ align-items: center;
+ gap: 12px !important;
+}
+
+.ks-toggle input {
+ appearance: none;
+ width: 44px;
+ height: 24px;
+ border-radius: 999px;
+ border: 1px solid var(--ks-rule);
+ background: var(--ks-gray);
+ position: relative;
+ cursor: pointer;
+ flex: none;
+}
+
+.ks-toggle input::before {
+ content: "";
+ position: absolute;
+ width: 16px;
+ height: 16px;
+ left: 3px;
+ top: 3px;
+ border-radius: 999px;
+ background: var(--ks-text-muted);
+ transition: transform 220ms var(--ks-ease), background 220ms var(--ks-ease);
+}
+
+.ks-toggle input:checked {
+ border-color: var(--ks-patina);
+ background: oklch(48% 0.08 188 / 0.2);
+}
+
+.ks-toggle input:checked::before {
+ transform: translateX(20px);
+ background: var(--ks-patina);
+}
+
+.ks-toggle span { color: var(--ks-ink); font-size: 0.92rem; }
+
+.ks-checkbox {
+ display: flex;
+ align-items: center;
+ gap: 10px;
+ color: var(--ks-ink);
+ font-size: 0.92rem;
+ cursor: pointer;
+}
+
+.ks-checkbox input {
+ appearance: none;
+ width: 18px;
+ height: 18px;
+ border: 1px solid var(--ks-rule);
+ border-radius: var(--ks-radius-sm);
+ background: var(--ks-paper-raised);
+ position: relative;
+ cursor: pointer;
+ flex: none;
+}
+
+.ks-checkbox input:checked {
+ border-color: var(--ks-ink);
+ background: var(--ks-ink);
+}
+
+.ks-checkbox input:checked::after {
+ content: "";
+ position: absolute;
+ left: 5px;
+ top: 2px;
+ width: 5px;
+ height: 9px;
+ border: solid var(--ks-paper-raised);
+ border-width: 0 1.5px 1.5px 0;
+ transform: rotate(45deg);
+}
+
+.ks-select {
+ appearance: none;
+ min-height: 46px;
+ padding: 0 38px 0 14px;
+ border: 1px solid var(--ks-rule);
+ border-radius: var(--ks-radius-sm);
+ background-color: var(--ks-paper-raised);
+ background-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 10 6' fill='none' stroke='%23222222' stroke-width='1.2'%3E%3Cpath d='M1 1l4 4 4-4'/%3E%3C/svg%3E");
+ background-repeat: no-repeat;
+ background-position: right 14px center;
+ background-size: 10px 6px;
+ color: var(--ks-ink);
+ font-size: 0.92rem;
+ cursor: pointer;
+}
+
+/* ============================================================
+ Icon button + tooltip
+ ============================================================ */
+
+.ks-icon-button {
+ width: 32px;
+ height: 32px;
+ display: grid;
+ place-items: center;
+ border: 1px solid var(--ks-rule);
+ border-radius: 999px;
+ background: transparent;
+ color: var(--ks-accent-ink);
+ cursor: pointer;
+}
+
+.ks-tooltip {
+ position: absolute;
+ bottom: calc(100% - 18px);
+ left: 50%;
+ transform: translateX(-50%);
+ width: 200px;
+ padding: 10px 12px;
+ border: 1px solid var(--ks-rule);
+ background: var(--ks-paper-deep);
+ color: var(--ks-ink);
+ font-size: 0.8rem;
+ line-height: 1.4;
+ border-radius: var(--ks-radius-sm);
+ opacity: 0;
+ pointer-events: none;
+ transition: opacity 160ms var(--ks-ease);
+}
+
+.ks-icon-button:focus-visible + .ks-tooltip {
+ opacity: 1;
+}
+
+/* ============================================================
+ Instrument strip: the site's one dark control.
+
+ A row of keys on a dark strip, sitting on the paper like a device on a
+ desk. The active key is raised and carries a gold indicator. Use for tab
+ strips, view switches and command pickers: anything the reader operates.
+ Never for decoration, and never for a link list.
+
+ Markup: <div class="ks-instrument-strip" role="tablist">
+ <button class="ks-instrument-key is-active">One</button>
+ <button class="ks-instrument-key">Two</button>
+ </div>
+ ============================================================ */
+.ks-instrument-strip {
+ display: inline-flex;
+ align-items: center;
+ gap: 2px;
+ padding: 3px;
+ background: var(--ks-instrument);
+ border: 1px solid var(--ks-instrument-deep);
+ border-radius: var(--ks-radius-pill);
+ box-shadow: inset 0 1px 0 var(--ks-instrument-rule), var(--ks-lift-1);
+}
+
+.ks-instrument-key {
+ display: inline-flex;
+ align-items: center;
+ gap: 8px;
+ min-height: var(--ks-control-md);
+ padding: 0 14px 0 12px;
+ color: var(--ks-instrument-muted);
+ background: transparent;
+ border: 0;
+ border-radius: var(--ks-radius-pill);
+ font-family: var(--ks-mono);
+ font-size: var(--ks-type-label-size);
+ letter-spacing: 0.02em;
+ text-transform: none;
+ line-height: 1;
+ white-space: nowrap;
+ cursor: pointer;
+ transition: color var(--ks-quick) var(--ks-ease), background-color var(--ks-quick) var(--ks-ease);
+}
+
+.ks-instrument-key::before {
+ content: "";
+ width: 6px;
+ height: 6px;
+ flex: none;
+ border-radius: 50%;
+ background: var(--ks-instrument-raised);
+ box-shadow: inset 0 0 0 1px var(--ks-instrument-rule);
+ transition: background-color var(--ks-quick) var(--ks-ease), box-shadow var(--ks-quick) var(--ks-ease);
+}
+
+.ks-instrument-key:hover,
+.ks-instrument-key:focus-visible {
+ color: var(--ks-instrument-text);
+}
+
+.ks-instrument-key:focus-visible {
+ outline: 2px solid var(--ks-focus-ring);
+ outline-offset: 2px;
+}
+
+.ks-instrument-key.is-active,
+.ks-instrument-key[aria-selected="true"] {
+ color: var(--ks-instrument-text);
+ background: var(--ks-instrument-raised);
+ box-shadow: inset 0 1px 0 var(--ks-instrument-edge), var(--ks-key-lift);
+}
+
+.ks-instrument-key.is-active::before,
+.ks-instrument-key[aria-selected="true"]::before {
+ background: var(--ks-kinpaku);
+ box-shadow: var(--ks-indicator-glow);
+}
+
+/* ============================================================
+ Grain.
+
+ Grain is part of a material, not a layer over the page. The page ground
+ (the paper) carries it, and so do the moulded surfaces: the recessed
+ track and raised caps of a paper strip, the dark instruments, code
+ blocks. Anything that sits on top of those (a card, a demo, an image,
+ type) is clean. One 160px tile of monochrome noise from an SVG filter,
+ held under 6% on paper and a little higher on dark, where it is what
+ makes a strip read as a part instead of a black rectangle.
+ ============================================================ */
+:root {
+ --ks-grain: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='160' height='160'%3E%3Cfilter id='n' x='0' y='0'%3E%3CfeTurbulence type='fractalNoise' baseFrequency='0.9' numOctaves='2' stitchTiles='stitch'/%3E%3CfeColorMatrix type='saturate' values='0'/%3E%3C/filter%3E%3Crect width='100%25' height='100%25' filter='url(%23n)'/%3E%3C/svg%3E");
+}
+
+/* The paper. Fixed behind the page's content, above the canvas colour. */
+body {
+ position: relative;
+ isolation: isolate;
+}
+
+body::before {
+ content: "";
+ position: fixed;
+ inset: 0;
+ z-index: -1;
+ pointer-events: none;
+ opacity: 0.055;
+ mix-blend-mode: multiply;
+ background-image: var(--ks-grain);
+ background-size: 160px 160px;
+}
+
+/* Moulded surfaces. The pseudo sits under the surface's own children. */
+.ks-grain,
+.ks-instrument-strip {
+ position: relative;
+}
+
+.ks-grain::before,
+.ks-instrument-strip::before {
+ content: "";
+ position: absolute;
+ inset: 0;
+ z-index: 0;
+ border-radius: inherit;
+ pointer-events: none;
+ opacity: 0.16;
+ mix-blend-mode: screen;
+ will-change: opacity;
+ background-image: var(--ks-grain);
+ background-size: 160px 160px;
+}
+
+.ks-instrument-strip.is-paper::before {
+ opacity: 0.05;
+ mix-blend-mode: normal;
+}
+
+/* The strip is its own stacking context: grain at 0, the cap at 1, the
+ labels at 2, whatever the page around it does. */
+.ks-instrument-strip {
+ isolation: isolate;
+}
+
+
+.ks-instrument-strip > :not(.ks-thumb) {
+ position: relative;
+ z-index: 2;
+}
+
+/* ============================================================
+ Switch: a physical slide switch for one on/off state.
+
+ A recessed track, a raised knob that slides from left (off) to right
+ (on), and a lit dot on the knob when on. Markup:
+ <button class="ks-switch" type="button" aria-pressed="true">
+ <span class="ks-switch-track" aria-hidden="true"><span class="ks-switch-knob"></span></span>
+ <span class="ks-switch-label">Detector on</span>
+ </button>
+ ============================================================ */
+.ks-switch {
+ display: inline-flex;
+ align-items: center;
+ gap: 10px;
+ padding: 0;
+ border: 0;
+ background: transparent;
+ color: var(--ks-text-muted);
+ font-family: var(--ks-font);
+ font-size: var(--ks-type-ui-size);
+ font-weight: 500;
+ cursor: pointer;
+}
+
+.ks-switch[aria-pressed="true"] {
+ color: var(--ks-ink);
+}
+
+.ks-switch-track {
+ position: relative;
+ width: 44px;
+ height: 24px;
+ border-radius: var(--ks-radius-pill);
+ background: var(--ks-gray-2);
+ box-shadow: var(--ks-track-recess);
+ transition: background-color var(--ks-quick) var(--ks-ease);
+}
+
+.ks-switch-knob {
+ position: absolute;
+ top: 3px;
+ left: 3px;
+ width: 18px;
+ height: 18px;
+ border-radius: 50%;
+ background: var(--ks-paper-raised);
+ box-shadow: var(--ks-cap-lift);
+ transition: transform 220ms cubic-bezier(0.3, 0.7, 0.2, 1);
+}
+
+.ks-switch-knob::after {
+ content: "";
+ position: absolute;
+ top: 50%;
+ left: 50%;
+ width: 6px;
+ height: 6px;
+ border-radius: 50%;
+ transform: translate(-50%, -50%);
+ background: var(--ks-gray-2);
+ box-shadow: inset 0 1px 1px oklch(13% 0 0 / 0.18);
+ transition: background-color var(--ks-quick) var(--ks-ease), box-shadow var(--ks-quick) var(--ks-ease);
+}
+
+.ks-switch[aria-pressed="true"] .ks-switch-knob {
+ transform: translateX(20px);
+}
+
+.ks-switch[aria-pressed="true"] .ks-switch-knob::after {
+ background: var(--ks-patina);
+ box-shadow: var(--ks-led);
+}
+
+.ks-switch:active .ks-switch-knob {
+ box-shadow: var(--ks-cap-press);
+}
+
+.ks-switch:focus-visible {
+ outline: none;
+}
+
+.ks-switch:focus-visible .ks-switch-track {
+ outline: 2px solid var(--ks-kinpaku);
+ outline-offset: 2px;
+}
+
+/* ============================================================
+ Tag: the brand's label.
+
+ The detector flags bad design with a small gold tag carrying dark mono
+ text. That tag is the one device a visitor already associates with
+ Impeccable, so it is also how the site labels things: section numerals,
+ a card's state, a release's status. Small, mono, ink on gold. It is the
+ only gold fill allowed on paper, and it never grows past a label.
+ ============================================================ */
+.ks-tag {
+ display: inline-flex;
+ align-items: center;
+ gap: 6px;
+ min-height: 22px;
+ padding: 0 7px;
+ color: var(--ks-ink);
+ background: var(--ks-kinpaku);
+ border-radius: var(--ks-radius-sm);
+ font-family: var(--ks-mono);
+ font-size: var(--ks-type-eyebrow-size);
+ font-weight: 600;
+ letter-spacing: 0.02em;
+ line-height: normal;
+ text-transform: uppercase;
+ white-space: nowrap;
+ vertical-align: middle;
+}
+
+/* A quiet tag for a secondary label sitting next to a gold one. */
+.ks-tag.is-quiet {
+ color: var(--ks-text-muted);
+ background: var(--ks-gray);
+}
+
+/* Paper variant. A page control (a view switch, a tab row) sits on paper
+ and keeps the gold dot, so it does not compete with the primary action
+ the way a dark strip does. The dark strip is for product chrome: the
+ live picker, lab toolbars, terminals. */
+
+.ks-instrument-strip.is-paper {
+ background: var(--ks-gray);
+ border-color: transparent;
+ box-shadow: var(--ks-track-recess);
+}
+
+.ks-instrument-strip.is-paper .ks-instrument-key {
+ color: var(--ks-text-muted);
+ transition: color var(--ks-quick) var(--ks-ease), background-color var(--ks-quick) var(--ks-ease), box-shadow var(--ks-quick) var(--ks-ease), transform var(--ks-quick) var(--ks-ease);
+}
+
+.ks-instrument-strip.is-paper .ks-instrument-key::before {
+ background: var(--ks-gray-2);
+ box-shadow: inset 0 1px 1px oklch(13% 0 0 / 0.18);
+}
+
+.ks-instrument-strip.is-paper .ks-instrument-key:hover,
+.ks-instrument-strip.is-paper .ks-instrument-key:focus-visible {
+ color: var(--ks-ink);
+}
+
+.ks-instrument-strip.is-paper .ks-instrument-key:active {
+ box-shadow: var(--ks-cap-press);
+ transform: translateY(1px);
+}
+
+/* The raised cap. Light from above: a white edge on top, a hard shadow
+ underneath, so it stands a millimetre proud of the track. */
+.ks-instrument-strip.is-paper .ks-instrument-key.is-active,
+.ks-instrument-strip.is-paper .ks-instrument-key[aria-selected="true"],
+.ks-instrument-strip.is-paper .ks-instrument-key[aria-pressed="true"] {
+ color: var(--ks-ink);
+ background: var(--ks-paper-raised);
+ box-shadow: var(--ks-cap-lift);
+}
+
+.ks-instrument-strip.is-paper .ks-instrument-key.is-active::before,
+.ks-instrument-strip.is-paper .ks-instrument-key[aria-selected="true"]::before,
+.ks-instrument-strip.is-paper .ks-instrument-key[aria-pressed="true"]::before {
+ background: var(--ks-patina);
+ box-shadow: 0 0 0 1px oklch(13% 0 0 / 0.12), 0 0 4px color-mix(in oklch, var(--ks-patina) 60%, transparent);
+}
+
+.ks-instrument-strip.is-paper .ks-instrument-key:focus-visible {
+ outline: 2px solid var(--ks-focus-ring);
+ outline-offset: 1px;
+}
+
+/* ============================================================
+ Instrument strip thumb (real element, positioned by
+ instrument-strip.js). Last in the file on purpose: these override the
+ key's own cap, and they must come after every key rule above.
+ ============================================================ */
+.ks-thumb {
+ position: absolute;
+ top: 3px;
+ bottom: 3px;
+ left: 0;
+ width: 0;
+ border-radius: var(--ks-radius-pill);
+ background: var(--ks-instrument-raised);
+ box-shadow: inset 0 1px 0 var(--ks-instrument-edge), var(--ks-key-lift);
+ transition: transform 360ms cubic-bezier(0.22, 1, 0.3, 1);
+ pointer-events: none;
+ z-index: 1;
+}
+
+.ks-instrument-strip.is-paper .ks-thumb {
+ background: var(--ks-paper-raised);
+ box-shadow: var(--ks-cap-lift);
+}
+
+.ks-instrument-strip.has-thumb .ks-instrument-key,
+.ks-instrument-strip.has-thumb .ks-instrument-key.is-active,
+.ks-instrument-strip.has-thumb .ks-instrument-key[aria-selected="true"],
+.ks-instrument-strip.has-thumb .ks-instrument-key[aria-pressed="true"],
+.ks-instrument-strip.is-paper.has-thumb .ks-instrument-key.is-active,
+.ks-instrument-strip.is-paper.has-thumb .ks-instrument-key[aria-selected="true"],
+.ks-instrument-strip.is-paper.has-thumb .ks-instrument-key[aria-pressed="true"] {
+ background: transparent;
+ box-shadow: none;
+ transform: none;
+ transition: color 120ms var(--ks-ease);
+}
+
+.ks-instrument-strip.has-thumb .ks-instrument-key::before {
+ transition: background-color 120ms var(--ks-ease), box-shadow 120ms var(--ks-ease);
+}
+
+/* Dark instruments need the light state color for keyboard focus. */
+.ks-instrument-strip:not(.is-paper),
+.live-demo-gbar,
+.live-demo-ctx,
+.worlds-rating {
+ --ks-focus-ring: var(--ks-patina);
+}
+
+/* Touch gets the kit's large target, without enlarging the desktop controls
+ or their labels. Pointer capability also covers tablets with a keyboard. */
+@media (any-pointer: coarse) {
+ .ks-instrument-strip .ks-instrument-key,
+ .ks-segmented button {
+ min-height: var(--ks-control-lg);
+ min-width: var(--ks-control-lg);
+ }
+
+ .site-header-menu {
+ width: var(--ks-control-lg);
+ height: var(--ks-control-lg);
+ }
+
+ .kinpaku-chrome .site-header-brand,
+ .kinpaku-chrome .site-header-github {
+ min-height: var(--ks-control-lg);
+ }
+
+ .kinpaku-chrome .site-header-nav a {
+ min-height: var(--ks-control-lg);
+ min-width: var(--ks-control-lg);
+ padding-block: 10px;
+ }
+}
diff --git a/ui/component-review/vendor/kinpaku-tokens.css b/ui/component-review/vendor/kinpaku-tokens.css
new file mode 100644
index 000000000..5cb08c9dc
--- /dev/null
+++ b/ui/component-review/vendor/kinpaku-tokens.css
@@ -0,0 +1,221 @@
+/* VENDORED from impeccable-site/site/styles/kinpaku-tokens.css (the source of truth).
+ Do not edit here: change the site, then run node scripts/sync-kinpaku-kit.mjs. */
+/*
+ * impeccable.style tokens (page-global, single source of truth)
+ *
+ * One theme. The page is neutral paper, the type is ink, and the brand gold
+ * appears as a mark, a line, or an indicator on a dark control surface. It
+ * never carries text and it never fills a large area on paper.
+ *
+ * Three families of surface:
+ * paper the page and everything that sits flat on it
+ * gray chips, inactive fills, sunk wells
+ * instrument dark control surfaces: sliders, tab strips, segmented
+ * controls, terminals. This is where gold and patina signal.
+ *
+ * New pages read these via var(--ks-*) rather than hand-typing oklch values.
+ * Pages may override a token locally when there is a documented reason.
+ * When in doubt, do not override; match.
+ */
+
+:root {
+ color-scheme: light;
+
+ /* ============================================================
+ Brand anchors. Kinpaku gold is the mark and the signal. Verdigris
+ patina carries state, links, and selection wherever color has to
+ be read as text, because gold cannot pass contrast on paper.
+ ============================================================ */
+
+ /* Kinpaku gold. Fills on instruments, the mark, hairlines, and the label
+ of the active key on a dark instrument. Never text on paper. */
+ --ks-kinpaku: oklch(84% 0.19 80.46); /* mark, indicators, gold fills on instruments */
+ --ks-kinpaku-vivid: oklch(87% 0.20 85); /* lit hover on a gold fill */
+ --ks-kinpaku-pale: oklch(86% 0.07 84); /* pale tint; rarely needed on paper */
+ --ks-kinpaku-rich: oklch(77% 0.13 82); /* hairline gold on paper, active rule */
+ --ks-kinpaku-deep: oklch(61% 0.085 78); /* gold border against paper */
+ --ks-on-gold: oklch(14% 0.018 95); /* foreground on a gold fill */
+ --ks-gold-line: var(--ks-kinpaku-rich); /* the one-pixel gold rule */
+
+ /* Verdigris patina. State, links, selection. */
+ --ks-patina: oklch(70% 0.12 188); /* indicator on instruments, focus */
+ --ks-patina-pale: oklch(82% 0.07 188); /* soft fill behind a selected row */
+ --ks-patina-deep: oklch(45% 0.10 190); /* text-safe patina, including selected gray surfaces */
+ --ks-patina-ink: oklch(41% 0.11 190); /* hover on patina text */
+
+ /* Semantic foregrounds. Labels, eyebrows and category names are muted
+ ink; color is not how this site labels things. Patina is reserved for
+ state: selected, live, passed. */
+ --ks-gold-ink: var(--ks-text-muted);
+ --ks-accent-ink: var(--ks-text-muted);
+ --ks-state-ink: var(--ks-patina-deep);
+ --ks-focus-ring: var(--ks-patina-deep); /* paper; dark controls override locally */
+ --ks-kinpaku-ink: var(--ks-text-muted); /* legacy alias, same rule */
+
+ /* Links on paper are ink with a quiet underline; the underline turns
+ gold on hover, which is the brand as a line. */
+ --ks-link-on-paper: var(--ks-ink);
+ --ks-link-on-paper-hover: var(--ks-ink);
+ --ks-link-on-paper-line: oklch(13% 0 0 / 0.28);
+ --ks-link-on-paper-line-hover: var(--ks-kinpaku);
+ --ks-nav-active: var(--ks-ink);
+
+ /* Warning. Failures and warnings only. */
+ --ks-vermilion: oklch(52% 0.16 35);
+
+ /* ============================================================
+ Paper. The page ground is a hair below white so a raised card can
+ read as raised. Neutral, no warm cast: gold on cream is gold on gold.
+ ============================================================ */
+ --ks-paper: oklch(97.8% 0 0); /* page ground */
+ --ks-paper-raised: oklch(99.5% 0 0); /* cards, panels, inputs */
+ --ks-paper-deep: oklch(95% 0 0); /* sunk wells, code blocks, footer */
+ --ks-gray: oklch(92% 0 0); /* chips, inactive fills */
+ --ks-gray-2: oklch(88% 0 0); /* one step down from gray */
+
+ /* ============================================================
+ Instrument. Dark control surfaces on the paper, like a device on a
+ desk. The only place the site goes dark, and the only place gold is
+ read as a signal rather than a mark.
+ ============================================================ */
+ --ks-instrument: oklch(24% 0 0); /* face */
+ --ks-instrument-deep: oklch(17% 0 0); /* track, well */
+ --ks-instrument-raised: oklch(31% 0 0); /* key cap, thumb */
+ --ks-instrument-text: oklch(93% 0 0);
+ --ks-instrument-muted: oklch(68% 0 0);
+ --ks-instrument-rule: oklch(100% 0 0 / 0.12);
+ --ks-instrument-edge: oklch(100% 0 0 / 0.3);
+
+ /* ============================================================
+ Ink. Neutral. Body copy is --ks-text; headlines and <strong> are
+ --ks-ink. Muted is for labels and captions, faint for meta.
+ ============================================================ */
+ --ks-ink: oklch(13% 0 0); /* headlines, <strong>, active nav */
+ --ks-text: oklch(22% 0 0); /* body */
+ --ks-text-muted: oklch(46% 0 0); /* captions, meta, eyebrows */
+ --ks-text-faint: oklch(51% 0 0); /* subdued meta, readable on paper and gray */
+ --ks-text-mute-deep: oklch(66% 0 0); /* disabled */
+
+ /* ============================================================
+ Rules. A divider is faint. The boundary of a control is not:
+ WCAG 1.4.11 asks 3:1 of anything that tells you where a control is.
+ Use --ks-rule to divide, --ks-edge to bound something you can operate.
+ ============================================================ */
+ --ks-rule: oklch(13% 0 0 / 0.08);
+ --ks-edge: oklch(13% 0 0 / 0.45);
+
+ /* ============================================================
+ Control scales. Three radii, three heights, two lifts.
+ ============================================================ */
+ --ks-radius-sm: 3px;
+ --ks-radius-md: 8px;
+ --ks-radius-pill: 999px;
+
+ --ks-control-sm: 26px;
+ --ks-control-md: 32px;
+ --ks-control-lg: 44px;
+
+ /* Section cadence. Every top-level section on a page takes this vertical
+ padding, so the seams between sections are one rhythm. */
+ --ks-section-pad: clamp(72px, 8vw, 120px);
+
+ /* Layered, so they read as one soft light from above rather than a
+ single blurred rectangle: a contact edge, a short throw, a long one. */
+ --ks-lift-1: 0 1px 1px oklch(13% 0 0 / 0.05), 0 2px 3px oklch(13% 0 0 / 0.04), 0 6px 12px oklch(13% 0 0 / 0.05);
+ --ks-lift-2: 0 1px 1px oklch(13% 0 0 / 0.04), 0 3px 5px oklch(13% 0 0 / 0.05), 0 12px 20px oklch(13% 0 0 / 0.06), 0 32px 48px oklch(13% 0 0 / 0.07);
+
+ /* Instrument depth. A raised key sits a pixel off its dark strip, and the
+ lit indicator throws a short gold glow. These are the only shadows that
+ read against a dark surface. */
+ --ks-key-lift: 0 1px 2px oklch(0% 0 0 / 0.4);
+
+ /* Light hardware. A paper key is a raised cap: a white highlight along
+ its top edge, a hard 1px shadow under it, a soft one behind. The track
+ it sits in is recessed. Gold is the lit indicator. */
+ --ks-cap-lift: inset 0 1px 0 oklch(100% 0 0 / 0.9), 0 1px 0 oklch(13% 0 0 / 0.14), 0 2px 3px oklch(13% 0 0 / 0.08);
+ --ks-cap-press: inset 0 1px 2px oklch(13% 0 0 / 0.14);
+ --ks-track-recess: inset 0 1px 3px oklch(13% 0 0 / 0.16), inset 0 -1px 0 oklch(100% 0 0 / 0.7);
+ --ks-led: 0 0 0 1px oklch(13% 0 0 / 0.12), 0 0 4px oklch(84% 0.19 80 / 0.6);
+ --ks-indicator-glow: 0 0 0 1px oklch(0% 0 0 / 0.3), 0 0 4px oklch(84% 0.19 80 / 0.65);
+
+ /* ============================================================
+ Code. Inline code is a gray chip. Blocks and CLI commands are a sunk
+ paper well with a hairline. A command that is itself a link reads as
+ a link.
+ ============================================================ */
+ --ks-code-fg: var(--ks-ink);
+ --ks-code-bg: var(--ks-gray);
+ --ks-code-radius: 3px;
+ --ks-code-pad: 0.2em 0.45em;
+ --ks-code-block-fg: var(--ks-text);
+ --ks-code-block-bg: var(--ks-paper-deep);
+ --ks-code-block-border: var(--ks-rule);
+ --ks-code-block-radius: 3px;
+ --ks-code-cmd: var(--ks-link-on-paper);
+
+ /* ============================================================
+ Typography. One family for everything that is read: Albert Sans, a
+ quiet geometric humanist, at normal weights. The wordmark keeps
+ Alumni Sans because it is part of the logo lockup, and that is the
+ only place it appears.
+ ============================================================ */
+ --ks-font: "Albert Sans", "Avenir Next", "Helvetica Neue", Arial, system-ui, sans-serif;
+ --ks-font-display: var(--ks-font-wordmark); /* Alumni Sans: the brand's own display voice, at a weight that holds on paper */
+ --ks-font-wordmark: "Alumni Sans", "Albert Sans", Arial, sans-serif;
+ --ks-mono: "JetBrains Mono", ui-monospace, "SFMono-Regular", Menlo, Consolas, monospace;
+
+ /* Display: page h1. */
+ --ks-type-display-size: clamp(3.2rem, 6.2vw, 5.6rem);
+ --ks-type-display-weight: 200;
+ --ks-type-display-line: 1.0;
+ --ks-type-display-track: 0;
+
+ /* Headline: section h2. */
+ --ks-type-headline-size: clamp(2.4rem, 3.6vw, 3.4rem);
+ --ks-type-headline-weight: 300;
+ --ks-type-headline-line: 1.04;
+ --ks-type-headline-track: 0;
+
+ /* Title: card and panel headings (h3). */
+ --ks-type-title-size: 1.0625rem;
+ --ks-type-title-weight: 600;
+ --ks-type-title-line: 1.35;
+
+ /* Body. */
+ --ks-type-body-size: 1rem;
+ --ks-type-body-line: 1.65;
+
+ /* Eyebrow: small mono labels above titles. */
+ --ks-type-eyebrow-size: 0.6875rem;
+ --ks-type-eyebrow-track: 0.14em;
+
+ /* Wordmark: IMPECCABLE in the header. */
+ --ks-type-wordmark-size: 1.25rem;
+ --ks-type-wordmark-track: 0.18em;
+
+ /* Mono: code, terminal, audit lines. */
+ --ks-type-mono-size: 0.6875rem;
+ --ks-type-mono-track: 0.12em;
+
+ /* Dense UI ramp. Micro is the floor for anything functional. */
+ --ks-type-micro-size: 0.6875rem; /* 11px */
+ --ks-type-label-size: 0.75rem; /* 12px */
+ --ks-type-ui-size: 0.8125rem; /* 13px */
+ --ks-type-ui-lead: 0.9375rem; /* 15px */
+
+ /* Reading ramp between body and headline. Small is secondary body copy
+ and captions that are read, not scanned; lead and subhead are the
+ intro paragraph and the card-level heading; title-lg is a bento tile
+ or panel heading that is larger than a card title but not a section. */
+ --ks-type-small-size: 0.875rem; /* 14px */
+ --ks-type-lead-size: 1.125rem; /* 18px */
+ --ks-type-subhead-size: 1.25rem; /* 20px */
+ --ks-type-title-lg-size: 1.5rem; /* 24px */
+
+ /* ============================================================
+ Motion. Quick is a state change, settle is something arriving.
+ ============================================================ */
+ --ks-ease: cubic-bezier(0.2, 0.8, 0.2, 1);
+ --ks-quick: 120ms;
+ --ks-settle: 200ms;
+}
diff --git a/ui/component-review/vendor/kit-css.ts b/ui/component-review/vendor/kit-css.ts
new file mode 100644
index 000000000..f4d82e043
--- /dev/null
+++ b/ui/component-review/vendor/kit-css.ts
@@ -0,0 +1,4 @@
+// GENERATED from the vendored stylesheets by scripts/sync-kinpaku-kit.mjs. Do not edit.
+export const tokens = "/* VENDORED from impeccable-site/site/styles/kinpaku-tokens.css (the source of truth).\n Do not edit here: change the site, then run node scripts/sync-kinpaku-kit.mjs. */\n/*\n * impeccable.style tokens (page-global, single source of truth)\n *\n * One theme. The page is neutral paper, the type is ink, and the brand gold\n * appears as a mark, a line, or an indicator on a dark control surface. It\n * never carries text and it never fills a large area on paper.\n *\n * Three families of surface:\n * paper the page and everything that sits flat on it\n * gray chips, inactive fills, sunk wells\n * instrument dark control surfaces: sliders, tab strips, segmented\n * controls, terminals. This is where gold and patina signal.\n *\n * New pages read these via var(--ks-*) rather than hand-typing oklch values.\n * Pages may override a token locally when there is a documented reason.\n * When in doubt, do not override; match.\n */\n\n:root {\n\tcolor-scheme: light;\n\n\t/* ============================================================\n\t Brand anchors. Kinpaku gold is the mark and the signal. Verdigris\n\t patina carries state, links, and selection wherever color has to\n\t be read as text, because gold cannot pass contrast on paper.\n\t ============================================================ */\n\n\t/* Kinpaku gold. Fills on instruments, the mark, hairlines, and the label\n\t of the active key on a dark instrument. Never text on paper. */\n\t--ks-kinpaku: oklch(84% 0.19 80.46); /* mark, indicators, gold fills on instruments */\n\t--ks-kinpaku-vivid: oklch(87% 0.20 85); /* lit hover on a gold fill */\n\t--ks-kinpaku-pale: oklch(86% 0.07 84); /* pale tint; rarely needed on paper */\n\t--ks-kinpaku-rich: oklch(77% 0.13 82); /* hairline gold on paper, active rule */\n\t--ks-kinpaku-deep: oklch(61% 0.085 78); /* gold border against paper */\n\t--ks-on-gold: oklch(14% 0.018 95); /* foreground on a gold fill */\n\t--ks-gold-line: var(--ks-kinpaku-rich); /* the one-pixel gold rule */\n\n\t/* Verdigris patina. State, links, selection. */\n\t--ks-patina: oklch(70% 0.12 188); /* indicator on instruments, focus */\n\t--ks-patina-pale: oklch(82% 0.07 188); /* soft fill behind a selected row */\n\t--ks-patina-deep: oklch(45% 0.10 190); /* text-safe patina, including selected gray surfaces */\n\t--ks-patina-ink: oklch(41% 0.11 190); /* hover on patina text */\n\n\t/* Semantic foregrounds. Labels, eyebrows and category names are muted\n\t ink; color is not how this site labels things. Patina is reserved for\n\t state: selected, live, passed. */\n\t--ks-gold-ink: var(--ks-text-muted);\n\t--ks-accent-ink: var(--ks-text-muted);\n\t--ks-state-ink: var(--ks-patina-deep);\n\t--ks-focus-ring: var(--ks-patina-deep); /* paper; dark controls override locally */\n\t--ks-kinpaku-ink: var(--ks-text-muted); /* legacy alias, same rule */\n\n\t/* Links on paper are ink with a quiet underline; the underline turns\n\t gold on hover, which is the brand as a line. */\n\t--ks-link-on-paper: var(--ks-ink);\n\t--ks-link-on-paper-hover: var(--ks-ink);\n\t--ks-link-on-paper-line: oklch(13% 0 0 / 0.28);\n\t--ks-link-on-paper-line-hover: var(--ks-kinpaku);\n\t--ks-nav-active: var(--ks-ink);\n\n\t/* Warning. Failures and warnings only. */\n\t--ks-vermilion: oklch(52% 0.16 35);\n\n\t/* ============================================================\n\t Paper. The page ground is a hair below white so a raised card can\n\t read as raised. Neutral, no warm cast: gold on cream is gold on gold.\n\t ============================================================ */\n\t--ks-paper: oklch(97.8% 0 0); /* page ground */\n\t--ks-paper-raised: oklch(99.5% 0 0); /* cards, panels, inputs */\n\t--ks-paper-deep: oklch(95% 0 0); /* sunk wells, code blocks, footer */\n\t--ks-gray: oklch(92% 0 0); /* chips, inactive fills */\n\t--ks-gray-2: oklch(88% 0 0); /* one step down from gray */\n\n\t/* ============================================================\n\t Instrument. Dark control surfaces on the paper, like a device on a\n\t desk. The only place the site goes dark, and the only place gold is\n\t read as a signal rather than a mark.\n\t ============================================================ */\n\t--ks-instrument: oklch(24% 0 0); /* face */\n\t--ks-instrument-deep: oklch(17% 0 0); /* track, well */\n\t--ks-instrument-raised: oklch(31% 0 0); /* key cap, thumb */\n\t--ks-instrument-text: oklch(93% 0 0);\n\t--ks-instrument-muted: oklch(68% 0 0);\n\t--ks-instrument-rule: oklch(100% 0 0 / 0.12);\n\t--ks-instrument-edge: oklch(100% 0 0 / 0.3);\n\n\t/* ============================================================\n\t Ink. Neutral. Body copy is --ks-text; headlines and <strong> are\n\t --ks-ink. Muted is for labels and captions, faint for meta.\n\t ============================================================ */\n\t--ks-ink: oklch(13% 0 0); /* headlines, <strong>, active nav */\n\t--ks-text: oklch(22% 0 0); /* body */\n\t--ks-text-muted: oklch(46% 0 0); /* captions, meta, eyebrows */\n\t--ks-text-faint: oklch(51% 0 0); /* subdued meta, readable on paper and gray */\n\t--ks-text-mute-deep: oklch(66% 0 0); /* disabled */\n\n\t/* ============================================================\n\t Rules. A divider is faint. The boundary of a control is not:\n\t WCAG 1.4.11 asks 3:1 of anything that tells you where a control is.\n\t Use --ks-rule to divide, --ks-edge to bound something you can operate.\n\t ============================================================ */\n\t--ks-rule: oklch(13% 0 0 / 0.08);\n\t--ks-edge: oklch(13% 0 0 / 0.45);\n\n\t/* ============================================================\n\t Control scales. Three radii, three heights, two lifts.\n\t ============================================================ */\n\t--ks-radius-sm: 3px;\n\t--ks-radius-md: 8px;\n\t--ks-radius-pill: 999px;\n\n\t--ks-control-sm: 26px;\n\t--ks-control-md: 32px;\n\t--ks-control-lg: 44px;\n\n\t/* Section cadence. Every top-level section on a page takes this vertical\n\t padding, so the seams between sections are one rhythm. */\n\t--ks-section-pad: clamp(72px, 8vw, 120px);\n\n\t/* Layered, so they read as one soft light from above rather than a\n\t single blurred rectangle: a contact edge, a short throw, a long one. */\n\t--ks-lift-1: 0 1px 1px oklch(13% 0 0 / 0.05), 0 2px 3px oklch(13% 0 0 / 0.04), 0 6px 12px oklch(13% 0 0 / 0.05);\n\t--ks-lift-2: 0 1px 1px oklch(13% 0 0 / 0.04), 0 3px 5px oklch(13% 0 0 / 0.05), 0 12px 20px oklch(13% 0 0 / 0.06), 0 32px 48px oklch(13% 0 0 / 0.07);\n\n\t/* Instrument depth. A raised key sits a pixel off its dark strip, and the\n\t lit indicator throws a short gold glow. These are the only shadows that\n\t read against a dark surface. */\n\t--ks-key-lift: 0 1px 2px oklch(0% 0 0 / 0.4);\n\n\t/* Light hardware. A paper key is a raised cap: a white highlight along\n\t its top edge, a hard 1px shadow under it, a soft one behind. The track\n\t it sits in is recessed. Gold is the lit indicator. */\n\t--ks-cap-lift: inset 0 1px 0 oklch(100% 0 0 / 0.9), 0 1px 0 oklch(13% 0 0 / 0.14), 0 2px 3px oklch(13% 0 0 / 0.08);\n\t--ks-cap-press: inset 0 1px 2px oklch(13% 0 0 / 0.14);\n\t--ks-track-recess: inset 0 1px 3px oklch(13% 0 0 / 0.16), inset 0 -1px 0 oklch(100% 0 0 / 0.7);\n\t--ks-led: 0 0 0 1px oklch(13% 0 0 / 0.12), 0 0 4px oklch(84% 0.19 80 / 0.6);\n\t--ks-indicator-glow: 0 0 0 1px oklch(0% 0 0 / 0.3), 0 0 4px oklch(84% 0.19 80 / 0.65);\n\n\t/* ============================================================\n\t Code. Inline code is a gray chip. Blocks and CLI commands are a sunk\n\t paper well with a hairline. A command that is itself a link reads as\n\t a link.\n\t ============================================================ */\n\t--ks-code-fg: var(--ks-ink);\n\t--ks-code-bg: var(--ks-gray);\n\t--ks-code-radius: 3px;\n\t--ks-code-pad: 0.2em 0.45em;\n\t--ks-code-block-fg: var(--ks-text);\n\t--ks-code-block-bg: var(--ks-paper-deep);\n\t--ks-code-block-border: var(--ks-rule);\n\t--ks-code-block-radius: 3px;\n\t--ks-code-cmd: var(--ks-link-on-paper);\n\n\t/* ============================================================\n\t Typography. One family for everything that is read: Albert Sans, a\n\t quiet geometric humanist, at normal weights. The wordmark keeps\n\t Alumni Sans because it is part of the logo lockup, and that is the\n\t only place it appears.\n\t ============================================================ */\n\t--ks-font: \"Albert Sans\", \"Avenir Next\", \"Helvetica Neue\", Arial, system-ui, sans-serif;\n\t--ks-font-display: var(--ks-font-wordmark); /* Alumni Sans: the brand's own display voice, at a weight that holds on paper */\n\t--ks-font-wordmark: \"Alumni Sans\", \"Albert Sans\", Arial, sans-serif;\n\t--ks-mono: \"JetBrains Mono\", ui-monospace, \"SFMono-Regular\", Menlo, Consolas, monospace;\n\n\t/* Display: page h1. */\n\t--ks-type-display-size: clamp(3.2rem, 6.2vw, 5.6rem);\n\t--ks-type-display-weight: 200;\n\t--ks-type-display-line: 1.0;\n\t--ks-type-display-track: 0;\n\n\t/* Headline: section h2. */\n\t--ks-type-headline-size: clamp(2.4rem, 3.6vw, 3.4rem);\n\t--ks-type-headline-weight: 300;\n\t--ks-type-headline-line: 1.04;\n\t--ks-type-headline-track: 0;\n\n\t/* Title: card and panel headings (h3). */\n\t--ks-type-title-size: 1.0625rem;\n\t--ks-type-title-weight: 600;\n\t--ks-type-title-line: 1.35;\n\n\t/* Body. */\n\t--ks-type-body-size: 1rem;\n\t--ks-type-body-line: 1.65;\n\n\t/* Eyebrow: small mono labels above titles. */\n\t--ks-type-eyebrow-size: 0.6875rem;\n\t--ks-type-eyebrow-track: 0.14em;\n\n\t/* Wordmark: IMPECCABLE in the header. */\n\t--ks-type-wordmark-size: 1.25rem;\n\t--ks-type-wordmark-track: 0.18em;\n\n\t/* Mono: code, terminal, audit lines. */\n\t--ks-type-mono-size: 0.6875rem;\n\t--ks-type-mono-track: 0.12em;\n\n\t/* Dense UI ramp. Micro is the floor for anything functional. */\n\t--ks-type-micro-size: 0.6875rem; /* 11px */\n\t--ks-type-label-size: 0.75rem; /* 12px */\n\t--ks-type-ui-size: 0.8125rem; /* 13px */\n\t--ks-type-ui-lead: 0.9375rem; /* 15px */\n\n\t/* Reading ramp between body and headline. Small is secondary body copy\n\t and captions that are read, not scanned; lead and subhead are the\n\t intro paragraph and the card-level heading; title-lg is a bento tile\n\t or panel heading that is larger than a card title but not a section. */\n\t--ks-type-small-size: 0.875rem; /* 14px */\n\t--ks-type-lead-size: 1.125rem; /* 18px */\n\t--ks-type-subhead-size: 1.25rem; /* 20px */\n\t--ks-type-title-lg-size: 1.5rem; /* 24px */\n\n\t/* ============================================================\n\t Motion. Quick is a state change, settle is something arriving.\n\t ============================================================ */\n\t--ks-ease: cubic-bezier(0.2, 0.8, 0.2, 1);\n\t--ks-quick: 120ms;\n\t--ks-settle: 200ms;\n}\n";
+export const kit = "/* VENDORED from impeccable-site/site/styles/kinpaku-kit.css (buttons, tabs, select, icon button, instrument strip, grain, switch, paper strip, thumb) (the source of truth).\n Do not edit here: change the site, then run node scripts/sync-kinpaku-kit.mjs. */\n/* ============================================================\n Buttons: primary, secondary, ghost, disabled\n\n The primary action is ink on paper. Gold does not fill a button on this\n site: a gold slab on paper is the hotel-lobby read. The brand is present\n on the primary as the gold arrow, not as the fill.\n\n Variants chain on .ks-button so specificity (0,2,0) wins over generic page\n anchor resets like `.kinpaku-system-page a { color: inherit }` (0,1,1).\n Use class=\"ks-button ks-button-primary\", both classes required.\n ============================================================ */\n\n.ks-button {\n position: relative;\n min-height: var(--ks-control-lg);\n display: inline-flex;\n align-items: center;\n justify-content: center;\n gap: 12px;\n padding: 0 22px;\n border-radius: var(--ks-radius-sm);\n font-family: var(--ks-font);\n font-size: 0.9375rem;\n font-weight: 500;\n line-height: 1;\n letter-spacing: -0.005em;\n text-decoration: none;\n border: 1px solid transparent;\n cursor: pointer;\n transition: background-color var(--ks-quick) var(--ks-ease), border-color var(--ks-quick) var(--ks-ease), color var(--ks-quick) var(--ks-ease);\n}\n\n.ks-button .ks-button-arrow {\n width: 16px;\n height: 8px;\n display: inline-block;\n flex: none;\n}\n\n.ks-button-arrow svg { width: 100%; height: 100%; display: block; overflow: visible; }\n\n/* The arrow says where the button goes. On a button whose target is further\n down the page (an in-page anchor, or .is-down on the arrow) it curves and\n points downward on hover, and straightens again on leave. The rest shape\n is set here too, as the same command list, so the two interpolate. */\n.ks-button-arrow path {\n d: path(\"M0 4C5 4 9 4 14 4M10 0L14 4L10 8\");\n transition: d 420ms var(--ks-ease);\n}\n\n.ks-button[href^=\"#\"]:hover .ks-button-arrow path,\n.ks-button:hover .ks-button-arrow.is-down path {\n d: path(\"M0 4C7 4 11 4 11 11M7 7L11 11L15 7\");\n}\n\n@media (prefers-reduced-motion: reduce) {\n .ks-button-arrow path { transition: none; }\n}\n\n.ks-button.ks-button-primary {\n color: var(--ks-paper-raised);\n background: var(--ks-ink);\n border-color: var(--ks-ink);\n}\n\n.ks-button.ks-button-primary .ks-button-arrow {\n color: var(--ks-kinpaku);\n}\n\n.ks-button.ks-button-primary:hover {\n color: var(--ks-paper-raised);\n background: var(--ks-text);\n border-color: var(--ks-text);\n}\n\n.ks-button.ks-button-primary:active {\n background: oklch(8% 0 0);\n border-color: oklch(8% 0 0);\n}\n\n.ks-button.ks-button-secondary {\n color: var(--ks-ink);\n background: var(--ks-paper-raised);\n border-color: var(--ks-edge);\n}\n\n.ks-button.ks-button-secondary:hover {\n color: var(--ks-ink);\n border-color: var(--ks-ink);\n}\n\n.ks-button.ks-button-secondary:active {\n background: var(--ks-gray);\n}\n\n.ks-button.ks-button-ghost {\n color: var(--ks-ink);\n background: transparent;\n border-color: transparent;\n padding: 0 12px;\n}\n\n.ks-button.ks-button-ghost:hover {\n color: var(--ks-accent-ink);\n}\n\n.ks-button[disabled],\n.ks-button.ks-button-disabled {\n color: var(--ks-text-mute-deep);\n background: transparent;\n border-color: var(--ks-rule);\n cursor: not-allowed;\n transform: none !important;\n}\n\n.ks-button:focus-visible {\n outline: 2px solid var(--ks-focus-ring);\n outline-offset: 3px;\n}\n\n.ks-button-row {\n display: flex;\n flex-wrap: wrap;\n align-items: center;\n gap: 18px;\n}\n\n/* ============================================================\n Tabs\n ============================================================ */\n\n.ks-tabs { max-width: 460px; }\n\n.ks-tab-list { display: flex; border-bottom: 1px solid var(--ks-rule); }\n\n.ks-tab-list button {\n flex: 1;\n min-height: 42px;\n border: 0;\n border-bottom: 2px solid transparent;\n background: transparent;\n color: var(--ks-text-muted);\n cursor: pointer;\n font-size: 0.92rem;\n transition: color 180ms var(--ks-ease), border-color 180ms var(--ks-ease);\n}\n\n.ks-tab-list button:hover { color: var(--ks-ink); }\n\n.ks-tab-list button[aria-selected=\"true\"] {\n color: var(--ks-accent-ink);\n border-bottom-color: var(--ks-kinpaku);\n}\n\n.ks-tab-panel {\n padding: 22px 4px 0;\n color: var(--ks-ink);\n font-size: 0.92rem;\n line-height: 1.6;\n}\n\n/* ============================================================\n Form controls — input, toggle, checkbox, select\n ============================================================ */\n\n.ks-form-sample {\n display: grid;\n gap: 22px;\n max-width: 360px;\n}\n\n.ks-form-sample label {\n display: grid;\n gap: 8px;\n color: var(--ks-text-muted);\n font-size: 0.82rem;\n letter-spacing: 0.04em;\n}\n\n.ks-form-sample input[type=\"search\"],\n.ks-form-sample input[type=\"text\"] {\n min-height: 46px;\n padding: 0 14px;\n border: 1px solid var(--ks-rule);\n border-radius: var(--ks-radius-sm);\n background: var(--ks-paper-raised);\n color: var(--ks-ink);\n font-size: 0.92rem;\n}\n\n.ks-form-sample input[type=\"search\"]:focus,\n.ks-form-sample input[type=\"text\"]:focus {\n outline: none;\n border-color: var(--ks-patina);\n}\n\n.ks-toggle {\n display: flex !important;\n align-items: center;\n gap: 12px !important;\n}\n\n.ks-toggle input {\n appearance: none;\n width: 44px;\n height: 24px;\n border-radius: 999px;\n border: 1px solid var(--ks-rule);\n background: var(--ks-gray);\n position: relative;\n cursor: pointer;\n flex: none;\n}\n\n.ks-toggle input::before {\n content: \"\";\n position: absolute;\n width: 16px;\n height: 16px;\n left: 3px;\n top: 3px;\n border-radius: 999px;\n background: var(--ks-text-muted);\n transition: transform 220ms var(--ks-ease), background 220ms var(--ks-ease);\n}\n\n.ks-toggle input:checked {\n border-color: var(--ks-patina);\n background: oklch(48% 0.08 188 / 0.2);\n}\n\n.ks-toggle input:checked::before {\n transform: translateX(20px);\n background: var(--ks-patina);\n}\n\n.ks-toggle span { color: var(--ks-ink); font-size: 0.92rem; }\n\n.ks-checkbox {\n display: flex;\n align-items: center;\n gap: 10px;\n color: var(--ks-ink);\n font-size: 0.92rem;\n cursor: pointer;\n}\n\n.ks-checkbox input {\n appearance: none;\n width: 18px;\n height: 18px;\n border: 1px solid var(--ks-rule);\n border-radius: var(--ks-radius-sm);\n background: var(--ks-paper-raised);\n position: relative;\n cursor: pointer;\n flex: none;\n}\n\n.ks-checkbox input:checked {\n border-color: var(--ks-ink);\n background: var(--ks-ink);\n}\n\n.ks-checkbox input:checked::after {\n content: \"\";\n position: absolute;\n left: 5px;\n top: 2px;\n width: 5px;\n height: 9px;\n border: solid var(--ks-paper-raised);\n border-width: 0 1.5px 1.5px 0;\n transform: rotate(45deg);\n}\n\n.ks-select {\n appearance: none;\n min-height: 46px;\n padding: 0 38px 0 14px;\n border: 1px solid var(--ks-rule);\n border-radius: var(--ks-radius-sm);\n background-color: var(--ks-paper-raised);\n background-image: url(\"data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 10 6' fill='none' stroke='%23222222' stroke-width='1.2'%3E%3Cpath d='M1 1l4 4 4-4'/%3E%3C/svg%3E\");\n background-repeat: no-repeat;\n background-position: right 14px center;\n background-size: 10px 6px;\n color: var(--ks-ink);\n font-size: 0.92rem;\n cursor: pointer;\n}\n\n/* ============================================================\n Icon button + tooltip\n ============================================================ */\n\n.ks-icon-button {\n width: 32px;\n height: 32px;\n display: grid;\n place-items: center;\n border: 1px solid var(--ks-rule);\n border-radius: 999px;\n background: transparent;\n color: var(--ks-accent-ink);\n cursor: pointer;\n}\n\n.ks-tooltip {\n position: absolute;\n bottom: calc(100% - 18px);\n left: 50%;\n transform: translateX(-50%);\n width: 200px;\n padding: 10px 12px;\n border: 1px solid var(--ks-rule);\n background: var(--ks-paper-deep);\n color: var(--ks-ink);\n font-size: 0.8rem;\n line-height: 1.4;\n border-radius: var(--ks-radius-sm);\n opacity: 0;\n pointer-events: none;\n transition: opacity 160ms var(--ks-ease);\n}\n\n.ks-icon-button:focus-visible + .ks-tooltip {\n opacity: 1;\n}\n\n/* ============================================================\n Instrument strip: the site's one dark control.\n\n A row of keys on a dark strip, sitting on the paper like a device on a\n desk. The active key is raised and carries a gold indicator. Use for tab\n strips, view switches and command pickers: anything the reader operates.\n Never for decoration, and never for a link list.\n\n Markup: <div class=\"ks-instrument-strip\" role=\"tablist\">\n <button class=\"ks-instrument-key is-active\">One</button>\n <button class=\"ks-instrument-key\">Two</button>\n </div>\n ============================================================ */\n.ks-instrument-strip {\n display: inline-flex;\n align-items: center;\n gap: 2px;\n padding: 3px;\n background: var(--ks-instrument);\n border: 1px solid var(--ks-instrument-deep);\n border-radius: var(--ks-radius-pill);\n box-shadow: inset 0 1px 0 var(--ks-instrument-rule), var(--ks-lift-1);\n}\n\n.ks-instrument-key {\n display: inline-flex;\n align-items: center;\n gap: 8px;\n min-height: var(--ks-control-md);\n padding: 0 14px 0 12px;\n color: var(--ks-instrument-muted);\n background: transparent;\n border: 0;\n border-radius: var(--ks-radius-pill);\n font-family: var(--ks-mono);\n font-size: var(--ks-type-label-size);\n letter-spacing: 0.02em;\n text-transform: none;\n line-height: 1;\n white-space: nowrap;\n cursor: pointer;\n transition: color var(--ks-quick) var(--ks-ease), background-color var(--ks-quick) var(--ks-ease);\n}\n\n.ks-instrument-key::before {\n content: \"\";\n width: 6px;\n height: 6px;\n flex: none;\n border-radius: 50%;\n background: var(--ks-instrument-raised);\n box-shadow: inset 0 0 0 1px var(--ks-instrument-rule);\n transition: background-color var(--ks-quick) var(--ks-ease), box-shadow var(--ks-quick) var(--ks-ease);\n}\n\n.ks-instrument-key:hover,\n.ks-instrument-key:focus-visible {\n color: var(--ks-instrument-text);\n}\n\n.ks-instrument-key:focus-visible {\n outline: 2px solid var(--ks-focus-ring);\n outline-offset: 2px;\n}\n\n.ks-instrument-key.is-active,\n.ks-instrument-key[aria-selected=\"true\"] {\n color: var(--ks-instrument-text);\n background: var(--ks-instrument-raised);\n box-shadow: inset 0 1px 0 var(--ks-instrument-edge), var(--ks-key-lift);\n}\n\n.ks-instrument-key.is-active::before,\n.ks-instrument-key[aria-selected=\"true\"]::before {\n background: var(--ks-kinpaku);\n box-shadow: var(--ks-indicator-glow);\n}\n\n/* ============================================================\n Grain.\n\n Grain is part of a material, not a layer over the page. The page ground\n (the paper) carries it, and so do the moulded surfaces: the recessed\n track and raised caps of a paper strip, the dark instruments, code\n blocks. Anything that sits on top of those (a card, a demo, an image,\n type) is clean. One 160px tile of monochrome noise from an SVG filter,\n held under 6% on paper and a little higher on dark, where it is what\n makes a strip read as a part instead of a black rectangle.\n ============================================================ */\n:root {\n --ks-grain: url(\"data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='160' height='160'%3E%3Cfilter id='n' x='0' y='0'%3E%3CfeTurbulence type='fractalNoise' baseFrequency='0.9' numOctaves='2' stitchTiles='stitch'/%3E%3CfeColorMatrix type='saturate' values='0'/%3E%3C/filter%3E%3Crect width='100%25' height='100%25' filter='url(%23n)'/%3E%3C/svg%3E\");\n}\n\n/* The paper. Fixed behind the page's content, above the canvas colour. */\nbody {\n position: relative;\n isolation: isolate;\n}\n\nbody::before {\n content: \"\";\n position: fixed;\n inset: 0;\n z-index: -1;\n pointer-events: none;\n opacity: 0.055;\n mix-blend-mode: multiply;\n background-image: var(--ks-grain);\n background-size: 160px 160px;\n}\n\n/* Moulded surfaces. The pseudo sits under the surface's own children. */\n.ks-grain,\n.ks-instrument-strip {\n position: relative;\n}\n\n.ks-grain::before,\n.ks-instrument-strip::before {\n content: \"\";\n position: absolute;\n inset: 0;\n z-index: 0;\n border-radius: inherit;\n pointer-events: none;\n opacity: 0.16;\n mix-blend-mode: screen;\n will-change: opacity;\n background-image: var(--ks-grain);\n background-size: 160px 160px;\n}\n\n.ks-instrument-strip.is-paper::before {\n opacity: 0.05;\n mix-blend-mode: normal;\n}\n\n/* The strip is its own stacking context: grain at 0, the cap at 1, the\n labels at 2, whatever the page around it does. */\n.ks-instrument-strip {\n isolation: isolate;\n}\n\n\n.ks-instrument-strip > :not(.ks-thumb) {\n position: relative;\n z-index: 2;\n}\n\n/* ============================================================\n Switch: a physical slide switch for one on/off state.\n\n A recessed track, a raised knob that slides from left (off) to right\n (on), and a lit dot on the knob when on. Markup:\n <button class=\"ks-switch\" type=\"button\" aria-pressed=\"true\">\n <span class=\"ks-switch-track\" aria-hidden=\"true\"><span class=\"ks-switch-knob\"></span></span>\n <span class=\"ks-switch-label\">Detector on</span>\n </button>\n ============================================================ */\n.ks-switch {\n display: inline-flex;\n align-items: center;\n gap: 10px;\n padding: 0;\n border: 0;\n background: transparent;\n color: var(--ks-text-muted);\n font-family: var(--ks-font);\n font-size: var(--ks-type-ui-size);\n font-weight: 500;\n cursor: pointer;\n}\n\n.ks-switch[aria-pressed=\"true\"] {\n color: var(--ks-ink);\n}\n\n.ks-switch-track {\n position: relative;\n width: 44px;\n height: 24px;\n border-radius: var(--ks-radius-pill);\n background: var(--ks-gray-2);\n box-shadow: var(--ks-track-recess);\n transition: background-color var(--ks-quick) var(--ks-ease);\n}\n\n.ks-switch-knob {\n position: absolute;\n top: 3px;\n left: 3px;\n width: 18px;\n height: 18px;\n border-radius: 50%;\n background: var(--ks-paper-raised);\n box-shadow: var(--ks-cap-lift);\n transition: transform 220ms cubic-bezier(0.3, 0.7, 0.2, 1);\n}\n\n.ks-switch-knob::after {\n content: \"\";\n position: absolute;\n top: 50%;\n left: 50%;\n width: 6px;\n height: 6px;\n border-radius: 50%;\n transform: translate(-50%, -50%);\n background: var(--ks-gray-2);\n box-shadow: inset 0 1px 1px oklch(13% 0 0 / 0.18);\n transition: background-color var(--ks-quick) var(--ks-ease), box-shadow var(--ks-quick) var(--ks-ease);\n}\n\n.ks-switch[aria-pressed=\"true\"] .ks-switch-knob {\n transform: translateX(20px);\n}\n\n.ks-switch[aria-pressed=\"true\"] .ks-switch-knob::after {\n background: var(--ks-patina);\n box-shadow: var(--ks-led);\n}\n\n.ks-switch:active .ks-switch-knob {\n box-shadow: var(--ks-cap-press);\n}\n\n.ks-switch:focus-visible {\n outline: none;\n}\n\n.ks-switch:focus-visible .ks-switch-track {\n outline: 2px solid var(--ks-kinpaku);\n outline-offset: 2px;\n}\n\n/* ============================================================\n Tag: the brand's label.\n\n The detector flags bad design with a small gold tag carrying dark mono\n text. That tag is the one device a visitor already associates with\n Impeccable, so it is also how the site labels things: section numerals,\n a card's state, a release's status. Small, mono, ink on gold. It is the\n only gold fill allowed on paper, and it never grows past a label.\n ============================================================ */\n.ks-tag {\n display: inline-flex;\n align-items: center;\n gap: 6px;\n min-height: 22px;\n padding: 0 7px;\n color: var(--ks-ink);\n background: var(--ks-kinpaku);\n border-radius: var(--ks-radius-sm);\n font-family: var(--ks-mono);\n font-size: var(--ks-type-eyebrow-size);\n font-weight: 600;\n letter-spacing: 0.02em;\n line-height: normal;\n text-transform: uppercase;\n white-space: nowrap;\n vertical-align: middle;\n}\n\n/* A quiet tag for a secondary label sitting next to a gold one. */\n.ks-tag.is-quiet {\n color: var(--ks-text-muted);\n background: var(--ks-gray);\n}\n\n/* Paper variant. A page control (a view switch, a tab row) sits on paper\n and keeps the gold dot, so it does not compete with the primary action\n the way a dark strip does. The dark strip is for product chrome: the\n live picker, lab toolbars, terminals. */\n\n.ks-instrument-strip.is-paper {\n background: var(--ks-gray);\n border-color: transparent;\n box-shadow: var(--ks-track-recess);\n}\n\n.ks-instrument-strip.is-paper .ks-instrument-key {\n color: var(--ks-text-muted);\n transition: color var(--ks-quick) var(--ks-ease), background-color var(--ks-quick) var(--ks-ease), box-shadow var(--ks-quick) var(--ks-ease), transform var(--ks-quick) var(--ks-ease);\n}\n\n.ks-instrument-strip.is-paper .ks-instrument-key::before {\n background: var(--ks-gray-2);\n box-shadow: inset 0 1px 1px oklch(13% 0 0 / 0.18);\n}\n\n.ks-instrument-strip.is-paper .ks-instrument-key:hover,\n.ks-instrument-strip.is-paper .ks-instrument-key:focus-visible {\n color: var(--ks-ink);\n}\n\n.ks-instrument-strip.is-paper .ks-instrument-key:active {\n box-shadow: var(--ks-cap-press);\n transform: translateY(1px);\n}\n\n/* The raised cap. Light from above: a white edge on top, a hard shadow\n underneath, so it stands a millimetre proud of the track. */\n.ks-instrument-strip.is-paper .ks-instrument-key.is-active,\n.ks-instrument-strip.is-paper .ks-instrument-key[aria-selected=\"true\"],\n.ks-instrument-strip.is-paper .ks-instrument-key[aria-pressed=\"true\"] {\n color: var(--ks-ink);\n background: var(--ks-paper-raised);\n box-shadow: var(--ks-cap-lift);\n}\n\n.ks-instrument-strip.is-paper .ks-instrument-key.is-active::before,\n.ks-instrument-strip.is-paper .ks-instrument-key[aria-selected=\"true\"]::before,\n.ks-instrument-strip.is-paper .ks-instrument-key[aria-pressed=\"true\"]::before {\n background: var(--ks-patina);\n box-shadow: 0 0 0 1px oklch(13% 0 0 / 0.12), 0 0 4px color-mix(in oklch, var(--ks-patina) 60%, transparent);\n}\n\n.ks-instrument-strip.is-paper .ks-instrument-key:focus-visible {\n outline: 2px solid var(--ks-focus-ring);\n outline-offset: 1px;\n}\n\n/* ============================================================\n Instrument strip thumb (real element, positioned by\n instrument-strip.js). Last in the file on purpose: these override the\n key's own cap, and they must come after every key rule above.\n ============================================================ */\n.ks-thumb {\n position: absolute;\n top: 3px;\n bottom: 3px;\n left: 0;\n width: 0;\n border-radius: var(--ks-radius-pill);\n background: var(--ks-instrument-raised);\n box-shadow: inset 0 1px 0 var(--ks-instrument-edge), var(--ks-key-lift);\n transition: transform 360ms cubic-bezier(0.22, 1, 0.3, 1);\n pointer-events: none;\n z-index: 1;\n}\n\n.ks-instrument-strip.is-paper .ks-thumb {\n background: var(--ks-paper-raised);\n box-shadow: var(--ks-cap-lift);\n}\n\n.ks-instrument-strip.has-thumb .ks-instrument-key,\n.ks-instrument-strip.has-thumb .ks-instrument-key.is-active,\n.ks-instrument-strip.has-thumb .ks-instrument-key[aria-selected=\"true\"],\n.ks-instrument-strip.has-thumb .ks-instrument-key[aria-pressed=\"true\"],\n.ks-instrument-strip.is-paper.has-thumb .ks-instrument-key.is-active,\n.ks-instrument-strip.is-paper.has-thumb .ks-instrument-key[aria-selected=\"true\"],\n.ks-instrument-strip.is-paper.has-thumb .ks-instrument-key[aria-pressed=\"true\"] {\n background: transparent;\n box-shadow: none;\n transform: none;\n transition: color 120ms var(--ks-ease);\n}\n\n.ks-instrument-strip.has-thumb .ks-instrument-key::before {\n transition: background-color 120ms var(--ks-ease), box-shadow 120ms var(--ks-ease);\n}\n\n/* Dark instruments need the light state color for keyboard focus. */\n.ks-instrument-strip:not(.is-paper),\n.live-demo-gbar,\n.live-demo-ctx,\n.worlds-rating {\n --ks-focus-ring: var(--ks-patina);\n}\n\n/* Touch gets the kit's large target, without enlarging the desktop controls\n or their labels. Pointer capability also covers tablets with a keyboard. */\n@media (any-pointer: coarse) {\n .ks-instrument-strip .ks-instrument-key,\n .ks-segmented button {\n min-height: var(--ks-control-lg);\n min-width: var(--ks-control-lg);\n }\n\n .site-header-menu {\n width: var(--ks-control-lg);\n height: var(--ks-control-lg);\n }\n\n .kinpaku-chrome .site-header-brand,\n .kinpaku-chrome .site-header-github {\n min-height: var(--ks-control-lg);\n }\n\n .kinpaku-chrome .site-header-nav a {\n min-height: var(--ks-control-lg);\n min-width: var(--ks-control-lg);\n padding-block: 10px;\n }\n}\n";
+export const rail = "/* VENDORED from impeccable-site/site/styles/docs-kinpaku.css (the command rail list: the site's selected-row pattern) (the source of truth).\n Do not edit here: change the site, then run node scripts/sync-kinpaku-kit.mjs. */\n/* Group headings are ink and bold, so they read as headings over their\n links rather than as meta beside them; the links are muted and a step\n smaller, ink on hover and on the current page. */\n.docs-kinpaku .skills-sidebar-category {\n display: block;\n font-family: var(--ks-font);\n font-size: 0.8125rem;\n font-weight: 650;\n letter-spacing: 0.01em;\n text-transform: none;\n color: var(--ks-ink);\n margin-bottom: 6px;\n padding: 0 0 0 14px;\n}\n\n.docs-kinpaku .skills-sidebar-list {\n list-style: none;\n padding: 0;\n margin: 0;\n}\n\n.docs-kinpaku .skills-sidebar-list li {\n margin: 0;\n}\n\n.docs-kinpaku .skills-sidebar-list a {\n display: block;\n padding: 4px 0 4px 12px;\n border-left: 2px solid transparent;\n font-family: var(--ks-font);\n font-size: 0.875rem;\n font-weight: 400;\n line-height: 1.5;\n color: var(--ks-text-muted);\n text-decoration: none;\n transition: color 160ms var(--ks-ease),\n border-color 160ms var(--ks-ease);\n}\n\n.docs-kinpaku .skills-sidebar-list a:hover {\n color: var(--ks-ink);\n}\n\n.docs-kinpaku .skills-sidebar-list a[aria-current=\"page\"] {\n color: var(--ks-ink);\n font-weight: 600;\n border-left-color: var(--ks-gold-line);\n}\n";