Skip to content

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

JavaScript

Put visualize.md in front of the agent before decision comps (#880)

Paul Bakaus555e841dbbc9
diff --git a/Cargo.lock b/Cargo.lock
index d97e331c2..e2d032b70 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -525,7 +525,7 @@ dependencies = [
[[package]]
name = "impeccable"
-version = "0.1.7"
+version = "0.1.8"
dependencies = [
"base64",
"impeccable-browser",
@@ -545,7 +545,7 @@ dependencies = [
[[package]]
name = "impeccable-browser"
-version = "0.1.7"
+version = "0.1.8"
dependencies = [
"base64",
"impeccable-core",
@@ -560,7 +560,7 @@ dependencies = [
[[package]]
name = "impeccable-bundle"
-version = "0.1.7"
+version = "0.1.8"
dependencies = [
"base64",
"impeccable-core",
@@ -569,14 +569,14 @@ dependencies = [
[[package]]
name = "impeccable-common"
-version = "0.1.7"
+version = "0.1.8"
dependencies = [
"libc",
]
[[package]]
name = "impeccable-comp"
-version = "0.1.7"
+version = "0.1.8"
dependencies = [
"image",
"once_cell",
@@ -588,7 +588,7 @@ dependencies = [
[[package]]
name = "impeccable-comp-verbs"
-version = "0.1.7"
+version = "0.1.8"
dependencies = [
"impeccable-common",
"impeccable-comp",
@@ -603,7 +603,7 @@ dependencies = [
[[package]]
name = "impeccable-context"
-version = "0.1.7"
+version = "0.1.8"
dependencies = [
"flate2",
"impeccable-common",
@@ -623,7 +623,7 @@ dependencies = [
[[package]]
name = "impeccable-core"
-version = "0.1.7"
+version = "0.1.8"
dependencies = [
"impeccable-core",
"impeccable-foundation",
@@ -635,7 +635,7 @@ dependencies = [
[[package]]
name = "impeccable-detect"
-version = "0.1.7"
+version = "0.1.8"
dependencies = [
"impeccable-common",
"impeccable-core",
@@ -647,7 +647,7 @@ dependencies = [
[[package]]
name = "impeccable-foundation"
-version = "0.1.7"
+version = "0.1.8"
dependencies = [
"cssparser",
"once_cell",
@@ -660,7 +660,7 @@ dependencies = [
[[package]]
name = "impeccable-hook"
-version = "0.1.7"
+version = "0.1.8"
dependencies = [
"impeccable-common",
"impeccable-comp-verbs",
@@ -675,7 +675,7 @@ dependencies = [
[[package]]
name = "impeccable-html"
-version = "0.1.7"
+version = "0.1.8"
dependencies = [
"cssparser",
"ego-tree",
@@ -696,7 +696,7 @@ dependencies = [
[[package]]
name = "impeccable-live"
-version = "0.1.7"
+version = "0.1.8"
dependencies = [
"getrandom 0.2.17",
"impeccable-common",
@@ -714,7 +714,7 @@ dependencies = [
[[package]]
name = "impeccable-skills"
-version = "0.1.7"
+version = "0.1.8"
dependencies = [
"impeccable-common",
"impeccable-context",
@@ -733,7 +733,7 @@ dependencies = [
[[package]]
name = "impeccable-wasm"
-version = "0.1.7"
+version = "0.1.8"
dependencies = [
"impeccable-core",
"impeccable-detect",
@@ -1764,7 +1764,7 @@ checksum = "3ad82d2a33cdc9674dc7465672f271e096168fcdbe0f799d9e6db8c5892679dc"
[[package]]
name = "xtask"
-version = "0.1.7"
+version = "0.1.8"
dependencies = [
"impeccable-bundle",
]
diff --git a/Cargo.toml b/Cargo.toml
index c1ca9af3f..dba510d74 100644
--- a/Cargo.toml
+++ b/Cargo.toml
@@ -6,7 +6,7 @@ resolver = "2"
members = ["crates/*"]
[workspace.package]
-version = "0.1.7"
+version = "0.1.8"
edition = "2021"
license = "Apache-2.0"
publish = false
diff --git a/ENGINE_VERSION b/ENGINE_VERSION
index 11808190d..699c6c6d4 100644
--- a/ENGINE_VERSION
+++ b/ENGINE_VERSION
@@ -1 +1 @@
-0.1.7
+0.1.8
diff --git a/bun.lock b/bun.lock
index 560c83cb2..547d9c29c 100644
--- a/bun.lock
+++ b/bun.lock
@@ -19,11 +19,11 @@
"zod": "^4.3.6",
},
"optionalDependencies": {
- "@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",
+ "@impeccable/cli-darwin-arm64": "0.1.8",
+ "@impeccable/cli-darwin-x64": "0.1.8",
+ "@impeccable/cli-linux-arm64": "0.1.8",
+ "@impeccable/cli-linux-x64": "0.1.8",
+ "@impeccable/cli-windows-x64": "0.1.8",
},
},
},
@@ -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-G8uMNqAfMiGx+4YwemH6GV1zY2PpV38LamdeVCzdvTLOOnbphPg44uEJtiP97wgPYkAsFRAo+rKyf/GaA2XZjg=="],
+ "@impeccable/cli-darwin-arm64": ["@impeccable/[email protected]", "", { "os": "darwin", "cpu": "arm64", "bin": { "impeccable-darwin-arm64": "bin/impeccable" } }, "sha512-FDsEezwcwi98EdyRl3eDgeo+O7+llhKgBz363I0BiiNkL13FocJ9DngbhFWmcBF3w2fQ1XEWZnwNNUBaRoeHjg=="],
- "@impeccable/cli-darwin-x64": ["@impeccable/[email protected]", "", { "os": "darwin", "cpu": "x64", "bin": { "impeccable-darwin-x64": "bin/impeccable" } }, "sha512-7GHedadRYKCsBVGXCSqHQJPvjY3tQiLZbVjnr7+wysRxfzKEHr7h2B/5EMR0rujCiriC0EDgJPch8X4SYKuAXQ=="],
+ "@impeccable/cli-darwin-x64": ["@impeccable/[email protected]", "", { "os": "darwin", "cpu": "x64", "bin": { "impeccable-darwin-x64": "bin/impeccable" } }, "sha512-iKQOxBK77NCHsIuVF3+4sjyNGcmGAcPELy3DWsGaTvt2y4jPRvOh5ux3PJaZ5bbWjywrUkXgsb3a6DQNDHXA5g=="],
- "@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-arm64": ["@impeccable/[email protected]", "", { "os": "linux", "cpu": "arm64", "bin": { "impeccable-linux-arm64": "bin/impeccable" } }, "sha512-q0to//lElwuQeondRnznufCiz+YQP5H6T2Mz1rA6O0yBtym3iOCUC8VkX/rV+0Cc1bz+Jqfjt4tqb8AHvXtBWw=="],
- "@impeccable/cli-linux-x64": ["@impeccable/[email protected]", "", { "os": "linux", "cpu": "x64", "bin": { "impeccable-linux-x64": "bin/impeccable" } }, "sha512-VcF9y/RcWIQOOBx5WybgRfwLzydL7ou8eZOiuaAraQqR3YITP8BSGxj4qr7I0zoy4Nli8iV2lbYxFmrJ6eDerw=="],
+ "@impeccable/cli-linux-x64": ["@impeccable/[email protected]", "", { "os": "linux", "cpu": "x64", "bin": { "impeccable-linux-x64": "bin/impeccable" } }, "sha512-b0VtTtbeX4BvEeGZEQ421npmnmDa0N4Wrd3JUW82tlFMBDkJzGa4WHwepxsc3GZM0WdbFxs3eLpE2j21t5pcmA=="],
- "@impeccable/cli-windows-x64": ["@impeccable/[email protected]", "", { "os": "win32", "cpu": "x64", "bin": { "impeccable-windows-x64": "bin/impeccable.exe" } }, "sha512-07Zipg5byFSGLnvjowmNrjYAlRhAYu5SsDqaDRDlqB+uleuUzcVxguHdcparYdfk/Oe0X9JOhatNgniH6l+XeQ=="],
+ "@impeccable/cli-windows-x64": ["@impeccable/[email protected]", "", { "os": "win32", "cpu": "x64", "bin": { "impeccable-windows-x64": "bin/impeccable.exe" } }, "sha512-LXv9QSaummA+FipFDP9hFwJsPItt8/8gcS4cdpAHUhKIIzcCr+LuCgD5RV78X/u5lAILWMeemjVHhBCwsmI5bw=="],
"@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/context/src/generate_image.rs b/crates/context/src/generate_image.rs
index 62d212b6f..8767dbfea 100644
--- a/crates/context/src/generate_image.rs
+++ b/crates/context/src/generate_image.rs
@@ -298,6 +298,7 @@ fn run_with_api_base(args: &[String], io: &mut Io, api_base: &str) -> i32 {
return 1;
}
io.out(&format!("IMAGE: {} ({}x{}, fake synthetic comp, $0.00, no API call)\n", out, w, h));
+ note_generated_slot(io, &out);
return 0;
}
let Some(key) = env.get("OPENAI_API_KEY").filter(|k| !k.is_empty()).cloned() else {
@@ -441,6 +442,7 @@ fn run_with_api_base(args: &[String], io: &mut Io, api_base: &str) -> i32 {
}
let _ = std::fs::write(abs(&format!("{}.json", out)), json_pretty(&Value::Object(m)));
}
+ note_generated_slot(io, &out);
io.out(&format!(
"IMAGE: {} ({}, {}, {}, billed to your OpenAI key); {} at {}.json\n",
out,
@@ -453,6 +455,17 @@ fn run_with_api_base(args: &[String], io: &mut Io, api_base: &str) -> i32 {
0
}
+/// A written image that fills a decision page's declared slot counts as that
+/// hand's comp even when its bytes match what sat there before (the same
+/// prompt regenerates the same bytes). A failed record is reported, not fatal:
+/// the image itself was written.
+fn note_generated_slot(io: &mut Io, out: &str) {
+ let cwd = io.cwd.to_string_lossy().into_owned();
+ if let Err(e) = crate::serve_question::record_generated(&cwd, out) {
+ io.err(&format!("generate-image: could not mark {} as generated for its decision page ({}); a --wait may report it stale\n", out, e));
+ }
+}
+
fn base64_decode(s: &str) -> Vec<u8> {
let table = |c: u8| -> Option<u32> {
match c {
diff --git a/crates/context/src/serve_question.rs b/crates/context/src/serve_question.rs
index d846d6849..0b905c4d6 100644
--- a/crates/context/src/serve_question.rs
+++ b/crates/context/src/serve_question.rs
@@ -89,6 +89,16 @@ fn is_alive(qdir: &str, key: &str) -> bool {
}
}
+/// A comp-round comp sits directly in `.impeccable/mocks/` (build-phase's
+/// comps gate lists that directory); decision comps live one level down in
+/// `.impeccable/mocks/decision/`. Anything else keeps the decision wording.
+fn is_comp_round_comp(path: &str) -> bool {
+ let p = path.replace('\\', "/");
+ let dir = p.rsplit_once('/').map(|(d, _)| d).unwrap_or("");
+ let dir = dir.strip_prefix("./").unwrap_or(dir);
+ dir == ".impeccable/mocks" || dir.ends_with("/.impeccable/mocks")
+}
+
fn print_answer(io: &mut Io, raw: &str) {
io.out(&format!("ANSWER: {}\n", raw));
let Ok(a) = serde_json::from_str::<Value>(raw) else { return };
@@ -96,7 +106,9 @@ fn print_answer(io: &mut Io, raw: &str) {
if truthy("hero") || truthy("board") {
io.out("CHOSEN CARD: open the chosen world's board and hero images now, before any code. When your harness only reads files, or runs sandboxed, download them INTO the workspace and open the relative path; a sandboxed viewer rejects absolute paths outside it. They set the craft bar the build must reach.\n");
}
- if truthy("comp") {
+ if truthy("comp") && is_comp_round_comp(&a.get("comp").map(js_str).unwrap_or_default()) {
+ io.out("APPROVED COMP: the user picked this composition in the comp round, so it is the approved comp. Set \"approved\": true in its prompt sidecar (<comp>.json), record its path in the surface brief, then close the comps phase with build-phase advance. Build from it as it stands; never regenerate it.\n");
+ } else if truthy("comp") {
io.out("CHOSEN COMP: the decision comp at that path is compositional option one. On a comp-led build the comp round adds two variations beside it; on a code-led build it returns at the finish review as the critique reference. Never regenerate it from scratch.\n");
}
let option_id = a.get("optionId").and_then(|v| v.as_str());
@@ -130,6 +142,292 @@ fn print_answer(io: &mut Io, raw: &str) {
}
}
+/// Local comp paths a round declares, in card order: every option's `comp`
+/// (or the legacy `sketch`) and the canon card's, as written in the payload.
+/// URLs are left out: they are rendered already, never generated here.
+fn declared_comps(payload: &Value) -> Vec<String> {
+ let mut cards: Vec<&Value> = payload.get("options").and_then(Value::as_array).map(|o| o.iter().collect()).unwrap_or_default();
+ if let Some(c) = payload.get("canonCard").filter(|c| c.is_object()) {
+ cards.push(c);
+ }
+ let mut out: Vec<String> = Vec::new();
+ for card in cards {
+ let comp = card.get("comp").filter(|v| !v.is_null()).or_else(|| card.get("sketch").filter(|v| !v.is_null()));
+ let Some(s) = comp.filter(|v| crate::staleness::js_truthy(v)).map(js_str) else { continue };
+ if s.starts_with("http://") || s.starts_with("https://") || out.contains(&s) {
+ continue;
+ }
+ out.push(s);
+ }
+ out
+}
+
+/// Provenance of a hand lives in `<key>.hand.json`, written atomically by
+/// `--start` and `--update` only, never by the server (whose heartbeat and
+/// claim writes rewrite `<key>.state.json` and would race a shared field).
+/// Shape: `{"digest": <hand_digest>, "comps": [<declared slots>], "pre":
+/// {<slot>: <sha256 of the file that sat there when the hand began>}}`.
+/// `--update` always starts a new hand; `--start` keeps the recorded hand when
+/// its digest matches (a restart) and starts a new one otherwise.
+fn hand_file(qdir: &str, key: &str) -> String {
+ jsp::join(&[qdir, &format!("{}.hand.json", key)])
+}
+
+/// The whole payload, not only its slot paths: a re-roll often reuses the
+/// previous hand's paths and must still read as a new hand.
+fn hand_digest(payload: &Value) -> String {
+ use sha2::{Digest, Sha256};
+ let d = Sha256::digest(json_compact(payload).as_bytes());
+ d.iter().take(8).map(|b| format!("{:02x}", b)).collect()
+}
+
+fn file_fingerprint(abs: &str) -> Option<String> {
+ use sha2::{Digest, Sha256};
+ let bytes = std::fs::read(abs).ok()?;
+ Some(Sha256::digest(&bytes).iter().map(|b| format!("{:02x}", b)).collect())
+}
+
+/// `<key>.generated/`: one marker per slot `impeccable generate-image` wrote
+/// during the hand, `<sha16 of slot>.json` = `{"slot", "digest"}`. A marker
+/// file per slot rather than a list inside the hand file, because parallel
+/// generators (one subagent per card) would race a shared read-modify-write.
+fn generated_dir(qdir: &str, key: &str) -> String {
+ jsp::join(&[qdir, &format!("{}.generated", key)])
+}
+
+/// The recorded hand, with the slots generated during it merged in as
+/// `generated` (markers from another digest are ignored).
+fn read_hand(qdir: &str, key: &str) -> Option<Map<String, Value>> {
+ let mut hand = safe_read(&hand_file(qdir, key)).and_then(|t| serde_json::from_str::<Value>(&t).ok()).and_then(|v| v.as_object().cloned())?;
+ let id = hand_marker_id(&hand);
+ let mut generated: Vec<String> = Vec::new();
+ if let Ok(entries) = std::fs::read_dir(generated_dir(qdir, key)) {
+ for e in entries.flatten() {
+ let Some(m) = safe_read(&e.path().to_string_lossy()).and_then(|t| serde_json::from_str::<Value>(&t).ok()) else { continue };
+ if m.get("hand").or_else(|| m.get("digest")).and_then(Value::as_str) == Some(id.as_str()) {
+ if let Some(slot) = m.get("slot").and_then(Value::as_str) {
+ generated.push(slot.to_string());
+ }
+ }
+ }
+ }
+ generated.sort();
+ if !generated.is_empty() {
+ hand.insert("generated".into(), json!(generated));
+ }
+ Some(hand)
+}
+
+/// Temp file beside the target, then rename: a reader never sees half a file.
+fn write_atomic(target: &str, text: &str) -> std::io::Result<()> {
+ let temp = format!("{}.tmp-{}", target, std::process::id());
+ std::fs::write(&temp, text)?;
+ std::fs::rename(&temp, target).map_err(|e| {
+ let _ = std::fs::remove_file(&temp);
+ e
+ })
+}
+
+fn same_path(a: &str, b: &str) -> bool {
+ let norm = |p: &str| {
+ let p = p.replace('\\', "/");
+ if cfg!(windows) { p.to_lowercase() } else { p }
+ };
+ norm(a) == norm(b)
+}
+
+/// Called by `impeccable generate-image` after it writes `out`: when `out` is
+/// a declared slot of a recorded hand in this project, mark it generated
+/// during that hand. A deterministic generator returns the same bytes for
+/// the same prompt, which the fingerprint rule alone would read as stale.
+/// Returns the keys whose hand was marked, or the first write error.
+pub fn record_generated(cwd: &str, out: &str) -> Result<Vec<String>, String> {
+ let qdir = jsp::join(&[cwd, ".impeccable", "questions"]);
+ let out_abs = jsp::resolve(cwd, &[out]);
+ let Ok(entries) = std::fs::read_dir(&qdir) else { return Ok(vec![]) };
+ let mut keys: Vec<String> = entries
+ .flatten()
+ .filter_map(|e| e.file_name().to_string_lossy().strip_suffix(".hand.json").map(str::to_string))
+ .collect();
+ keys.sort();
+ let mut marked = Vec::new();
+ for key in keys {
+ let Some(hand) = read_hand(&qdir, &key) else { continue };
+ let id = hand_marker_id(&hand);
+ for slot in round_comps(Some(&hand), None) {
+ if !same_path(&jsp::resolve(cwd, &[slot.as_str()]), &out_abs) {
+ continue;
+ }
+ let dir = generated_dir(&qdir, &key);
+ let marker = jsp::join(&[&dir, &format!("{}.json", hand_digest(&Value::String(slot.clone())))]);
+ std::fs::create_dir_all(&dir)
+ .and_then(|_| write_atomic(&marker, &json_compact(&json!({ "slot": slot, "hand": id }))))
+ .map_err(|e| format!("{}: {}", marker, e))?;
+ marked.push(key.clone());
+ }
+ }
+ Ok(marked)
+}
+
+/// A new hand: its digest, its slots, and the fingerprint of every slot that
+/// already holds a file, so that file never passes for this hand's comp.
+fn new_hand(cwd: &str, payload: &Value) -> Map<String, Value> {
+ let comps = declared_comps(payload);
+ let mut pre = Map::new();
+ for c in &comps {
+ if let Some(fp) = file_fingerprint(&jsp::resolve(cwd, &[c.as_str()])) {
+ pre.insert(c.clone(), Value::String(fp));
+ }
+ }
+ let mut m = Map::new();
+ // A per-hand id: an --update re-roll can repeat a payload, so the digest
+ // alone cannot tell one hand's generated markers from the next one's.
+ let nonce = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).map(|d| d.as_nanos()).unwrap_or(0);
+ m.insert("id".into(), Value::String(hand_digest(&json!([hand_digest(payload), nonce.to_string(), std::process::id()]))));
+ m.insert("digest".into(), Value::String(hand_digest(payload)));
+ m.insert("comps".into(), json!(comps));
+ m.insert("pre".into(), Value::Object(pre));
+ m
+}
+
+/// Records a new hand atomically (temp file then rename, so a reader never
+/// sees half a hand), then prunes generated markers that belong to another
+/// hand. Pruning waits for a successful write, so a failed write leaves the
+/// live hand and its markers intact, and it spares this hand's own markers,
+/// which a parallel generate-image may already have written. The error names
+/// the file.
+fn write_hand(qdir: &str, key: &str, hand: &Map<String, Value>) -> Result<(), String> {
+ let target = hand_file(qdir, key);
+ write_atomic(&target, &json_compact(&Value::Object(hand.clone()))).map_err(|e| format!("{}: {}", target, e))?;
+ let id = hand_marker_id(hand);
+ if let Ok(entries) = std::fs::read_dir(generated_dir(qdir, key)) {
+ for e in entries.flatten() {
+ let owner = safe_read(&e.path().to_string_lossy())
+ .and_then(|t| serde_json::from_str::<Value>(&t).ok())
+ .and_then(|m| m.get("hand").or_else(|| m.get("digest")).and_then(Value::as_str).map(str::to_string));
+ if owner.as_deref() != Some(id.as_str()) {
+ let _ = std::fs::remove_file(e.path());
+ }
+ }
+ }
+ Ok(())
+}
+
+/// What a generated marker records as its hand: the hand's id, or its digest
+/// for a hand file written before ids existed.
+fn hand_marker_id(hand: &Map<String, Value>) -> String {
+ hand.get("id").or_else(|| hand.get("digest")).and_then(Value::as_str).unwrap_or("").to_string()
+}
+
+/// The hand a `--start` serves: the recorded one when the key's hand file
+/// carries this payload's digest (a restart keeps its fingerprints), else a
+/// new one, written before the server spawns.
+fn start_hand(qdir: &str, key: &str, cwd: &str, payload: &Value) -> Result<Map<String, Value>, String> {
+ let digest = hand_digest(payload);
+ if let Some(h) = read_hand(qdir, key).filter(|h| h.get("digest").and_then(Value::as_str) == Some(digest.as_str())) {
+ return Ok(h);
+ }
+ let h = new_hand(cwd, payload);
+ write_hand(qdir, key, &h)?;
+ Ok(h)
+}
+
+/// The comps a `--wait` judges: the hand's, else the state's (a round served
+/// before hands were recorded).
+fn round_comps(hand: Option<&Map<String, Value>>, state: Option<&Map<String, Value>>) -> Vec<String> {
+ match hand {
+ Some(h) => h.get("comps").and_then(Value::as_array).map(|a| a.iter().filter_map(|v| v.as_str().map(str::to_string)).collect()).unwrap_or_default(),
+ None => state.map(state_comps).unwrap_or_default(),
+ }
+}
+
+/// A declared comp is this hand's when its file exists and differs from the
+/// file that sat at the slot when the hand began (or none sat there). The comp
+/// round generates its comps directly in `.impeccable/mocks/` before it serves
+/// them, so those always count; with no hand recorded, existence decides.
+fn comp_is_this_hands(cwd: &str, comp: &str, hand: Option<&Map<String, Value>>) -> bool {
+ let abs = jsp::resolve(cwd, &[comp]);
+ if !exists(&abs) {
+ return false;
+ }
+ let Some(hand) = hand else { return true };
+ if is_comp_round_comp(comp) {
+ return true;
+ }
+ let generated = hand.get("generated").and_then(Value::as_array).map(|g| g.iter().any(|v| v.as_str() == Some(comp))).unwrap_or(false);
+ if generated {
+ return true;
+ }
+ match hand.get("pre").and_then(|p| p.get(comp)).and_then(Value::as_str) {
+ None => true,
+ Some(before) => file_fingerprint(&abs).map(|now| now != before).unwrap_or(false),
+ }
+}
+
+/// Declared comps whose file is still the one an earlier round left.
+fn stale_comps(cwd: &str, comps: &[String], hand: Option<&Map<String, Value>>) -> Vec<String> {
+ comps.iter().filter(|c| exists(&jsp::resolve(cwd, &[c.as_str()])) && !comp_is_this_hands(cwd, c, hand)).cloned().collect()
+}
+
+fn any_comp_pending(cwd: &str, comps: &[String], hand: Option<&Map<String, Value>>) -> bool {
+ comps.iter().any(|c| !comp_is_this_hands(cwd, c, hand))
+}
+
+/// A round whose comps get generated now: it is not code-led (a code-led
+/// round's slots are a flip reserve) and a declared local comp slot still has
+/// no comp of this hand. A fresh decision round serves first and generates
+/// after; a restart of the same hand finds the comps that already landed; the
+/// comp round's comps are its own.
+fn comps_expected(payload: &Value, cwd: &str, hand: Option<&Map<String, Value>>) -> bool {
+ let code_led = payload.pointer("/buildPath/value").and_then(Value::as_str) == Some("code");
+ !code_led && any_comp_pending(cwd, &declared_comps(payload), hand)
+}
+
+fn visualize_ref(env: &Env, cwd: &str) -> String {
+ crate::provider::detect(env, cwd).reference_path("visualize").unwrap_or_else(|| "reference/visualize.md".to_string())
+}
+
+/// The directive that puts visualize.md in front of the agent at the moment
+/// the decision round's comps are about to be written.
+fn visualize_next_line(env: &Env, cwd: &str) -> String {
+ format!(
+ "NEXT read {} now, before writing any decision comp prompt; its comp rules govern every card's image. Then generate each declared comp into its slot, lead first, and record the exact prompt in its sidecar (<comp>.json).\n",
+ visualize_ref(env, cwd)
+ )
+}
+
+/// This hand's landed comps without a `<comp>.json` prompt sidecar.
+fn comps_missing_sidecar(cwd: &str, comps: &[String], hand: Option<&Map<String, Value>>) -> Vec<String> {
+ comps
+ .iter()
+ .filter(|c| comp_is_this_hands(cwd, c, hand) && !exists(&format!("{}.json", jsp::resolve(cwd, &[c.as_str()]))))
+ .cloned()
+ .collect()
+}
+
+/// The `--wait` note for files an earlier round left at this hand's slots.
+fn stale_comps_line(env: &Env, cwd: &str, stale: &[String]) -> String {
+ format!(
+ "COMP STALE: files left from an earlier round sit at this hand's slots, and the page is showing them: {}. Regenerate each into its slot now under the comp rules in {}, with its prompt sidecar, before the user decides.\n",
+ stale.join(", "),
+ visualize_ref(env, cwd)
+ )
+}
+
+/// The `--wait` backstop: names every landed decision comp with no sidecar.
+fn sidecar_missing_line(env: &Env, cwd: &str, missing: &[String]) -> String {
+ format!(
+ "COMP SIDECAR MISSING: {} landed with no prompt sidecar. Every decision comp records the exact prompt that produced it in <comp>.json ({{\"prompt\": \"...\"}}; generate-image writes it itself, a harness image tool does not), and that prompt is written under the comp rules in {}. Write each missing sidecar now, and read that file before the next comp prompt if you have not.\n",
+ missing.join(", "),
+ visualize_ref(env, cwd)
+ )
+}
+
+/// The comps recorded for the live round in `<key>.state.json`.
+fn state_comps(state: &Map<String, Value>) -> Vec<String> {
+ state.get("comps").and_then(Value::as_array).map(|a| a.iter().filter_map(|v| v.as_str().map(str::to_string)).collect()).unwrap_or_default()
+}
+
fn js_str(v: &Value) -> String {
match v {
Value::String(s) => s.clone(),
@@ -227,10 +525,17 @@ pub fn run(argv: &[String], io: &mut Io) -> i32 {
if exists(&flip_file(&qdir, &key)) {
let _ = std::fs::remove_file(flip_file(&qdir, &key));
io.out("BUILD PATH FLIPPED: comp (for this session only; never write it to settings). The table is still open and the page shows shimmer where the images will land: generate each open card’s comp into its declared path now, lead first, then collect the answer with --wait again. A card whose comp already exists needs nothing.\n");
+ // State without comps (a round from before comps were recorded)
+ // still gets the line; a round whose comps all landed does not.
+ let hand = read_hand(&qdir, &key);
+ let comps = round_comps(hand.as_ref(), read_state(&qdir, &key).as_ref());
+ if comps.is_empty() || any_comp_pending(&cwd, &comps, hand.as_ref()) {
+ io.out(&visualize_next_line(&env, &cwd));
+ }
return 0;
}
if !is_alive(&qdir, &key) {
- io.out("serve-question: the question server is gone with no answer. This is a server failure, not a user decision: restart it with --start and the same payload, reopen the URL for the user, and wait again. Never proceed without their choice while their browser session is open.\n");
+ io.out(&format!("serve-question: the question server is gone with no answer. This is a server failure, not a user decision: restart it with --start --key {} and the same payload, reopen the URL for the user, and wait again. Never proceed without their choice while their browser session is open.\n", key));
return 2;
}
if let Some(state) = read_state(&qdir, &key) {
@@ -251,13 +556,30 @@ pub fn run(argv: &[String], io: &mut Io) -> i32 {
io.out("PAGE CLOSED: the question page went away without an answer; re-present, reopen the URL, or fall back to the structured question tool\n");
return 4;
}
+ // Read before the answer path may delete the state file.
+ let (missing, stale) = {
+ let hand = read_hand(&qdir, &key);
+ let comps = round_comps(hand.as_ref(), read_state(&qdir, &key).as_ref());
+ (comps_missing_sidecar(&cwd, &comps, hand.as_ref()), stale_comps(&cwd, &comps, hand.as_ref()))
+ };
if !answered() {
io.out(&format!("WAITING: no answer yet after {}s; run --wait --key {} again\n", crate::util::js_number_to_string(poll_sec), key));
+ if !missing.is_empty() {
+ io.out(&sidecar_missing_line(&env, &cwd, &missing));
+ }
+ // Only while the user is still deciding: once they pick, the image
+ // they saw is the one they chose.
+ if !stale.is_empty() {
+ io.out(&stale_comps_line(&env, &cwd, &stale));
+ }
return 3;
}
let collected = safe_read(&answer_file(&qdir, &key)).unwrap_or_default();
let collected = crate::util::js_trim(&collected).to_string();
print_answer(io, &collected);
+ if !missing.is_empty() {
+ io.out(&sidecar_missing_line(&env, &cwd, &missing));
+ }
let mut keeps_open = false;
if let Ok(p) = serde_json::from_str::<Value>(&collected) {
keeps_open = p.get("optionId").and_then(|v| v.as_str()) == Some("reroll") || p.get("followup") == Some(&Value::Bool(true));
@@ -265,6 +587,8 @@ pub fn run(argv: &[String], io: &mut Io) -> i32 {
let _ = std::fs::remove_file(answer_file(&qdir, &key));
if !keeps_open {
let _ = std::fs::remove_file(state_file(&qdir, &key));
+ let _ = std::fs::remove_file(hand_file(&qdir, &key));
+ let _ = std::fs::remove_dir_all(generated_dir(&qdir, &key));
}
return 0;
}
@@ -281,6 +605,8 @@ pub fn run(argv: &[String], io: &mut Io) -> i32 {
}
let _ = std::fs::remove_file(answer_file(&qdir, &key));
let _ = std::fs::remove_file(state_file(&qdir, &key));
+ let _ = std::fs::remove_file(hand_file(&qdir, &key));
+ let _ = std::fs::remove_dir_all(generated_dir(&qdir, &key));
io.out("stopped\n");
return 0;
}
@@ -307,10 +633,21 @@ pub fn run(argv: &[String], io: &mut Io) -> i32 {
io.err("serve-question: no live question server for that key; the page it served is gone too. Re-present the round with --start and a fresh key, or fall back to the structured question tool.\n");
return 2;
}
+ // A delivered round is always a new hand. Recorded before delivery:
+ // on failure the page keeps the previous round, whose hand file is
+ // untouched, so nothing is served without its provenance.
+ let hand = new_hand(&cwd, &next_round);
+ if let Err(e) = write_hand(&qdir, &key, &hand) {
+ io.err(&format!("serve-question: could not record the hand ({}); nothing was delivered. Make .impeccable/questions/ writable and rerun --update on the same key.\n", e));
+ return 1;
+ }
let delivered = next_file(&qdir, &key);
let _ = std::fs::copy(jsp::resolve(&cwd, &[&pp]), &delivered);
touch_now(&delivered);
io.out("next round delivered; the page reloads itself\n");
+ if comps_expected(&next_round, &cwd, Some(&hand)) {
+ io.out(&visualize_next_line(&env, &cwd));
+ }
return 0;
}
@@ -319,12 +656,26 @@ pub fn run(argv: &[String], io: &mut Io) -> i32 {
io.err("serve-question: --start needs --payload <file>\n");
return 1;
};
- if let Err(msg) = read_json_file(&jsp::resolve(&cwd, &[&pp])) {
- io.err(&format!("{}\n", msg));
- return 1;
- }
+ let start_payload = match read_json_file(&jsp::resolve(&cwd, &[&pp])) {
+ Ok(v) => v,
+ Err(msg) => {
+ io.err(&format!("{}\n", msg));
+ return 1;
+ }
+ };
let _ = std::fs::create_dir_all(&qdir);
let key = a.arg("key").unwrap_or_else(random_key);
+ let hand = match start_hand(&qdir, &key, &cwd, &start_payload) {
+ Ok(h) => h,
+ Err(e) => {
+ io.err(&format!("serve-question: could not record the hand ({}); the page was not served. Make .impeccable/questions/ writable and rerun --start.\n", e));
+ return 1;
+ }
+ };
+ // The old state goes either way, so the wait below sees the new
+ // server's state, not the dead one's; its pid is never signalled,
+ // since a dead server's pid may have been reused.
+ let _ = std::fs::remove_file(state_file(&qdir, &key));
let log_file = jsp::join(&[&qdir, &format!("{}.log", key)]);
let log = std::fs::OpenOptions::new().append(true).create(true).open(&log_file);
let exe = std::env::current_exe().map(|p| p.to_string_lossy().into_owned()).unwrap_or_else(|_| "impeccable".to_string());
@@ -386,6 +737,9 @@ pub fn run(argv: &[String], io: &mut Io) -> i32 {
io.out(&format!("QUESTION URL: {}\n", state.get("url").map(js_str).unwrap_or_default()));
io.out(&format!("QUESTION KEY: {}\n", key));
io.out("Open the URL for the user now: in-app browser when the harness has one, otherwise the system opener (macOS `open`, Linux `xdg-open`), otherwise show the URL.\n");
+ if comps_expected(&start_payload, &cwd, Some(&hand)) {
+ io.out(&visualize_next_line(&env, &cwd));
+ }
io.out(&format!("Then collect the answer with: {} --wait --key {}\n", crate::provider::detect(&env, &cwd).verb_cmd("serve-question"), key));
return 0;
}
@@ -423,7 +777,11 @@ pub fn run(argv: &[String], io: &mut Io) -> i32 {
if a.has("detached-serve") {
let _ = std::fs::create_dir_all(&qdir);
let key = a.arg("key").unwrap_or_default();
- let st = json!({ "pid": std::process::id(), "port": actual_port, "url": url });
+ let mut st = json!({ "pid": std::process::id(), "port": actual_port, "url": url });
+ let comps = declared_comps(&state.lock().unwrap().payload);
+ if !comps.is_empty() {
+ st["comps"] = json!(comps);
+ }
let _ = std::fs::write(state_file(&qdir, &key), json_compact(&st));
} else {
io.out(&format!("QUESTION URL: {}\n", url));
@@ -495,6 +853,12 @@ pub fn run(argv: &[String], io: &mut Io) -> i32 {
if let Some(k) = st.detached_key.clone() {
if let Some(mut s) = read_state(&st.qdir, &k) {
s.insert("claimedAt".into(), Value::from(st.last_claim_at as i64));
+ let comps = declared_comps(&st.payload);
+ if comps.is_empty() {
+ s.remove("comps");
+ } else {
+ s.insert("comps".into(), json!(comps));
+ }
let _ = std::fs::write(state_file(&st.qdir, &k), json_compact(&Value::Object(s)));
}
}
@@ -1276,6 +1640,447 @@ mod tests {
assert!(!PAGE.contains("color-scheme: dark"));
}
+ fn temp_project(name: &str) -> std::path::PathBuf {
+ let dir = std::env::temp_dir().join(format!("impeccable-sq-{}-{}", name, std::process::id()));
+ let _ = std::fs::remove_dir_all(&dir);
+ std::fs::create_dir_all(dir.join(".impeccable/questions")).unwrap();
+ std::fs::create_dir_all(dir.join(".impeccable/mocks/decision")).unwrap();
+ dir
+ }
+
+ fn run_captured(dir: &std::path::Path, args: &[&str]) -> (i32, String) {
+ let env = Env::from([("IMPECCABLE_SKILL_DIR".into(), "/skill".into())]);
+ let (mut io, cap) = Io::captured("", dir.to_path_buf(), env);
+ let argv: Vec<String> = args.iter().map(|s| s.to_string()).collect();
+ let code = run(&argv, &mut io);
+ let out = String::from_utf8(cap.stdout.borrow().clone()).unwrap();
+ (code, out)
+ }
+
+ #[test]
+ fn declared_comps_reads_options_sketch_alias_and_canon_in_card_order() {
+ let payload = json!({
+ "options": [
+ { "id": "a", "comp": ".impeccable/mocks/decision/a.png" },
+ { "id": "b", "sketch": ".impeccable/mocks/decision/b.png" },
+ { "id": "c", "comp": "https://x/c.png" },
+ { "id": "d" },
+ { "id": "e", "comp": ".impeccable/mocks/decision/a.png" }
+ ],
+ "canonCard": { "label": "canon", "comp": ".impeccable/mocks/decision/canon.png" }
+ });
+ assert_eq!(
+ declared_comps(&payload),
+ vec![".impeccable/mocks/decision/a.png", ".impeccable/mocks/decision/b.png", ".impeccable/mocks/decision/canon.png"]
+ );
+ }
+
+ fn write_file(path: &std::path::Path, bytes: &[u8]) {
+ std::fs::write(path, bytes).unwrap();
+ }
+
+ fn write_state(dir: &std::path::Path, state: &Value) {
+ std::fs::write(dir.join(".impeccable/questions/k1.state.json"), state.to_string()).unwrap();
+ }
+
+ #[test]
+ fn comps_expected_only_for_pending_comp_slots_outside_a_code_led_round() {
+ let dir = temp_project("expected");
+ let cwd = dir.to_string_lossy().into_owned();
+ let with = json!({ "options": [{ "id": "a", "comp": "m/a.png" }] });
+ let hand = new_hand(&cwd, &with);
+ assert!(comps_expected(&with, &cwd, Some(&hand)));
+ let comp_led = json!({ "options": [{ "id": "a", "comp": "m/a.png" }], "buildPath": { "value": "comp", "toggle": true } });
+ assert!(comps_expected(&comp_led, &cwd, Some(&hand)));
+ let code_led = json!({ "options": [{ "id": "a", "comp": "m/a.png" }], "buildPath": { "value": "code", "toggle": true } });
+ assert!(!comps_expected(&code_led, &cwd, Some(&hand)));
+ let wireframes = json!({ "options": [{ "id": "a", "wireframe": { "cols": 12 } }] });
+ assert!(!comps_expected(&wireframes, &cwd, None));
+ let urls_only = json!({ "options": [{ "id": "a", "comp": "https://x/a.png" }] });
+ assert!(!comps_expected(&urls_only, &cwd, None));
+ // The comp round generates before it serves: its comps are on disk when
+ // the hand begins and are still its own.
+ write_file(&dir.join(".impeccable/mocks/comp-a.png"), b"a");
+ write_file(&dir.join(".impeccable/mocks/comp-b.png"), b"b");
+ let comp_round = json!({ "options": [{ "id": "a", "comp": ".impeccable/mocks/comp-a.png" }, { "id": "b", "comp": ".impeccable/mocks/comp-b.png" }] });
+ let hand = new_hand(&cwd, &comp_round);
+ assert!(!comps_expected(&comp_round, &cwd, Some(&hand)));
+ // One slot still empty is enough.
+ let partial = json!({ "options": [{ "id": "a", "comp": ".impeccable/mocks/comp-a.png" }, { "id": "c", "comp": ".impeccable/mocks/comp-c.png" }] });
+ let hand = new_hand(&cwd, &partial);
+ assert!(comps_expected(&partial, &cwd, Some(&hand)));
+ let _ = std::fs::remove_dir_all(&dir);
+ }
+
+ #[test]
+ fn a_comp_counts_for_the_hand_only_when_its_bytes_changed_since_the_hand_began() {
+ let dir = temp_project("provenance");
+ let cwd = dir.to_string_lossy().into_owned();
+ let slot = ".impeccable/mocks/decision/assigned.webp";
+ let payload = json!({ "options": [{ "id": "assigned", "comp": slot }] });
+ write_file(&dir.join(slot), b"old");
+ let hand = new_hand(&cwd, &payload);
+ // Same second, same bytes: the file an earlier round left is stale,
+ // whatever its timestamp says.
+ assert!(!comp_is_this_hands(&cwd, slot, Some(&hand)));
+ assert_eq!(stale_comps(&cwd, &[slot.to_string()], Some(&hand)), vec![slot.to_string()]);
+ assert!(comps_expected(&payload, &cwd, Some(&hand)));
+ write_file(&dir.join(slot), b"old");
+ assert!(!comp_is_this_hands(&cwd, slot, Some(&hand)));
+ // New bytes at the slot, even within the same second: this hand's.
+ write_file(&dir.join(slot), b"new");
+ assert!(comp_is_this_hands(&cwd, slot, Some(&hand)));
+ assert!(!comps_expected(&payload, &cwd, Some(&hand)));
+ // No file at the slot when the hand began: whatever lands is this hand's.
+ let fresh = ".impeccable/mocks/decision/pick.webp";
+ let payload2 = json!({ "options": [{ "id": "pick", "comp": fresh }] });
+ let hand2 = new_hand(&cwd, &payload2);
+ write_file(&dir.join(fresh), b"pick");
+ assert!(comp_is_this_hands(&cwd, fresh, Some(&hand2)));
+ // No hand recorded falls back to existence.
+ write_file(&dir.join(slot), b"old");
+ assert!(comp_is_this_hands(&cwd, slot, None));
+ let _ = std::fs::remove_dir_all(&dir);
+ }
+
+ #[test]
+ fn start_restarts_the_same_hand_and_starts_a_new_one_otherwise() {
+ let dir = temp_project("start-hand");
+ let cwd = dir.to_string_lossy().into_owned();
+ let qdir = jsp::join(&[&cwd, ".impeccable", "questions"]);
+ let slot = ".impeccable/mocks/decision/a.png";
+ let hand1 = json!({ "title": "Pick", "options": [{ "id": "a", "comp": slot }] });
+ let hand2 = json!({ "title": "Pick again", "options": [{ "id": "a", "comp": slot }] });
+
+ // Fresh start, a file an earlier session left at the slot: NEXT.
+ write_file(&dir.join(slot), b"earlier session");
+ let fresh = start_hand(&qdir, "k1", &cwd, &hand1).unwrap();
+ assert!(comps_expected(&hand1, &cwd, Some(&fresh)));
+ assert_eq!(read_hand(&qdir, "k1").as_ref(), Some(&fresh));
+
+ // The comp lands; the server dies; a restart of the same payload on the
+ // same key keeps the recorded fingerprints: no NEXT.
+ write_file(&dir.join(slot), b"this hand");
+ let restart = start_hand(&qdir, "k1", &cwd, &hand1).unwrap();
+ assert_eq!(restart, fresh);
+ assert!(!comps_expected(&hand1, &cwd, Some(&restart)));
+
+ // A different payload on that key is a new hand: the landed file is stale.
+ let other = start_hand(&qdir, "k1", &cwd, &hand2).unwrap();
+ assert_ne!(other, fresh);
+ assert!(comps_expected(&hand2, &cwd, Some(&other)));
+ let _ = std::fs::remove_dir_all(&dir);
+ }
+
+ #[test]
+ fn reroll_reusing_slots_owes_comps_until_they_land_even_across_a_restart() {
+ let dir = temp_project("reroll-hand");
+ let cwd = dir.to_string_lossy().into_owned();
+ let qdir = jsp::join(&[&cwd, ".impeccable", "questions"]);
+ let slot = ".impeccable/mocks/decision/a.png";
+ // The first hand's comp landed at the slot the re-roll reuses.
+ write_file(&dir.join(slot), b"first hand");
+ write_state(&dir, &json!({ "pid": std::process::id(), "port": 1, "url": "http://127.0.0.1:1/" }));
+ let reroll = json!({ "title": "Round 2", "options": [{ "id": "a", "comp": slot }] });
+ std::fs::write(dir.join("reroll.json"), reroll.to_string()).unwrap();
+ let (code, out) = run_captured(&dir, &["--update", "--key", "k1", "--payload", "reroll.json"]);
+ assert_eq!(code, 0);
+ assert!(out.contains("NEXT read "), "{out}");
+ let hand = read_hand(&qdir, "k1").unwrap();
+ assert_eq!(hand.get("digest").and_then(Value::as_str), Some(hand_digest(&reroll).as_str()));
+ assert_eq!(round_comps(Some(&hand), None), vec![slot.to_string()]);
+
+ // The server dies before the new comp lands; a restart of the re-roll
+ // payload keeps the re-roll's hand, so the old file still does not count.
+ let restart = start_hand(&qdir, "k1", &cwd, &reroll).unwrap();
+ assert_eq!(restart, hand);
+ assert!(comps_expected(&reroll, &cwd, Some(&restart)));
+ let _ = std::fs::remove_dir_all(&dir);
+ }
+
+ #[test]
+ fn server_state_writes_after_update_do_not_lose_the_hand() {
+ let dir = temp_project("hand-race");
+ let cwd = dir.to_string_lossy().into_owned();
+ let qdir = jsp::join(&[&cwd, ".impeccable", "questions"]);
+ let slot = ".impeccable/mocks/decision/a.png";
+ write_file(&dir.join(slot), b"first hand");
+ write_state(&dir, &json!({ "pid": std::process::id(), "port": 1, "url": "http://127.0.0.1:1/", "comps": [slot] }));
+ std::fs::write(dir.join("reroll.json"), json!({ "options": [{ "id": "a", "comp": slot }] }).to_string()).unwrap();
+ // The server read its state just before --update ran ...
+ let stale_read = read_state(&qdir, "k1").unwrap();
+ let (_, out) = run_captured(&dir, &["--update", "--key", "k1", "--payload", "reroll.json"]);
+ assert!(out.contains("NEXT read "), "{out}");
+ // ... and writes it back afterwards, as a heartbeat or claim does.
+ let mut s = stale_read.clone();
+ s.insert("lastBeat".into(), Value::from(now_ms() as i64));
+ std::fs::write(state_file(&qdir, "k1"), json_compact(&Value::Object(s.clone()))).unwrap();
+ s.insert("claimedAt".into(), Value::from(now_ms() as i64));
+ std::fs::write(state_file(&qdir, "k1"), json_compact(&Value::Object(s.clone()))).unwrap();
+ // The hand survives: the first hand's file is still named stale.
+ assert!(read_hand(&qdir, "k1").is_some());
+ let (_, out) = run_captured(&dir, &["--wait", "--key", "k1", "--poll", "0"]);
+ let out = out.replace('\\', "/");
+ assert!(out.contains("COMP STALE: ") && out.contains(slot), "{out}");
+ let _ = std::fs::remove_dir_all(&dir);
+ }
+
+ #[test]
+ fn deterministic_regeneration_into_a_reused_slot_counts_via_generated() {
+ let dir = temp_project("regen");
+ let cwd = dir.to_string_lossy().into_owned();
+ let qdir = jsp::join(&[&cwd, ".impeccable", "questions"]);
+ let slot = ".impeccable/mocks/decision/a.png";
+ let gen = |out: &str| {
+ let env = Env::from([("IMPECCABLE_IMAGE_GEN_FAKE".into(), "1".into())]);
+ let (mut io, cap) = Io::captured("", dir.clone(), env);
+ let args: Vec<String> = ["--prompt", "Same prompt, same bytes.", "--out", out, "--size", "64x40"].iter().map(|s| s.to_string()).collect();
+ let code = crate::generate_image::run(&args, &mut io);
+ assert_eq!(code, 0, "{}", String::from_utf8_lossy(&cap.stderr.borrow()));
+ };
+ // The previous hand generated into the slot.
+ gen(slot);
+ let before = std::fs::read(dir.join(slot)).unwrap();
+ write_state(&dir, &json!({ "pid": std::process::id(), "port": 1, "url": "http://127.0.0.1:1/" }));
+ std::fs::write(dir.join("reroll.json"), json!({ "options": [{ "id": "a", "comp": slot }] }).to_string()).unwrap();
+ let (_, out) = run_captured(&dir, &["--update", "--key", "k1", "--payload", "reroll.json"]);
+ assert!(out.contains("NEXT read "), "{out}");
+ let (_, out) = run_captured(&dir, &["--wait", "--key", "k1", "--poll", "0"]);
+ assert!(out.contains("COMP STALE: "), "{out}");
+ // The re-roll regenerates the same prompt: identical bytes, still this hand's.
+ gen(&format!("./{}", slot));
+ assert_eq!(std::fs::read(dir.join(slot)).unwrap(), before);
+ let hand = read_hand(&qdir, "k1").unwrap();
+ assert_eq!(hand.get("generated"), Some(&json!([slot])));
+ assert!(comp_is_this_hands(&cwd, slot, Some(&hand)));
+ let (_, out) = run_captured(&dir, &["--wait", "--key", "k1", "--poll", "0"]);
+ assert!(!out.contains("COMP STALE"), "{out}");
+ // Rewriting the prompt sidecar alone never counts: only generation or new bytes do.
+ std::fs::write(dir.join("again.json"), json!({ "title": "3", "options": [{ "id": "a", "comp": slot }] }).to_string()).unwrap();
+ run_captured(&dir, &["--update", "--key", "k1", "--payload", "again.json"]);
+ std::fs::write(dir.join(format!("{}.json", slot)), r#"{"prompt":"rewritten"}"#).unwrap();
+ let hand = read_hand(&qdir, "k1").unwrap();
+ assert!(hand.get("generated").is_none());
+ assert!(!comp_is_this_hands(&cwd, slot, Some(&hand)));
+ let _ = std::fs::remove_dir_all(&dir);
+ }
+
+ #[test]
+ fn a_failed_hand_write_fails_start_and_update() {
+ let dir = temp_project("hand-fail");
+ let qdir = jsp::join(&[&dir.to_string_lossy(), ".impeccable", "questions"]);
+ // A directory where the hand file belongs: the rename cannot land, on
+ // every platform.
+ std::fs::create_dir_all(hand_file(&qdir, "k1")).unwrap();
+ std::fs::write(dir.join("p.json"), json!({ "options": [{ "id": "a", "comp": ".impeccable/mocks/decision/a.png" }] }).to_string()).unwrap();
+ let err_of = |args: &[&str]| {
+ let env = Env::from([("IMPECCABLE_SKILL_DIR".into(), "/skill".into())]);
+ let (mut io, cap) = Io::captured("", dir.clone(), env);
+ let argv: Vec<String> = args.iter().map(|s| s.to_string()).collect();
+ let code = run(&argv, &mut io);
+ let out = String::from_utf8(cap.stdout.borrow().clone()).unwrap();
+ let err = String::from_utf8(cap.stderr.borrow().clone()).unwrap();
+ (code, out, err)
+ };
+ let (code, out, err) = err_of(&["--start", "--no-open", "--key", "k1", "--payload", "p.json"]);
+ assert_eq!(code, 1);
+ assert!(out.is_empty(), "{out}");
+ assert!(err.starts_with("serve-question: could not record the hand (") && err.contains("the page was not served"), "{err}");
+ assert!(!std::path::Path::new(&state_file(&qdir, "k1")).exists());
+
+ write_state(&dir, &json!({ "pid": std::process::id(), "port": 1, "url": "http://127.0.0.1:1/" }));
+ let (code, out, err) = err_of(&["--update", "--key", "k1", "--payload", "p.json"]);
+ assert_eq!(code, 1);
+ assert!(out.is_empty(), "{out}");
+ assert!(err.contains("nothing was delivered"), "{err}");
+ assert!(!std::path::Path::new(&next_file(&qdir, "k1")).exists());
+ let _ = std::fs::remove_dir_all(&dir);
+ }
+
+ #[test]
+ fn markers_survive_a_failed_hand_write_and_leave_with_the_question() {
+ let dir = temp_project("markers");
+ let cwd = dir.to_string_lossy().into_owned();
+ let qdir = jsp::join(&[&cwd, ".impeccable", "questions"]);
+ let payload = json!({ "options": [{ "id": "a", "comp": ".impeccable/mocks/decision/a.png" }] });
+ let live = new_hand(&cwd, &payload);
+ write_hand(&qdir, "k1", &live).unwrap();
+ std::fs::create_dir_all(dir.join(".impeccable/mocks/decision")).unwrap();
+ std::fs::write(dir.join(".impeccable/mocks/decision/a.png"), b"png").unwrap();
+ assert_eq!(record_generated(&cwd, ".impeccable/mocks/decision/a.png").unwrap(), vec!["k1".to_string()]);
+
+ // A failed write of the next hand keeps the live hand's marker.
+ let hand_path = hand_file(&qdir, "k1");
+ std::fs::remove_file(&hand_path).unwrap();
+ std::fs::create_dir_all(&hand_path).unwrap();
+ assert!(write_hand(&qdir, "k1", &new_hand(&cwd, &payload)).is_err());
+ std::fs::remove_dir_all(&hand_path).unwrap();
+ write_atomic(&hand_path, &json_compact(&Value::Object(live.clone()))).unwrap();
+ assert_eq!(read_hand(&qdir, "k1").unwrap().get("generated"), Some(&json!([".impeccable/mocks/decision/a.png"])));
+
+ // A new hand with the same payload does not inherit the old marker.
+ write_hand(&qdir, "k1", &new_hand(&cwd, &payload)).unwrap();
+ assert!(read_hand(&qdir, "k1").unwrap().get("generated").is_none());
+
+ // --stop takes the marker folder with the hand file.
+ record_generated(&cwd, ".impeccable/mocks/decision/a.png").unwrap();
+ write_state(&dir, &json!({ "pid": 0, "port": 1, "url": "http://127.0.0.1:1/" }));
+ let _ = run_captured(&dir, &["--stop", "--key", "k1"]);
+ assert!(!std::path::Path::new(&hand_file(&qdir, "k1")).exists());
+ assert!(!std::path::Path::new(&generated_dir(&qdir, "k1")).exists());
+ let _ = std::fs::remove_dir_all(&dir);
+ }
+
+ #[test]
+ fn comp_round_comps_sit_directly_in_mocks() {
+ assert!(is_comp_round_comp(".impeccable/mocks/comp-b-open-book.png"));
+ assert!(is_comp_round_comp("./.impeccable/mocks/comp-b.png"));
+ assert!(is_comp_round_comp("/abs/proj/.impeccable/mocks/comp-b.png"));
+ assert!(!is_comp_round_comp(".impeccable/mocks/decision/a.png"));
+ assert!(!is_comp_round_comp("https://x/a.png"));
+ assert!(!is_comp_round_comp("elsewhere/a.png"));
+ }
+
+ fn answer_lines(raw: &str) -> String {
+ let (mut io, cap) = Io::captured("", std::env::temp_dir(), Env::new());
+ print_answer(&mut io, raw);
+ let out = String::from_utf8(cap.stdout.borrow().clone()).unwrap();
+ out
+ }
+
+ #[test]
+ fn comp_round_pick_is_the_approved_comp_not_option_one() {
+ let out = answer_lines(r#"{"optionId":"b","steer":"","comp":".impeccable/mocks/comp-b-open-book.png"}"#);
+ assert!(out.contains("APPROVED COMP: the user picked this composition in the comp round"), "{out}");
+ assert!(out.contains("\"approved\": true"), "{out}");
+ assert!(!out.contains("CHOSEN COMP") && !out.contains("option one") && !out.contains("two variations"), "{out}");
+
+ let out = answer_lines(r#"{"optionId":"a","steer":"","comp":".impeccable/mocks/decision/a.png"}"#);
+ assert!(out.contains("CHOSEN COMP: the decision comp at that path is compositional option one."), "{out}");
+ assert!(!out.contains("APPROVED COMP"), "{out}");
+ }
+
+ #[test]
+ fn visualize_next_line_names_the_skill_reference() {
+ let env = Env::from([("IMPECCABLE_SKILL_DIR".into(), "/skill".into())]);
+ let line = visualize_next_line(&env, "/proj").replace('\\', "/");
+ assert!(line.starts_with("NEXT read /skill/reference/visualize.md now, before writing any decision comp prompt;"), "{line}");
+ assert!(line.ends_with("(<comp>.json).\n"));
+ }
+
+ #[test]
+ fn wait_names_landed_comps_without_a_prompt_sidecar() {
+ let dir = temp_project("wait-sidecar");
+ let comps = [".impeccable/mocks/decision/a.png", ".impeccable/mocks/decision/b.png", ".impeccable/mocks/decision/c.png"];
+ let state = json!({ "pid": std::process::id(), "port": 1, "url": "http://127.0.0.1:1/", "comps": comps });
+ std::fs::write(dir.join(".impeccable/questions/k1.state.json"), state.to_string()).unwrap();
+ // a landed without a sidecar, b landed with one, c has not landed yet.
+ std::fs::write(dir.join(comps[0]), b"png").unwrap();
+ std::fs::write(dir.join(comps[1]), b"png").unwrap();
+ std::fs::write(dir.join(format!("{}.json", comps[1])), r#"{"prompt":"p"}"#).unwrap();
+
+ let (code, out) = run_captured(&dir, &["--wait", "--key", "k1", "--poll", "0"]);
+ let out = out.replace('\\', "/");
+ assert_eq!(code, 3);
+ assert!(out.starts_with("WAITING: "), "{out}");
+ assert!(out.contains("COMP SIDECAR MISSING: .impeccable/mocks/decision/a.png landed with no prompt sidecar."), "{out}");
+ assert!(out.contains("/skill/reference/visualize.md"), "{out}");
+ assert!(!out.contains("decision/b.png") && !out.contains("decision/c.png"), "{out}");
+
+ std::fs::write(dir.join(".impeccable/questions/k1.answer.json"), r#"{"optionId":"a","comp":".impeccable/mocks/decision/a.png"}"#).unwrap();
+ let (code, out) = run_captured(&dir, &["--wait", "--key", "k1", "--poll", "2"]);
+ let out = out.replace('\\', "/");
+ assert_eq!(code, 0);
+ let answer_at = out.find("ANSWER: ").unwrap();
+ let missing_at = out.find("COMP SIDECAR MISSING: .impeccable/mocks/decision/a.png").unwrap();
+ assert!(answer_at < missing_at, "{out}");
+
+ // Once every landed comp has its sidecar, the backstop stays quiet.
+ std::fs::write(dir.join(format!("{}.json", comps[0])), r#"{"prompt":"p"}"#).unwrap();
+ std::fs::write(dir.join(".impeccable/questions/k1.state.json"), state.to_string()).unwrap();
+ let (_, out) = run_captured(&dir, &["--wait", "--key", "k1", "--poll", "0"]);
+ assert!(!out.contains("COMP SIDECAR MISSING"), "{out}");
+
+ // A file an earlier round left at a slot is named stale while the user
+ // decides, never as a missing sidecar, and not after the pick.
+ std::fs::remove_file(dir.join(format!("{}.json", comps[0]))).unwrap();
+ let qdir = jsp::join(&[&dir.to_string_lossy(), ".impeccable", "questions"]);
+ let payload = json!({ "options": comps.iter().map(|c| json!({ "comp": c })).collect::<Vec<_>>() });
+ write_hand(&qdir, "k1", &new_hand(&dir.to_string_lossy(), &payload)).unwrap();
+ std::fs::remove_file(dir.join(format!("{}.json", comps[1]))).unwrap();
+ std::fs::remove_file(dir.join(comps[1])).unwrap();
+ let (_, out) = run_captured(&dir, &["--wait", "--key", "k1", "--poll", "0"]);
+ let out = out.replace('\\', "/");
+ assert!(!out.contains("COMP SIDECAR MISSING"), "{out}");
+ assert!(out.contains("COMP STALE: files left from an earlier round sit at this hand's slots, and the page is showing them: .impeccable/mocks/decision/a.png."), "{out}");
+ std::fs::write(dir.join(".impeccable/questions/k1.answer.json"), r#"{"optionId":"a"}"#).unwrap();
+ let (_, out) = run_captured(&dir, &["--wait", "--key", "k1", "--poll", "2"]);
+ assert!(!out.contains("COMP STALE") && !out.contains("COMP SIDECAR MISSING"), "{out}");
+ let _ = std::fs::remove_dir_all(&dir);
+ }
+
+ #[test]
+ fn update_prints_the_visualize_directive_only_when_comps_are_due() {
+ let dir = temp_project("update-next");
+ let state = json!({ "pid": std::process::id(), "port": 1, "url": "http://127.0.0.1:1/" });
+ std::fs::write(dir.join(".impeccable/questions/k1.state.json"), state.to_string()).unwrap();
+ std::fs::write(dir.join("comp.json"), json!({ "options": [{ "id": "a", "comp": ".impeccable/mocks/decision/a.png" }] }).to_string()).unwrap();
+ let (code, out) = run_captured(&dir, &["--update", "--key", "k1", "--payload", "comp.json"]);
+ let out = out.replace('\\', "/");
+ assert_eq!(code, 0);
+ assert_eq!(out.lines().next(), Some("next round delivered; the page reloads itself"));
+ let next = out.lines().nth(1).unwrap();
+ assert!(next.starts_with("NEXT read ") && next.contains("/skill/reference/visualize.md now"), "{out}");
+
+ std::fs::write(dir.join("code.json"), json!({ "options": [{ "id": "a", "comp": ".impeccable/mocks/decision/a.png" }], "buildPath": { "value": "code", "toggle": true } }).to_string()).unwrap();
+ let (_, out) = run_captured(&dir, &["--update", "--key", "k1", "--payload", "code.json"]);
+ assert!(!out.contains("NEXT"), "{out}");
+
+ // A re-roll into the same decision slot still owes a new comp.
+ write_file(&dir.join(".impeccable/mocks/decision/a.png"), b"earlier");
+ let (_, out) = run_captured(&dir, &["--update", "--key", "k1", "--payload", "comp.json"]);
+ assert!(out.contains("NEXT read "), "{out}");
+
+ // A comp round serves comps already on disk directly in mocks/: no NEXT line.
+ write_file(&dir.join(".impeccable/mocks/comp-a.png"), b"comp");
+ std::fs::write(dir.join("round.json"), json!({ "options": [{ "id": "a", "comp": ".impeccable/mocks/comp-a.png" }] }).to_string()).unwrap();
+ let (_, out) = run_captured(&dir, &["--update", "--key", "k1", "--payload", "round.json"]);
+ assert_eq!(out, "next round delivered; the page reloads itself\n");
+ let _ = std::fs::remove_dir_all(&dir);
+ }
+
+ #[test]
+ fn flip_to_comp_puts_visualize_in_front_of_the_comps() {
+ let dir = temp_project("flip-next");
+ let state = json!({ "pid": std::process::id(), "port": 1, "url": "http://127.0.0.1:1/" });
+ std::fs::write(dir.join(".impeccable/questions/k1.state.json"), state.to_string()).unwrap();
+ std::fs::write(dir.join(".impeccable/questions/k1.flip.json"), r#"{"buildPath":"comp"}"#).unwrap();
+ let (code, out) = run_captured(&dir, &["--wait", "--key", "k1", "--poll", "2"]);
+ let out = out.replace('\\', "/");
+ assert_eq!(code, 0);
+ let lines: Vec<&str> = out.lines().collect();
+ assert!(lines[0].starts_with("BUILD PATH FLIPPED: comp"), "{out}");
+ assert!(lines[1].starts_with("NEXT read ") && lines[1].contains("/skill/reference/visualize.md now"), "{out}");
+
+ // A flip whose recorded comps all landed owes no new prompt.
+ std::fs::write(dir.join(".impeccable/mocks/decision/a.png"), b"png").unwrap();
+ let state = json!({ "pid": std::process::id(), "port": 1, "url": "http://127.0.0.1:1/", "comps": [".impeccable/mocks/decision/a.png"] });
+ std::fs::write(dir.join(".impeccable/questions/k1.state.json"), state.to_string()).unwrap();
+ std::fs::write(dir.join(".impeccable/questions/k1.flip.json"), r#"{"buildPath":"comp"}"#).unwrap();
+ let (_, out) = run_captured(&dir, &["--wait", "--key", "k1", "--poll", "2"]);
+ assert!(out.starts_with("BUILD PATH FLIPPED: comp") && !out.contains("NEXT"), "{out}");
+
+ // The file that sat at the slot when the hand began is not this hand's
+ // comp: still owed.
+ let qdir = jsp::join(&[&dir.to_string_lossy(), ".impeccable", "questions"]);
+ let payload = json!({ "options": [{ "id": "a", "comp": ".impeccable/mocks/decision/a.png" }] });
+ write_hand(&qdir, "k1", &new_hand(&dir.to_string_lossy(), &payload)).unwrap();
+ std::fs::write(dir.join(".impeccable/questions/k1.flip.json"), r#"{"buildPath":"comp"}"#).unwrap();
+ let (_, out) = run_captured(&dir, &["--wait", "--key", "k1", "--poll", "2"]);
+ assert!(out.contains("\nNEXT read "), "{out}");
+ let _ = std::fs::remove_dir_all(&dir);
+ }
+
// JS scenarios: tests/serve-question.test.mjs (public repo main,
// eaaecbd1 + 2e075dc5 + 7982002d).
diff --git a/docs/CLI-CONTRACT.md b/docs/CLI-CONTRACT.md
index f6a13db55..58b319528 100644
--- a/docs/CLI-CONTRACT.md
+++ b/docs/CLI-CONTRACT.md
@@ -421,18 +421,24 @@ retain their local-development trust behavior. See [bundle signing](BUNDLE-SIGNI
- **Invoked from**: `reference/new-work.md` "Run `node {{scripts_path}}/serve-question.mjs --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..."; `visualize.md:24` "Show the three together on the decision page (`serve-question.mjs`, one option per comp with the comp as its hero)"; `new-work.md` "each card carries a `wireframe` schematic (`serve-question.mjs --schema`)". Degraded concept-seed also names it.
- **Arg helper**: `arg(name)` = value after `--name` unless it starts with `--`; `hasFlag`.
- **Env gates** (evaluated at top): `IMPECCABLE_QUESTION_DISABLED` → `stdout> serve-question: disabled in this session (no browser); use the structured question tool instead.`, exit 2. Headless detection only when `wantsBrowser = !--no-open && !--wait && !--stop && !--schema && !--update` and `IMPECCABLE_QUESTION_FORCE` unset: `CI || (SSH_CONNECTION && !DISPLAY) || (linux && !DISPLAY && !WAYLAND_DISPLAY)` → `stdout> serve-question: no browser detected in this environment (CI/headless/remote); use the structured question tool instead. Set IMPECCABLE_QUESTION_FORCE=1 to serve anyway.`, exit 2.
-- **Common params**: `--payload <file>` (else stdin), `--timeout <sec>` (default 900; `0` = wait forever for a page; negative/NaN → 900), `--idle-grace <sec>` (default 600; ≤0/NaN → 600), `--port <n>` (default 0 = ephemeral), `--key`, `--no-open`, `--open`, `--poll <sec>` (wait, default 60). State dir `QUESTION_DIR = <cwd>/.impeccable/questions/` with files `<key>.state.json` (`{pid, port, url, lastBeat?, claimedAt?}`), `<key>.answer.json`, `<key>.flip.json`, `<key>.next.json`, `<key>.log`. `NEXT_CLAIM_GRACE_MS = 10000`.
+- **Common params**: `--payload <file>` (else stdin), `--timeout <sec>` (default 900; `0` = wait forever for a page; negative/NaN → 900), `--idle-grace <sec>` (default 600; ≤0/NaN → 600), `--port <n>` (default 0 = ephemeral), `--key`, `--no-open`, `--open`, `--poll <sec>` (wait, default 60). State dir `QUESTION_DIR = <cwd>/.impeccable/questions/` with files `<key>.state.json` (`{pid, port, url, comps?, lastBeat?, claimedAt?}`; `comps` is the live round's local decision comp paths, see **Decision comps** below), `<key>.hand.json` and `<key>.generated/` (the hand's provenance, **Decision comps**), `<key>.answer.json`, `<key>.flip.json`, `<key>.next.json`, `<key>.log`. `NEXT_CLAIM_GRACE_MS = 10000`.
- **Modes**:
- `--schema`: prints canonical payload JSON (2-space) then a long explanatory paragraph; exit 0. (Copy verbatim from source lines 210-232.)
- - `--wait --key K [--poll N]`: loops up to N s (1 s ticks): answer file → break; flip file exists → delete it, `stdout> BUILD PATH FLIPPED: comp (for this session only; never write it to settings). The table is still open and the page shows shimmer where the images will land: generate each open card’s comp into its declared path now, lead first, then collect the answer with --wait again. A card whose comp already exists needs nothing.` exit 0; server dead (no fresh `lastBeat` <12 s and `process.kill(pid,0)` fails with non-EPERM) → `stdout> serve-question: the question server is gone with no answer. This is a server failure, not a user decision: restart it with --start and the same payload, reopen the URL for the user, and wait again. Never proceed without their choice while their browser session is open.` exit 2; `lastBeat` older than 15 s and not mid-delivery (next.json mtime <10 s or `claimedAt` <10 s) → `PAGE CLOSED: the question page went away without an answer; re-present, reopen the URL, or fall back to the structured question tool` exit 4; no answer after poll → `WAITING: no answer yet after ${N}s; run --wait --key ${K} again` exit 3; answer → `printAnswer`, delete answer file, delete state file unless optionId `reroll` or `followup:true`; exit 0. Missing `--key` → `stderr> serve-question: --wait needs --key` exit 1.
- - `--stop --key K`: kill pid from state, remove answer/state, `stdout> stopped`, exit 0.
- - `--update --key K --payload F`: payload must have non-empty `options` (else stderr `serve-question: --update payload needs an options array; nothing was delivered. Fix the payload and rerun --update on the same key.` exit 1); server liveness like wait (dead → stderr `serve-question: no live question server for that key; the page it served is gone too. Re-present the round with --start and a fresh key, or fall back to the structured question tool.` exit 2); copies payload to `<key>.next.json`, touches mtime, `stdout> next round delivered; the page reloads itself`, exit 0.
- - `--start --payload F [--key K] [--open] [--timeout] [--idle-grace]`: validates JSON, spawns detached child `node serve-question.mjs --payload F --detached-serve --key K --timeout T [--idle-grace G] [--no-open unless --open]` with stdio to `<key>.log`; waits ≤8 s for state file; failure → stderr `serve-question: server failed to start` + last 4 log lines + `serve-question: log at <rel>. A sandboxed exec that cannot listen on localhost causes exactly this; rerun this command once through the harness's network-enabled or unsandboxed command tool before falling back.` exit 1; success stdout: `QUESTION URL: ${url}`, `QUESTION KEY: ${key}`, `Open the URL for the user now: in-app browser when the harness has one, otherwise the system opener (macOS \`open\`, Linux \`xdg-open\`), otherwise show the URL.`, `Then collect the answer with: node <abs script> --wait --key ${key}`; exit 0. Key default `Math.random().toString(16).slice(2,10)`.
+ - `--wait --key K [--poll N]`: loops up to N s (1 s ticks): answer file → break; flip file exists → delete it, `stdout> BUILD PATH FLIPPED: comp (for this session only; never write it to settings). The table is still open and the page shows shimmer where the images will land: generate each open card’s comp into its declared path now, lead first, then collect the answer with --wait again. A card whose comp already exists needs nothing.` followed by the `NEXT` visualize line (**Decision comps**), exit 0; server dead (no fresh `lastBeat` <12 s and `process.kill(pid,0)` fails with non-EPERM) → `stdout> serve-question: the question server is gone with no answer. This is a server failure, not a user decision: restart it with --start --key ${K} and the same payload, reopen the URL for the user, and wait again. Never proceed without their choice while their browser session is open.` exit 2; `lastBeat` older than 15 s and not mid-delivery (next.json mtime <10 s or `claimedAt` <10 s) → `PAGE CLOSED: the question page went away without an answer; re-present, reopen the URL, or fall back to the structured question tool` exit 4; no answer after poll → `WAITING: no answer yet after ${N}s; run --wait --key ${K} again` exit 3; answer → `printAnswer`, delete answer file, delete state and hand files unless optionId `reroll` or `followup:true`; exit 0. Missing `--key` → `stderr> serve-question: --wait needs --key` exit 1.
+ - `--stop --key K`: kill pid from state, remove answer/state/hand, `stdout> stopped`, exit 0.
+ - `--update --key K --payload F`: payload must have non-empty `options` (else stderr `serve-question: --update payload needs an options array; nothing was delivered. Fix the payload and rerun --update on the same key.` exit 1); server liveness like wait (dead → stderr `serve-question: no live question server for that key; the page it served is gone too. Re-present the round with --start and a fresh key, or fall back to the structured question tool.` exit 2); copies payload to `<key>.next.json`, touches mtime, writes a new hand to `<key>.hand.json`, `stdout> next round delivered; the page reloads itself`, then the `NEXT` visualize line when the new round's comps are due (**Decision comps**), exit 0.
+ - `--start --payload F [--key K] [--open] [--timeout] [--idle-grace]`: validates JSON, decides the hand and writes `<key>.hand.json` when it is new (**Decision comps**), removes the key's previous state file without signalling its pid, spawns detached child `node serve-question.mjs --payload F --detached-serve --key K --timeout T [--idle-grace G] [--no-open unless --open]` with stdio to `<key>.log`; waits ≤8 s for state file; failure → stderr `serve-question: server failed to start` + last 4 log lines + `serve-question: log at <rel>. A sandboxed exec that cannot listen on localhost causes exactly this; rerun this command once through the harness's network-enabled or unsandboxed command tool before falling back.` exit 1; success stdout: `QUESTION URL: ${url}`, `QUESTION KEY: ${key}`, `Open the URL for the user now: in-app browser when the harness has one, otherwise the system opener (macOS \`open\`, Linux \`xdg-open\`), otherwise show the URL.`, the `NEXT` visualize line when the payload's comps are due (**Decision comps**), `Then collect the answer with: node <abs script> --wait --key ${key}`; exit 0. Key default `Math.random().toString(16).slice(2,10)`.
- default (blocking): loads payload (error → stderr `serve-question: payload needs an options array` exit 1), listens on `127.0.0.1:${port}`, `stdout> QUESTION URL: http://127.0.0.1:${port}/` and `Waiting for the user to choose in the browser (Ctrl-C aborts)...`, opens browser unless `--no-open`; on answer prints via `printAnswer` and exits 0 after 150 ms. Detached mode writes state instead of printing.
+- **Decision comps** (engine addition, not in the JS): a round's declared comps are the local paths in each option's `comp` (or legacy `sketch`) and `canonCard.comp`, in card order, deduplicated; URLs are left out. The detached server writes them to the state file as `comps` (omitted when empty) and rewrites them when it claims a `--update` round.
+ - **Hands and provenance.** Each served hand's provenance lives in `<key>.hand.json`, `{"id": "<per-hand id>", "digest": "<first 16 hex of sha256 over the compact JSON of the whole payload>", "comps": [<declared comps>], "pre": {"<slot>": "<sha256 hex of the file bytes>"}}`. Only `--start` and `--update` write it, atomically (a temp file beside it, then a rename), and a failed write fails the command: `--start` prints `serve-question: could not record the hand (<file>: <error>); the page was not served. Make .impeccable/questions/ writable and rerun --start.` on stderr and exits 1 before spawning the server or touching the old state; `--update` prints `serve-question: could not record the hand (<file>: <error>); nothing was delivered. Make .impeccable/questions/ writable and rerun --update on the same key.` and exits 1 before copying `<key>.next.json`, so the page keeps the previous round with its hand file intact; the server never does, so its heartbeat and claim rewrites of the state file cannot drop a hand. `--update` always starts a new hand. `--start` keeps the recorded hand when the key's hand file carries the same digest (a restart) and otherwise starts a new one. A new hand fingerprints every declared slot that already holds a file into `pre`. The digest covers the whole payload, not only the slot paths, because a re-roll often reuses the previous hand's paths. `impeccable generate-image`, after writing `--out`, scans `.impeccable/questions/*.hand.json` for a hand that declares that path (resolved against the cwd; compared case-insensitively on Windows) and marks it generated during that hand with a marker file `<key>.generated/<16 hex of sha256 over the JSON string of the slot>.json` = `{"slot", "hand"}` (the hand's `id`), written atomically. Markers are one file per slot rather than a list inside the hand file because parallel generators (one subagent per card) would race a shared read-modify-write. A marker counts only while its `hand` matches the hand file's `id` (a hand file without an `id` matches on `digest`), so a re-roll that repeats a payload never inherits the previous hand's markers. Writing a new hand writes the hand file first and only then prunes markers that belong to another hand, so a failed write leaves the live hand and its markers intact and a parallel generation's marker for the new hand survives. `--stop` and a closing answer remove `<key>.generated/` with the hand file. A failed marker write prints `generate-image: could not mark <out> as generated for its decision page (<file>: <error>); a --wait may report it stale` on stderr and leaves the exit at 0, since the image itself was written. Readers merge the valid markers into the hand as `generated: [<slot>, ...]`. A declared comp is **this hand's** when its file exists and its slot is in `generated`, has no `pre` entry, or its current bytes hash differently from `pre`; timestamps play no part, so an old file rewritten unchanged in the same second is still not this hand's, while a deterministic generator's identical regeneration still counts through `generated`. Rewriting a comp's prompt sidecar never counts on its own: only new bytes or an engine generation do. Two exceptions: a comp directly in `.impeccable/mocks/` is the comp round's, generated before that round serves, and counts whenever it exists; with no hand file, existence decides. `--wait` judges the hand file's `comps`, else the state's. A declared comp that exists but is not this hand's is **stale**. The page itself still shows whatever file sits at a slot; hiding stale files there is out of scope.
+ - Three directives follow:
+ - `NEXT read ${skillDir}/reference/visualize.md now, before writing any decision comp prompt; its comp rules govern every card's image. Then generate each declared comp into its slot, lead first, and record the exact prompt in its sidecar (<comp>.json).` The path is the provider's skill dir (`IMPECCABLE_SKILL_DIR`, else the one found beside the binary); with neither it reads `reference/visualize.md`. Printed by `--start` between the `Open the URL` line and the `Then collect` line, and by `--update` after `next round delivered`, when `buildPath.value` is not `code` (a code-led round's slots are a flip reserve) and some declared comp is not this hand's yet; and by `--wait` right after `BUILD PATH FLIPPED`, when the state has no `comps` or one of them is not this hand's. The engine cannot see a harness-native image tool, so a slot without this hand's comp is the signal that comps are about to be written. So a fresh decision round (serve first, generate after) gets the line even when an earlier round left files at its slots; a restart of the same hand after its comps landed does not; a re-roll through `--update` that reuses slot paths does, and so does a restart of that re-roll before its comps land; the comp round, whose comps sit directly in `mocks/`, does not.
+ - `COMP SIDECAR MISSING: ${paths joined by ", "} landed with no prompt sidecar. Every decision comp records the exact prompt that produced it in <comp>.json ({"prompt": "..."}; generate-image writes it itself, a harness image tool does not), and that prompt is written under the comp rules in ${visualize path}. Write each missing sidecar now, and read that file before the next comp prompt if you have not.` Printed by `--wait` as the last line of a WAITING (exit 3) or answered (exit 0) return when a state `comps` path is this hand's comp and has no `<path>.json`. Comps that have not landed, and stale files, are skipped. It is a warning: exit codes and the answer are unchanged, because the user is mid-decision in the browser and blocking `--wait` would strand their answer.
+ - `COMP STALE: files left from an earlier round sit at this hand's slots, and the page is showing them: ${paths joined by ", "}. Regenerate each into its slot now under the comp rules in ${visualize path}, with its prompt sidecar, before the user decides.` Printed by `--wait` as the last line of a WAITING return (after `COMP SIDECAR MISSING` when both apply) when a state `comps` path is stale. Never on an answered return: once the user picks, the image they saw is the one they chose.
- **Payload processing** (`loadRound`): options decorated with `heroSrc`/`boardSrc` (http(s) URL passthrough; local path must exist → `/img/<i>`), `compSrc` (`comp` or legacy `sketch`; local path registered even if missing); `verdict==='declined'` cards moved to the end; `canonCard` appended as `{...card, id:'canon', isCanon:true}` before declined; `buildPath` `{value:'comp'|'code', toggle:bool}`.
- **HTTP routes**: `GET /` → HTML page (claims `<key>.next.json` if present, stamps `claimedAt`); `POST /heartbeat` → 204, updates `lastBeat` in state at most every 4 s; `GET /next-status` → `{"ready":bool}`; `GET /img/<n>` → local file stream (content-type by ext: webp/png/svg+xml/gif, else jpeg; 404 if missing); `POST /build-path` `{value}` → `{"ok":true}`, writes `<key>.flip.json` `{"buildPath":"comp"}` on a flip to comp; `POST /answer` `{optionId, steer, register?}` → `{"ok":true}` and answer JSON `{optionId, steer, [register], [followup:true], [hero, board], [comp], [buildPath, buildPathFlipped]}` written to answer file (detached) or printed; process exits 150 ms later unless reroll/followup in detached mode; else 404.
- **Page** (server-rendered HTML; `<title>${payload.title || 'impeccable · decision'}</title>`, `<h1>` payload.title or `Choose a direction`): cards with kicker, media (comp with shimmer + polling until `/img/<n>` returns 200; hero/board inspiration; wireframe grid), thesis, palette swatches (≤6), material tags (≤4), raise lines, facts, `Build this` / `Adopt anyway` (declined) / `Play it straight` (canon) buttons; optional `#steer` input (placeholder `Optional steer: what should be different or kept?`), `Re-roll` button with optional safer/bolder register buttons, `#canon` footer button when `canon && !canonCard`, build-path toggle. Client heartbeats every 5000 ms via `navigator.sendBeacon('/heartbeat')`; posts `/answer`; after reroll/followup polls `/next-status` and reloads.
-- **printAnswer**: `ANSWER: ${raw}` then conditional directive lines `CHOSEN CARD: ...`, `CHOSEN COMP: ...`, `CANON CHOSEN: ...`, `REGISTER: ...`, `FOLLOWUP OPEN: ...`, `BUILD PATH: ${value} (${origin}). ...` (verbatim in source lines 152-190).
+- **printAnswer**: `ANSWER: ${raw}` then conditional directive lines `CHOSEN CARD: ...`, `CHOSEN COMP: ...` (or, engine addition, `APPROVED COMP: the user picked this composition in the comp round, so it is the approved comp. Set "approved": true in its prompt sidecar (<comp>.json), record its path in the surface brief, then close the comps phase with build-phase advance. Build from it as it stands; never regenerate it.` in its place when the answer's `comp` sits directly in `.impeccable/mocks/`, where the comp round writes; decision comps under `.impeccable/mocks/decision/` and any other path keep `CHOSEN COMP`), `CANON CHOSEN: ...`, `REGISTER: ...`, `FOLLOWUP OPEN: ...`, `BUILD PATH: ${value} (${origin}). ...` (verbatim in source lines 152-190).
- **Lifetime**: no page ever beat → exit 2 `serve-question: timed out with no answer` after `--timeout` (unless 0); after beats, silence > idle-grace (with 10 s claim window for a delivered next hand) → exit 2 `serve-question: the page stopped beating and never came back; exiting`.
- **Browser opener** (`lib/open-system-browser.mjs`): darwin `open <url>`; win32 `${ComSpec||COMSPEC||'cmd.exe'} /c start "" <url>`; else `xdg-open <url>`; spawned `detached, stdio:'ignore'`, `unref`, errors swallowed; returns true/false.
- Tests: `tests/serve-question.test.mjs` (opener commands, blocking answer, reroll, start/wait cycle, headless gating, empty payload, heartbeat/timeouts, refresh semantics, --update, comps streaming), `tests/new-work-e2e.test.mjs`.
@@ -443,6 +449,7 @@ retain their local-development trust behavior. See [bundle signing](BUNDLE-SIGNI
- **Args**: `--prompt <text>` or `--prompt-file <path>` (file wins), `--out <path>` (required), `--size <WxH>` (default `1536x1024`), `--quality` (default `medium`), `--ref <img>` repeatable.
- **Fake mode** `IMPECCABLE_IMAGE_GEN_FAKE=1`: no network; `.svg` out → SVG with prompt-hashed 2-3 color gradient (FNV-1a), wrapped prompt text, `SYNTHETIC COMP` label; otherwise a minimal PNG (palette stripes, `tEXt` chunk `Comment\0SYNTHETIC COMP: <prompt>`); size parsed by `/^(\d+)x(\d+)$/` else 1536x1024; `stdout> IMAGE: ${out} (${w}x${h}, fake synthetic comp, $0.00, no API call)`; exit 0. Missing prompt/out → stderr `generate-image: --prompt (or --prompt-file) and --out are required.` exit 1.
- **Real mode**: no `OPENAI_API_KEY` → stderr `generate-image: OPENAI_API_KEY is not set; use the harness-native image tool instead.` exit 1. Without refs: `POST https://api.openai.com/v1/images/generations`, headers `Authorization: Bearer <key>`, `content-type: application/json`, body `{"model":"gpt-image-2","prompt":...,"size":...,"quality":...,"n":1}`. With refs: `POST https://api.openai.com/v1/images/edits` multipart FormData fields `model=gpt-image-2`, `prompt`, `size`, `quality`, `n=1`, `image[]` blobs (type png/webp else jpeg, filename basename). Non-ok → stderr `generate-image: API error ${status}: ${first 300 chars}` exit 1; no `data[0].b64_json` → `generate-image: no image in response` exit 1. Writes decoded bytes to `--out`; best-effort `node embed-prompt.mjs <out> --prompt <prompt>` and sidecar `${out}.json` = `{prompt, createdAt: ISO, tool: 'generate-image.mjs', model: 'gpt-image-2', [refs]}` (2-space). stdout `IMAGE: ${out} (${size}, ${quality}, gpt-image-2, billed to your OpenAI key); prompt embedded + sidecar at ${out}.json`; exit 0.
+- **Decision slots** (engine addition, both modes): after the image is written, `--out` is marked generated in any recorded decision hand that declares it (`serve-question` **Decision comps**); a failed mark is a stderr warning, never an exit change.
- Tests: `tests/new-work-e2e.test.mjs` (fake mode chain, opt-in `test:new-work-e2e`).
#### comp-fidelity verbs: `comp-spec` / `comp-diff` / `font-match` / `build-phase`
diff --git a/package.json b/package.json
index 98eb26801..e488912c4 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.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"
+ "@impeccable/cli-darwin-arm64": "0.1.8",
+ "@impeccable/cli-darwin-x64": "0.1.8",
+ "@impeccable/cli-linux-x64": "0.1.8",
+ "@impeccable/cli-linux-arm64": "0.1.8",
+ "@impeccable/cli-windows-x64": "0.1.8"
},
"devDependencies": {
"@ai-sdk/anthropic": "^4.0.7",
diff --git a/skill/reference/new-work.md b/skill/reference/new-work.md
index a77b5d511..c11977550 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. 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 -->
+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. Once a round declares comps it has not generated yet, `impeccable serve-question --start` (and `--update`, and a flip to comp) prints a `NEXT read <path>/visualize.md` line; read that file then, before the first prompt. `--wait` prints `COMP SIDECAR MISSING` for any landed decision comp with no prompt sidecar; write the missing sidecar before you continue. `COMP STALE` names a file an earlier round left at one of this hand's slots; regenerate it there. 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 -->
diff --git a/skill/scripts/VERSION b/skill/scripts/VERSION
index 11808190d..699c6c6d4 100644
--- a/skill/scripts/VERSION
+++ b/skill/scripts/VERSION
@@ -1 +1 @@
-0.1.7
+0.1.8
diff --git a/tests/oracle/DELTAS.md b/tests/oracle/DELTAS.md
index 0e7fd505b..2aca83c03 100644
--- a/tests/oracle/DELTAS.md
+++ b/tests/oracle/DELTAS.md
@@ -246,3 +246,26 @@ 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.
+
+## Recorded 2026-09-29: visualize.md before decision comps
+
+Agents wrote decision comp prompts before opening `reference/visualize.md`, which holds every comp-prompt rule, while they followed the engine's printed NEXT lines reliably. `serve-question` now prints a `NEXT read <skill>/reference/visualize.md now, before writing any decision comp prompt; ...` line when a round's comps are due, and `--wait` names landed decision comps that have no prompt sidecar.
+
+- `question-wait-flip`: after the unchanged `BUILD PATH FLIPPED` line, one added `NEXT read <REPO>/skill/reference/visualize.md now, ...` line (a flip to comp is the moment a code-led round's comps start). Exit status and files are unchanged.
+
+New cases, recorded from the binary and reviewed by hand: `question-wait-comp-sidecar-missing` (WAITING plus `COMP SIDECAR MISSING` naming only the landed comp without a sidecar), `question-wait-answer-comp-sidecar-missing` (the same line after the ANSWER block), `question-update-comps-next` (the NEXT line after `next round delivered`), `question-update-code-led-no-next` (a code-led round prints no NEXT line). `--start` is not in the corpus because it binds a port; Rust tests in `crates/context/src/serve_question.rs` cover its trigger.
+
+Follow-up on the same branch: the NEXT line now also requires a declared comp that is not on disk yet (a comp-round page serves comps that already exist, so "before writing any decision comp prompt" was stale there), and a comp-round pick no longer prints the decision-round `CHOSEN COMP` line ("compositional option one ... adds two variations"), which predates this branch. It prints `APPROVED COMP: ...` instead, keyed on the comp sitting directly in `.impeccable/mocks/`. No existing golden changed. New cases: `question-update-comps-landed-no-next` (every declared comp exists, no NEXT line) and `question-wait-answer-comp-round` (`APPROVED COMP` in place of `CHOSEN COMP`).
+
+Provenance by hand timestamp (same branch): deciding whether a comp is owed by existence alone misread files an earlier round left at reused slot paths. Every served hand now records `handAt` and `handDigest` in the state file, and a declared comp counts for the hand only when written at or after `handAt` (comp-round comps directly in `.impeccable/mocks/` excepted). A restart is `--start` with the same key and payload, so the dead-server message now names the key:
+
+- `question-wait-no-server`, `question-wait-dead-pid`: `restart it with --start and the same payload` reads `restart it with --start --key k1 and the same payload`. Exit status and files are unchanged.
+
+New case `question-wait-comp-stale`: `handAt` in 2100 makes the staged comp one an earlier round left, so WAITING is followed by `COMP STALE: ...` naming it, and no `COMP SIDECAR MISSING`. The other decision-comp goldens carry no `handAt`, which falls back to existence, so they did not move.
+
+Hand file and content fingerprints (same branch, supersedes the `handAt` rule above): `--update` wrote the hand into `<key>.state.json`, which the server rewrites on heartbeat and claim, so an overlapping write could drop the hand; and flooring `handAt` to the second let an old image rewritten in the same second pass. Provenance now lives in `<key>.hand.json` (`digest`, `comps`, `pre` fingerprints), written atomically by `--start` and `--update` only, and a comp is this hand's when its bytes differ from the slot's `pre` fingerprint (or the slot had none).
+
+- `question-wait-comp-stale`: the staged provenance moved from `handAt`/`handDigest` in the state file to a hand file whose `pre` fingerprint matches the staged `a.png`. Stdout and exit are unchanged; the snapshot now lists the hand file, and the state file no longer carries hand fields.
+- `question-update-comps-next`: now snapshots `.impeccable/questions/k1.hand.json`, the new hand `--update` writes (`pre` is empty because neither slot holds a file). Stdout and exit are unchanged.
+
+Generated slots and hand-write failures (same branch): a deterministic generator returns identical bytes for an unchanged prompt, so a re-roll regenerating into a reused slot failed the fingerprint rule forever. `impeccable generate-image` now marks a written `--out` that a recorded hand declares with a marker file in `<key>.generated/`, and such a slot counts as this hand's. A failed hand write now fails `--start` (before spawning) and `--update` (before delivering) with exit 1. No existing golden changed. New case `genimg-fake-marks-hand-slot`: the fake generator writes a declared slot and the snapshot shows the marker beside the untouched hand file. The failure path is covered by Rust tests, not the oracle, because its stderr carries the OS error text, which differs per platform. Follow-up: markers name their hand by `hand` (the hand's per-hand `id`, falling back to `digest` for a hand file without one) instead of `digest`, so `genimg-fake-marks-hand-slot` now shows `"hand":"0123456789abcdef"` where it showed `"digest"`; a new hand prunes other hands' markers only after its own write succeeds, and `--stop` and a closing answer remove the marker folder. `question-update-comps-next` now snapshots the hand file with its per-hand `id`, which mixes the clock and the pid, so that case masks it as `<HAND_ID>` with a case-scoped normalizer.
diff --git a/tests/oracle/cases/context.mjs b/tests/oracle/cases/context.mjs
index 97097e50b..5f05719b5 100644
--- a/tests/oracle/cases/context.mjs
+++ b/tests/oracle/cases/context.mjs
@@ -687,6 +687,8 @@ const cases = [
{ id: 'genimg-fake-svg-default-size', verb: 'generate-image', workspace: 'ctx-empty', args: ['--prompt', 'Short.', '--out', 'hero.svg', '--size', 'huge'], env: env({ IMPECCABLE_IMAGE_GEN_FAKE: '1' }), files: ['hero.svg*'] },
{ id: 'genimg-fake-png', verb: 'generate-image', workspace: 'ctx-empty', setup: (ws) => fs.mkdirSync(path.join(ws, 'comps')), args: ['--prompt', 'A dashboard comp.', '--out', 'comps/dash.png', '--size', '640x400'], env: env({ IMPECCABLE_IMAGE_GEN_FAKE: '1' }), files: ['comps/**'], steps: [{}, { verb: 'embed-prompt', args: ['comps/dash.png', '--read'] }] },
{ id: 'genimg-fake-prompt-file', verb: 'generate-image', workspace: 'ctx-empty', setup: (ws) => write(ws, 'prompt.txt', 'Prompt from file wins.\n'), args: ['--prompt', 'inline loses', '--prompt-file', 'prompt.txt', '--out', 'x.svg', '--size', '400x300'], env: env({ IMPECCABLE_IMAGE_GEN_FAKE: '1' }), files: ['x.svg*'] },
+ // generate-image writing a declared slot of a recorded hand marks it generated during that hand (one marker file per slot), so a deterministic regeneration with identical bytes still counts; a path no hand declares gets no marker.
+ { id: 'genimg-fake-marks-hand-slot', verb: 'generate-image', workspace: 'ctx-empty', setup: (ws) => { fs.mkdirSync(path.join(ws, '.impeccable/mocks/decision'), { recursive: true }); write(ws, '.impeccable/questions/k1.hand.json', JSON.stringify({ digest: '0123456789abcdef', comps: ['.impeccable/mocks/decision/a.png', '.impeccable/mocks/decision/b.png'], pre: {} })); }, args: ['--prompt', 'A decision comp.', '--out', '.impeccable/mocks/decision/a.png', '--size', '64x40'], env: env({ IMPECCABLE_IMAGE_GEN_FAKE: '1' }), files: ['.impeccable/questions/**'] },
{ id: 'genimg-real-no-key', verb: 'generate-image', workspace: 'ctx-empty', args: ['--prompt', 'x', '--out', 'x.png'], env: env() },
{ id: 'genimg-real-missing-args', verb: 'generate-image', workspace: 'ctx-empty', args: ['--out', 'x.png'], env: env({ OPENAI_API_KEY: 'sk-oracle' }) },
@@ -706,6 +708,20 @@ const cases = [
{ id: 'question-wait-flip', verb: 'serve-question', workspace: 'ctx-empty', setup: (ws) => { write(ws, '.impeccable/questions/k1.state.json', JSON.stringify({ pid: 1, port: 1, url: 'http://127.0.0.1:1/' })); write(ws, '.impeccable/questions/k1.flip.json', JSON.stringify({ buildPath: 'comp' })); }, args: ['--wait', '--key', 'k1', '--poll', '2'], env: env(), files: ['.impeccable/questions/**'] },
{ id: 'question-wait-page-closed', verb: 'serve-question', workspace: 'ctx-empty', setup: (ws) => write(ws, '.impeccable/questions/k1.state.json', JSON.stringify({ pid: 1, port: 1, url: 'http://127.0.0.1:1/', lastBeat: 1000 })), args: ['--wait', '--key', 'k1', '--poll', '2'], env: env(), files: ['.impeccable/questions/**'] },
{ id: 'question-wait-dead-pid', verb: 'serve-question', workspace: 'ctx-empty', setup: (ws) => write(ws, '.impeccable/questions/k1.state.json', JSON.stringify({ pid: 2147483000, port: 1, url: 'http://127.0.0.1:1/', lastBeat: 1000 })), args: ['--wait', '--key', 'k1', '--poll', '2'], env: env(), files: ['.impeccable/questions/**'] },
+ // The decision-comp backstop: comps the live round declared (state.comps) that landed without a <comp>.json sidecar are named on every --wait return; b has its sidecar and c has not landed, so only a is named.
+ { id: 'question-wait-comp-sidecar-missing', verb: 'serve-question', workspace: 'ctx-empty', setup: (ws) => { write(ws, '.impeccable/questions/k1.state.json', JSON.stringify({ pid: 1, port: 1, url: 'http://127.0.0.1:1/', comps: ['.impeccable/mocks/decision/a.png', '.impeccable/mocks/decision/b.png', '.impeccable/mocks/decision/c.png'] })); write(ws, '.impeccable/mocks/decision/a.png', 'png'); write(ws, '.impeccable/mocks/decision/b.png', 'png'); write(ws, '.impeccable/mocks/decision/b.png.json', JSON.stringify({ prompt: 'b' })); }, args: ['--wait', '--key', 'k1', '--poll', '0'], env: env(), files: ['.impeccable/questions/**'] },
+ { id: 'question-wait-answer-comp-sidecar-missing', verb: 'serve-question', workspace: 'ctx-empty', setup: (ws) => { write(ws, '.impeccable/questions/k1.state.json', JSON.stringify({ pid: 1, port: 1, url: 'http://127.0.0.1:1/', comps: ['.impeccable/mocks/decision/a.png', '.impeccable/mocks/decision/b.png'] })); write(ws, '.impeccable/mocks/decision/a.png', 'png'); write(ws, '.impeccable/mocks/decision/b.png', 'png'); write(ws, '.impeccable/questions/k1.answer.json', JSON.stringify({ optionId: 'a', steer: '', comp: '.impeccable/mocks/decision/a.png', buildPath: 'comp', buildPathFlipped: false })); }, args: ['--wait', '--key', 'k1', '--poll', '2'], env: env(), files: ['.impeccable/questions/**'] },
+ // Provenance: a declared comp counts for the hand only when its bytes differ from the file that sat at the slot when the hand began (the hand file's `pre` fingerprints). a is still those bytes (sha256 of "png"), so it is named COMP STALE, not a missing sidecar; b never landed.
+ { id: 'question-wait-comp-stale', verb: 'serve-question', workspace: 'ctx-empty', setup: (ws) => { write(ws, '.impeccable/questions/k1.state.json', JSON.stringify({ pid: 1, port: 1, url: 'http://127.0.0.1:1/', comps: ['.impeccable/mocks/decision/a.png', '.impeccable/mocks/decision/b.png'] })); write(ws, '.impeccable/questions/k1.hand.json', JSON.stringify({ digest: '0000000000000000', comps: ['.impeccable/mocks/decision/a.png', '.impeccable/mocks/decision/b.png'], pre: { '.impeccable/mocks/decision/a.png': '8f8cbb7dcf46e0bc7d53265749a6c17d116093a6ba95e442764060c76fd4a86c' } })); write(ws, '.impeccable/mocks/decision/a.png', 'png'); }, args: ['--wait', '--key', 'k1', '--poll', '0'], env: env(), files: ['.impeccable/questions/**'] },
+ // --update with a round that declares comps prints the NEXT visualize.md line; a code-led round (comp slots as flip reserve) does not.
+ { id: 'question-update-comps-next', verb: 'serve-question', workspace: 'ctx-empty', setup: (ws) => { write(ws, '.impeccable/questions/k1.state.json', JSON.stringify({ pid: 1, port: 1, url: 'http://127.0.0.1:1/' })); write(ws, 'payload.json', JSON.stringify({ title: 'Pick', options: [{ id: 'a', label: 'A', thesis: 'One.', comp: '.impeccable/mocks/decision/a.png' }, { id: 'b', label: 'B', thesis: 'Two.', comp: '.impeccable/mocks/decision/b.png' }], buildPath: { value: 'comp', toggle: true } })); }, args: ['--update', '--key', 'k1', '--payload', 'payload.json'], env: env(), files: ['.impeccable/questions/*.hand.json'],
+ // The per-hand id mixes the clock and the pid, so it is masked.
+ normalize: [['("id":")[0-9a-f]{16}', 'g', '$1<HAND_ID>']] },
+ { id: 'question-update-code-led-no-next', verb: 'serve-question', workspace: 'ctx-empty', setup: (ws) => { write(ws, '.impeccable/questions/k1.state.json', JSON.stringify({ pid: 1, port: 1, url: 'http://127.0.0.1:1/' })); write(ws, 'payload.json', JSON.stringify({ title: 'Pick', options: [{ id: 'a', label: 'A', thesis: 'One.', comp: '.impeccable/mocks/decision/a.png' }], buildPath: { value: 'code', toggle: true } })); }, args: ['--update', '--key', 'k1', '--payload', 'payload.json'], env: env() },
+ // A comp-round payload serves comps that already exist, so --update prints no NEXT line.
+ { id: 'question-update-comps-landed-no-next', verb: 'serve-question', workspace: 'ctx-empty', setup: (ws) => { write(ws, '.impeccable/questions/k1.state.json', JSON.stringify({ pid: 1, port: 1, url: 'http://127.0.0.1:1/' })); write(ws, '.impeccable/mocks/comp-a.png', 'png'); write(ws, '.impeccable/mocks/comp-b.png', 'png'); write(ws, 'payload.json', JSON.stringify({ title: 'Pick', options: [{ id: 'a', label: 'A', thesis: 'One.', comp: '.impeccable/mocks/comp-a.png' }, { id: 'b', label: 'B', thesis: 'Two.', comp: '.impeccable/mocks/comp-b.png' }] })); }, args: ['--update', '--key', 'k1', '--payload', 'payload.json'], env: env() },
+ // A comp-round pick (comp directly under .impeccable/mocks/) is the approved comp, not decision option one.
+ { id: 'question-wait-answer-comp-round', verb: 'serve-question', workspace: 'ctx-empty', setup: (ws) => { write(ws, '.impeccable/questions/k1.state.json', JSON.stringify({ pid: 1, port: 1, url: 'http://127.0.0.1:1/', comps: ['.impeccable/mocks/comp-b-open-book.png'] })); write(ws, '.impeccable/mocks/comp-b-open-book.png', 'png'); write(ws, '.impeccable/mocks/comp-b-open-book.png.json', JSON.stringify({ prompt: 'b' })); write(ws, '.impeccable/questions/k1.answer.json', JSON.stringify({ optionId: 'b', steer: '', comp: '.impeccable/mocks/comp-b-open-book.png' })); }, args: ['--wait', '--key', 'k1', '--poll', '2'], env: env(), files: ['.impeccable/questions/**'] },
{ id: 'question-stop-no-key', verb: 'serve-question', workspace: 'ctx-empty', args: ['--stop'], env: env() },
{ id: 'question-stop-nothing', verb: 'serve-question', workspace: 'ctx-empty', args: ['--stop', '--key', 'k1'], env: env(), files: ['.impeccable/questions/**'] },
{ id: 'question-stop-clears-files', verb: 'serve-question', workspace: 'ctx-empty', setup: (ws) => { write(ws, '.impeccable/questions/k1.state.json', JSON.stringify({ pid: 2147483000, port: 1, url: 'x' })); write(ws, '.impeccable/questions/k1.answer.json', '{}'); write(ws, '.impeccable/questions/k1.log', 'log\n'); }, args: ['--stop', '--key', 'k1'], env: env(), files: ['.impeccable/questions/**'] },
diff --git a/tests/oracle/golden/genimg-fake-marks-hand-slot.json b/tests/oracle/golden/genimg-fake-marks-hand-slot.json
new file mode 100644
index 000000000..574705902
--- /dev/null
+++ b/tests/oracle/golden/genimg-fake-marks-hand-slot.json
@@ -0,0 +1,10 @@
+{
+ "stdout": "IMAGE: .impeccable/mocks/decision/a.png (64x40, fake synthetic comp, $0.00, no API call)\n",
+ "stderr": "",
+ "exit": 0,
+ "signal": null,
+ "files": {
+ ".impeccable/questions/k1.generated/bc804e5cae3cb360.json": "{\"slot\":\".impeccable/mocks/decision/a.png\",\"hand\":\"0123456789abcdef\"}",
+ ".impeccable/questions/k1.hand.json": "{\"digest\":\"0123456789abcdef\",\"comps\":[\".impeccable/mocks/decision/a.png\",\".impeccable/mocks/decision/b.png\"],\"pre\":{}}"
+ }
+}
diff --git a/tests/oracle/golden/question-update-code-led-no-next.json b/tests/oracle/golden/question-update-code-led-no-next.json
new file mode 100644
index 000000000..bda76be2c
--- /dev/null
+++ b/tests/oracle/golden/question-update-code-led-no-next.json
@@ -0,0 +1,7 @@
+{
+ "stdout": "next round delivered; the page reloads itself\n",
+ "stderr": "",
+ "exit": 0,
+ "signal": null,
+ "files": {}
+}
diff --git a/tests/oracle/golden/question-update-comps-landed-no-next.json b/tests/oracle/golden/question-update-comps-landed-no-next.json
new file mode 100644
index 000000000..bda76be2c
--- /dev/null
+++ b/tests/oracle/golden/question-update-comps-landed-no-next.json
@@ -0,0 +1,7 @@
+{
+ "stdout": "next round delivered; the page reloads itself\n",
+ "stderr": "",
+ "exit": 0,
+ "signal": null,
+ "files": {}
+}
diff --git a/tests/oracle/golden/question-update-comps-next.json b/tests/oracle/golden/question-update-comps-next.json
new file mode 100644
index 000000000..130cd0c19
--- /dev/null
+++ b/tests/oracle/golden/question-update-comps-next.json
@@ -0,0 +1,9 @@
+{
+ "stdout": "next round delivered; the page reloads itself\nNEXT read <REPO>/skill/reference/visualize.md now, before writing any decision comp prompt; its comp rules govern every card's image. Then generate each declared comp into its slot, lead first, and record the exact prompt in its sidecar (<comp>.json).\n",
+ "stderr": "",
+ "exit": 0,
+ "signal": null,
+ "files": {
+ ".impeccable/questions/k1.hand.json": "{\"id\":\"<HAND_ID>\",\"digest\":\"b8a44b4d47c1219e\",\"comps\":[\".impeccable/mocks/decision/a.png\",\".impeccable/mocks/decision/b.png\"],\"pre\":{}}"
+ }
+}
diff --git a/tests/oracle/golden/question-wait-answer-comp-round.json b/tests/oracle/golden/question-wait-answer-comp-round.json
new file mode 100644
index 000000000..8c00aa55a
--- /dev/null
+++ b/tests/oracle/golden/question-wait-answer-comp-round.json
@@ -0,0 +1,7 @@
+{
+ "stdout": "ANSWER: {\"optionId\":\"b\",\"steer\":\"\",\"comp\":\".impeccable/mocks/comp-b-open-book.png\"}\nAPPROVED COMP: the user picked this composition in the comp round, so it is the approved comp. Set \"approved\": true in its prompt sidecar (<comp>.json), record its path in the surface brief, then close the comps phase with build-phase advance. Build from it as it stands; never regenerate it.\n",
+ "stderr": "",
+ "exit": 0,
+ "signal": null,
+ "files": {}
+}
diff --git a/tests/oracle/golden/question-wait-answer-comp-sidecar-missing.json b/tests/oracle/golden/question-wait-answer-comp-sidecar-missing.json
new file mode 100644
index 000000000..42c94a1b7
--- /dev/null
+++ b/tests/oracle/golden/question-wait-answer-comp-sidecar-missing.json
@@ -0,0 +1,7 @@
+{
+ "stdout": "ANSWER: {\"optionId\":\"a\",\"steer\":\"\",\"comp\":\".impeccable/mocks/decision/a.png\",\"buildPath\":\"comp\",\"buildPathFlipped\":false}\nCHOSEN COMP: the decision comp at that path is compositional option one. On a comp-led build the comp round adds two variations beside it; on a code-led build it returns at the finish review as the critique reference. Never regenerate it from scratch.\nBUILD PATH: comp (the round’s recorded default). Comp-led: the chosen card’s comp is law; generate it before building when it does not exist yet, and the finish review audits the build against it.\nCOMP SIDECAR MISSING: .impeccable/mocks/decision/a.png, .impeccable/mocks/decision/b.png landed with no prompt sidecar. Every decision comp records the exact prompt that produced it in <comp>.json ({\"prompt\": \"...\"}; generate-image writes it itself, a harness image tool does not), and that prompt is written under the comp rules in <REPO>/skill/reference/visualize.md. Write each missing sidecar now, and read that file before the next comp prompt if you have not.\n",
+ "stderr": "",
+ "exit": 0,
+ "signal": null,
+ "files": {}
+}
diff --git a/tests/oracle/golden/question-wait-comp-sidecar-missing.json b/tests/oracle/golden/question-wait-comp-sidecar-missing.json
new file mode 100644
index 000000000..a5a3bf7d2
--- /dev/null
+++ b/tests/oracle/golden/question-wait-comp-sidecar-missing.json
@@ -0,0 +1,9 @@
+{
+ "stdout": "WAITING: no answer yet after 0s; run --wait --key k1 again\nCOMP SIDECAR MISSING: .impeccable/mocks/decision/a.png landed with no prompt sidecar. Every decision comp records the exact prompt that produced it in <comp>.json ({\"prompt\": \"...\"}; generate-image writes it itself, a harness image tool does not), and that prompt is written under the comp rules in <REPO>/skill/reference/visualize.md. Write each missing sidecar now, and read that file before the next comp prompt if you have not.\n",
+ "stderr": "",
+ "exit": 3,
+ "signal": null,
+ "files": {
+ ".impeccable/questions/k1.state.json": "{\"pid\":<PID>,\"port\":1,\"url\":\"http://127.0.0.1:1/\",\"comps\":[\".impeccable/mocks/decision/a.png\",\".impeccable/mocks/decision/b.png\",\".impeccable/mocks/decision/c.png\"]}"
+ }
+}
diff --git a/tests/oracle/golden/question-wait-comp-stale.json b/tests/oracle/golden/question-wait-comp-stale.json
new file mode 100644
index 000000000..2d059538a
--- /dev/null
+++ b/tests/oracle/golden/question-wait-comp-stale.json
@@ -0,0 +1,10 @@
+{
+ "stdout": "WAITING: no answer yet after 0s; run --wait --key k1 again\nCOMP STALE: files left from an earlier round sit at this hand's slots, and the page is showing them: .impeccable/mocks/decision/a.png. Regenerate each into its slot now under the comp rules in <REPO>/skill/reference/visualize.md, with its prompt sidecar, before the user decides.\n",
+ "stderr": "",
+ "exit": 3,
+ "signal": null,
+ "files": {
+ ".impeccable/questions/k1.hand.json": "{\"digest\":\"0000000000000000\",\"comps\":[\".impeccable/mocks/decision/a.png\",\".impeccable/mocks/decision/b.png\"],\"pre\":{\".impeccable/mocks/decision/a.png\":\"8f8cbb7dcf46e0bc7d53265749a6c17d116093a6ba95e442764060c76fd4a86c\"}}",
+ ".impeccable/questions/k1.state.json": "{\"pid\":<PID>,\"port\":1,\"url\":\"http://127.0.0.1:1/\",\"comps\":[\".impeccable/mocks/decision/a.png\",\".impeccable/mocks/decision/b.png\"]}"
+ }
+}
diff --git a/tests/oracle/golden/question-wait-dead-pid.json b/tests/oracle/golden/question-wait-dead-pid.json
index 86413dc51..6c7075e93 100644
--- a/tests/oracle/golden/question-wait-dead-pid.json
+++ b/tests/oracle/golden/question-wait-dead-pid.json
@@ -1,5 +1,5 @@
{
- "stdout": "serve-question: the question server is gone with no answer. This is a server failure, not a user decision: restart it with --start and the same payload, reopen the URL for the user, and wait again. Never proceed without their choice while their browser session is open.\n",
+ "stdout": "serve-question: the question server is gone with no answer. This is a server failure, not a user decision: restart it with --start --key k1 and the same payload, reopen the URL for the user, and wait again. Never proceed without their choice while their browser session is open.\n",
"stderr": "",
"exit": 2,
"signal": null,
diff --git a/tests/oracle/golden/question-wait-flip.json b/tests/oracle/golden/question-wait-flip.json
index 35f8846c0..e1e4b3aa9 100644
--- a/tests/oracle/golden/question-wait-flip.json
+++ b/tests/oracle/golden/question-wait-flip.json
@@ -1,5 +1,5 @@
{
- "stdout": "BUILD PATH FLIPPED: comp (for this session only; never write it to settings). The table is still open and the page shows shimmer where the images will land: generate each open card’s comp into its declared path now, lead first, then collect the answer with --wait again. A card whose comp already exists needs nothing.\n",
+ "stdout": "BUILD PATH FLIPPED: comp (for this session only; never write it to settings). The table is still open and the page shows shimmer where the images will land: generate each open card’s comp into its declared path now, lead first, then collect the answer with --wait again. A card whose comp already exists needs nothing.\nNEXT read <REPO>/skill/reference/visualize.md now, before writing any decision comp prompt; its comp rules govern every card's image. Then generate each declared comp into its slot, lead first, and record the exact prompt in its sidecar (<comp>.json).\n",
"stderr": "",
"exit": 0,
"signal": null,
diff --git a/tests/oracle/golden/question-wait-no-server.json b/tests/oracle/golden/question-wait-no-server.json
index e2be1945c..2ebc67813 100644
--- a/tests/oracle/golden/question-wait-no-server.json
+++ b/tests/oracle/golden/question-wait-no-server.json
@@ -1,5 +1,5 @@
{
- "stdout": "serve-question: the question server is gone with no answer. This is a server failure, not a user decision: restart it with --start and the same payload, reopen the URL for the user, and wait again. Never proceed without their choice while their browser session is open.\n",
+ "stdout": "serve-question: the question server is gone with no answer. This is a server failure, not a user decision: restart it with --start --key k1 and the same payload, reopen the URL for the user, and wait again. Never proceed without their choice while their browser session is open.\n",
"stderr": "",
"exit": 2,
"signal": null,