Skip to content

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

JavaScript

Count the chosen decision comp as option one; fix choice-ping and DESIGN.md precondition text (#956)

Paul Bakausb89311dc7193
diff --git a/crates/comp-verbs/src/build_phase.rs b/crates/comp-verbs/src/build_phase.rs
index 2bea1f794..1f66dad82 100644
--- a/crates/comp-verbs/src/build_phase.rs
+++ b/crates/comp-verbs/src/build_phase.rs
@@ -258,9 +258,26 @@ struct CompEntry {
approved: bool,
}
-fn list_comps(io: &Io) -> Vec<CompEntry> {
+fn comp_entry(io: &Io, file: String) -> CompEntry {
+ let sidecar = std::fs::read_to_string(abs(io, &format!("{file}.json"))).ok().and_then(|raw| serde_json::from_str::<Value>(&raw).ok());
+ let approved = sidecar.as_ref().map(|s| s.get("approved") == Some(&Value::Bool(true))).unwrap_or(false);
+ CompEntry { file, sidecar, approved }
+}
+
+/// The chosen decision comp `build-phase start --decision-comp` recorded for
+/// this comp round: compositional option one. It stays recorded when its file
+/// goes missing, so the gate refuses rather than forgetting it.
+fn decision_comp(state: &Value) -> Option<String> {
+ state.get("decisionComp").and_then(Value::as_str).map(String::from)
+}
+
+/// The comp round's options: the recorded decision comp first, wherever it
+/// sits, then the comps directly in `.impeccable/mocks/`. Any other decision
+/// comp under `.impeccable/mocks/decision/` never counts.
+fn list_comps(io: &Io, state: &Value) -> Vec<CompEntry> {
let dir = abs(io, MOCKS_DIR);
- let mut out = Vec::new();
+ let chosen = decision_comp(state);
+ let mut out: Vec<CompEntry> = chosen.iter().filter(|c| abs(io, c).is_file()).map(|c| comp_entry(io, c.clone())).collect();
let Ok(entries) = std::fs::read_dir(&dir) else {
return out;
};
@@ -273,13 +290,10 @@ fn list_comps(io: &Io) -> Vec<CompEntry> {
}
let file = format!("{MOCKS_DIR}/{name}");
let abs_file = abs(io, &file);
- if !abs_file.is_file() {
+ if !abs_file.is_file() || chosen.as_deref().is_some_and(|c| crate::approved_comp::same_file(io, c, &file)) {
continue;
}
- let sidecar_path = format!("{file}.json");
- let sidecar = std::fs::read_to_string(abs(io, &sidecar_path)).ok().and_then(|raw| serde_json::from_str::<Value>(&raw).ok());
- let approved = sidecar.as_ref().map(|s| s.get("approved") == Some(&Value::Bool(true))).unwrap_or(false);
- out.push(CompEntry { file, sidecar, approved });
+ out.push(comp_entry(io, file));
}
out
}
@@ -288,12 +302,20 @@ fn basename(p: &str) -> String {
Path::new(p).file_name().map(|s| s.to_string_lossy().to_string()).unwrap_or_else(|| p.to_string())
}
-fn gate_comps(io: &Io) -> Gate {
- let comps = list_comps(io);
+fn gate_comps(io: &Io, state: &Value) -> Gate {
+ let comps = list_comps(io, state);
let mut reasons = Vec::new();
+ let chosen = decision_comp(state);
+ if let Some(c) = chosen.as_ref().filter(|c| !abs(io, c).is_file()) {
+ reasons.push(format!("the chosen decision comp {c} is missing: it is option one of this comp round and is never regenerated or replaced. Restore the file the user chose at that path (with its prompt sidecar), then advance again."));
+ }
if comps.len() < 3 {
+ let place = match chosen {
+ Some(c) => format!(" (the chosen decision comp {c} as option one, the others directly under {MOCKS_DIR})"),
+ None => format!(" under {MOCKS_DIR}"),
+ };
reasons.push(format!(
- "{} comp{} under {MOCKS_DIR}; the comp round puts three compositional options of the chosen direction in front of the user (reference/visualize.md). Generate the missing ones (harness image tool or generate-image.mjs), each with a .json sidecar holding its prompt.",
+ "{} comp{}{place}; the comp round puts three compositional options of the chosen direction in front of the user (reference/visualize.md). Generate the missing ones (harness image tool or generate-image.mjs), each with a .json sidecar holding its prompt.",
comps.len(),
if comps.len() == 1 { "" } else { "s" }
));
@@ -2654,7 +2676,7 @@ struct GateOpts {
fn run_gate(io: &Io, state: &mut Value, phase: &str, opts: &GateOpts, organic_scan: OrganicScan, renderer: Option<&dyn EntryRenderer>) -> Gate {
match phase {
"comps" => {
- let mut gate = gate_comps(io);
+ let mut gate = gate_comps(io, state);
// The approval fixes the reference: keep the engine's own copy now
// (a quoted --force closes on the approved comp too), and refuse to
// close on an approval that cannot be kept.
@@ -2896,6 +2918,9 @@ fn next_instruction(io: &Io, state: &Value) -> String {
match phase {
"comps" => {
let dir = direction.map(|d| format!(" (seed {d})")).unwrap_or_default();
+ if let Some(chosen) = decision_comp(state) {
+ return format!("Comp round for the chosen direction{dir}: read reference/visualize.md. The chosen decision comp {chosen} is compositional option one; it stays where it is and is never regenerated. Generate two more compositional comps of the requested surface at its viewport into {MOCKS_DIR}/ (each with a prompt sidecar), put all three in front of the user, and set \"approved\": true in the chosen comp's sidecar ({chosen}.json when they keep option one). Then {s} build-phase advance. No page code before this closes.");
+ }
format!("Comp round for the chosen direction{dir}: read reference/visualize.md, generate three compositional comps of the requested surface at its own viewport into {MOCKS_DIR}/ (each with a prompt sidecar), put them in front of the user, and set \"approved\": true in the chosen comp's sidecar. Then {s} build-phase advance. No page code before this closes.")
}
"spec" => format!(
@@ -3281,7 +3306,7 @@ pub fn run_with_renderer(argv: &[String],io: &mut Io,organic_scan: OrganicScan,r
let cmd = argv.first().map(String::as_str);
if cmd.is_none() || flag(argv, "help") {
io.out("CANDIDATE CHECK: build-phase check-plate <region-id> --candidate <png> [--json] validates a separate file with the normal plate gate; never replaces the selected asset, records approval, or advances the phase.\n");
- io.err("usage: build-phase.mjs start --comp <png> [--breakpoint WxH] [--artifact <entry file>] [--session-id <id>] | status [--json] | completion [--session-id <id>] | advance [--force --reason \"...\"] | record hero --build <png> | scaffold | note \"<text>\" | finish --disposition <word> | restore-comp\n");
+ io.err("usage: build-phase.mjs start --comp <png> | --direction <key> [--decision-comp <png>] [--breakpoint WxH] [--artifact <entry file>] [--session-id <id>] | status [--json] | completion [--session-id <id>] | advance [--force --reason \"...\"] | record hero --build <png> | scaffold | note \"<text>\" | finish --disposition <word> | restore-comp\n");
return 1;
}
let cmd = cmd.unwrap();
@@ -3331,6 +3356,11 @@ pub fn run_with_renderer(argv: &[String],io: &mut Io,organic_scan: OrganicScan,r
if cmd == "start" {
let comp = arg(argv, "comp");
let direction = arg(argv, "direction");
+ let chosen_decision = arg(argv, "decision-comp");
+ if chosen_decision.is_some() && (comp.is_some() || direction.is_none()) {
+ io.err("build-phase: --decision-comp names option one of a comp round, so it goes with --direction and never with --comp\n");
+ return 1;
+ }
if comp.is_none() && direction.is_none() {
io.err("build-phase: start needs --comp <approved comp png> (comp already approved) or --direction <seed key> (comp round still to run)\n");
return 1;
@@ -3341,6 +3371,12 @@ pub fn run_with_renderer(argv: &[String],io: &mut Io,organic_scan: OrganicScan,r
return 1;
}
}
+ if let Some(d) = chosen_decision {
+ if !abs(io, d).is_file() {
+ io.err(&format!("build-phase: decision comp {d} does not exist\n"));
+ return 1;
+ }
+ }
if direction.is_some() && arg(argv, "kind").is_some() {
io.out("choice ping skipped\n");
}
@@ -3381,6 +3417,7 @@ pub fn run_with_renderer(argv: &[String],io: &mut Io,organic_scan: OrganicScan,r
None => crate::approved_comp::forget(io),
}
let mut state = new_state(comp, breakpoint.as_deref(), arg(argv, "artifact"), direction);
+ if let Some(d) = chosen_decision { state["decisionComp"] = json!(d); }
if io.env("IMPECCABLE_NATIVE_CAPTURE")==Some("1") {state["capturePolicy"]=json!("native-html-v1");}
// Session identity is transport metadata, never guessed from a project
// path or an earlier build. Old/unidentified states remain unscoped.
diff --git a/crates/comp-verbs/src/build_phase/integrity_tests.rs b/crates/comp-verbs/src/build_phase/integrity_tests.rs
index 7dcbc39aa..7bc43a832 100644
--- a/crates/comp-verbs/src/build_phase/integrity_tests.rs
+++ b/crates/comp-verbs/src/build_phase/integrity_tests.rs
@@ -1826,6 +1826,74 @@ fn comps_gate_keeps_the_approved_comp_and_a_new_round_forgets_it() {
assert!(state["phases"]["comps"]["forced"].is_null());
}
+#[test]
+fn chosen_decision_comp_is_option_one_and_becomes_the_approved_reference() {
+ const CHOSEN: &str = ".impeccable/mocks/decision/assigned.png";
+ const OTHER: &str = ".impeccable/mocks/decision/pick.png";
+ let ws = Workspace::new();
+ for (file, color) in [(CHOSEN, [20u8, 70, 110, 255]), (OTHER, [200, 200, 20, 255])] {
+ ws.write(file, &png_io::encode_png(&r::create_image(40, 20, color), &[]).unwrap());
+ ws.write(&format!("{file}.json"), br#"{"prompt":"decision comp"}"#);
+ }
+ // Without --decision-comp no decision comp counts toward the round.
+ let mut io = ws.io();
+ assert_eq!(run(&["start", "--direction", "seed"].map(String::from), &mut io, &no_organic_scan), 0);
+ let gate = gate_comps(&io, &load_state(&io).unwrap());
+ assert!(gate.reasons[0].starts_with("0 comps under .impeccable/mocks;"), "{:?}", gate.reasons);
+ // --decision-comp goes with --direction only, and must exist.
+ let (mut io, c) = captured(&ws);
+ assert_eq!(run(&["start", "--reset", "--comp", CHOSEN, "--decision-comp", CHOSEN].map(String::from), &mut io, &no_organic_scan), 1);
+ assert!(out_err(&c).contains("goes with --direction and never with --comp"), "{}", out_err(&c));
+ let (mut io, c) = captured(&ws);
+ assert_eq!(run(&["start", "--reset", "--decision-comp", CHOSEN].map(String::from), &mut io, &no_organic_scan), 1);
+ assert!(out_err(&c).contains("goes with --direction and never with --comp"), "{}", out_err(&c));
+ assert_eq!(run(&["start", "--reset", "--direction", "seed", "--decision-comp", ".impeccable/mocks/decision/none.png"].map(String::from), &mut io, &no_organic_scan), 1);
+
+ let mut io = ws.io();
+ assert_eq!(run(&["start", "--reset", "--direction", "seed", "--decision-comp", CHOSEN].map(String::from), &mut io, &no_organic_scan), 0);
+ let state = load_state(&io).unwrap();
+ assert_eq!(state["decisionComp"], CHOSEN);
+ assert!(next_instruction(&io, &state).contains(&format!("The chosen decision comp {CHOSEN} is compositional option one")));
+ // The chosen decision comp counts as option one; the unrelated one never does.
+ let gate = gate_comps(&io, &state);
+ assert!(gate.reasons[0].starts_with(&format!("1 comp (the chosen decision comp {CHOSEN} as option one, the others directly under .impeccable/mocks);")), "{:?}", gate.reasons);
+ for (i, color) in [[90u8, 20, 20, 255], [10, 90, 10, 255]].iter().enumerate() {
+ let file = format!(".impeccable/mocks/comp-{}.png", i + 2);
+ ws.write(&file, &png_io::encode_png(&r::create_image(40, 20, *color), &[]).unwrap());
+ ws.write(&format!("{file}.json"), br#"{"prompt":"variation"}"#);
+ }
+ let gate = gate_comps(&io, &state);
+ assert_eq!(gate.reasons, vec!["no comp is approved: put the three comps in front of the user (decision page via serve-question.mjs, or the structured question tool), then set \"approved\": true in the chosen comp's sidecar. A delegated pick is recorded the same way and disclosed.".to_string()]);
+ // An approval on the unrelated decision comp is not an approval of the round.
+ ws.write(&format!("{OTHER}.json"), br#"{"prompt":"decision comp","approved":true}"#);
+ assert!(!gate_comps(&io, &state).ok);
+ // A deleted option one is not forgotten: three root comps cannot close the round without it.
+ let kept = std::fs::read(ws.path.join(CHOSEN)).unwrap();
+ std::fs::remove_file(ws.path.join(CHOSEN)).unwrap();
+ ws.write(".impeccable/mocks/comp-4.png", &png_io::encode_png(&r::create_image(40, 20, [5, 5, 5, 255]), &[]).unwrap());
+ ws.write(".impeccable/mocks/comp-4.png.json", br#"{"prompt":"replacement","approved":true}"#);
+ let gate = gate_comps(&io, &state);
+ assert!(!gate.ok && gate.reasons[0].starts_with(&format!("the chosen decision comp {CHOSEN} is missing")), "{:?}", gate.reasons);
+ std::fs::remove_file(ws.path.join(".impeccable/mocks/comp-4.png")).unwrap();
+ std::fs::remove_file(ws.path.join(".impeccable/mocks/comp-4.png.json")).unwrap();
+ ws.write(CHOSEN, &kept);
+ // The user keeps option one: the comps gate closes on it where it stands.
+ ws.write(&format!("{CHOSEN}.json"), br#"{"prompt":"decision comp","approved":true}"#);
+ assert_eq!(run(&["advance"].map(String::from), &mut io, &no_organic_scan), 0);
+ let state = load_state(&io).unwrap();
+ assert_eq!(state["comp"], CHOSEN);
+ assert_eq!(state["phase"], "spec");
+ let record: Value = serde_json::from_slice(&std::fs::read(ws.path.join(crate::approved_comp::RECORD_PATH)).unwrap()).unwrap();
+ assert_eq!(record["comp"], CHOSEN);
+ assert_eq!(record["pixelSha256"].as_str(), crate::approved_comp::file_pixel_sha256(&io, CHOSEN).as_deref());
+ assert_eq!(std::fs::read(ws.path.join(record["copy"].as_str().unwrap())).unwrap(), std::fs::read(ws.path.join(CHOSEN)).unwrap());
+ // The decision comp is now the fixed reference: an edit is refused and restore-comp puts it back.
+ ws.write(CHOSEN, &png_io::encode_png(&r::create_image(40, 20, [0, 0, 0, 255]), &[]).unwrap());
+ assert!(crate::approved_comp::issue_for_comp(&io, CHOSEN, "impeccable").is_some());
+ assert_eq!(run(&["restore-comp"].map(String::from), &mut io, &no_organic_scan), 0);
+ assert_eq!(crate::approved_comp::file_pixel_sha256(&io, CHOSEN).as_deref(), record["pixelSha256"].as_str());
+}
+
/// The code-led first viewport with a lettered export control (`export`), or
/// with that control left out of the page.
fn lettered_text_only_hero(restyled: bool, export: bool) -> Image {
diff --git a/crates/context/src/serve_question.rs b/crates/context/src/serve_question.rs
index 345091b94..e5742f119 100644
--- a/crates/context/src/serve_question.rs
+++ b/crates/context/src/serve_question.rs
@@ -105,17 +105,34 @@ fn is_comp_round_comp(path: &str) -> bool {
dir == ".impeccable/mocks" || dir.ends_with("/.impeccable/mocks")
}
-fn print_answer(io: &mut Io, raw: &str) {
+/// The comp round's option one: the decision comp `build-phase start
+/// --decision-comp` recorded, while that build's comps phase is open, served
+/// on a page that is the comp round (it also serves a comp directly in
+/// `.impeccable/mocks/`). A pick of it there is the approval, not a new
+/// option one; on any other page the same path is an ordinary decision slot.
+fn is_comp_rounds_option_one(cwd: &str, path: &str, served: &[String]) -> bool {
+ served.iter().any(|c| is_comp_round_comp(c)) && is_open_rounds_decision_comp(cwd, path)
+}
+
+fn is_open_rounds_decision_comp(cwd: &str, path: &str) -> bool {
+ let Some(state) = safe_read(&jsp::resolve(cwd, &[".impeccable/build/state.json"])).and_then(|raw| serde_json::from_str::<Value>(&raw).ok()) else { return false };
+ let Some(chosen) = state.get("decisionComp").and_then(Value::as_str) else { return false };
+ state.get("phase").and_then(Value::as_str) == Some("comps") && same_path(&jsp::resolve(cwd, &[chosen]), &jsp::resolve(cwd, &[path]))
+}
+
+fn print_answer(io: &mut Io, raw: &str, served: &[String]) {
io.out(&format!("ANSWER: {}\n", raw));
let Ok(a) = serde_json::from_str::<Value>(raw) else { return };
let truthy = |k: &str| a.get(k).map(crate::staleness::js_truthy).unwrap_or(false);
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") && is_comp_round_comp(&a.get("comp").map(js_str).unwrap_or_default()) {
+ let comp = a.get("comp").map(js_str).unwrap_or_default();
+ let cwd = io.cwd.to_string_lossy().to_string();
+ if truthy("comp") && (is_comp_round_comp(&comp) || is_comp_rounds_option_one(&cwd, &comp, served)) {
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, the image's full file name plus .json (a.png gets a.png.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");
+ io.out("CHOSEN COMP: the decision comp at that path is compositional option one. On a comp-led build pass it to build-phase start as --decision-comp <that path>, and the comp round adds two variations beside it where it stands; 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());
if option_id == Some("canon") {
@@ -403,14 +420,16 @@ fn round_comps(hand: Option<&Map<String, Value>>, state: Option<&Map<String, Val
/// 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.
+/// them, so those always count, as does its option one, the decision comp an
+/// open build recorded; 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) {
+ let served = hand.get("comps").and_then(Value::as_array).map(|a| a.iter().filter_map(|v| v.as_str().map(str::to_string)).collect::<Vec<_>>()).unwrap_or_default();
+ if is_comp_round_comp(comp) || is_comp_rounds_option_one(cwd, comp, &served) {
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);
@@ -486,7 +505,7 @@ fn sidecar_missing_line(env: &Env, cwd: &str, missing: &[String]) -> String {
/// renders the agent owes visualize.md's post-render checks. Comp-round comps
/// sit outside this: the decision round is where the checks go unrun.
fn landed_decision_comps(cwd: &str, comps: &[String], hand: Option<&Map<String, Value>>) -> bool {
- comps.iter().any(|c| !is_comp_round_comp(c) && comp_is_this_hands(cwd, c, hand) && exists(&format!("{}.json", jsp::resolve(cwd, &[c.as_str()]))))
+ comps.iter().any(|c| !is_comp_round_comp(c) && !is_comp_rounds_option_one(cwd, c, comps) && comp_is_this_hands(cwd, c, hand) && exists(&format!("{}.json", jsp::resolve(cwd, &[c.as_str()]))))
}
/// The `--wait` render-check directive: once per hand, the first poll that
@@ -645,9 +664,9 @@ pub fn run(argv: &[String], io: &mut Io) -> i32 {
}
// Read before the answer path may delete the state file.
let hand = read_hand(&qdir, &key);
- let (missing, stale, landed) = {
+ let (missing, stale, landed, served) = {
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()), landed_decision_comps(&cwd, &comps, hand.as_ref()))
+ (comps_missing_sidecar(&cwd, &comps, hand.as_ref()), stale_comps(&cwd, &comps, hand.as_ref()), landed_decision_comps(&cwd, &comps, hand.as_ref()), comps)
};
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));
@@ -666,7 +685,7 @@ pub fn run(argv: &[String], io: &mut Io) -> i32 {
}
let collected = safe_read(&answer_file(&qdir, &key)).unwrap_or_default();
let collected = crate::util::js_trim(&collected).to_string();
- print_answer(io, &collected);
+ print_answer(io, &collected, &served);
if !missing.is_empty() {
io.out(&sidecar_missing_line(&env, &cwd, &missing));
}
@@ -1098,7 +1117,7 @@ pub fn run(argv: &[String], io: &mut Io) -> i32 {
let _ = std::fs::create_dir_all(&st.qdir);
let _ = std::fs::write(answer_file(&st.qdir, &k), format!("{}\n", answer));
} else {
- print_answer(io, &answer);
+ print_answer(io, &answer, &declared_comps(&st.payload));
let _ = io.stdout.flush();
}
if !((is_reroll || followup_open) && st.detached_key.is_some()) {
@@ -2134,7 +2153,7 @@ mod tests {
fn answer_lines(raw: &str) -> String {
let (mut io, cap) = Io::captured("", std::env::temp_dir(), Env::new());
- print_answer(&mut io, raw);
+ print_answer(&mut io, raw, &[]);
let out = String::from_utf8(cap.stdout.borrow().clone()).unwrap();
out
}
@@ -2148,9 +2167,54 @@ mod tests {
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("--decision-comp <that path>"), "{out}");
assert!(!out.contains("APPROVED COMP"), "{out}");
}
+ #[test]
+ fn comp_round_pick_of_the_recorded_decision_comp_is_the_approval() {
+ let dir = std::env::temp_dir().join(format!("impeccable-sq-decision-{}-{}", std::process::id(), now_ms() as u64));
+ std::fs::create_dir_all(dir.join(".impeccable/build")).unwrap();
+ let slot = ".impeccable/mocks/decision/a.png";
+ let round: Vec<String> = vec![slot.into(), ".impeccable/mocks/comp-2.png".into(), ".impeccable/mocks/comp-3.png".into()];
+ let decision_page: Vec<String> = vec![slot.into(), ".impeccable/mocks/decision/b.png".into()];
+ let answer = |raw: &str, served: &[String]| {
+ let (mut io, cap) = Io::captured("", dir.clone(), Env::new());
+ print_answer(&mut io, raw, served);
+ let out = String::from_utf8(cap.stdout.borrow().clone()).unwrap();
+ out
+ };
+ let state = |phase: &str| json!({ "phase": phase, "decisionComp": slot }).to_string();
+ std::fs::write(dir.join(".impeccable/build/state.json"), state("comps")).unwrap();
+ let out = answer(r#"{"optionId":"one","comp":"./.impeccable/mocks/decision/a.png"}"#, &round);
+ assert!(out.contains("APPROVED COMP") && !out.contains("CHOSEN COMP"), "{out}");
+ // Served again in the comp round, option one is this hand's comp, never stale.
+ std::fs::create_dir_all(dir.join(".impeccable/mocks/decision")).unwrap();
+ std::fs::write(dir.join(slot), b"png").unwrap();
+ let cwd = dir.to_string_lossy().to_string();
+ let options: Vec<Value> = round.iter().map(|c| json!({ "id": c, "comp": c })).collect();
+ let hand = new_hand(&cwd, &json!({ "options": options }));
+ assert!(comp_is_this_hands(&cwd, slot, Some(&hand)));
+ assert!(stale_comps(&cwd, &[slot.to_string()], Some(&hand)).is_empty());
+ // Option one is not a decision-round comp: no render-check directive for it.
+ std::fs::write(dir.join(format!("{slot}.json")), b"{}").unwrap();
+ assert!(!landed_decision_comps(&cwd, &round, Some(&hand)));
+ // A new direction round reusing that slot is not the comp round: the old image is stale there.
+ let options: Vec<Value> = decision_page.iter().map(|c| json!({ "id": c, "comp": c })).collect();
+ let hand = new_hand(&cwd, &json!({ "options": options }));
+ assert!(!comp_is_this_hands(&cwd, slot, Some(&hand)));
+ assert_eq!(stale_comps(&cwd, &[slot.to_string()], Some(&hand)), vec![slot.to_string()]);
+ let out = answer(r#"{"optionId":"one","comp":".impeccable/mocks/decision/a.png"}"#, &decision_page);
+ assert!(out.contains("CHOSEN COMP") && !out.contains("APPROVED COMP"), "{out}");
+ // Another decision comp, or the same one once the round closed, stays a decision pick.
+ let out = answer(r#"{"optionId":"b","comp":".impeccable/mocks/decision/b.png"}"#, &round);
+ assert!(out.contains("CHOSEN COMP") && !out.contains("APPROVED COMP"), "{out}");
+ std::fs::write(dir.join(".impeccable/build/state.json"), state("spec")).unwrap();
+ let out = answer(r#"{"optionId":"one","comp":".impeccable/mocks/decision/a.png"}"#, &round);
+ assert!(out.contains("CHOSEN COMP") && !out.contains("APPROVED COMP"), "{out}");
+ let _ = std::fs::remove_dir_all(&dir);
+ }
+
#[test]
fn visualize_next_line_names_the_skill_reference() {
let env = Env::from([("IMPECCABLE_SKILL_DIR".into(), "/skill".into())]);
diff --git a/docs/CLI-CONTRACT.md b/docs/CLI-CONTRACT.md
index 8c8324f4c..f4fac192d 100644
--- a/docs/CLI-CONTRACT.md
+++ b/docs/CLI-CONTRACT.md
@@ -449,7 +449,7 @@ retain their local-development trust behavior. See [bundle signing](BUNDLE-SIGNI
- **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: ...` (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, the image's full file name plus .json (a.png gets a.png.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).
+- **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, the image's full file name plus .json (a.png gets a.png.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, or is the `decisionComp` that `.impeccable/build/state.json` records while its phase is `comps` and the page also serves a comp directly in `.impeccable/mocks/` (the comp round; under the same condition that comp counts as the served hand's own, so serving it prints no `NEXT read` and no `COMP STALE` for it, while a direction round reusing its slot still flags it stale); other decision comps under `.impeccable/mocks/decision/` and any other path keep `CHOSEN COMP`, whose comp-led clause names the flag: `On a comp-led build pass it to build-phase start as --decision-comp <that path>, and the comp round adds two variations beside it where it stands;`), `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`.
@@ -473,7 +473,9 @@ Ported from the former `skill/scripts/{comp-spec,comp-diff,font-match,build-phas
- **`comp-diff`** — `--comp <png> --build <png> [--spec spec.json] [--out-dir dir] [--align top|stretch|cover] [--label name] [--threshold t] [--json] [--no-files]`. Scores structure / color / detail / bands and per-region verdicts (`match`/`drift`/`missing`/`contradicted`); writes `side-by-side.png`, `heatmap.png`, `regions/<id>.png`, and `report.json` under `--out-dir` (unless `--no-files`); prints the text summary or, with `--json`, the report. Exit 0 measured, 1 usage/unreadable input, 2 the approved comp changed (see the fixed-reference paragraph under `build-phase`), 3 below `--threshold`. The JSON report and text summary are byte-identical to the JS.
- **`font-match`** — `--measure <text-region-id>` fingerprints the comp crop of a text region (cap height, width/weight class, shape vector), records it on the region's `type` block in the spec, and prints the MEASURE line (pure; byte-identical to the JS). `--rank <id> [--candidates "Family:700,…"] [--text "…"] [--transform …] [--category …]` additionally renders candidate faces in a headless browser and ranks them by fingerprint distance, writing a stamped `chosen` face onto the region and a proof sheet under `.impeccable/build/font-match/`. **Browser**: an installed Chrome discovered and driven over CDP (the same browser the URL engine uses; the JS used Playwright/Puppeteer). With no browser resolvable, the catalog's nearest face is recorded (source `catalog`, estimated size) or, with no catalog either, the MEASURE line stands — matching the JS fallbacks; the sha1 `chosen` stamp is byte-identical. Screenshots vary by Chrome version, so the rendered ranking is not byte-stable.
- **`font-index` catalog (paid moat)** — resolved at run time, never committed to the engine repo: `IMPECCABLE_CATALOG_DIR/font-index.json` first, then the skill's shipped `IMPECCABLE_SKILL_DIR/scripts/data/font-index.json`; absent → the built-in per-width shortlist stands in (the JS degraded path).
-- **`build-phase`** — the comp-led build state machine at `.impeccable/build/state.json`. `start --comp <png> | --direction <key>` (opens the phases; reads comp dimensions for the breakpoint), `status [--json]`, `advance [--force --reason "…"]` (runs the current phase's gate; exit 2 on gate failure, state unchanged), `record hero --build <png>`, `scaffold`, `note "<text>"`, `finish --disposition ship|fix|rebuild|recapture`, `restore-comp`. Phases and gates (`comps`, `spec`, `plates`, `hero`, `sections`, `motion`, `responsive`, `review`) are unchanged from the JS; the hero/responsive gates call comp-diff in-process (the JS spawned it). The organic-clip-path CSS scan is the engine's own rule (`organic-clip-path`), injected into the gate; The spec gate (re-run by hero and responsive) also refuses unknown kinds, noteless bands, sub-pixel regions, and a band-only map. `--force` is refused unless `--reason` quotes the user downgrading the comp (the JS `forceAllowed` logic verbatim).
+- **`build-phase`** — the comp-led build state machine at `.impeccable/build/state.json`. `start --comp <png> | --direction <key> [--decision-comp <png>]` (opens the phases; reads comp dimensions for the breakpoint), `status [--json]`, `advance [--force --reason "…"]` (runs the current phase's gate; exit 2 on gate failure, state unchanged), `record hero --build <png>`, `scaffold`, `note "<text>"`, `finish --disposition ship|fix|rebuild|recapture`, `restore-comp`. Phases and gates (`comps`, `spec`, `plates`, `hero`, `sections`, `motion`, `responsive`, `review`) are unchanged from the JS; the hero/responsive gates call comp-diff in-process (the JS spawned it). The organic-clip-path CSS scan is the engine's own rule (`organic-clip-path`), injected into the gate; The spec gate (re-run by hero and responsive) also refuses unknown kinds, noteless bands, sub-pixel regions, and a band-only map. `--force` is refused unless `--reason` quotes the user downgrading the comp (the JS `forceAllowed` logic verbatim). `start --direction --kind` prints `choice ping skipped` and sends nothing; the choice ping is `concept-seed --kind`.
+
+ **The chosen decision comp is option one (engine addition).** `start --direction <key> --decision-comp <png>` records the direction round's chosen comp as `decisionComp` in the state (exit 1 with `build-phase: --decision-comp names option one of a comp round, so it goes with --direction and never with --comp` when combined with `--comp` or given without `--direction`, and `build-phase: decision comp <png> does not exist` when the file is missing). When the recorded file goes missing, the comps gate fails first with `the chosen decision comp <png> is missing: it is option one of this comp round and is never regenerated or replaced. Restore the file the user chose at that path (with its prompt sidecar), then advance again.`, so three other comps cannot close the round without it. While it exists the gate counts it first, wherever it sits (normally `.impeccable/mocks/decision/`), ahead of the comps directly in `.impeccable/mocks/`; no other file under `.impeccable/mocks/decision/` ever counts, approved sidecar or not. Its count reason reads `<n> comp[s] (the chosen decision comp <png> as option one, the others directly under .impeccable/mocks); ...` instead of `<n> comp[s] under .impeccable/mocks; ...`, and the comps NEXT line names it as option one, kept where it is and never regenerated, with two more comps to generate. When its sidecar carries `"approved": true` the gate closes on it like any approved comp: `state.comp` becomes the decision path, and the approved-comp record, kept copy, integrity checks and `restore-comp` below all bind to that path.
`build-phase check-plate <region-id> --candidate <png> [--json]` runs the normal plate gate on a separate candidate, retaining the full spec for reference exclusions. Exit 0 means pass, 2 means gate failure, 1 means invalid input. It does not write files (apart from the approved-comp copy a build that predates it gets on its first check), select an asset, record an approval, or advance build state. JSON includes `ok`, `region`, `candidate`, `reasons`, `plates`, and `stateChanged: false`.
diff --git a/skill/reference/new-work.md b/skill/reference/new-work.md
index 6bc8b1fae..6e24a4afb 100644
--- a/skill/reference/new-work.md
+++ b/skill/reference/new-work.md
@@ -102,7 +102,7 @@ Build the assigned direction, not a safer interpretation of it. The form supplie
When an approved comp exists, it is a spatial contract, not a mood board: only the user can downgrade its authority, in explicit words. Models systematically believe their HTML, CSS, and SVG recreation of an image succeeded when it did not, so the build runs as a state machine on disk whose gates measure the screen against the comp instead of asking you to remember it. Start it once, and let it tell you what is next:
-`{{scripts_path}}/impeccable build-phase start --direction <seed key> --kind <assigned|pick|challenger|canon> --artifact <entry file>` right after the direction choice (this is also the choice ping; the roll's output names the exact command), or `start --comp <approved comp> --artifact <entry file>` when a surface round already locked one.
+`{{scripts_path}}/impeccable build-phase start --direction <seed key> --artifact <entry file>` right after the direction choice, adding `--decision-comp <path>` when the chosen card has a decision comp (the path CHOSEN COMP names) so the comps gate counts it as option one, or `start --comp <approved comp> --artifact <entry file>` when a surface round already locked one. Start is not the choice ping: that is the `concept-seed --kind` rerun the roll's TELEMETRY line names, sent once when the roll printed one.
Then, in order, each closed by `{{scripts_path}}/impeccable build-phase advance` (every verb below runs as `{{scripts_path}}/impeccable <verb>`; exit 2 means the gate failed and printed why; fix that and advance again; write nothing for a later phase while an earlier gate is open):
diff --git a/skill/reference/visualize.md b/skill/reference/visualize.md
index 458018bb0..26fa7b273 100644
--- a/skill/reference/visualize.md
+++ b/skill/reference/visualize.md
@@ -1,14 +1,14 @@
# Visualize: Direction Comps & Asset Production
-Load this from [new-work.md](new-work.md) on a comp-led build, when image generation is available (a harness-native tool or the API fallback `impeccable context` reports). A code-led contract skips this file by design, not by drift; do not load it then. PRODUCT.md and DESIGN.md are preconditions. The MODE RULES block concept-seed printed for this surface (COMPS) governs these comps together with this file and wins where they conflict; with no roll this session, read the mode's file named in new-work.md. New-work has already resolved the visual world; this file must not reopen it. A surface-scope structure round that already put three visualized cards before the user (new-work.md, established world) has discharged this round: the locked card's comp is the approved comp, so record the approval and continue at After approval; generate nothing new.
+Load this from [new-work.md](new-work.md) on a comp-led build, when image generation is available (a harness-native tool or the API fallback `impeccable context` reports). A code-led contract skips this file by design, not by drift; do not load it then. PRODUCT.md is a precondition; DESIGN.md is one only on an established world, since a new or replacement world writes it at the finish. The MODE RULES block concept-seed printed for this surface (COMPS) governs these comps together with this file and wins where they conflict; with no roll this session, read the mode's file named in new-work.md. New-work has already resolved the visual world; this file must not reopen it. A surface-scope structure round that already put three visualized cards before the user (new-work.md, established world) has discharged this round: the locked card's comp is the approved comp, so record the approval and continue at After approval; generate nothing new.
-A probe tests composition, narrative, hierarchy, density, focal moment, signature use, and image requirements. It is not a second identity workshop. Keep DESIGN.md's palette, typography direction, material language, component character, imagery stance, and motion grammar fixed.
+A probe tests composition, narrative, hierarchy, density, focal moment, signature use, and image requirements. It is not a second identity workshop. Keep the world's palette, typography direction, material language, component character, imagery stance, and motion grammar fixed: DESIGN.md's on an established world, the chosen direction's on a new one.
## Generate three compositional options
-The comp round runs inside the build's phase state: `impeccable build-phase start --direction <seed key> --kind <...>` has already run (the roll's output names the command) and its `comps` phase is open before the first comp is generated; a comp rendered before that sits outside the state, and a session resumed from that point has no phases to follow. `impeccable generate-image` refuses to write under `.impeccable/mocks/` until start has run; a harness-native image tool is bound by the same order.
+The comp round runs inside the build's phase state: `impeccable build-phase start --direction <seed key>` has already run (with `--decision-comp <path>` when the chosen card has a decision comp) and its `comps` phase is open before the first comp is generated; a comp rendered before that sits outside the state, and a session resumed from that point has no phases to follow. `impeccable generate-image` refuses to write under `.impeccable/mocks/` until start has run; a harness-native image tool is bound by the same order.
-Render three distinct high-fidelity north-star comps of the requested surface, saved under `.impeccable/mocks/` so they survive the session. Comp at the surface's own viewport: portrait at device size for a native app or mobile-first surface, desktop landscape otherwise; a phone screen comped landscape misstates the composition before anything is built against it. Comps are the build thread's own work, never delegated: the thread that writes the prompts holds the direction's full context and has seen every comp when the build starts. Open every image by its workspace-relative path; sandboxed viewers reject absolute paths, and everything under the project root has a relative one. Base the comps on real content and the surface concepts already developed with the user. On an established world, anchor every comp on the real identity: capture a screenshot of a representative existing page and pass it as a reference image (the harness image tool's input image, or `impeccable generate-image --ref`); the prompt leads with the new surface's structure while the reference carries palette, type, and component character, because DESIGN.md words alone drift where a pixel reference does not. Name what the reference contributes and what it must not: chrome, palette, type, and component character carry over; the reference page's own content does not, and a banner, hero, or card lifted verbatim is the reference leaking, not fidelity. Three is the number: one comp invites rubber-stamping; the spread between three surfaces the composition worth building. The chosen card's decision comp is the first of the three: it already renders this direction at full fidelity under this discipline, so generate two more that vary what the first held fixed, from the direction in words rather than with the first comp as an input image (a reference image anchors the layout, and three comps collapse into one composition). How comps two and three vary from the first is the mode's call, in its COMPS rules. A variant that simplifies the first into a tidier version of itself adds no choice to the round. Send all three to the approval point together. Only a round arriving with no decision comp (a degraded roll, an identity-mode page, a direction pinned without the decision round) renders all three here.
+Render three distinct high-fidelity north-star comps of the requested surface, saved under `.impeccable/mocks/` so they survive the session. When the chosen card has a decision comp, it is option one: it stays at its path under `.impeccable/mocks/decision/`, where the gate counts it through `--decision-comp`, and is never regenerated; render the other two. Comp at the surface's own viewport: portrait at device size for a native app or mobile-first surface, desktop landscape otherwise; a phone screen comped landscape misstates the composition before anything is built against it. Comps are the build thread's own work, never delegated: the thread that writes the prompts holds the direction's full context and has seen every comp when the build starts. Open every image by its workspace-relative path; sandboxed viewers reject absolute paths, and everything under the project root has a relative one. Base the comps on real content and the surface concepts already developed with the user. On an established world, anchor every comp on the real identity: capture a screenshot of a representative existing page and pass it as a reference image (the harness image tool's input image, or `impeccable generate-image --ref`); the prompt leads with the new surface's structure while the reference carries palette, type, and component character, because DESIGN.md words alone drift where a pixel reference does not. Name what the reference contributes and what it must not: chrome, palette, type, and component character carry over; the reference page's own content does not, and a banner, hero, or card lifted verbatim is the reference leaking, not fidelity. Three is the number: one comp invites rubber-stamping; the spread between three surfaces the composition worth building. The chosen card's decision comp is the first of the three: it already renders this direction at full fidelity under this discipline, so generate two more that vary what the first held fixed, from the direction in words rather than with the first comp as an input image (a reference image anchors the layout, and three comps collapse into one composition). How comps two and three vary from the first is the mode's call, in its COMPS rules. A variant that simplifies the first into a tidier version of itself adds no choice to the round. Send all three to the approval point together. Only a round arriving with no decision comp (a degraded roll, an identity-mode page, a direction pinned without the decision round) renders all three here.
- A comp is a designed surface, not a picture of the subject. Lead the prompt with the surface's own structure: the regions this design has, named in order with their scale relationships. Write it in the order the visitor reads it: the headline in its own words and the primary action first, then the one focal move in full detail, then each remaining region in a phrase; the image model fills whatever the prompt describes in detail, so a region you inventory renders as a second focal move. A page with no navigation says so instead of inventing one, and an unconventional surface states its unconventional skeleton. A prompt that leads with atmosphere gets a vignette back: the model paints the fish market instead of the fish market's website. How far the world reaches into the page, and what it may carry, is the mode's call, in its COMPS rules. Render the page itself edge to edge: no browser window, address bar, device or desk around it, so prompt it as the page, never as a screenshot of a browser. Self-check every render: if it could hang as a poster, or reads as a photograph with some text on it, it is not a comp; regenerate with the dealt composition's regions named and its parts working in place.
- The inverse is also a failure: a surface with none of its subject in it. The subject appears as the content the regions hold; the world dresses the frame and never displaces what the frame shows. The deletion usually rides in on the prompt's exclusion list, so exclusions bind invented claims, and a medium ban belongs to the committed imagery stance, never to caution. Before accepting a render, point at the subject; a render that depicts everything about the world and nothing of the subject fails however faithful its atmosphere. Regenerate with the subject's content named region by region.
diff --git a/tests/oracle/DELTAS.md b/tests/oracle/DELTAS.md
index 13cc1555b..503282ebb 100644
--- a/tests/oracle/DELTAS.md
+++ b/tests/oracle/DELTAS.md
@@ -378,3 +378,15 @@ A Gemini run wrote decision comp prompts that inventoried every region and never
New case, recorded from the binary and reviewed by hand:
- `question-wait-render-check-once`: `k1.render-check` already holds the hand's id `h1`, so a poll with a landed, sidecar-carrying decision comp prints only the WAITING line and leaves the marker as it was.
+
+## Recorded 2026-10-05: the chosen decision comp is option one of the comp round
+
+The skill says the direction round's chosen decision comp enters the comp round as compositional option one and is never regenerated, but the comps gate counted only files directly in `.impeccable/mocks/`, while decision comps live in `.impeccable/mocks/decision/`. `build-phase start --direction <key> --decision-comp <png>` now records that comp as `decisionComp` in the state; the comps gate counts it first where it stands, never any other decision comp, and an approval on it closes the gate with the decision path as the approved comp (record, kept copy and `restore-comp` bind to it). `serve-question --wait` treats a pick of that recorded comp during the open comps phase as the approval (`APPROVED COMP`), and the `CHOSEN COMP` line names the flag.
+
+- `build-phase-usage`: the usage line now reads `start --comp <png> | --direction <key> [--decision-comp <png>] [--breakpoint WxH] ...`. Nothing else in the case moved.
+- `question-wait-answer-ready`, `question-wait-answer-comp-sidecar-missing`: the `CHOSEN COMP` comp-led clause reads `On a comp-led build pass it to build-phase start as --decision-comp <that path>, and the comp round adds two variations beside it where it stands;`. Exit status, stderr and files are unchanged.
+
+New cases, recorded from the binary and reviewed by hand:
+
+- `build-phase-decision-comp-option-one`: `--decision-comp` with `--comp` and with a missing file exit 1; `start --direction seed --decision-comp` prints the option-one NEXT; the first `advance` fails with `1 comp (the chosen decision comp ... as option one, the others directly under .impeccable/mocks)` and no approval, although an unrelated decision comp carries `"approved": true`; after two comps land in `.impeccable/mocks/` and the decision comp's sidecar is approved, `advance` closes on it (`3 comps, 1 approved`), and the snapshotted state and `approved-comp.json` name the decision path.
+- `question-wait-answer-decision-comp-in-round`: with a build state in the `comps` phase recording `decisionComp` and a page that also serves a comp directly in `.impeccable/mocks/`, a pick of that path prints `APPROVED COMP`, not `CHOSEN COMP`.
diff --git a/tests/oracle/cases/comp.mjs b/tests/oracle/cases/comp.mjs
index e8dda3722..0fcd5631d 100644
--- a/tests/oracle/cases/comp.mjs
+++ b/tests/oracle/cases/comp.mjs
@@ -88,6 +88,39 @@ const cases = [
},
{ id: 'build-phase-usage', verb: 'build-phase', workspace: WS, args: [], env: env() },
+ // The direction round's chosen comp is option one of the comp round: start
+ // records it, the comps gate counts it from .impeccable/mocks/decision/ (an
+ // unrelated decision comp never counts), and an approval on it closes the
+ // gate with the decision path as the approved comp. --decision-comp with
+ // --comp, or naming a missing file, is refused.
+ {
+ id: 'build-phase-decision-comp-option-one', verb: 'build-phase', workspace: WS,
+ files: ['.impeccable/build/state.json', '.impeccable/build/approved-comp.json'], env: env(),
+ setup: (ws) => {
+ fs.mkdirSync(path.join(ws, '.impeccable/mocks/decision'), { recursive: true });
+ fs.copyFileSync(path.join(ws, 'comp.png'), path.join(ws, '.impeccable/mocks/decision/assigned.png'));
+ write(ws, '.impeccable/mocks/decision/assigned.png.json', JSON.stringify({ prompt: 'assigned' }));
+ fs.copyFileSync(path.join(ws, 'build.png'), path.join(ws, '.impeccable/mocks/decision/pick.png'));
+ write(ws, '.impeccable/mocks/decision/pick.png.json', JSON.stringify({ prompt: 'pick', approved: true }));
+ },
+ steps: [
+ { args: ['start', '--comp', 'comp.png', '--decision-comp', '.impeccable/mocks/decision/assigned.png'] },
+ { args: ['start', '--direction', 'seed', '--decision-comp', '.impeccable/mocks/decision/missing.png'] },
+ { args: ['start', '--direction', 'seed', '--decision-comp', '.impeccable/mocks/decision/assigned.png'] },
+ { args: ['advance'] },
+ {
+ setup: (ws) => {
+ for (const n of [2, 3]) {
+ fs.copyFileSync(path.join(ws, 'build.png'), path.join(ws, `.impeccable/mocks/comp-${n}.png`));
+ write(ws, `.impeccable/mocks/comp-${n}.png.json`, JSON.stringify({ prompt: `variation ${n}` }));
+ }
+ write(ws, '.impeccable/mocks/decision/assigned.png.json', JSON.stringify({ prompt: 'assigned', approved: true }));
+ },
+ args: ['advance'],
+ },
+ ],
+ },
+
// The approved comp is a fixed reference: start keeps a copy, comp-spec binds
// the same pixels, and once the comp is edited (build.png copied over it, the
// shape of compositing plates into it) the gate, a re-measure and comp-diff
diff --git a/tests/oracle/cases/context.mjs b/tests/oracle/cases/context.mjs
index 716306c45..92edf5ced 100644
--- a/tests/oracle/cases/context.mjs
+++ b/tests/oracle/cases/context.mjs
@@ -743,6 +743,8 @@ const cases = [
{ 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/**'] },
+ // In the comp round, a pick of the decision comp build-phase recorded as option one is the approval too.
+ { id: 'question-wait-answer-decision-comp-in-round', verb: 'serve-question', workspace: 'ctx-empty', setup: (ws) => { write(ws, '.impeccable/build/state.json', JSON.stringify({ phase: 'comps', decisionComp: '.impeccable/mocks/decision/a.png' })); 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/comp-2.png'] })); write(ws, '.impeccable/mocks/decision/a.png', 'png'); write(ws, '.impeccable/mocks/decision/a.png.json', JSON.stringify({ prompt: 'a' })); write(ws, '.impeccable/mocks/comp-2.png', 'png'); write(ws, '.impeccable/mocks/comp-2.png.json', JSON.stringify({ prompt: 'b' })); write(ws, '.impeccable/questions/k1.answer.json', JSON.stringify({ optionId: 'one', steer: '', comp: '.impeccable/mocks/decision/a.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/build-phase-decision-comp-option-one.json b/tests/oracle/golden/build-phase-decision-comp-option-one.json
new file mode 100644
index 000000000..8ac550137
--- /dev/null
+++ b/tests/oracle/golden/build-phase-decision-comp-option-one.json
@@ -0,0 +1,38 @@
+{
+ "steps": [
+ {
+ "stdout": "",
+ "stderr": "build-phase: --decision-comp names option one of a comp round, so it goes with --direction and never with --comp\n",
+ "exit": 1,
+ "signal": null
+ },
+ {
+ "stdout": "",
+ "stderr": "build-phase: decision comp .impeccable/mocks/decision/missing.png does not exist\n",
+ "exit": 1,
+ "signal": null
+ },
+ {
+ "stdout": "BUILD-PHASE COMPS comp (pending comp round) direction seed\n comps open \n spec pending \n plates pending \n hero pending \n sections pending \n motion pending \n responsive pending \n review pending \nNEXT Comp round for the chosen direction (seed seed): read reference/visualize.md. The chosen decision comp .impeccable/mocks/decision/assigned.png is compositional option one; it stays where it is and is never regenerated. Generate two more compositional comps of the requested surface at its viewport into .impeccable/mocks/ (each with a prompt sidecar), put all three in front of the user, and set \"approved\": true in the chosen comp's sidecar (.impeccable/mocks/decision/assigned.png.json when they keep option one). Then impeccable build-phase advance. No page code before this closes.\n",
+ "stderr": "",
+ "exit": 0,
+ "signal": null
+ },
+ {
+ "stdout": "GATE COMPS FAILED (state unchanged)\n - 1 comp (the chosen decision comp .impeccable/mocks/decision/assigned.png as option one, the others directly under .impeccable/mocks); the comp round puts three compositional options of the chosen direction in front of the user (reference/visualize.md). Generate the missing ones (harness image tool or generate-image.mjs), each with a .json sidecar holding its prompt.\n - no comp is approved: put the three comps in front of the user (decision page via serve-question.mjs, or the structured question tool), then set \"approved\": true in the chosen comp's sidecar. A delegated pick is recorded the same way and disclosed.\n",
+ "stderr": "",
+ "exit": 2,
+ "signal": null
+ },
+ {
+ "stdout": "ADVANCED comps -> spec 3 comps, 1 approved\nNEXT Measure the comp: impeccable comp-spec --comp .impeccable/mocks/decision/assigned.png --grid, open .impeccable/build/comp-grid.png, write regions.json (every illustration, photo, texture as its own plate region; every text block its own text region), run impeccable comp-spec --comp .impeccable/mocks/decision/assigned.png --regions regions.json. Then measure the type: impeccable font-match --measure <id> for each text region (cap height, width class, weight class) and impeccable font-match --rank <lead text region> --text \"<its first words>\" to choose the headline face by metrics (the USE line is the CSS; with no browser it records the catalog's nearest face, which is the choice; do not install one, and do not write a chosen face into the spec by hand). Then impeccable build-phase advance.\n",
+ "stderr": "",
+ "exit": 0,
+ "signal": null
+ }
+ ],
+ "files": {
+ ".impeccable/build/approved-comp.json": "{\n \"comp\": \".impeccable/mocks/decision/assigned.png\",\n \"pixelSha256\": \"4c640a415d36339b4895de01ef99f1ab7726d8e4cf70029652485137c24d914e\",\n \"fileSha256\": \"b4dd0dcead73188eb9a4043e70f9050c8a397182d3dfbad6f4be4f06a6a1db64\",\n \"copy\": \".impeccable/build/approved-comp.png\",\n \"at\": \"<ISO>\"\n}",
+ ".impeccable/build/state.json": "{\n \"tool\": \"build-phase\",\n \"version\": 2,\n \"startedAt\": \"<ISO>\",\n \"comp\": \".impeccable/mocks/decision/assigned.png\",\n \"direction\": \"seed\",\n \"breakpoint\": \"768x512\",\n \"artifact\": null,\n \"phase\": \"spec\",\n \"phases\": {\n \"comps\": {\n \"status\": \"closed\",\n \"openedAt\": \"<ISO>\",\n \"closedAt\": \"<ISO>\",\n \"attempts\": 2,\n \"notes\": [],\n \"gate\": {\n \"ok\": true,\n \"reasons\": [],\n \"summary\": \"3 comps, 1 approved\",\n \"approved\": \".impeccable/mocks/decision/assigned.png\",\n \"at\": \"<ISO>\"\n },\n \"forced\": null\n },\n \"spec\": {\n \"status\": \"open\",\n \"openedAt\": \"<ISO>\",\n \"closedAt\": null,\n \"attempts\": 0,\n \"notes\": [],\n \"gate\": null,\n \"forced\": null\n },\n \"plates\": {\n \"status\": \"pending\",\n \"openedAt\": null,\n \"closedAt\": null,\n \"attempts\": 0,\n \"notes\": [],\n \"gate\": null,\n \"forced\": null\n },\n \"hero\": {\n \"status\": \"pending\",\n \"openedAt\": null,\n \"closedAt\": null,\n \"attempts\": 0,\n \"notes\": [],\n \"gate\": null,\n \"forced\": null\n },\n \"sections\": {\n \"status\": \"pending\",\n \"openedAt\": null,\n \"closedAt\": null,\n \"attempts\": 0,\n \"notes\": [],\n \"gate\": null,\n \"forced\": null\n },\n \"motion\": {\n \"status\": \"pending\",\n \"openedAt\": null,\n \"closedAt\": null,\n \"attempts\": 0,\n \"notes\": [],\n \"gate\": null,\n \"forced\": null\n },\n \"responsive\": {\n \"status\": \"pending\",\n \"openedAt\": null,\n \"closedAt\": null,\n \"attempts\": 0,\n \"notes\": [],\n \"gate\": null,\n \"forced\": null\n },\n \"review\": {\n \"status\": \"pending\",\n \"openedAt\": null,\n \"closedAt\": null,\n \"attempts\": 0,\n \"notes\": [],\n \"gate\": null,\n \"forced\": null\n }\n },\n \"finish\": null,\n \"decisionComp\": \".impeccable/mocks/decision/assigned.png\",\n \"sessionId\": \"<UUID>\"\n}"
+ }
+}
diff --git a/tests/oracle/golden/build-phase-usage.json b/tests/oracle/golden/build-phase-usage.json
index 27c00d614..b273d3a4f 100644
--- a/tests/oracle/golden/build-phase-usage.json
+++ b/tests/oracle/golden/build-phase-usage.json
@@ -1,6 +1,6 @@
{
"stdout": "CANDIDATE CHECK: build-phase check-plate <region-id> --candidate <png> [--json] validates a separate file with the normal plate gate; never replaces the selected asset, records approval, or advances the phase.\n",
- "stderr": "usage: build-phase.mjs start --comp <png> [--breakpoint WxH] [--artifact <entry file>] [--session-id <id>] | status [--json] | completion [--session-id <id>] | advance [--force --reason \"...\"] | record hero --build <png> | scaffold | note \"<text>\" | finish --disposition <word> | restore-comp\n",
+ "stderr": "usage: build-phase.mjs start --comp <png> | --direction <key> [--decision-comp <png>] [--breakpoint WxH] [--artifact <entry file>] [--session-id <id>] | status [--json] | completion [--session-id <id>] | advance [--force --reason \"...\"] | record hero --build <png> | scaffold | note \"<text>\" | finish --disposition <word> | restore-comp\n",
"exit": 1,
"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
index ddbee336d..d8b74757b 100644
--- a/tests/oracle/golden/question-wait-answer-comp-sidecar-missing.json
+++ b/tests/oracle/golden/question-wait-answer-comp-sidecar-missing.json
@@ -1,5 +1,5 @@
{
- "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 its sidecar, the image's full file name plus .json (a.png gets a.png.json), as {\"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",
+ "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 pass it to build-phase start as --decision-comp <that path>, and the comp round adds two variations beside it where it stands; 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 its sidecar, the image's full file name plus .json (a.png gets a.png.json), as {\"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,
diff --git a/tests/oracle/golden/question-wait-answer-decision-comp-in-round.json b/tests/oracle/golden/question-wait-answer-decision-comp-in-round.json
new file mode 100644
index 000000000..13e187b0a
--- /dev/null
+++ b/tests/oracle/golden/question-wait-answer-decision-comp-in-round.json
@@ -0,0 +1,7 @@
+{
+ "stdout": "ANSWER: {\"optionId\":\"one\",\"steer\":\"\",\"comp\":\".impeccable/mocks/decision/a.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, the image's full file name plus .json (a.png gets a.png.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-ready.json b/tests/oracle/golden/question-wait-answer-ready.json
index 864d8d7a0..0c6115ab1 100644
--- a/tests/oracle/golden/question-wait-answer-ready.json
+++ b/tests/oracle/golden/question-wait-answer-ready.json
@@ -1,5 +1,5 @@
{
- "stdout": "ANSWER: {\"optionId\":\"a\",\"steer\":\"keep the type\",\"hero\":\"https://x/hero.webp\",\"comp\":\".impeccable/mocks/decision/a.webp\",\"buildPath\":\"comp\",\"buildPathFlipped\":false}\nCHOSEN 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.\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.\n",
+ "stdout": "ANSWER: {\"optionId\":\"a\",\"steer\":\"keep the type\",\"hero\":\"https://x/hero.webp\",\"comp\":\".impeccable/mocks/decision/a.webp\",\"buildPath\":\"comp\",\"buildPathFlipped\":false}\nCHOSEN 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.\nCHOSEN COMP: the decision comp at that path is compositional option one. On a comp-led build pass it to build-phase start as --decision-comp <that path>, and the comp round adds two variations beside it where it stands; 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.\n",
"stderr": "",
"exit": 0,
"signal": null,