The design language that makes your AI harness better at design.
JavaScript
Hand the dealt worlds' card images to the agent when decision comps are due (#976)
Paul Bakaus12cddef81675
diff --git a/crates/context/src/concept_seed.rs b/crates/context/src/concept_seed.rsindex 66aefa5e0..20e22ef85 100644--- a/crates/context/src/concept_seed.rs+++ b/crates/context/src/concept_seed.rs@@ -108,7 +108,7 @@ fn api_base(env: &Env) -> String {base.strip_suffix('/').unwrap_or(&base).to_string()}-fn card_base(env: &Env) -> String {+pub(crate) fn card_base(env: &Env) -> String {env.get("IMPECCABLE_CARD_BASE").filter(|v| !v.is_empty()).cloned().unwrap_or_else(|| "https://impeccable.style/worlds/cards".to_string())}@@ -235,10 +235,7 @@ fn render_challenger(env: &Env, concept: &Value, index: usize) -> String {.and_then(|s| s.as_array()).map(|a| a.iter().map(|r| fill(t::RENDER_CHALLENGER_RULE, &[("RULE", &value_str(r))])).collect()).unwrap_or_default();- let cb = card_base(env);- let id = vs(concept, "id");- let board = concept.get("cardBoard").filter(|v| crate::staleness::js_truthy(v)).map(value_str).unwrap_or_else(|| format!("{}/{}.webp", cb, id));- let hero = concept.get("cardHero").filter(|v| crate::staleness::js_truthy(v)).map(value_str).unwrap_or_else(|| format!("{}/{}-hero.webp", cb, id));+ let (id, board, hero) = challenger_card(env, concept);fill(t::RENDER_CHALLENGER,&[@@ -254,6 +251,16 @@ fn render_challenger(env: &Env, concept: &Value, index: usize) -> String {)}+/// A dealt challenger's catalog id and its two card images: the QUALITY BAR+/// line prints them and the roll record carries them, from this one place.+fn challenger_card(env: &Env, concept: &Value) -> (String, String, String) {+ let cb = card_base(env);+ let id = vs(concept, "id");+ let board = concept.get("cardBoard").filter(|v| crate::staleness::js_truthy(v)).map(value_str).unwrap_or_else(|| format!("{}/{}.webp", cb, id));+ let hero = concept.get("cardHero").filter(|v| crate::staleness::js_truthy(v)).map(value_str).unwrap_or_else(|| format!("{}/{}-hero.webp", cb, id));+ (id, board, hero)+}+fn value_str(v: &Value) -> String {match v {Value::String(s) => s.clone(),@@ -326,16 +333,19 @@ fn unit(scope: &str, salt: &str, key: &str) -> f64 {}/// JS: renderConceptSeed-fn render_concept_seed(env: &Env, cwd: &str, budget: &mut ApiBudget, a: &SeedArgs) -> Result<String, String> {- let (scope, reroll, roll, degraded) = render_roll(env, cwd, budget, a)?;+/// Returns the text plus the catalog worlds the roll printed as challengers+/// (`{"id", "board", "hero"}` each), for the roll record.+fn render_concept_seed(env: &Env, cwd: &str, budget: &mut ApiBudget, a: &SeedArgs) -> Result<(String, Vec<Value>), String> {+ let (scope, reroll, roll, degraded, worlds) = render_roll(env, cwd, budget, a)?;// PRESENTATION closes every roll, where a middle-truncated read still// reaches it, like the restated lines above it.let register = a.register.clone().flatten();- Ok(roll + &presentation_block(env, cwd, scope, reroll, degraded, register.as_deref(), a.build_path.as_ref()))+ Ok((roll + &presentation_block(env, cwd, scope, reroll, degraded, register.as_deref(), a.build_path.as_ref()), worlds))}-/// The roll itself: (scope, re-roll round, text, degraded).-fn render_roll(env: &Env, cwd: &str, budget: &mut ApiBudget, a: &SeedArgs) -> Result<(&'static str, usize, String, bool), String> {+/// The roll itself: (scope, re-roll round, text, degraded, printed worlds).+#[allow(clippy::type_complexity)]+fn render_roll(env: &Env, cwd: &str, budget: &mut ApiBudget, a: &SeedArgs) -> Result<(&'static str, usize, String, bool, Vec<Value>), String> {let scope = match a.scope.as_deref() {Some("surface") => "surface",Some("direction") => "direction",@@ -476,7 +486,7 @@ fn render_roll(env: &Env, cwd: &str, budget: &mut ApiBudget, a: &SeedArgs) -> Relet mut pairs = common.clone();pairs.push(("DEGRADEDHEADER", °raded_header));pairs.push(("AUTHORITYINSTRUCTION", &authority));- return Ok((scope, reroll, fill(t::DEGRADED_SAFER, &pairs), true));+ return Ok((scope, reroll, fill(t::DEGRADED_SAFER, &pairs), true, vec![]));}let degraded_register = if register == Some("bolder") { t::DEGRADED_BOLDER.to_string() } else { String::new() };let mut pairs = common.clone();@@ -486,7 +496,7 @@ fn render_roll(env: &Env, cwd: &str, budget: &mut ApiBudget, a: &SeedArgs) -> Repairs.push(("PROMOTEDINSTRUCTION", &promoted));pairs.push(("AUTHORITYINSTRUCTION", &authority));pairs.push(("RESTATED_ASSIGNED_OR_DEALT", &restated_assigned_or_dealt));- return Ok((scope, reroll, fill(t::DEGRADED_BODY, &pairs), true));+ return Ok((scope, reroll, fill(t::DEGRADED_BODY, &pairs), true, vec![]));};let compositions_enabled = env.get("IMPECCABLE_COMPOSITIONS").map(|v| v == "1").unwrap_or(false);@@ -532,9 +542,16 @@ fn render_roll(env: &Env, cwd: &str, budget: &mut ApiBudget, a: &SeedArgs) -> Re_ => t::BOLDER_BLOCK.to_string(),};let round_challenger_instruction = if register == Some("bolder") { t::BOLDER_CHALLENGER.to_string() } else { challenger_instruction };+ // The safer register spends its hand unseen, so it prints no challenger+ // and records no world.+ let mut worlds: Vec<Value> = Vec::new();let challenger_section = if register == Some("safer") {String::new()} else {+ for c in &data.challengers {+ let (id, board, hero) = challenger_card(env, c);+ worlds.push(serde_json::json!({ "id": id, "board": board, "hero": hero }));+ }let rendered: Vec<String> = data.challengers.iter().enumerate().map(|(i, c)| render_challenger(env, c, i)).collect();fill(t::CHALLENGER_SECTION,@@ -561,7 +578,7 @@ fn render_roll(env: &Env, cwd: &str, budget: &mut ApiBudget, a: &SeedArgs) -> Repairs.push(("RICHNESSINSTRUCTION", &richness));pairs.push(("TELEMETRYBLOCK", &telemetry_block));pairs.push(("RESTATED", &restated));- Ok((scope, reroll, fill(t::MAIN, &pairs), false))+ Ok((scope, reroll, fill(t::MAIN, &pairs), false, worlds))}fn random_hex8() -> String {@@ -622,11 +639,12 @@ pub fn run(args: &[String], io: &mut Io) -> i32 {build_path: crate::context_cli::recorded_build_path(&ctx, &cwd),};match render_concept_seed(&env, &cwd, &mut budget, &seed) {- Ok(text) => {+ Ok((text, worlds)) => {// A valid roll: the scope and re-roll round passed validation.// serve-question reads the record to know a surface round when- // it serves one (`record_roll`).- crate::serve_question::record_roll(&cwd, seed.scope.as_deref().unwrap_or("surface"), &seed.key, seed.reroll as usize);+ // it serves one, and which catalog worlds were dealt, so it can+ // name their card images when the comps are due (`record_roll`).+ crate::serve_question::record_roll(&cwd, seed.scope.as_deref().unwrap_or("surface"), &seed.key, seed.reroll as usize, &worlds);io.out(&text);0}@@ -909,10 +927,26 @@ mod tests {assert_eq!(code, 0);let r = read();assert_eq!((r["scope"].as_str(), r["key"].as_str(), r["reroll"].as_u64()), (Some("surface"), Some("k1"), Some(0)));+ // The record names every challenger the roll printed, with the same+ // board and hero URLs as its QUALITY BAR line.+ let (_, out) = seed(&proj, &skill, true, &["--scope", "surface", "--mode", "operate", "--from", "k1"]);+ let worlds = read()["worlds"].as_array().cloned().unwrap();+ assert_eq!(worlds.len(), out.matches(" SOURCE ID: ").count().min(out.matches(" QUALITY BAR: ").count()));+ assert!(!worlds.is_empty());+ for w in &worlds {+ let (id, board, hero) = (w["id"].as_str().unwrap(), w["board"].as_str().unwrap(), w["hero"].as_str().unwrap());+ assert!(out.contains(&format!(" SOURCE ID: {id}\n")), "{id}: {out}");+ assert!(out.contains(&format!(" QUALITY BAR: board {board} · hero {hero}")), "{id}: {out}");+ }+ // The safer register prints no challenger, so it records no world.+ seed(&proj, &skill, true, &["--scope", "direction", "--from", "k1", "--reroll", "1", "--register", "safer"]);+ assert!(read().get("worlds").is_none(), "{}", read());assert!(r["at"].as_f64().is_some_and(|at| (crate::util::now_ms() - at).abs() < 60_000.0), "{r}");let (code, _) = seed(&proj, &skill, false, &["--scope", "direction", "--from", "k2", "--reroll", "1"]);assert_eq!(code, 0);let r = read();assert_eq!((r["scope"].as_str(), r["key"].as_str(), r["reroll"].as_u64()), (Some("direction"), Some("k2"), Some(1)));+ // A degraded roll dealt no world: the record keeps its old shape.+ assert!(r.get("worlds").is_none(), "{r}");}}diff --git a/crates/context/src/generate_image.rs b/crates/context/src/generate_image.rsindex 7e08983bd..ade78e05c 100644--- a/crates/context/src/generate_image.rs+++ b/crates/context/src/generate_image.rs@@ -245,6 +245,73 @@ fn parse_size(s: &str) -> (usize, usize) {(1536, 1024)}+/// How long one `--ref <url>` download may take, connect to last byte.+const REF_DOWNLOAD_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(30);++/// The largest reference image a URL may hand back.+const MAX_IMAGE_BYTES: u64 = 30 * 1024 * 1024;++/// Whether a `--ref` value (or a card image) is a URL rather than a path.+pub(crate) fn is_url(s: &str) -> bool {+ s.starts_with("https://") || s.starts_with("http://")+}++/// The URL without its query and fragment.+fn url_path(url: &str) -> &str {+ let end = url.find(['?', '#']).unwrap_or(url.len());+ &url[..end]+}++fn sniffed_type(bytes: &[u8]) -> Option<&'static str> {+ if bytes.starts_with(b"\x89PNG\r\n\x1a\n") {+ Some("image/png")+ } else if bytes.len() >= 12 && &bytes[..4] == b"RIFF" && &bytes[8..12] == b"WEBP" {+ Some("image/webp")+ } else if bytes.starts_with(&[0xff, 0xd8, 0xff]) {+ Some("image/jpeg")+ } else {+ None+ }+}++/// Downloads one png, webp, or jpeg image. The bytes' signature decides the+/// type and is required: a `200` HTML page behind a `.webp` URL or an image+/// Content-Type (a soft 404, an auth wall, a proxy interstitial) is refused+/// rather than uploaded or kept as an image. `redirects` is how many the+/// request may follow. The error is a short reason with no OS-specific text;+/// the caller names the URL.+pub(crate) fn fetch_image(url: &str, timeout: std::time::Duration, redirects: u32) -> Result<(Vec<u8>, &'static str), String> {+ use std::io::Read;+ let agent = crate::http::agent_builder().timeout_connect(timeout).timeout(timeout).redirects(redirects).build();+ let response = match agent.get(url).call() {+ Ok(r) => r,+ Err(ureq::Error::Status(code, _)) => return Err(format!("HTTP {}", code)),+ Err(_) => return Err("the request failed".into()),+ };+ if !(200..300).contains(&response.status()) {+ return Err(format!("HTTP {}", response.status()));+ }+ let mut bytes = Vec::new();+ if response.into_reader().take(MAX_IMAGE_BYTES + 1).read_to_end(&mut bytes).is_err() {+ return Err("the response was cut short".into());+ }+ if bytes.len() as u64 > MAX_IMAGE_BYTES {+ return Err("the image is larger than 30 MB".into());+ }+ if bytes.is_empty() {+ return Err("the response was empty".into());+ }+ sniffed_type(&bytes).map(|t| (bytes, t)).ok_or_else(|| "the response is not a png, webp, or jpeg image".into())+}++/// The multipart file name for a URL ref: its last path segment.+fn url_file_name(url: &str) -> String {+ let rest = url_path(url).split_once("://").map(|(_, r)| r).unwrap_or("");+ let segment = rest.split_once('/').map(|(_, p)| p.rsplit('/').next().unwrap_or("")).unwrap_or("");+ let name: String = segment.chars().filter(|c| !c.is_control() && *c != '"' && *c != '\\').collect();+ if name.is_empty() { "ref".to_string() } else { name }+}+pub fn run(args: &[String], io: &mut Io) -> i32 {run_with_api_base(args, io, "https://api.openai.com/v1")}@@ -347,21 +414,33 @@ fn run_with_api_base(args: &[String], io: &mut Io, api_base: &str) -> i32 {field("output_format", "png");}for r in &refs {- let bytes = match std::fs::read(abs(r)) {- Ok(b) => b,- Err(e) => {- io.err(&format!("Error: {}\n", node_read_error(r, &e)));- return 1;+ // A URL ref (a catalog world's card image, say) is downloaded+ // and attached like a file; nothing is written when one fails.+ let (bytes, ty, filename) = if is_url(r) {+ match fetch_image(r, REF_DOWNLOAD_TIMEOUT, 5) {+ Ok((bytes, ty)) => (bytes, ty, url_file_name(r)),+ Err(reason) => {+ io.err(&format!("generate-image: could not download --ref {}: {}; nothing was generated.\n", r, reason));+ return 1;+ }}- };- let ty = if r.ends_with(".png") {- "image/png"- } else if r.ends_with(".webp") {- "image/webp"} else {- "image/jpeg"+ let bytes = match std::fs::read(abs(r)) {+ Ok(b) => b,+ Err(e) => {+ io.err(&format!("Error: {}\n", node_read_error(r, &e)));+ return 1;+ }+ };+ let ty = if r.ends_with(".png") {+ "image/png"+ } else if r.ends_with(".webp") {+ "image/webp"+ } else {+ "image/jpeg"+ };+ (bytes, ty, r.rsplit('/').next().unwrap_or(r).to_string())};- let filename = r.rsplit('/').next().unwrap_or(r);body.extend_from_slice(format!("--{}\r\nContent-Disposition: form-data; name=\"image[]\"; filename=\"{}\"\r\nContent-Type: {}\r\n\r\n", boundary, filename, ty).as_bytes(),);@@ -576,6 +655,151 @@ mod tests {assert!(stdout.contains("prompt embedded + sidecar"));}+ /// Serves `GET` requests from `routes` (path -> status, content type,+ /// body) and answers one `POST` with a generated image; returns every+ /// request it saw as (method, path, body).+ fn serve(server: tiny_http::Server, routes: Vec<(&'static str, u16, &'static str, Vec<u8>)>, requests: usize) -> std::thread::JoinHandle<Vec<(String, String, String)>> {+ std::thread::spawn(move || {+ let mut seen = Vec::new();+ while seen.len() < requests {+ let Some(mut request) = server.recv_timeout(Duration::from_secs(10)).unwrap() else { break };+ let mut bytes = Vec::new();+ request.as_reader().read_to_end(&mut bytes).unwrap();+ let (method, path) = (request.method().to_string(), request.url().to_string());+ seen.push((method.clone(), path.clone(), String::from_utf8_lossy(&bytes).into_owned()));+ if method == "POST" {+ request.respond(tiny_http::Response::from_string(r#"{"data":[{"b64_json":"iVBORw0KGgoAAAANSUhEUgAAAAQAAAABCAYAAAD5PA/NAAAAGklEQVR4nGP4////f7mAigYGBgaG/////wMAUdQJXhk2RAEAAAAASUVORK5CYII="}]}"#)).unwrap();+ } else if let Some((_, status, ty, body)) = routes.iter().find(|r| r.0 == path) {+ let mut response = tiny_http::Response::from_data(body.clone()).with_status_code(*status);+ if !ty.is_empty() {+ response = response.with_header(tiny_http::Header::from_bytes(&b"Content-Type"[..], ty.as_bytes()).unwrap());+ }+ request.respond(response).unwrap();+ } else {+ request.respond(tiny_http::Response::from_string("not found").with_status_code(404)).unwrap();+ }+ }+ seen+ })+ }++ fn temp(name: &str) -> std::path::PathBuf {+ let dir = std::env::temp_dir().join(format!("impeccable-image-{}-{}", name, std::process::id()));+ let _ = std::fs::remove_dir_all(&dir);+ std::fs::create_dir_all(&dir).unwrap();+ dir+ }++ #[test]+ fn url_refs_are_downloaded_attached_and_recorded_as_urls() {+ let _proxy_lock = crate::http::PROXY_ENV_LOCK.lock().unwrap();+ let server = tiny_http::Server::http("127.0.0.1:0").unwrap();+ let base = format!("http://{}", server.server_addr());+ let dir = temp("url-ref");+ std::fs::write(dir.join("local.png"), png_fake("local", 8, 8)).unwrap();+ let webp = [&b"RIFF\x10\0\0\0WEBPVP8 "[..], &[0u8; 8][..]].concat();+ let handle = serve(+ server,+ vec![+ // The bytes decide the type, whatever the header and the+ // URL's extension say (or do not say).+ ("/cards/world.webp?v=2", 200, "image/webp; charset=binary", webp),+ ("/cards/world-hero.png", 200, "application/octet-stream", png_fake("hero", 8, 8)),+ ("/cards/blob", 200, "", vec![0xff, 0xd8, 0xff, 0xe0, 1, 2, 3]),+ ("/cards/mislabeled.webp", 200, "image/webp", png_fake("mislabeled", 8, 8)),+ ],+ 5,+ );+ let (board, hero, blob, mislabeled) = (format!("{base}/cards/world.webp?v=2"), format!("{base}/cards/world-hero.png"), format!("{base}/cards/blob"), format!("{base}/cards/mislabeled.webp"));+ let env = Env::from([("OPENAI_API_KEY".into(), "test-key".into())]);+ let (mut io, captured) = Io::captured("", dir.clone(), env);+ let args: Vec<String> = ["--prompt", "Comp with cards", "--out", "comp.png", "--ref", &board, "--ref", "local.png", "--ref", &hero, "--ref", &blob, "--ref", &mislabeled].iter().map(|s| s.to_string()).collect();+ let exit = run_with_api_base(&args, &mut io, &base);+ let seen = handle.join().unwrap();+ let stderr = String::from_utf8(captured.stderr.borrow().clone()).unwrap();+ assert_eq!(exit, 0, "{stderr}");+ let paths: Vec<(&str, &str)> = seen.iter().map(|r| (r.0.as_str(), r.1.as_str())).collect();+ assert_eq!(paths, vec![("GET", "/cards/world.webp?v=2"), ("GET", "/cards/world-hero.png"), ("GET", "/cards/blob"), ("GET", "/cards/mislabeled.webp"), ("POST", "/images/edits")]);+ let body = &seen[4].2;+ assert!(body.contains("name=\"image[]\"; filename=\"world.webp\"\r\nContent-Type: image/webp\r\n\r\nRIFF"), "{body}");+ assert!(body.contains("name=\"image[]\"; filename=\"local.png\"\r\nContent-Type: image/png\r\n"), "{body}");+ assert!(body.contains("name=\"image[]\"; filename=\"world-hero.png\"\r\nContent-Type: image/png\r\n"), "{body}");+ assert!(body.contains("name=\"image[]\"; filename=\"blob\"\r\nContent-Type: image/jpeg\r\n"), "{body}");+ assert!(body.contains("name=\"image[]\"; filename=\"mislabeled.webp\"\r\nContent-Type: image/png\r\n"), "{body}");+ // The sidecar records each ref as it was given: the URL itself.+ let sidecar: Value = serde_json::from_slice(&std::fs::read(dir.join("comp.png.json")).unwrap()).unwrap();+ assert_eq!(sidecar["refs"], serde_json::json!([board, "local.png", hero, blob, mislabeled]));+ assert!(dir.join("comp.png").exists());+ std::fs::remove_dir_all(&dir).unwrap();+ }++ #[test]+ fn a_failed_url_ref_names_the_url_and_writes_nothing() {+ let _proxy_lock = crate::http::PROXY_ENV_LOCK.lock().unwrap();+ let server = tiny_http::Server::http("127.0.0.1:0").unwrap();+ let base = format!("http://{}", server.server_addr());+ let dir = temp("url-ref-fail");+ let handle = serve(server, vec![("/cards/page.html", 200, "text/html", b"<html>blocked</html>".to_vec()), ("/cards/world.webp", 200, "image/webp", b"<html>sign in</html>".to_vec())], 3);+ let run_ref = |url: &str| {+ let env = Env::from([("OPENAI_API_KEY".into(), "test-key".into())]);+ let (mut io, captured) = Io::captured("", dir.clone(), env);+ let args: Vec<String> = ["--prompt", "p", "--out", "comp.png", "--ref", url].iter().map(|s| s.to_string()).collect();+ let exit = run_with_api_base(&args, &mut io, &base);+ let err = String::from_utf8(captured.stderr.borrow().clone()).unwrap();+ let out = String::from_utf8(captured.stdout.borrow().clone()).unwrap();+ (exit, err, out)+ };+ // A missing image, then a page that is not an image.+ let missing = format!("{base}/cards/gone.webp");+ let (exit, err, out) = run_ref(&missing);+ assert_eq!((exit, out.as_str()), (1, ""));+ assert_eq!(err, format!("generate-image: could not download --ref {missing}: HTTP 404; nothing was generated.\n"));+ let page = format!("{base}/cards/page.html");+ let (exit, err, _) = run_ref(&page);+ assert_eq!(exit, 1);+ assert_eq!(err, format!("generate-image: could not download --ref {page}: the response is not a png, webp, or jpeg image; nothing was generated.\n"));+ // A 200 page behind an image URL and an image Content-Type is still not an image.+ let wall = format!("{base}/cards/world.webp");+ let (exit, err, _) = run_ref(&wall);+ assert_eq!(exit, 1);+ assert_eq!(err, format!("generate-image: could not download --ref {wall}: the response is not a png, webp, or jpeg image; nothing was generated.\n"));+ // Only the three downloads reached the server: no generation request.+ let seen = handle.join().unwrap();+ assert!(seen.iter().all(|r| r.0 == "GET"), "{seen:?}");+ // An unreachable host reads the same on every OS.+ let (exit, err, _) = run_ref("http://127.0.0.1:9/ref.png");+ assert_eq!(exit, 1);+ assert_eq!(err, "generate-image: could not download --ref http://127.0.0.1:9/ref.png: the request failed; nothing was generated.\n");+ assert!(!dir.join("comp.png").exists() && !dir.join("comp.png.json").exists());+ std::fs::remove_dir_all(&dir).unwrap();+ }++ #[test]+ fn fake_mode_never_requests_a_url_ref() {+ let _proxy_lock = crate::http::PROXY_ENV_LOCK.lock().unwrap();+ let server = tiny_http::Server::http("127.0.0.1:0").unwrap();+ let url = format!("http://{}/cards/world.webp", server.server_addr());+ let dir = temp("url-ref-fake");+ let env = Env::from([("IMPECCABLE_IMAGE_GEN_FAKE".into(), "1".into()), ("OPENAI_API_KEY".into(), "test-key".into())]);+ let (mut io, captured) = Io::captured("", dir.clone(), env);+ let args: Vec<String> = ["--prompt", "p", "--out", "comp.png", "--ref", &url].iter().map(|s| s.to_string()).collect();+ assert_eq!(run(&args, &mut io), 0);+ assert!(String::from_utf8(captured.stdout.borrow().clone()).unwrap().contains("fake synthetic comp"));+ assert!(server.recv_timeout(Duration::from_millis(300)).unwrap().is_none());+ assert!(dir.join("comp.png").exists());+ std::fs::remove_dir_all(&dir).unwrap();+ }++ #[test]+ fn url_file_names_and_types() {+ assert_eq!(url_file_name("https://x.test/cards/a-hero.webp?v=1#f"), "a-hero.webp");+ assert_eq!(url_file_name("https://x.test/"), "ref");+ assert_eq!(url_file_name("https://x.test"), "ref");+ assert_eq!(sniffed_type(b"<html>"), None);+ assert_eq!(sniffed_type(b"RIFF\x10\0\0\0WEBPVP8 "), Some("image/webp"));+ assert!(is_url("http://a") && is_url("https://a") && !is_url("refs/a.png") && !is_url("ftp://a"));+ }+#[test]fn generation_uses_image_25_and_records_model() {round_trip(false, None, None);diff --git a/crates/context/src/serve_question.rs b/crates/context/src/serve_question.rsindex 14ad1a87c..b9e5badea 100644--- a/crates/context/src/serve_question.rs+++ b/crates/context/src/serve_question.rs@@ -306,8 +306,9 @@ fn missing_comps_message(round: CompRound, missing: &[String], rerun: &str, outcconst ROLL_WINDOW_MS: f64 = 60.0 * 60.0 * 1000.0;/// `.impeccable/questions/roll.json`: concept-seed's latest roll in this-/// project, `{"scope", "key", "reroll", "at"}` (`at` in epoch ms). Every-/// roll replaces it; a decision page (a payload carrying `buildPath`) that+/// project, `{"scope", "key", "reroll", "at"}` (`at` in epoch ms) plus+/// `"worlds"`, the catalog worlds it printed as challengers, when it printed+/// any. Every roll replaces it; a decision page (a payload carrying `buildPath`) that/// `--start` serves or `--update` delivers removes it, so a roll binds to/// the one page that presents it.fn roll_file(qdir: &str) -> String {@@ -316,9 +317,12 @@ fn roll_file(qdir: &str) -> String {/// Records a concept-seed roll for the next decision page. Best effort: a/// roll never fails because its record could not be written.-pub fn record_roll(cwd: &str, scope: &str, key: &str, reroll: usize) {+pub fn record_roll(cwd: &str, scope: &str, key: &str, reroll: usize, worlds: &[Value]) {let qdir = jsp::join(&[cwd, ".impeccable", "questions"]);- let record = json!({ "scope": scope, "key": key, "reroll": reroll, "at": now_ms() as u64 });+ let mut record = json!({ "scope": scope, "key": key, "reroll": reroll, "at": now_ms() as u64 });+ if !worlds.is_empty() {+ record["worlds"] = Value::Array(worlds.to_vec());+ }let _ = std::fs::create_dir_all(&qdir).and_then(|_| write_atomic(&roll_file(&qdir), &json_compact(&record)));}@@ -339,6 +343,133 @@ fn surface_roll_pending(roll: Option<&str>) -> bool {fresh && record.get("scope").and_then(Value::as_str) == Some("surface")}+/// One dealt catalog world as the NEXT line names it. The record is a local+/// file an API response fed, and the id becomes a file name, so an entry is+/// kept only when its id is a plain slug (`[A-Za-z0-9._-]`, no leading dot)+/// and both URLs are http(s) single tokens of sane length: nothing else can+/// ride an engine-printed line or name a path.+fn world_card(w: &Value) -> Option<Value> {+ let text = |k: &str, max: usize| w.get(k).and_then(Value::as_str).filter(|s| !s.is_empty() && s.len() <= max);+ let id = text("id", 120).filter(|s| !s.starts_with('.') && s.bytes().all(|b| b.is_ascii_alphanumeric() || matches!(b, b'.' | b'_' | b'-')))?;+ let url = |k: &str| text(k, 500).filter(|s| crate::generate_image::is_url(s) && !s.chars().any(|c| c.is_whitespace() || c.is_control() || c == '|' || c == '`'));+ Some(json!({ "id": id, "board": url("board")?, "hero": url("hero")? }))+}++/// Where a dealt world's card images are kept in the workspace, relative to+/// the project: reference images a harness image tool can take as files.+const WORLD_CARDS_DIR: &str = ".impeccable/mocks/worlds";++/// One card download may take this long, so a slow or blocked network never+/// holds `--start` for more than a few seconds (they run in parallel).+const WORLD_CARD_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(8);++/// The extensions a kept card image may carry, in the order they are looked for.+const WORLD_CARD_EXTS: [&str; 4] = ["webp", "png", "jpg", "jpeg"];++/// The workspace-relative path of a world's card image when one is already+/// kept: `<WORLD_CARDS_DIR>/<id>-<board|hero>.<ext>`.+fn kept_world_card(cwd: &str, id: &str, kind: &str) -> Option<String> {+ WORLD_CARD_EXTS.iter().map(|ext| format!("{}/{}-{}.{}", WORLD_CARDS_DIR, id, kind, ext)).find(|rel| exists(&jsp::resolve(cwd, &[rel.as_str()])))+}++/// Whether the engine may request a card URL on its own. The URLs come from+/// the roll record, a project file an API response fed, and `--start` fetches+/// them unasked, so a crafted record must not turn it into a probe of+/// loopback, link-local, or private services: a URL is fetched only when it+/// sits under the configured card base (`IMPECCABLE_CARD_BASE`, else+/// impeccable.style's), or is `https` to a named public-looking host (no IP+/// address in any spelling, no userinfo, no single-label, `localhost`,+/// `.local` or `.internal` name). Card fetches follow no redirect either. A URL that+/// fails this is still listed, by URL, for the agent to judge.+fn card_fetch_allowed(env: &Env, url: &str) -> bool {+ let base = crate::concept_seed::card_base(env);+ if url.starts_with(&format!("{}/", base.trim_end_matches('/'))) {+ return true;+ }+ let Some(rest) = url.strip_prefix("https://") else { return false };+ let authority = rest.split(['/', '?', '#']).next().unwrap_or("");+ if authority.contains('@') || authority.starts_with('[') {+ return false;+ }+ let host = authority.rsplit_once(':').map(|(h, _)| h).unwrap_or(authority).trim_end_matches('.').to_ascii_lowercase();+ let private_name = host == "localhost" || [".localhost", ".local", ".internal", ".lan", ".home.arpa"].iter().any(|s| host.ends_with(s));+ // A numeric host is an address however it is spelled (`127.1`,+ // `0177.0.0.1`, `0x7f.1` all resolve to loopback), so the last label+ // must be a name: letters only, or punycode.+ let tld = host.rsplit('.').next().unwrap_or("");+ let named = !tld.is_empty() && (tld.bytes().all(|b| b.is_ascii_alphabetic()) || (tld.starts_with("xn--") && tld.bytes().all(|b| b.is_ascii_alphanumeric() || b == b'-')));+ host.contains('.') && named && host.parse::<std::net::IpAddr>().is_err() && !private_name+}++/// Puts every dealt world's board and hero in the workspace and returns, per+/// world, `(id, board, hero)` where each image is its workspace-relative path+/// when the file is there and its URL when it could not be fetched. A file+/// already there is kept, not fetched again. Downloads run in parallel, each+/// under `WORLD_CARD_TIMEOUT`, and are best effort: a failure only leaves+/// that image named by URL. A fetched file takes its extension from the+/// image's own type, so a later `--ref` of the path sends the right one.+/// `IMPECCABLE_IMAGE_GEN_FAKE` makes no request.+fn fetch_world_cards(env: &Env, cwd: &str, worlds: &[Value]) -> Vec<(String, String, String)> {+ let s = |w: &Value, k: &str| w.get(k).and_then(Value::as_str).unwrap_or_default().to_string();+ let offline = env_set(env, "IMPECCABLE_IMAGE_GEN_FAKE");+ // (id, kind, url) per image, board then hero per world.+ let images: Vec<(String, &str, String)> = worlds.iter().flat_map(|w| ["board", "hero"].map(|kind| (s(w, "id"), kind, s(w, kind)))).collect();+ let fetch = |id: &str, kind: &str, url: &str| -> Option<String> {+ if let Some(kept) = kept_world_card(cwd, id, kind) {+ return Some(kept);+ }+ if offline || !card_fetch_allowed(env, url) {+ return None;+ }+ let (bytes, ty) = crate::generate_image::fetch_image(url, WORLD_CARD_TIMEOUT, 0).ok()?;+ let ext = match ty {+ "image/png" => "png",+ "image/jpeg" => "jpg",+ _ => "webp",+ };+ let rel = format!("{}/{}-{}.{}", WORLD_CARDS_DIR, id, kind, ext);+ let abs = jsp::resolve(cwd, &[rel.as_str()]);+ // Temp file then rename: a parallel session never reads half an image.+ let temp = format!("{}.tmp-{}", abs, std::process::id());+ let written = std::fs::create_dir_all(jsp::resolve(cwd, &[WORLD_CARDS_DIR])).and_then(|_| std::fs::write(&temp, &bytes)).and_then(|_| std::fs::rename(&temp, &abs));+ if written.is_err() {+ let _ = std::fs::remove_file(&temp);+ }+ written.is_ok().then_some(rel)+ };+ let have: Vec<Option<String>> = std::thread::scope(|scope| {+ let handles: Vec<_> = images.iter().map(|(id, kind, url)| scope.spawn(|| fetch(id, kind, url))).collect();+ handles.into_iter().map(|h| h.join().unwrap_or(None)).collect()+ });+ let named = |i: usize| have[i].clone().unwrap_or_else(|| images[i].2.clone());+ worlds.iter().enumerate().map(|(i, w)| (s(w, "id"), named(i * 2), named(i * 2 + 1))).collect()+}++/// The catalog worlds a decision page's hand was dealt: the roll record's+/// `worlds` (as `read_roll` returned it) when the page takes that roll (a+/// payload carrying `buildPath`, as in `take_roll`), the roll is a direction+/// roll, and it is younger than `ROLL_WINDOW_MS`. A surface roll's+/// challengers change topology under an identity already committed, so their+/// cards are never style references. Empty in every other case.+fn dealt_worlds(roll: Option<&str>, payload: &Value) -> Vec<Value> {+ if !payload.get("buildPath").is_some_and(|b| !b.is_null()) {+ return vec![];+ }+ let Some(record) = roll.and_then(|t| serde_json::from_str::<Value>(t).ok()) else {+ return vec![];+ };+ let fresh = record.get("at").and_then(Value::as_f64).is_some_and(|at| now_ms() - at < ROLL_WINDOW_MS);+ if !fresh || record.get("scope").and_then(Value::as_str) != Some("direction") {+ return vec![];+ }+ record.get("worlds").and_then(Value::as_array).map(|a| a.iter().filter_map(world_card).collect()).unwrap_or_default()+}++/// The worlds recorded in a hand (`dealt_worlds` at the time it was dealt).+fn hand_worlds(hand: Option<&Map<String, Value>>) -> Vec<Value> {+ hand.and_then(|h| h.get("worlds")).and_then(Value::as_array).map(|a| a.iter().filter_map(world_card).collect()).unwrap_or_default()+}+/// A decision page took the roll it was gated against: the payload carries/// `buildPath`, which only direction and surface rounds do. Removes the/// record only while it still holds that roll (`read` is the text read@@ -355,7 +486,8 @@ fn take_roll(qdir: &str, read: Option<&str>, payload: &Value) {/// `--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>}}`.+/// {<slot>: <sha256 of the file that sat there when the hand began>}}`, plus+/// `"worlds"` (`dealt_worlds`) when the hand took a roll that dealt any./// `--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 {@@ -507,7 +639,15 @@ pub fn record_generated(cwd: &str, out: &str) -> Result<Vec<String>, String> {/// 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.+#[cfg(test)]fn new_hand(cwd: &str, payload: &Value) -> Map<String, Value> {+ new_hand_dealt(cwd, payload, &[])+}++/// `new_hand` for a page that takes a roll: `worlds` (`dealt_worlds`) ride in+/// the hand, because the roll record is gone once the page has taken it and+/// the NEXT line is printed after that, and again by a later `--wait` flip.+fn new_hand_dealt(cwd: &str, payload: &Value, worlds: &[Value]) -> Map<String, Value> {let comps = declared_comps(payload);let mut pre = Map::new();for c in &comps {@@ -523,6 +663,9 @@ fn new_hand(cwd: &str, payload: &Value) -> Map<String, Value> {m.insert("digest".into(), Value::String(hand_digest(payload)));m.insert("comps".into(), json!(comps));m.insert("pre".into(), Value::Object(pre));+ if !worlds.is_empty() {+ m.insert("worlds".into(), Value::Array(worlds.to_vec()));+ }m}@@ -563,13 +706,14 @@ fn hand_marker_id(hand: &Map<String, Value>) -> 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> {+/// new one, written before the server spawns. `worlds` (`dealt_worlds`) go+/// into a new hand only: a restart keeps the worlds its hand was dealt.+fn start_hand(qdir: &str, key: &str, cwd: &str, payload: &Value, worlds: &[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);+ let h = new_hand_dealt(cwd, payload, worlds);write_hand(qdir, key, &h)?;Ok(h)}@@ -632,11 +776,35 @@ fn visualize_ref(env: &Env, cwd: &str) -> 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 {+/// the decision round's comps are about to be written. When the hand was+/// dealt catalog worlds (`hand_worlds`), the same line hands over their card+/// images, fetched into the workspace first (`fetch_world_cards`): a model+/// follows an engine line where it skips the prose rule that says to open+/// them, and a harness image tool takes reference images only as files.+fn visualize_next_line(env: &Env, cwd: &str, hand: Option<&Map<String, Value>>) -> String {+ let cards = fetch_world_cards(env, cwd, &hand_worlds(hand));format!(- "NEXT read {} now, before writing any decision comp prompt; it and the MODE RULES block concept-seed printed for this surface govern every card's image. Then generate each declared comp into its slot, lead first, and record the exact prompt in its sidecar, the image's full file name plus .json (a.png gets a.png.json).\n",- visualize_ref(env, cwd)+ "NEXT read {} now, before writing any decision comp prompt; it and the MODE RULES block concept-seed printed for this surface govern every card's image. Then generate each declared comp into its slot, lead first, and record the exact prompt in its sidecar, the image's full file name plus .json (a.png gets a.png.json).{}\n",+ visualize_ref(env, cwd),+ world_cards_clause(env, cwd, &cards)+ )+}++/// The NEXT line's tail naming each dealt world's card images (`cards` as+/// `fetch_world_cards` returned them); empty when none was dealt. The list+/// closes the line, `|` between worlds, so no path or URL ever touches+/// sentence punctuation.+fn world_cards_clause(env: &Env, cwd: &str, cards: &[(String, String, String)]) -> String {+ if cards.is_empty() {+ return String::new();+ }+ let list: Vec<String> = cards.iter().map(|(id, board, hero)| format!("{} board {} hero {}", id, board, hero)).collect();+ let unfetched = cards.iter().any(|(_, board, hero)| crate::generate_image::is_url(board) || crate::generate_image::is_url(hero));+ format!(+ " The catalog worlds dealt in this roll have card images, listed at the end of this line: when a card's direction builds on one of these worlds, attach that world's board and hero as reference images to that card's comp (the harness image tool's input images, or `{} --ref <board> --ref <hero>`{}), as style inspiration only, never to copy layout or content; a card for a direction you invented yourself has no card images and gets none. WORLD CARDS: {}",+ crate::provider::detect(env, cwd).verb_cmd("generate-image"),+ if unfetched { "; any image listed as a URL could not be fetched, so download it into the workspace first when the tool takes files" } else { "" },+ list.join(" | "))}@@ -802,7 +970,7 @@ pub fn run(argv: &[String], io: &mut Io) -> i32 {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));+ io.out(&visualize_next_line(&env, &cwd, hand.as_ref()));}return 0;}@@ -918,7 +1086,7 @@ pub fn run(argv: &[String], io: &mut Io) -> i32 {// 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);+ let hand = new_hand_dealt(&cwd, &next_round, &dealt_worlds(roll.as_deref(), &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;@@ -929,7 +1097,7 @@ pub fn run(argv: &[String], io: &mut Io) -> i32 {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));+ io.out(&visualize_next_line(&env, &cwd, Some(&hand)));}return 0;}@@ -953,7 +1121,7 @@ pub fn run(argv: &[String], io: &mut Io) -> i32 {}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) {+ let hand = match start_hand(&qdir, &key, &cwd, &start_payload, &dealt_worlds(roll.as_deref(), &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));@@ -1027,7 +1195,7 @@ pub fn run(argv: &[String], io: &mut Io) -> i32 {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(&visualize_next_line(&env, &cwd, Some(&hand)));}io.out(&format!("Then collect the answer with: {} --wait --key {}\n", crate::provider::detect(&env, &cwd).verb_cmd("serve-question"), key));return 0;@@ -2043,19 +2211,19 @@ mod tests {// 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();+ 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();+ 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();+ 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);@@ -2081,7 +2249,7 @@ mod tests {// 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();+ 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);@@ -2402,7 +2570,7 @@ mod tests {let qdir = jsp::join(&[&dir.to_string_lossy(), ".impeccable", "questions"]);let roll = dir.join(".impeccable/questions/roll.json");// Recorded the way concept-seed records a roll.- record_roll(&dir.to_string_lossy(), "surface", "seed-1", 0);+ record_roll(&dir.to_string_lossy(), "surface", "seed-1", 0, &[]);assert!(surface_roll_pending(read_roll(&qdir).as_deref()));std::fs::write(dir.join("p.json"), surface_round(false).to_string()).unwrap();let run_err = |args: &[&str]| {@@ -2655,10 +2823,264 @@ mod tests {let _ = std::fs::remove_dir_all(&dir);}++ /// A roll record as concept-seed writes it for a roll that dealt worlds.+ fn write_dealt_roll(dir: &std::path::Path, scope: &str, at: f64, worlds: &Value) {+ std::fs::write(dir.join(".impeccable/questions/roll.json"), json!({ "scope": scope, "key": "k", "reroll": 0, "at": at as u64, "worlds": worlds }).to_string()).unwrap();+ }++ fn two_worlds(base: &str) -> Value {+ json!([+ { "id": "print-fillmore-handbill", "board": format!("{base}/cards/print-fillmore-handbill.webp"), "hero": format!("{base}/cards/print-fillmore-handbill-hero.webp") },+ { "id": "broadcast-teletext", "board": format!("{base}/cards/broadcast-teletext.png?v=3"), "hero": format!("{base}/cards/broadcast-teletext-hero.webp") }+ ])+ }++ const NEXT_TODAY: &str = "NEXT read /skill/reference/visualize.md now, before writing any decision comp prompt; it and the MODE RULES block concept-seed printed for this surface govern every card's image. Then generate each declared comp into its slot, lead first, and record the exact prompt in its sidecar, the image's full file name plus .json (a.png gets a.png.json).\n";++ fn run_env(dir: &std::path::Path, extra: &[(&str, &str)], args: &[&str]) -> (i32, String) {+ let mut env = Env::from([("IMPECCABLE_SKILL_DIR".into(), "/skill".into()), ("IMPECCABLE_SELF".into(), "impeccable".into())]);+ for (k, v) in extra {+ env.insert(k.to_string(), v.to_string());+ }+ 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().replace('\\', "/");+ (code, out)+ }++ /// The NEXT visualize line of `out`, the skill path without the drive+ /// letter Windows resolves `/skill` under.+ fn next_line(out: &str) -> String {+ let Some(line) = out.lines().find(|l| l.starts_with("NEXT read ")) else { return String::new() };+ let rest = &line["NEXT read ".len()..];+ let rest = if rest.as_bytes().get(1) == Some(&b':') { &rest[2..] } else { rest };+ format!("NEXT read {rest}\n")+ }++ /// Answers card image requests until `stop` is set; returns the paths asked for.+ fn card_server(server: tiny_http::Server, stop: std::sync::Arc<std::sync::atomic::AtomicBool>) -> std::thread::JoinHandle<Vec<String>> {+ std::thread::spawn(move || {+ let mut seen = Vec::new();+ while !stop.load(std::sync::atomic::Ordering::SeqCst) {+ let Ok(Some(request)) = server.recv_timeout(std::time::Duration::from_millis(50)) else { continue };+ let path = request.url().to_string();+ seen.push(path.clone());+ if path.contains("missing") {+ let _ = request.respond(tiny_http::Response::from_string("gone").with_status_code(404));+ } else if path.contains("wall") {+ // A 200 sign-in page behind an image URL and Content-Type.+ let _ = request.respond(tiny_http::Response::from_string("<html>sign in</html>").with_header(tiny_http::Header::from_bytes("content-type", "image/webp").unwrap()));+ } else if path.contains("teletext.png") {+ // A PNG served as webp: the bytes decide.+ let body = [&b"\x89PNG\r\n\x1a\n"[..], path.as_bytes()].concat();+ let _ = request.respond(tiny_http::Response::from_data(body).with_header(tiny_http::Header::from_bytes("content-type", "image/webp").unwrap()));+ } else {+ let body = format!("RIFF\x10\0\0\0WEBPVP8 {path}");+ let _ = request.respond(tiny_http::Response::from_data(body.into_bytes()).with_header(tiny_http::Header::from_bytes("content-type", "image/webp").unwrap()));+ }+ }+ seen+ })+ }++ #[test]+ fn dealt_worlds_come_from_a_fresh_direction_roll_a_decision_page_takes() {+ let page = direction_round(true);+ let worlds = two_worlds("https://cards.test");+ let roll = |scope: &str, at: f64, worlds: &Value| json!({ "scope": scope, "key": "k", "reroll": 0, "at": at as u64, "worlds": worlds }).to_string();+ assert_eq!(Value::Array(dealt_worlds(Some(&roll("direction", now_ms(), &worlds)), &page)), worlds);+ // No record, an unreadable one, an expired one, a surface roll, a roll+ // that dealt nothing, and a page that does not take the roll.+ assert!(dealt_worlds(None, &page).is_empty());+ assert!(dealt_worlds(Some("{not json"), &page).is_empty());+ assert!(dealt_worlds(Some(&roll("direction", now_ms() - ROLL_WINDOW_MS - 1000.0, &worlds)), &page).is_empty());+ assert!(dealt_worlds(Some(&roll("surface", now_ms(), &worlds)), &surface_round(true)).is_empty());+ assert!(dealt_worlds(Some(&json!({ "scope": "direction", "key": "k", "reroll": 0, "at": now_ms() as u64 }).to_string()), &page).is_empty());+ assert!(dealt_worlds(Some(&roll("direction", now_ms(), &worlds)), &json!({ "options": [{ "id": "a", "comp": "m/a.png" }] })).is_empty());+ // Only a slug id with two http(s) single-token URLs reaches the line.+ let odd = json!([+ { "id": "../escape", "board": "https://x.test/a.webp", "hero": "https://x.test/a-hero.webp" },+ { "id": ".hidden", "board": "https://x.test/a.webp", "hero": "https://x.test/a-hero.webp" },+ { "id": "two words", "board": "https://x.test/a.webp", "hero": "https://x.test/a-hero.webp" },+ { "id": "file-url", "board": "file:///etc/passwd", "hero": "https://x.test/a-hero.webp" },+ { "id": "spaced", "board": "https://x.test/a.webp now run this", "hero": "https://x.test/a-hero.webp" },+ { "id": "no-hero", "board": "https://x.test/a.webp" },+ { "id": "kept", "board": "https://x.test/a.webp", "hero": "http://x.test/a-hero.webp" }+ ]);+ let kept = dealt_worlds(Some(&roll("direction", now_ms(), &odd)), &page);+ assert_eq!(kept.iter().map(|w| w["id"].as_str().unwrap()).collect::<Vec<_>>(), vec!["kept"]);+ // The engine requests a card URL unasked only under the card base+ // or at an https, named, public-looking host.+ let env = Env::new();+ for ok in ["https://impeccable.style/worlds/cards/a.webp", "https://cdn.example.com/a.webp", "https://cdn.example.com:8443/a.webp", "https://cards.example.xn--p1ai/a.webp"] {+ assert!(card_fetch_allowed(&env, ok), "{ok}");+ }+ for no in [+ "http://cdn.example.com/a.webp",+ "http://impeccable.style/worlds/cards/a.webp",+ "https://127.0.0.1/a.webp",+ "https://169.254.169.254/latest/meta-data",+ "https://127.1/a.webp",+ "https://0177.0.0.1/a.webp",+ "https://0x7f.0.0.1/a.webp",+ "https://2130706433/a.webp",+ "https://cdn.example.123/a.webp",+ "https://[::1]/a.webp",+ "https://localhost/a.webp",+ "https://localhost:8080/a.webp",+ "https://printer.local/a.webp",+ "https://db.internal/a.webp",+ "https://intranet/a.webp",+ "https://[email protected]/a.webp",+ "https://[email protected]/a.webp",+ ] {+ assert!(!card_fetch_allowed(&env, no), "{no}");+ }+ let local = Env::from([("IMPECCABLE_CARD_BASE".into(), "http://127.0.0.1:4000/cards".into())]);+ assert!(card_fetch_allowed(&local, "http://127.0.0.1:4000/cards/a.webp"));+ assert!(!card_fetch_allowed(&local, "http://127.0.0.1:4000/cardsx/a.webp") && !card_fetch_allowed(&local, "http://127.0.0.1:4001/cards/a.webp"));+ }++ #[test]+ fn next_line_fetches_and_names_the_dealt_worlds_card_images() {+ let _proxy_lock = crate::http::PROXY_ENV_LOCK.lock().unwrap();+ let server = tiny_http::Server::http("127.0.0.1:0").unwrap();+ let base = format!("http://{}", server.server_addr());+ let stop = std::sync::Arc::new(std::sync::atomic::AtomicBool::new(false));+ let handle = card_server(server, stop.clone());+ let dir = temp_project("world-cards");+ let qdir = jsp::join(&[&dir.to_string_lossy(), ".impeccable", "questions"]);+ write_state(&dir, &json!({ "pid": std::process::id(), "port": 1, "url": "http://127.0.0.1:1/" }));+ std::fs::write(dir.join("p.json"), direction_round(true).to_string()).unwrap();+ let card_base = format!("{base}/cards");+ let update = |extra: &[(&str, &str)]| run_env(&dir, &[extra, &[("IMPECCABLE_CARD_BASE", card_base.as_str())]].concat(), &["--update", "--key", "k1", "--payload", "p.json"]);+ const SENTENCE: &str = " The catalog worlds dealt in this roll have card images, listed at the end of this line: when a card's direction builds on one of these worlds, attach that world's board and hero as reference images to that card's comp (the harness image tool's input images, or `impeccable generate-image --ref <board> --ref <hero>`), as style inspiration only, never to copy layout or content; a card for a direction you invented yourself has no card images and gets none. WORLD CARDS: ";+ const FILES: &str = "print-fillmore-handbill board .impeccable/mocks/worlds/print-fillmore-handbill-board.webp hero .impeccable/mocks/worlds/print-fillmore-handbill-hero.webp | broadcast-teletext board .impeccable/mocks/worlds/broadcast-teletext-board.png hero .impeccable/mocks/worlds/broadcast-teletext-hero.webp\n";++ // Two dealt worlds: four files land in the workspace and the line+ // names them, after the page took the roll (the record is gone).+ write_dealt_roll(&dir, "direction", now_ms(), &two_worlds(&base));+ let (code, out) = update(&[]);+ assert_eq!(code, 0);+ assert_eq!(next_line(&out), format!("{}{}{}", NEXT_TODAY.trim_end(), SENTENCE, FILES));+ assert!(read_roll(&qdir).is_none());+ let card = |name: &str| String::from_utf8_lossy(&std::fs::read(dir.join(".impeccable/mocks/worlds").join(name)).unwrap_or_default()).into_owned();+ assert!(card("print-fillmore-handbill-board.webp").ends_with("/cards/print-fillmore-handbill.webp"));+ assert!(card("broadcast-teletext-board.png").ends_with("/cards/broadcast-teletext.png?v=3"));+ assert!(card("broadcast-teletext-hero.webp").ends_with("/cards/broadcast-teletext-hero.webp"));+ // The hand keeps the worlds, so a --wait flip names them too.+ assert_eq!(Value::Array(hand_worlds(read_hand(&qdir, "k1").as_ref())), two_worlds(&base));++ // The same worlds dealt again: every file is there, nothing is fetched.+ write_dealt_roll(&dir, "direction", now_ms(), &two_worlds(&base));+ let (_, out) = update(&[]);+ assert_eq!(next_line(&out), format!("{}{}{}", NEXT_TODAY.trim_end(), SENTENCE, FILES));+ stop.store(true, std::sync::atomic::Ordering::SeqCst);+ let mut seen = handle.join().unwrap();+ seen.sort();+ assert_eq!(seen, vec!["/cards/broadcast-teletext-hero.webp", "/cards/broadcast-teletext.png?v=3", "/cards/print-fillmore-handbill-hero.webp", "/cards/print-fillmore-handbill.webp"]);++ // An expired record, a surface roll, and no record print today's line.+ write_dealt_roll(&dir, "direction", now_ms() - ROLL_WINDOW_MS - 1000.0, &two_worlds(&base));+ assert_eq!(next_line(&update(&[]).1), NEXT_TODAY);+ std::fs::write(dir.join("s.json"), surface_round(true).to_string()).unwrap();+ write_dealt_roll(&dir, "surface", now_ms(), &two_worlds(&base));+ assert_eq!(next_line(&run_env(&dir, &[("IMPECCABLE_CARD_BASE", card_base.as_str())], &["--update", "--key", "k1", "--payload", "s.json"]).1), NEXT_TODAY);+ assert!(read_roll(&qdir).is_none());+ assert_eq!(next_line(&update(&[]).1), NEXT_TODAY);+ let _ = std::fs::remove_dir_all(&dir);+ }++ #[test]+ fn a_card_that_cannot_be_fetched_is_named_by_url_and_fails_nothing() {+ let _proxy_lock = crate::http::PROXY_ENV_LOCK.lock().unwrap();+ let server = tiny_http::Server::http("127.0.0.1:0").unwrap();+ let base = format!("http://{}", server.server_addr());+ let stop = std::sync::Arc::new(std::sync::atomic::AtomicBool::new(false));+ let handle = card_server(server, stop.clone());+ let dir = temp_project("world-cards-fail");+ write_state(&dir, &json!({ "pid": std::process::id(), "port": 1, "url": "http://127.0.0.1:1/" }));+ std::fs::write(dir.join("p.json"), direction_round(true).to_string()).unwrap();+ // One image 404s, one URL sits outside the card base on a loopback+ // host (never requested), one answers 200 with a sign-in page, an+ // extensionless one is a webp, and one is served.+ let worlds = json!([+ { "id": "a", "board": format!("{base}/cards/a.webp"), "hero": format!("{base}/cards/missing-hero.webp") },+ { "id": "b", "board": format!("{base}/elsewhere/b.webp"), "hero": format!("{base}/cards/b-hero") },+ { "id": "c", "board": format!("{base}/cards/wall.webp"), "hero": format!("{base}/cards/c-hero.webp") }+ ]);+ write_dealt_roll(&dir, "direction", now_ms(), &worlds);+ let card_base = format!("{base}/cards");+ let (code, out) = run_env(&dir, &[("IMPECCABLE_CARD_BASE", card_base.as_str())], &["--update", "--key", "k1", "--payload", "p.json"]);+ assert_eq!(code, 0);+ assert!(out.starts_with("next round delivered; the page reloads itself\n"), "{out}");+ let line = next_line(&out);+ assert!(line.contains("`impeccable generate-image --ref <board> --ref <hero>`; any image listed as a URL could not be fetched, so download it into the workspace first when the tool takes files), as style inspiration only"), "{line}");+ assert!(line.ends_with(&format!("WORLD CARDS: a board .impeccable/mocks/worlds/a-board.webp hero {base}/cards/missing-hero.webp | b board {base}/elsewhere/b.webp hero .impeccable/mocks/worlds/b-hero.webp | c board {base}/cards/wall.webp hero .impeccable/mocks/worlds/c-hero.webp\n")), "{line}");+ // Nothing but the three real images is kept: no page saved as a card.+ let cards = dir.join(".impeccable/mocks/worlds");+ let mut kept: Vec<String> = std::fs::read_dir(&cards).unwrap().flatten().map(|e| e.file_name().to_string_lossy().into_owned()).collect();+ kept.sort();+ assert_eq!(kept, vec!["a-board.webp", "b-hero.webp", "c-hero.webp"]);+ stop.store(true, std::sync::atomic::Ordering::SeqCst);+ let seen = handle.join().unwrap();+ assert!(!seen.iter().any(|p| p.contains("elsewhere")), "{seen:?}");+ let _ = std::fs::remove_dir_all(&dir);+ }++ #[test]+ fn fake_image_mode_fetches_no_card_and_names_what_is_there() {+ let server = tiny_http::Server::http("127.0.0.1:0").unwrap();+ let base = format!("http://{}", server.server_addr());+ let dir = temp_project("world-cards-fake");+ write_state(&dir, &json!({ "pid": std::process::id(), "port": 1, "url": "http://127.0.0.1:1/" }));+ std::fs::write(dir.join("p.json"), direction_round(true).to_string()).unwrap();+ // One card image an earlier round already fetched.+ std::fs::create_dir_all(dir.join(".impeccable/mocks/worlds")).unwrap();+ write_file(&dir.join(".impeccable/mocks/worlds/broadcast-teletext-hero.webp"), b"kept");+ write_dealt_roll(&dir, "direction", now_ms(), &two_worlds(&base));+ let (code, out) = run_env(&dir, &[("IMPECCABLE_IMAGE_GEN_FAKE", "1")], &["--update", "--key", "k1", "--payload", "p.json"]);+ assert_eq!(code, 0);+ assert!(next_line(&out).ends_with(&format!("WORLD CARDS: print-fillmore-handbill board {base}/cards/print-fillmore-handbill.webp hero {base}/cards/print-fillmore-handbill-hero.webp | broadcast-teletext board {base}/cards/broadcast-teletext.png?v=3 hero .impeccable/mocks/worlds/broadcast-teletext-hero.webp\n")), "{out}");+ assert!(server.recv_timeout(std::time::Duration::from_millis(300)).unwrap().is_none());+ assert_eq!(std::fs::read(dir.join(".impeccable/mocks/worlds/broadcast-teletext-hero.webp")).unwrap(), b"kept");+ let _ = std::fs::remove_dir_all(&dir);+ }++ #[test]+ fn a_restart_and_a_flip_keep_the_worlds_the_hand_was_dealt() {+ let dir = temp_project("world-cards-hand");+ let cwd = dir.to_string_lossy().into_owned();+ let qdir = jsp::join(&[&cwd, ".impeccable", "questions"]);+ let fake = [("IMPECCABLE_IMAGE_GEN_FAKE", "1")];+ let worlds = two_worlds("https://cards.test");+ let mut code_led = direction_round(true);+ code_led["buildPath"]["value"] = json!("code");+ // --start records the worlds in a new hand; the roll record is then+ // gone, and a restart of the same payload keeps the hand's worlds.+ let dealt = dealt_worlds(Some(&json!({ "scope": "direction", "key": "k", "reroll": 0, "at": now_ms() as u64, "worlds": worlds }).to_string()), &code_led);+ let hand = start_hand(&qdir, "k1", &cwd, &code_led, &dealt).unwrap();+ let restart = start_hand(&qdir, "k1", &cwd, &code_led, &[]).unwrap();+ assert_eq!(restart, hand);+ assert_eq!(Value::Array(hand_worlds(Some(&restart))), worlds);+ // The code-led round flips to comp: its NEXT line names the cards.+ write_state(&dir, &json!({ "pid": std::process::id(), "port": 1, "url": "http://127.0.0.1:1/" }));+ std::fs::write(flip_file(&qdir, "k1"), "1").unwrap();+ let (code, out) = run_env(&dir, &fake, &["--wait", "--key", "k1", "--poll", "2"]);+ assert_eq!(code, 0);+ assert!(out.starts_with("BUILD PATH FLIPPED: comp"), "{out}");+ assert!(next_line(&out).ends_with("WORLD CARDS: print-fillmore-handbill board https://cards.test/cards/print-fillmore-handbill.webp hero https://cards.test/cards/print-fillmore-handbill-hero.webp | broadcast-teletext board https://cards.test/cards/broadcast-teletext.png?v=3 hero https://cards.test/cards/broadcast-teletext-hero.webp\n"), "{out}");+ // A hand dealt no world records no `worlds` key.+ assert!(new_hand(&cwd, &code_led).get("worlds").is_none());+ 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())]);- let line = visualize_next_line(&env, "/proj").replace('\\', "/");+ let line = visualize_next_line(&env, "/proj", None).replace('\\', "/");assert!(line.starts_with("NEXT read /skill/reference/visualize.md now, before writing any decision comp prompt; it and the MODE RULES block concept-seed printed for this surface govern every card's image."), "{line}");assert!(line.ends_with("the image's full file name plus .json (a.png gets a.png.json).\n"));}diff --git a/docs/CLI-CONTRACT.md b/docs/CLI-CONTRACT.mdindex 0fd99e9ab..a38279d95 100644--- a/docs/CLI-CONTRACT.md+++ b/docs/CLI-CONTRACT.md@@ -466,7 +466,7 @@ retain their local-development trust behavior. See [bundle signing](BUNDLE-SIGNI````${mode}` is the mode as given (`experience` stays `experience`). When the file cannot be read, or either section is missing or empty, the block is the single line `MODE RULES unavailable: read ${path} before writing directions or comps.` and the roll still succeeds. Without `--mode` nothing is printed. The richness instruction is mode-neutral; the per-mode guidance on committing to an interface language lives in the mode files.- **Presentation** (binary only; every successful roll, direction or surface, full or degraded, every re-roll and both registers; never on validation errors, the PRODUCT.md gate, or telemetry pings): after the last line of the roll, a `PRESENTATION (the decision round, condensed from new-work.md; follow it even when your read of that file came back cut):` header and five `- ` lines, in order: how to serve the hand (round 0: `<self> serve-question --schema`, `--start --payload <file>`, open the URL; re-roll: `--update --key <same key> --payload <file>` while a page is open, never a second `--start`, and `--start` when no page opened yet); the comp line (direction: every card declares a comp under `.impeccable/mocks/decision/`, canon included, declined excepted, generated after serving in reading order with its `a.png.json` sidecar; degraded direction other than the safer register: one text-only card, no comp; surface: comps or wireframes, no pick or canon card; a recorded `code` default turns either scope's line into the code-led flip-reserve variant); `<self> serve-question --wait --key <key>`, led by `After the last comp lands (at once when this round generates none),` or, on a code-led round or a single degraded card, `Right after serving, with no comp to generate first,`, with the session-polling rule (rerun only after exit 3); the build-path line (`recorded default <comp|code> (from .impeccable/config.json|.impeccable/config.local.json)`, resolved exactly like `context`'s `BUILD_PATH_DEFAULT`, or `none recorded ...` with the comp default and the one-time offer after a flip); and the structured-tool fallback (`--start` exit 2, `--wait` exit 4, or a harness that cannot hold a blocking `--wait`). Text in `crates/context/src/seed_text.rs`; `reference/new-work.md` is its source and names the block.-- **Roll record** (binary only; every successful roll, the same set that prints the presentation block): writes `.impeccable/questions/roll.json` atomically (temp file, then rename), creating the directory, as `{"scope":"surface"|"direction","key":<key>,"reroll":<n>,"at":<epoch ms>}`, replacing the previous record. Best effort: a write failure is silent and never fails the roll. Validation errors, the PRODUCT.md gate, and telemetry pings write nothing. `serve-question` reads it for the surface-round comp gate and removes it when a decision page takes the roll (**Missing decision comps**).+- **Roll record** (binary only; every successful roll, the same set that prints the presentation block): writes `.impeccable/questions/roll.json` atomically (temp file, then rename), creating the directory, as `{"scope":"surface"|"direction","key":<key>,"reroll":<n>,"at":<epoch ms>}`, replacing the previous record. When the roll printed challengers, the record also carries `"worlds":[{"id":<SOURCE ID>,"board":<url>,"hero":<url>}, ...]` after `at`, one entry per printed challenger in print order, with the same board and hero URLs as its `QUALITY BAR` line; a degraded roll and the safer register (whose hand is spent unseen) print none and write no `worlds` key. `serve-question` hands those card images over when the decision comps are due (**World cards**). Best effort: a write failure is silent and never fails the roll. Validation errors, the PRODUCT.md gate, and telemetry pings write nothing. `serve-question` reads it for the surface-round comp gate and removes it when a decision page takes the roll (**Missing decision comps**).- **Telemetry ping** (`--chosen` and/or `--kind` present; never gated by PRODUCT.md): `pingChosen({chosenId, key, scope, mode, kind, register})`: skipped (returns false) when `IMPECCABLE_NO_TELEMETRY` or `DO_NOT_TRACK` set, `kind` not in `{assigned,pick,challenger,canon}`, `register` not `safer|bolder`, neither chosenId nor kind, or kind challenger/absent without chosenId. Else `POST ${API_BASE}/chosen` with `Content-Type: application/json`, body `JSON.stringify({ [chosenId], key, scope, mode, [kind], [register] })` (undefined values omitted by JSON.stringify), abort at budget. stdout `choice recorded\n` on success else `choice ping skipped\n`; always exit 0.- **Exit**: destroys undici global dispatcher then `process.exit(exitCode ?? 0)`.- Tests: `tests/concept-seed.test.mjs` (scopes reproducibility, degraded seed, register, ratings/breadth/mode/grain/platform, init gate, `pingChosen` validation & opt-out, API roll path + dispatcher destroy).@@ -486,9 +486,10 @@ retain their local-development trust behavior. See [bundle signing](BUNDLE-SIGNI- 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.- **Missing decision comps** (engine addition, not in the JS): `--start` and `--update` refuse a payload that is a comp-led direction round (or, per **Surface rounds** below, surface round) with image generation while some card that owes a decision comp declares none. The round owes them when all of these hold: `buildPath.value` is `"comp"` and `buildPath.toggle` is `true` (the toggle is only offered where image generation exists; a code-led round's slots are a flip reserve); the payload carries the canon exit, a truthy `canon` or an object `canonCard` (direction rounds only: surface rounds and the comp round never carry it); and `options` has at least two entries (a degraded roll's single text-only card declares no comp). The cards that owe one are every option whose `verdict` is not `"declined"`, plus `canonCard` when present; a card declares one with a truthy `comp` or legacy `sketch` (a URL counts). Missing cards are named by `id` (`options[<n>]` when the option has none, `canonCard` for the canon card), in card order. Message on stderr, exit 1 (exit 2 keeps its fallback meaning): `serve-question: this direction round is comp-led with image generation (buildPath value "comp", toggle true), so every card declares a decision comp, canon included, declined challengers excepted; ${outcome}. Missing a "comp": ${ids joined by ", "}. Give each of those cards "comp": ".impeccable/mocks/decision/<card id>.png" (the canon card's goes inside canonCard), then ${rerun}; the comps are generated after the page serves, as its NEXT line says.` with `${outcome}`/`${rerun}` = `the page was not served`/`rerun --start` for `--start` and `nothing was delivered`/`rerun --update on the same key` for `--update`. **Surface rounds**: the payload alone cannot tell a surface round (three dealt structures as full cards, no canon, no pick card) from the comp round or any other canon-less page, so the engine links it to concept-seed's roll record (`.impeccable/questions/roll.json`, **Roll record** under concept-seed). When the payload owes no direction comps and the record exists, parses, has `scope` `"surface"`, and its `at` is less than one hour old, a payload with no canon exit that is comp-led with image generation and carries at least two options owes a comp on every option whose `verdict` is not `"declined"`, named as above. Message: `serve-question: this surface round (concept-seed's latest roll here was --scope surface) is comp-led with image generation (buildPath value "comp", toggle true), so every dealt card declares a decision comp; ${outcome}. Missing a "comp": ${ids joined by ", "}. Give each of those cards "comp": ".impeccable/mocks/decision/<card id>.png", then ${rerun}; the comps are generated after the page serves, as its NEXT line says.` with the same `${outcome}`/`${rerun}` pairs. The record binds a roll to the one page that presents it: a refusal leaves it in place, and a `--start` that records its hand, or an `--update` that records its hand, removes it when the payload carries a non-null `buildPath` (only direction and surface rounds do), whatever the round's build path. The record is read once, before the gate, and removed only while the file still holds that same text: a newer roll another session recorded in between stays for its own page. So a later page in the same project (the comp round, a page after a direction roll, anything after the surface round was served) is not gated by it, and a page without `buildPath` (an unrelated question) neither takes nor is gated by it. Checked after the JSON parse (and, for `--update`, the options check) and before anything else; the env and headless gates run first, so a session that falls back to the structured tool never sees it. The blocking (non-`--start`) server does not check.- **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>-<hand tag>.json` = `{"slot", "hand"}` (the hand's `id`), written atomically. The hand tag is the hand's `id` (a hand file without an `id` uses its `digest`) when that is 1 to 64 characters of `[a-z0-9_]`, else the first 16 hex of sha256 over its JSON string (lowercase only, so ids that differ in case never share a path on a case-insensitive file system). 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, and the tag in the name keeps one hand's markers off every path another hand writes. A marker counts only while its name carries the hand file's tag, 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, deciding from the file name alone: it deletes only markers (and their temp files) tagged with another hand, so a failed write leaves the live hand and its markers intact and a parallel generation's marker for the new hand is never touched, even when it regenerates a reused slot while the prune runs (#886). A legacy untagged marker `<16 hex>.json` (written before names carried the hand) counts, and survives a prune, only while its content's `hand` (else `digest`) matches the hand's `id` (else `digest`); the engine never writes that name again. `--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.+ - **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>"}}`, plus `"worlds": [...]` last when the hand was dealt catalog worlds (**World cards**). 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>-<hand tag>.json` = `{"slot", "hand"}` (the hand's `id`), written atomically. The hand tag is the hand's `id` (a hand file without an `id` uses its `digest`) when that is 1 to 64 characters of `[a-z0-9_]`, else the first 16 hex of sha256 over its JSON string (lowercase only, so ids that differ in case never share a path on a case-insensitive file system). 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, and the tag in the name keeps one hand's markers off every path another hand writes. A marker counts only while its name carries the hand file's tag, 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, deciding from the file name alone: it deletes only markers (and their temp files) tagged with another hand, so a failed write leaves the live hand and its markers intact and a parallel generation's marker for the new hand is never touched, even when it regenerates a reused slot while the prune runs (#886). A legacy untagged marker `<16 hex>.json` (written before names carried the hand) counts, and survives a prune, only while its content's `hand` (else `digest`) matches the hand's `id` (else `digest`); the engine never writes that name again. `--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.- Four directives follow:- `NEXT read ${skillDir}/reference/visualize.md now, before writing any decision comp prompt; it and the MODE RULES block concept-seed printed for this surface govern every card's image. Then generate each declared comp into its slot, lead first, and record the exact prompt in its sidecar, the image's full file name plus .json (a.png gets a.png.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.+ - **World cards** (engine addition): when the hand was dealt catalog worlds, that same `NEXT` line continues, before its newline, with ` The catalog worlds dealt in this roll have card images, listed at the end of this line: when a card's direction builds on one of these worlds, attach that world's board and hero as reference images to that card's comp (the harness image tool's input images, or \`${impeccable} generate-image --ref <board> --ref <hero>\`${unfetched}), as style inspiration only, never to copy layout or content; a card for a direction you invented yourself has no card images and gets none. WORLD CARDS: ${worlds joined by " | "}` where each world is `${id} board ${board} hero ${hero}` and `${unfetched}` is `; any image listed as a URL could not be fetched, so download it into the workspace first when the tool takes files` when some image is named by URL, else empty. The list closes the line so no path or URL touches sentence punctuation. Models skip the prose rule that says to open the card images and follow an engine line, and a harness image tool takes reference images only as workspace files, so the engine fetches them. **Which worlds**: a new hand copies the roll record's `worlds` (**Roll record** under concept-seed; the record text read once before the gate, since the page then removes it) when the payload carries a non-null `buildPath` (the page that takes the roll), the record parses, its `scope` is `"direction"`, and its `at` is less than one hour old. A surface roll hands over none: its challengers change topology under an identity already committed. An entry is kept only when its `id` is 1 to 120 characters of `[A-Za-z0-9._-]` not starting with a dot (it becomes a file name) and `board` and `hero` are `http://` or `https://` URLs of at most 500 characters with no whitespace, control character, `|` or backtick. The payload is never consulted for which card builds on which world (its `hero` / `board` fields are model-authored and optional), so every dealt world is listed once. The worlds live in the hand file, so a `--start` restart of the same hand and the `--wait` flip line name them too. **Fetching**: right before the line prints, each listed world's board and hero go to `.impeccable/mocks/worlds/<id>-board.<ext>` and `<id>-hero.<ext>` (`<ext>` is `webp`, `png` or `jpg`, from the fetched bytes' signature, so a later `--ref` of the path sends the right type). A file already there under `webp`, `png`, `jpg` or `jpeg` (looked for in that order) is kept and not requested. The rest download in parallel, each one GET under an 8 s timeout through the shared agent (OS trust store, env proxies), following no redirect, accepted like a `generate-image --ref` URL (2xx, non-empty, at most 30 MB, a PNG, WebP or JPEG by signature, so an HTML page served at a card URL is never kept as a card), written to a temp file and renamed. **Which URLs the engine requests unasked**: the record is a project file, so a crafted one must not turn `--start` into a probe of loopback, link-local or private services. A URL is requested only when it starts with the configured card base plus `/` (`IMPECCABLE_CARD_BASE`, else `https://impeccable.style/worlds/cards`), or is `https` to a named host with a dot in it whose last label is letters only or punycode (so no IP address in any spelling: `127.0.0.1`, `127.1`, `0x7f.1`, a bracketed IPv6), carries no userinfo, and is not `localhost` or under `.localhost`, `.local`, `.internal`, `.lan` or `.home.arpa`. Any other URL is never requested and is listed by URL. (`generate-image --ref <url>` is an explicit request and stays unrestricted.) Best effort: a failed, blocked or refused download changes no exit code and prints nothing; that image is named by its URL instead of its path. With `IMPECCABLE_IMAGE_GEN_FAKE` set no request is made: files already there are named by path, the rest by URL. With no world to list (no roll record, an unreadable or expired one, a surface or degraded roll, a page without `buildPath`) the line is exactly the one above and nothing is fetched or created.- `COMP SIDECAR MISSING: ${paths joined by ", "} 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 ${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.- `NEXT open each decision comp once and run ${visualize path}'s render checks (shipped screen, one dominant move); regenerate any that fail before the user answers.` Printed by `--wait` as the last line of a WAITING return (after `COMP SIDECAR MISSING` and `COMP STALE` when they apply) when at least one state `comps` path outside `.impeccable/mocks/` itself (a decision comp, not a comp-round comp) is this hand's comp and has its `<path>.json` sidecar. Once per hand: the first such return writes the hand's `id` (else its `digest`, else the empty string with no hand file) to `<key>.render-check`, and a later return finds that id there and stays quiet; a new hand carries a new id, so its round prints the line again. A code-led round's slots stay empty or stale until a flip to comp, so it gets no line. Never on an answered return. `--stop` and a closing answer remove `<key>.render-check` with the hand file.@@ -503,9 +504,10 @@ retain their local-development trust behavior. See [bundle signing](BUNDLE-SIGNI#### `generate-image.mjs` -> `node {{scripts_path}}/generate-image.mjs`- **Invoked from**: `context.mjs appendImageGenDirective` (only when `OPENAI_API_KEY` set): "IMAGE_GEN_AVAILABLE: ... `node ${scriptsPath}/generate-image.mjs --prompt "..." --out <file>` (gpt-image-2, billed to the user's key; say so before the first render, and never reach for it when a native tool exists)."; `new-work.md` ("the harness image tool's input image, or `generate-image.mjs --ref`"); `visualize.md:30` ("every comp generated through `generate-image.mjs` has one [.json sidecar]").-- **Args**: `--prompt <text>` or `--prompt-file <path>` (file wins), `--out <path>` (required), `--size <WxH>` (default `1536x1024`), `--quality` (default `medium`), `--ref <img>` repeatable.+- **Args**: `--prompt <text>` or `--prompt-file <path>` (file wins), `--out <path>` (required), `--size <WxH>` (default `1536x1024`), `--quality` (default `medium`), `--ref <img>` repeatable; `<img>` is a file path or, engine addition, an `http://` / `https://` URL.- **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.+- **URL refs** (engine addition, real mode): a `--ref` starting with `http://` or `https://` is downloaded (one GET, 30 s timeout, redirects followed, through the shared agent with the OS trust store and env proxies) after the key and argument checks and before the generation request, then attached as an `image[]` part like a file ref, in argument order with the file refs. Its content type is the one the bytes' signature names (PNG, WebP, JPEG), and a signature is required: the response `Content-Type` and the URL's extension decide nothing, so a `200` HTML page behind a `.webp` URL (a soft 404, an auth wall, a proxy interstitial) is refused rather than uploaded as an image. Its file name is the URL path's last segment (`ref` when there is none). The sidecar `refs` records the URL string itself. A download that fails prints `generate-image: could not download --ref ${url}: ${reason}; nothing was generated.` on stderr and exits 1 with no generation request, no image and no sidecar; `${reason}` is `HTTP ${status}`, `the request failed` (no response: refused, unresolvable, timed out), `the response was cut short`, `the response was empty`, `the image is larger than 30 MB`, or `the response is not a png, webp, or jpeg image`. Fake mode never reads `--ref`, so it requests nothing.- **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`).diff --git a/tests/oracle/DELTAS.md b/tests/oracle/DELTAS.mdindex 7536029f9..bf119a51e 100644--- a/tests/oracle/DELTAS.md+++ b/tests/oracle/DELTAS.md@@ -6968,6 +6968,20 @@ New cases, recorded from the binary and reviewed by hand:- `question-update-surface-missing-comps`: a surface re-roll, then `--update` of the same hand with only `ledger` declared exits 1 naming `rail, field`; nothing is delivered and `roll.json` stays.- `question-update-surface-shape-after-direction-roll`: after a direction roll the same comp-less hand is delivered, and the page takes the roll (`roll.json` is gone).+## Recorded 2026-10-06: the NEXT line hands over the dealt worlds' card images++Three of four frontier models never opened a catalog world's card images before writing decision comp prompts, although the prose says to, and comps written with the card attached are much better. `concept-seed` now adds the worlds it printed as challengers to the roll record (`worlds`: id, board URL, hero URL), the decision page that takes a fresh direction roll copies them into its hand, and the `NEXT read ... visualize.md` line that `serve-question --start`, `--update` and the `--wait` flip print continues with one sentence and a `WORLD CARDS:` list, after fetching each board and hero into `.impeccable/mocks/worlds/` (best effort, 8 s each, nothing fetched under `IMPECCABLE_IMAGE_GEN_FAKE`). `generate-image --ref` also takes an `http(s)` URL. No existing golden moved: a roll that printed no challenger writes the record it wrote before, and a hand dealt no world prints the line it printed before.++New cases, recorded from the binary and reviewed by hand:++- `seed-roll-record-worlds`: a local-catalog direction roll with `IMPECCABLE_CARD_BASE` set writes `roll.json` with six `worlds`, each id and URL pair equal to the `SOURCE ID` and `QUALITY BAR` lines of the same stdout.+- `question-update-world-cards`: that roll (default card base), then `--update` of a comp-led direction round under `IMPECCABLE_IMAGE_GEN_FAKE=1`: the NEXT line carries the sentence with the unfetched clause and lists all six worlds by URL in deal order; `k1.hand.json` ends with the same `worlds`; `roll.json` is gone and `.impeccable/mocks/worlds/` was never created.+- `question-update-world-cards-in-workspace`: a recorded roll of two worlds with three of the four card files already in the workspace: those three are named by path (`fixture-signal-board.png` takes its extension from a URL with a query), the fourth by URL, and the three files are untouched.+- `question-update-world-cards-expired`: the same record with `at` an hour past prints the plain NEXT line.+- `question-update-world-cards-surface-roll`: a fresh surface roll's worlds are not handed over; a surface hand with every comp declared gets the plain NEXT line.+- `genimg-real-ref-url-unreachable`: `--ref http://127.0.0.1:9/cards/world.webp` with a key set exits 1 with `generate-image: could not download --ref http://127.0.0.1:9/cards/world.webp: the request failed; nothing was generated.` and writes neither `x.png` nor its sidecar.+- `genimg-fake-ref-url`: fake mode with the same URL ref prints the usual `IMAGE:` line and exits 0 without a request.+## Recorded 2026-10-06: an open native dialog is a popover layer`clipped-overflow-container` counted a positioned child as a layer that has to escape its clip only by `[popover]` or a role, so a clipped `<dialog open>` without `role="dialog"` was not reported. `POPOVER_LAYER_SELECTOR` now includes `dialog[open]` in both engines, and the fixture gained a `flag-native-dialog` row (and a closed-dialog pass row, which stays quiet). Re-recorded from the binary and reviewed by hand: in each of the fixture's own cases (the JSON form `detect-fixture-json-clipped-overflow-container-html` and the text form `detect-fixture-text-clipped-overflow-container-html`) and in the directory sweeps that read it (`detect-dir-json-all-fixtures`, `detect-dir-text-all-fixtures`, `detect-dir-quiet-all-fixtures`, `detect-scope-layout-text`, `detect-scope-both`), the one change is the new advisory finding `div.box.flag-native-dialog clips positioned dialog.pop.native-dialog` and the advisory count one higher. No other finding moved. The side-tab fixture's new elliptical pass row (`border-radius: 0 12px 12px 0 / 0`) is quiet in both engines, so its goldens did not move.diff --git a/tests/oracle/cases/context.mjs b/tests/oracle/cases/context.mjsindex 8a8df824f..1cd0c8bfc 100644--- a/tests/oracle/cases/context.mjs+++ b/tests/oracle/cases/context.mjs@@ -174,6 +174,12 @@ const MODE_RULES_SKILL = `${REPO}/tests/fixtures/mode-rules-skill`;const seedEnv = (extra = {}) => env({ IMPECCABLE_SKILL_DIR: MODE_RULES_SKILL, IMPECCABLE_CATALOG_DIR: CATALOG, IMPECCABLE_API_URL: 'http://127.0.0.1:9/api', IMPECCABLE_API_TIMEOUT: '300', ...extra });const degradedEnv = (extra = {}) => env({ IMPECCABLE_SKILL_DIR: MODE_RULES_SKILL, IMPECCABLE_CATALOG_DIR: `${WS}/no-such-catalog`, IMPECCABLE_API_URL: 'http://127.0.0.1:9/api', IMPECCABLE_API_TIMEOUT: '300', ...extra });+// Two dealt catalog worlds as concept-seed records them in roll.json.+const WORLDS = [+ { id: 'fixture-press', board: 'https://cards.example/fixture-press.webp', hero: 'https://cards.example/fixture-press-hero.webp' },+ { id: 'fixture-signal', board: 'https://cards.example/fixture-signal.png?v=2', hero: 'https://cards.example/fixture-signal-hero.webp' },+];+// A direction round as the eval run wrote it: comp-led with image generation, canon card, no comps.const DIRECTION_NO_COMPS = {title: 'Choose the visual world',@@ -188,6 +194,12 @@ const DIRECTION_NO_COMPS = {canon: true,canonCard: { label: 'The category standard', thesis: 'Five.' },};+// The same round with every owed comp declared (the declined challenger owes none).+const DIRECTION_WITH_COMPS = {+ ...DIRECTION_NO_COMPS,+ options: DIRECTION_NO_COMPS.options.map((o) => (o.verdict === 'declined' ? o : { ...o, comp: `.impeccable/mocks/decision/${o.id}.png` })),+ canonCard: { ...DIRECTION_NO_COMPS.canonCard, comp: '.impeccable/mocks/decision/canon.png' },+};// A surface round on an established world: three dealt structures as full cards, comp-led with image generation, no canon, no comps.const SURFACE_NO_COMPS = {title: 'Choose the structure',@@ -707,6 +719,8 @@ const cases = [{ id: 'seed-surface-local-grain-flow', verb: 'concept-seed', workspace: 'ctx-product-only', args: ['--scope', 'surface', '--mode', 'read', '--from', 'oracle-key-2', '--grain', 'flow', '--platform', 'ios'], env: seedEnv() },{ id: 'seed-surface-local-compositions', verb: 'concept-seed', workspace: 'ctx-product-only', args: ['--scope', 'surface', '--mode', 'persuade', '--from', 'oracle-key-1', '--platform', 'web'], env: seedEnv({ IMPECCABLE_COMPOSITIONS: '1' }) },{ id: 'seed-surface-local-card-base', verb: 'concept-seed', workspace: 'ctx-product-only', args: ['--scope', 'surface', '--mode', 'experience', '--from', 'oracle-key-4', '--reroll', '1'], env: seedEnv({ IMPECCABLE_CARD_BASE: 'https://cards.example/base/' }) },+ // The roll record names every catalog world the roll printed, with the QUALITY BAR line's board and hero URLs; serve-question hands their card images over when the comps are due.+ { id: 'seed-roll-record-worlds', verb: 'concept-seed', workspace: 'ctx-product-only', args: ['--scope', 'direction', '--mode', 'persuade', '--from', 'oracle-key-1'], env: seedEnv({ IMPECCABLE_CARD_BASE: 'https://cards.example/c' }), files: ['.impeccable/questions/roll.json'] },{ id: 'seed-degraded-direction', verb: 'concept-seed', workspace: 'ctx-product-only', args: ['--scope', 'direction', '--mode', 'persuade', '--from', 'oracle-key-1'], env: degradedEnv() },{ id: 'seed-degraded-surface', verb: 'concept-seed', workspace: 'ctx-product-only', args: ['--scope', 'surface', '--mode', 'operate', '--from', 'oracle-key-1'], env: degradedEnv() },{ id: 'seed-degraded-safer', verb: 'concept-seed', workspace: 'ctx-product-only', args: ['--scope', 'direction', '--from', 'oracle-key-1', '--reroll', '1', '--register', 'safer'], env: degradedEnv() },@@ -734,6 +748,10 @@ const cases = [// 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() },+ // --ref takes a URL too; one that cannot be downloaded names the URL and generates nothing.+ { id: 'genimg-real-ref-url-unreachable', verb: 'generate-image', workspace: 'ctx-empty', args: ['--prompt', 'x', '--out', 'x.png', '--ref', 'http://127.0.0.1:9/cards/world.webp'], env: env({ OPENAI_API_KEY: 'sk-oracle' }), files: ['x.png*'] },+ // Fake mode never fetches a URL ref.+ { id: 'genimg-fake-ref-url', verb: 'generate-image', workspace: 'ctx-empty', args: ['--prompt', 'A comp.', '--out', 'x.png', '--size', '64x40', '--ref', 'http://127.0.0.1:9/cards/world.webp'], env: env({ IMPECCABLE_IMAGE_GEN_FAKE: '1' }) },{ id: 'genimg-real-missing-args', verb: 'generate-image', workspace: 'ctx-empty', args: ['--out', 'x.png'], env: env({ OPENAI_API_KEY: 'sk-oracle' }) },// ======================================================================@@ -766,6 +784,21 @@ const cases = [{ 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() },+ // When the comps are due, the NEXT line also hands over the card images of the catalog worlds the roll dealt. concept-seed records them in roll.json; the decision page that takes the roll copies them into its hand, puts each board and hero in .impeccable/mocks/worlds/, and names the files (IMPECCABLE_IMAGE_GEN_FAKE fetches nothing, so the images are named by URL here).+ {+ id: 'question-update-world-cards', verb: 'serve-question', workspace: 'ctx-product-only', 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(DIRECTION_WITH_COMPS)); }, env: env({ IMPECCABLE_IMAGE_GEN_FAKE: '1' }), files: ['.impeccable/questions/roll.json', '.impeccable/questions/*.hand.json', '.impeccable/mocks/worlds/**'],+ normalize: [['("id":")[0-9a-f]{16}', 'g', '$1<HAND_ID>']],+ steps: [+ { verb: 'concept-seed', args: ['--scope', 'direction', '--mode', 'persuade', '--from', 'oracle-key-1'], env: seedEnv() },+ { args: ['--update', '--key', 'k1', '--payload', 'payload.json'] },+ ],+ },+ // Card images already in the workspace are named by path and never fetched again; the one that is not there keeps its URL, and the line says what to do with it.+ {+ id: 'question-update-world-cards-in-workspace', verb: 'serve-question', workspace: 'ctx-product-only', 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(DIRECTION_WITH_COMPS)); write(ws, '.impeccable/questions/roll.json', JSON.stringify({ scope: 'direction', key: 'k', reroll: 0, at: Date.now(), worlds: WORLDS })); for (const f of ['fixture-press-board.webp', 'fixture-press-hero.webp', 'fixture-signal-board.png']) write(ws, `.impeccable/mocks/worlds/${f}`, 'card'); }, args: ['--update', '--key', 'k1', '--payload', 'payload.json'], env: env({ IMPECCABLE_IMAGE_GEN_FAKE: '1' }), files: ['.impeccable/questions/roll.json', '.impeccable/mocks/worlds/**'] },+ // A roll record past its hour, and a surface roll (its challengers change topology under a committed identity), hand over no card: the NEXT line is the plain one.+ { id: 'question-update-world-cards-expired', verb: 'serve-question', workspace: 'ctx-product-only', 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(DIRECTION_WITH_COMPS)); write(ws, '.impeccable/questions/roll.json', JSON.stringify({ scope: 'direction', key: 'k', reroll: 0, at: 1000, worlds: WORLDS })); }, args: ['--update', '--key', 'k1', '--payload', 'payload.json'], env: env({ IMPECCABLE_IMAGE_GEN_FAKE: '1' }), files: ['.impeccable/mocks/worlds/**'] },+ { id: 'question-update-world-cards-surface-roll', verb: 'serve-question', workspace: 'ctx-product-only', 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({ ...SURFACE_NO_COMPS, options: SURFACE_NO_COMPS.options.map((o) => ({ ...o, comp: `.impeccable/mocks/decision/${o.id}.png` })) })); write(ws, '.impeccable/questions/roll.json', JSON.stringify({ scope: 'surface', key: 'k', reroll: 0, at: Date.now(), worlds: WORLDS })); }, args: ['--update', '--key', 'k1', '--payload', 'payload.json'], env: env({ IMPECCABLE_IMAGE_GEN_FAKE: '1' }), files: ['.impeccable/mocks/worlds/**'] },// 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.diff --git a/tests/oracle/golden/genimg-fake-ref-url.json b/tests/oracle/golden/genimg-fake-ref-url.jsonnew file mode 100644index 000000000..4542fec3d--- /dev/null+++ b/tests/oracle/golden/genimg-fake-ref-url.json@@ -0,0 +1,7 @@+{+ "stdout": "IMAGE: x.png (64x40, fake synthetic comp, $0.00, no API call)\n",+ "stderr": "",+ "exit": 0,+ "signal": null,+ "files": {}+}diff --git a/tests/oracle/golden/genimg-real-ref-url-unreachable.json b/tests/oracle/golden/genimg-real-ref-url-unreachable.jsonnew file mode 100644index 000000000..b8ed42e14--- /dev/null+++ b/tests/oracle/golden/genimg-real-ref-url-unreachable.json@@ -0,0 +1,7 @@+{+ "stdout": "",+ "stderr": "generate-image: could not download --ref http://127.0.0.1:9/cards/world.webp: the request failed; nothing was generated.\n",+ "exit": 1,+ "signal": null,+ "files": {}+}diff --git a/tests/oracle/golden/question-update-world-cards-expired.json b/tests/oracle/golden/question-update-world-cards-expired.jsonnew file mode 100644index 000000000..457c43d43--- /dev/null+++ b/tests/oracle/golden/question-update-world-cards-expired.json@@ -0,0 +1,7 @@+{+ "stdout": "next round delivered; the page reloads itself\nNEXT read <REPO>/skill/reference/visualize.md now, before writing any decision comp prompt; it and the MODE RULES block concept-seed printed for this surface govern every card's image. Then generate each declared comp into its slot, lead first, and record the exact prompt in its sidecar, the image's full file name plus .json (a.png gets a.png.json).\n",+ "stderr": "",+ "exit": 0,+ "signal": null,+ "files": {}+}diff --git a/tests/oracle/golden/question-update-world-cards-in-workspace.json b/tests/oracle/golden/question-update-world-cards-in-workspace.jsonnew file mode 100644index 000000000..7b88af957--- /dev/null+++ b/tests/oracle/golden/question-update-world-cards-in-workspace.json@@ -0,0 +1,11 @@+{+ "stdout": "next round delivered; the page reloads itself\nNEXT read <REPO>/skill/reference/visualize.md now, before writing any decision comp prompt; it and the MODE RULES block concept-seed printed for this surface govern every card's image. Then generate each declared comp into its slot, lead first, and record the exact prompt in its sidecar, the image's full file name plus .json (a.png gets a.png.json). The catalog worlds dealt in this roll have card images, listed at the end of this line: when a card's direction builds on one of these worlds, attach that world's board and hero as reference images to that card's comp (the harness image tool's input images, or `<IMPECCABLE> generate-image --ref <board> --ref <hero>`; any image listed as a URL could not be fetched, so download it into the workspace first when the tool takes files), as style inspiration only, never to copy layout or content; a card for a direction you invented yourself has no card images and gets none. WORLD CARDS: fixture-press board .impeccable/mocks/worlds/fixture-press-board.webp hero .impeccable/mocks/worlds/fixture-press-hero.webp | fixture-signal board .impeccable/mocks/worlds/fixture-signal-board.png hero https://cards.example/fixture-signal-hero.webp\n",+ "stderr": "",+ "exit": 0,+ "signal": null,+ "files": {+ ".impeccable/mocks/worlds/fixture-press-board.webp": "card",+ ".impeccable/mocks/worlds/fixture-press-hero.webp": "card",+ ".impeccable/mocks/worlds/fixture-signal-board.png": "card"+ }+}diff --git a/tests/oracle/golden/question-update-world-cards-surface-roll.json b/tests/oracle/golden/question-update-world-cards-surface-roll.jsonnew file mode 100644index 000000000..457c43d43--- /dev/null+++ b/tests/oracle/golden/question-update-world-cards-surface-roll.json@@ -0,0 +1,7 @@+{+ "stdout": "next round delivered; the page reloads itself\nNEXT read <REPO>/skill/reference/visualize.md now, before writing any decision comp prompt; it and the MODE RULES block concept-seed printed for this surface govern every card's image. Then generate each declared comp into its slot, lead first, and record the exact prompt in its sidecar, the image's full file name plus .json (a.png gets a.png.json).\n",+ "stderr": "",+ "exit": 0,+ "signal": null,+ "files": {}+}diff --git a/tests/oracle/golden/question-update-world-cards.json b/tests/oracle/golden/question-update-world-cards.jsonnew file mode 100644index 000000000..3e639aff9--- /dev/null+++ b/tests/oracle/golden/question-update-world-cards.json@@ -0,0 +1,19 @@+{+ "steps": [+ {+ "stdout": "DIRECTION CONCEPT SEED (key: oracle-key-1; mode: persuade; source: local; approved pool: 6c20a02b6dc4; 30/35 human-approved; rerun with --scope direction --mode persuade --from oracle-key-1 --candidate-count 7 to reproduce this roll against this catalog revision)\nASSIGNED INDEX: 6\n After ordering the grounded directions by resonance, build candidate\n 6 of your own grounded list; the assignment never points at a\n challenger. The assignment is the roll, not a suggestion: your top-ranked\n direction is what every run would ship, so the script decides which grounded\n direction gets built. Each direction joins a durable visual system to a\n concrete expression for the requested first surface, decided as one. It must\n survive the current task plus navigation, quiet and dense content,\n interaction and state, and a substantially different future surface. In an\n attended run, present the assigned direction fully committed and offer\n re-roll. You may add ONE card for your top-ranked grounded candidate when\n it is not the assigned direction, kicker IMPECCABLE’S PICK, with an honest risk line\n naming its familiarity; one pick card, never a ranked lineup, and the pick\n never takes the lead position. When the assignment IS your top candidate,\n there is no pick card. Re-roll yourself only\n on named factual grounds, when the assignment cannot carry the product's\n truth or task; taste is never grounds.\n The assignment exists to refuse the model's ranking rut, never to outrank\n the user or the brief. Never expose assignment metadata in user-facing labels.\nCHALLENGERS:\n 1. a banner press of the fixture canon, where ranked plates, shutters, and registers stage attention across one continuous working field\n SOURCE ID: fixture-print-family-banner-press\n CREATIVE SPARK: The banner press wakes as its plates roll over one by one, every register finding its rank while a single saturated signal tracks the decision you have not made yet.\n SYSTEM GRAMMAR:\n - Palette/material: ink-dark ground, unbleached paper field, and one saturated signal color reserved for the active decision in zone 4\n - Type/composition: compact grotesk labels over generous editorial serif, ranked on a strict modular grid of order 4\n - Topology/navigation: move between the whole field and one consequential detail along route 4\n - Controls/state: reveal, compare, and preserve every meaningful authored state in register 4\n - Responsive/motion: recompose the spatial law while retaining orientation across breakpoint 4\n WEB LEVERAGE: CSS grid plate choreography with a keyboard-readable register index and scroll-driven rank reveal\n QUALITY BAR: board https://impeccable.style/worlds/cards/fixture-print-family-banner-press.webp · hero https://impeccable.style/worlds/cards/fixture-print-family-banner-press-hero.webp\n 2. a card index of the fixture canon, where ranked plates, shutters, and registers stage attention across one continuous working field\n SOURCE ID: fixture-canon-family-card-index\n CREATIVE SPARK: The card index wakes as its plates roll over one by one, every register finding its rank while a single saturated signal tracks the decision you have not made yet.\n SYSTEM GRAMMAR:\n - Palette/material: ink-dark ground, unbleached paper field, and one saturated signal color reserved for the active decision in zone 9\n - Type/composition: compact grotesk labels over generous editorial serif, ranked on a strict modular grid of order 9\n - Topology/navigation: move between the whole field and one consequential detail along route 9\n - Controls/state: reveal, compare, and preserve every meaningful authored state in register 9\n - Responsive/motion: recompose the spatial law while retaining orientation across breakpoint 9\n WEB LEVERAGE: CSS grid plate choreography with a keyboard-readable register index and scroll-driven rank reveal\n QUALITY BAR: board https://impeccable.style/worlds/cards/fixture-canon-family-card-index.webp · hero https://impeccable.style/worlds/cards/fixture-canon-family-card-index-hero.webp\n 3. a reed basin of the fixture canon, where ranked plates, shutters, and registers stage attention across one continuous working field\n SOURCE ID: fixture-material-family-reed-basin\n CREATIVE SPARK: The reed basin wakes as its plates roll over one by one, every register finding its rank while a single saturated signal tracks the decision you have not made yet.\n SYSTEM GRAMMAR:\n - Palette/material: ink-dark ground, unbleached paper field, and one saturated signal color reserved for the active decision in zone 26\n - Type/composition: compact grotesk labels over generous editorial serif, ranked on a strict modular grid of order 26\n - Topology/navigation: move between the whole field and one consequential detail along route 26\n - Controls/state: reveal, compare, and preserve every meaningful authored state in register 26\n - Responsive/motion: recompose the spatial law while retaining orientation across breakpoint 26\n WEB LEVERAGE: CSS grid plate choreography with a keyboard-readable register index and scroll-driven rank reveal\n QUALITY BAR: board https://impeccable.style/worlds/cards/fixture-material-family-reed-basin.webp · hero https://impeccable.style/worlds/cards/fixture-material-family-reed-basin-hero.webp\n 4. a rain atrium of the fixture canon, where ranked plates, shutters, and registers stage attention across one continuous working field\n SOURCE ID: fixture-performed-family-rain-atrium\n CREATIVE SPARK: The rain atrium wakes as its plates roll over one by one, every register finding its rank while a single saturated signal tracks the decision you have not made yet.\n SYSTEM GRAMMAR:\n - Palette/material: ink-dark ground, unbleached paper field, and one saturated signal color reserved for the active decision in zone 30\n - Type/composition: compact grotesk labels over generous editorial serif, ranked on a strict modular grid of order 30\n - Topology/navigation: move between the whole field and one consequential detail along route 30\n - Controls/state: reveal, compare, and preserve every meaningful authored state in register 30\n - Responsive/motion: recompose the spatial law while retaining orientation across breakpoint 30\n WEB LEVERAGE: CSS grid plate choreography with a keyboard-readable register index and scroll-driven rank reveal\n QUALITY BAR: board https://impeccable.style/worlds/cards/fixture-performed-family-rain-atrium.webp · hero https://impeccable.style/worlds/cards/fixture-performed-family-rain-atrium-hero.webp\n 5. a meter row of the fixture canon, where ranked plates, shutters, and registers stage attention across one continuous working field\n SOURCE ID: fixture-instruments-family-meter-row\n CREATIVE SPARK: The meter row wakes as its plates roll over one by one, every register finding its rank while a single saturated signal tracks the decision you have not made yet.\n SYSTEM GRAMMAR:\n - Palette/material: ink-dark ground, unbleached paper field, and one saturated signal color reserved for the active decision in zone 18\n - Type/composition: compact grotesk labels over generous editorial serif, ranked on a strict modular grid of order 18\n - Topology/navigation: move between the whole field and one consequential detail along route 18\n - Controls/state: reveal, compare, and preserve every meaningful authored state in register 18\n - Responsive/motion: recompose the spatial law while retaining orientation across breakpoint 18\n WEB LEVERAGE: CSS grid plate choreography with a keyboard-readable register index and scroll-driven rank reveal\n QUALITY BAR: board https://impeccable.style/worlds/cards/fixture-instruments-family-meter-row.webp · hero https://impeccable.style/worlds/cards/fixture-instruments-family-meter-row-hero.webp\n 6. a gauge bench of the fixture canon, where ranked plates, shutters, and registers stage attention across one continuous working field\n SOURCE ID: fixture-instruments-family-gauge-bench\n CREATIVE SPARK: The gauge bench wakes as its plates roll over one by one, every register finding its rank while a single saturated signal tracks the decision you have not made yet.\n SYSTEM GRAMMAR:\n - Palette/material: ink-dark ground, unbleached paper field, and one saturated signal color reserved for the active decision in zone 16\n - Type/composition: compact grotesk labels over generous editorial serif, ranked on a strict modular grid of order 16\n - Topology/navigation: move between the whole field and one consequential detail along route 16\n - Controls/state: reveal, compare, and preserve every meaningful authored state in register 16\n - Responsive/motion: recompose the spatial law while retaining orientation across breakpoint 16\n WEB LEVERAGE: CSS grid plate choreography with a keyboard-readable register index and scroll-driven rank reveal\n QUALITY BAR: board https://impeccable.style/worlds/cards/fixture-instruments-family-gauge-bench.webp · hero https://impeccable.style/worlds/cards/fixture-instruments-family-gauge-bench-hero.webp\nFuse each challenger before judging it: the challenger supplies the form\n and its system grammar, the product supplies every fact, and clarity wins\n conflicts. Weigh the fused result against the assigned direction on exactly\n two axes, audience identification and product clarity. Losing to strong\n grounded material is a valid outcome; beating a thin or tool-monoculture\n list is the point. A fused challenger that wins both axes becomes the build.\n Close the weighing with a verdict per challenger, decided before any\n borrowing is considered: wins (beats the assigned direction on both axes),\n competitive (holds one axis), or declined (loses both). A declined\n challenger is not spent: name the one discipline of its system the assigned\n direction lacks, and raise the assigned direction to match before\n presenting it. A donation transfers ambition and system discipline, never\n the challenger's clothes. A component treatment, such as a button's shadow\n or a display face, is clothes, not discipline; one world owns the page.\n Write each raise as its own named line on the presented direction, and\n carry every verdict, kept line, and raise into the decision page payload.\nWhen you can view images, open the QUALITY BAR board and hero for any\nchallenger you weigh seriously and for the world you build. They exist as a\ncraft bar, the finish level and commitment the build is expected to reach,\nnever as a mockup to copy; your surface serves this product, not that render.\nPRODUCT.md and explicit incumbent brand commitments constrain every direction.\nThe seed never chooses exact colors, fonts, tokens, or a user preference, and\nit never permits the world and first surface to be selected independently.\nThe CREATIVE SPARK is a complete visual system, not a theme or decorative\nreference. Translate every supplied system rule into the product: palette and\nmaterial, type and composition, topology, controls and states, and adaptation.\nKeep the source's visible character, scale, rhythm, and interaction instead of\nreducing vivid grammar to generic nouns. Keep a literal carrier only when it\nbecomes functional.\nAmbitious motion, spatial media, or interaction is welcome when it strengthens\nthe product without weakening semantics, performance, or fallback behavior.\nMODE RULES (persuade, from <REPO>/tests/fixtures/mode-rules-skill/reference/mode-persuade.md). They govern this surface's directions and every comp you write or judge for it, the decision comps included; where shared guidance conflicts, these win.\nDIRECTIONS\n- PERSUADE DIRECTION RULE ONE.\n- PERSUADE DIRECTION RULE TWO.\nCOMPS\n- PERSUADE COMP RULE.\nA user- or brief-pinned decision beats the roll, always.\nASSIGNED INDEX (restated for truncated readers): 6. Build candidate\n6 of your own grounded list; seed key oracle-key-1.\nPRESENTATION (the decision round, condensed from new-work.md; follow it even when your read of that file came back cut):\n- Present this hand on the decision page: write the options payload (`<IMPECCABLE> serve-question --schema` prints its shape), run `<IMPECCABLE> serve-question --start --payload <file>`, and open the URL it prints for the user.\n- With image generation, every card declares a comp under .impeccable/mocks/decision/, canon included, declined challengers excepted. Serve first, then generate each comp in reading order (assigned, pick, full-card hand, canon), writing its prompt sidecar as it lands (a.png gets a.png.json).\n- After the last comp lands (at once when this round generates none), hold `<IMPECCABLE> serve-question --wait --key <key>`. If your shell hands back a session before --wait exits, keep polling that session until it exits; rerun --wait only after it exits 3 with no answer.\n- Build path: none recorded in .impeccable/config.json or .impeccable/config.local.json, so comp-led whenever image generation exists. Then put \"buildPath\": {\"value\": \"comp\", \"toggle\": true} in the payload; without image generation there is no toggle and the build is code-led. Never ask about the build path during the round; only when the ANSWER returns buildPathFlipped: true, offer once afterwards to keep the flipped value as the default.\n- The structured question tool is the fallback, never the first channel: take it when --start exits 2, when --wait exits 4 after the page closed unanswered, or when your harness cannot hold a blocking --wait at all (say so in your first reply). It carries the same options and asks nothing about the build path.\n",+ "stderr": "",+ "exit": 0,+ "signal": null+ },+ {+ "stdout": "next round delivered; the page reloads itself\nNEXT read <REPO>/skill/reference/visualize.md now, before writing any decision comp prompt; it and the MODE RULES block concept-seed printed for this surface govern every card's image. Then generate each declared comp into its slot, lead first, and record the exact prompt in its sidecar, the image's full file name plus .json (a.png gets a.png.json). The catalog worlds dealt in this roll have card images, listed at the end of this line: when a card's direction builds on one of these worlds, attach that world's board and hero as reference images to that card's comp (the harness image tool's input images, or `<IMPECCABLE> generate-image --ref <board> --ref <hero>`; any image listed as a URL could not be fetched, so download it into the workspace first when the tool takes files), as style inspiration only, never to copy layout or content; a card for a direction you invented yourself has no card images and gets none. WORLD CARDS: fixture-print-family-banner-press board https://impeccable.style/worlds/cards/fixture-print-family-banner-press.webp hero https://impeccable.style/worlds/cards/fixture-print-family-banner-press-hero.webp | fixture-canon-family-card-index board https://impeccable.style/worlds/cards/fixture-canon-family-card-index.webp hero https://impeccable.style/worlds/cards/fixture-canon-family-card-index-hero.webp | fixture-material-family-reed-basin board https://impeccable.style/worlds/cards/fixture-material-family-reed-basin.webp hero https://impeccable.style/worlds/cards/fixture-material-family-reed-basin-hero.webp | fixture-performed-family-rain-atrium board https://impeccable.style/worlds/cards/fixture-performed-family-rain-atrium.webp hero https://impeccable.style/worlds/cards/fixture-performed-family-rain-atrium-hero.webp | fixture-instruments-family-meter-row board https://impeccable.style/worlds/cards/fixture-instruments-family-meter-row.webp hero https://impeccable.style/worlds/cards/fixture-instruments-family-meter-row-hero.webp | fixture-instruments-family-gauge-bench board https://impeccable.style/worlds/cards/fixture-instruments-family-gauge-bench.webp hero https://impeccable.style/worlds/cards/fixture-instruments-family-gauge-bench-hero.webp\n",+ "stderr": "",+ "exit": 0,+ "signal": null+ }+ ],+ "files": {+ ".impeccable/questions/k1.hand.json": "{\"id\":\"<HAND_ID>\",\"digest\":\"562b0cc524940856\",\"comps\":[\".impeccable/mocks/decision/assigned.png\",\".impeccable/mocks/decision/model-pick.png\",\".impeccable/mocks/decision/challenger-a.png\",\".impeccable/mocks/decision/canon.png\"],\"pre\":{},\"worlds\":[{\"id\":\"fixture-print-family-banner-press\",\"board\":\"https://impeccable.style/worlds/cards/fixture-print-family-banner-press.webp\",\"hero\":\"https://impeccable.style/worlds/cards/fixture-print-family-banner-press-hero.webp\"},{\"id\":\"fixture-canon-family-card-index\",\"board\":\"https://impeccable.style/worlds/cards/fixture-canon-family-card-index.webp\",\"hero\":\"https://impeccable.style/worlds/cards/fixture-canon-family-card-index-hero.webp\"},{\"id\":\"fixture-material-family-reed-basin\",\"board\":\"https://impeccable.style/worlds/cards/fixture-material-family-reed-basin.webp\",\"hero\":\"https://impeccable.style/worlds/cards/fixture-material-family-reed-basin-hero.webp\"},{\"id\":\"fixture-performed-family-rain-atrium\",\"board\":\"https://impeccable.style/worlds/cards/fixture-performed-family-rain-atrium.webp\",\"hero\":\"https://impeccable.style/worlds/cards/fixture-performed-family-rain-atrium-hero.webp\"},{\"id\":\"fixture-instruments-family-meter-row\",\"board\":\"https://impeccable.style/worlds/cards/fixture-instruments-family-meter-row.webp\",\"hero\":\"https://impeccable.style/worlds/cards/fixture-instruments-family-meter-row-hero.webp\"},{\"id\":\"fixture-instruments-family-gauge-bench\",\"board\":\"https://impeccable.style/worlds/cards/fixture-instruments-family-gauge-bench.webp\",\"hero\":\"https://impeccable.style/worlds/cards/fixture-instruments-family-gauge-bench-hero.webp\"}]}"+ }+}diff --git a/tests/oracle/golden/seed-roll-record-worlds.json b/tests/oracle/golden/seed-roll-record-worlds.jsonnew file mode 100644index 000000000..17eee5631--- /dev/null+++ b/tests/oracle/golden/seed-roll-record-worlds.json@@ -0,0 +1,9 @@+{+ "stdout": "DIRECTION CONCEPT SEED (key: oracle-key-1; mode: persuade; source: local; approved pool: 6c20a02b6dc4; 30/35 human-approved; rerun with --scope direction --mode persuade --from oracle-key-1 --candidate-count 7 to reproduce this roll against this catalog revision)\nASSIGNED INDEX: 6\n After ordering the grounded directions by resonance, build candidate\n 6 of your own grounded list; the assignment never points at a\n challenger. The assignment is the roll, not a suggestion: your top-ranked\n direction is what every run would ship, so the script decides which grounded\n direction gets built. Each direction joins a durable visual system to a\n concrete expression for the requested first surface, decided as one. It must\n survive the current task plus navigation, quiet and dense content,\n interaction and state, and a substantially different future surface. In an\n attended run, present the assigned direction fully committed and offer\n re-roll. You may add ONE card for your top-ranked grounded candidate when\n it is not the assigned direction, kicker IMPECCABLE’S PICK, with an honest risk line\n naming its familiarity; one pick card, never a ranked lineup, and the pick\n never takes the lead position. When the assignment IS your top candidate,\n there is no pick card. Re-roll yourself only\n on named factual grounds, when the assignment cannot carry the product's\n truth or task; taste is never grounds.\n The assignment exists to refuse the model's ranking rut, never to outrank\n the user or the brief. Never expose assignment metadata in user-facing labels.\nCHALLENGERS:\n 1. a banner press of the fixture canon, where ranked plates, shutters, and registers stage attention across one continuous working field\n SOURCE ID: fixture-print-family-banner-press\n CREATIVE SPARK: The banner press wakes as its plates roll over one by one, every register finding its rank while a single saturated signal tracks the decision you have not made yet.\n SYSTEM GRAMMAR:\n - Palette/material: ink-dark ground, unbleached paper field, and one saturated signal color reserved for the active decision in zone 4\n - Type/composition: compact grotesk labels over generous editorial serif, ranked on a strict modular grid of order 4\n - Topology/navigation: move between the whole field and one consequential detail along route 4\n - Controls/state: reveal, compare, and preserve every meaningful authored state in register 4\n - Responsive/motion: recompose the spatial law while retaining orientation across breakpoint 4\n WEB LEVERAGE: CSS grid plate choreography with a keyboard-readable register index and scroll-driven rank reveal\n QUALITY BAR: board https://cards.example/c/fixture-print-family-banner-press.webp · hero https://cards.example/c/fixture-print-family-banner-press-hero.webp\n 2. a card index of the fixture canon, where ranked plates, shutters, and registers stage attention across one continuous working field\n SOURCE ID: fixture-canon-family-card-index\n CREATIVE SPARK: The card index wakes as its plates roll over one by one, every register finding its rank while a single saturated signal tracks the decision you have not made yet.\n SYSTEM GRAMMAR:\n - Palette/material: ink-dark ground, unbleached paper field, and one saturated signal color reserved for the active decision in zone 9\n - Type/composition: compact grotesk labels over generous editorial serif, ranked on a strict modular grid of order 9\n - Topology/navigation: move between the whole field and one consequential detail along route 9\n - Controls/state: reveal, compare, and preserve every meaningful authored state in register 9\n - Responsive/motion: recompose the spatial law while retaining orientation across breakpoint 9\n WEB LEVERAGE: CSS grid plate choreography with a keyboard-readable register index and scroll-driven rank reveal\n QUALITY BAR: board https://cards.example/c/fixture-canon-family-card-index.webp · hero https://cards.example/c/fixture-canon-family-card-index-hero.webp\n 3. a reed basin of the fixture canon, where ranked plates, shutters, and registers stage attention across one continuous working field\n SOURCE ID: fixture-material-family-reed-basin\n CREATIVE SPARK: The reed basin wakes as its plates roll over one by one, every register finding its rank while a single saturated signal tracks the decision you have not made yet.\n SYSTEM GRAMMAR:\n - Palette/material: ink-dark ground, unbleached paper field, and one saturated signal color reserved for the active decision in zone 26\n - Type/composition: compact grotesk labels over generous editorial serif, ranked on a strict modular grid of order 26\n - Topology/navigation: move between the whole field and one consequential detail along route 26\n - Controls/state: reveal, compare, and preserve every meaningful authored state in register 26\n - Responsive/motion: recompose the spatial law while retaining orientation across breakpoint 26\n WEB LEVERAGE: CSS grid plate choreography with a keyboard-readable register index and scroll-driven rank reveal\n QUALITY BAR: board https://cards.example/c/fixture-material-family-reed-basin.webp · hero https://cards.example/c/fixture-material-family-reed-basin-hero.webp\n 4. a rain atrium of the fixture canon, where ranked plates, shutters, and registers stage attention across one continuous working field\n SOURCE ID: fixture-performed-family-rain-atrium\n CREATIVE SPARK: The rain atrium wakes as its plates roll over one by one, every register finding its rank while a single saturated signal tracks the decision you have not made yet.\n SYSTEM GRAMMAR:\n - Palette/material: ink-dark ground, unbleached paper field, and one saturated signal color reserved for the active decision in zone 30\n - Type/composition: compact grotesk labels over generous editorial serif, ranked on a strict modular grid of order 30\n - Topology/navigation: move between the whole field and one consequential detail along route 30\n - Controls/state: reveal, compare, and preserve every meaningful authored state in register 30\n - Responsive/motion: recompose the spatial law while retaining orientation across breakpoint 30\n WEB LEVERAGE: CSS grid plate choreography with a keyboard-readable register index and scroll-driven rank reveal\n QUALITY BAR: board https://cards.example/c/fixture-performed-family-rain-atrium.webp · hero https://cards.example/c/fixture-performed-family-rain-atrium-hero.webp\n 5. a meter row of the fixture canon, where ranked plates, shutters, and registers stage attention across one continuous working field\n SOURCE ID: fixture-instruments-family-meter-row\n CREATIVE SPARK: The meter row wakes as its plates roll over one by one, every register finding its rank while a single saturated signal tracks the decision you have not made yet.\n SYSTEM GRAMMAR:\n - Palette/material: ink-dark ground, unbleached paper field, and one saturated signal color reserved for the active decision in zone 18\n - Type/composition: compact grotesk labels over generous editorial serif, ranked on a strict modular grid of order 18\n - Topology/navigation: move between the whole field and one consequential detail along route 18\n - Controls/state: reveal, compare, and preserve every meaningful authored state in register 18\n - Responsive/motion: recompose the spatial law while retaining orientation across breakpoint 18\n WEB LEVERAGE: CSS grid plate choreography with a keyboard-readable register index and scroll-driven rank reveal\n QUALITY BAR: board https://cards.example/c/fixture-instruments-family-meter-row.webp · hero https://cards.example/c/fixture-instruments-family-meter-row-hero.webp\n 6. a gauge bench of the fixture canon, where ranked plates, shutters, and registers stage attention across one continuous working field\n SOURCE ID: fixture-instruments-family-gauge-bench\n CREATIVE SPARK: The gauge bench wakes as its plates roll over one by one, every register finding its rank while a single saturated signal tracks the decision you have not made yet.\n SYSTEM GRAMMAR:\n - Palette/material: ink-dark ground, unbleached paper field, and one saturated signal color reserved for the active decision in zone 16\n - Type/composition: compact grotesk labels over generous editorial serif, ranked on a strict modular grid of order 16\n - Topology/navigation: move between the whole field and one consequential detail along route 16\n - Controls/state: reveal, compare, and preserve every meaningful authored state in register 16\n - Responsive/motion: recompose the spatial law while retaining orientation across breakpoint 16\n WEB LEVERAGE: CSS grid plate choreography with a keyboard-readable register index and scroll-driven rank reveal\n QUALITY BAR: board https://cards.example/c/fixture-instruments-family-gauge-bench.webp · hero https://cards.example/c/fixture-instruments-family-gauge-bench-hero.webp\nFuse each challenger before judging it: the challenger supplies the form\n and its system grammar, the product supplies every fact, and clarity wins\n conflicts. Weigh the fused result against the assigned direction on exactly\n two axes, audience identification and product clarity. Losing to strong\n grounded material is a valid outcome; beating a thin or tool-monoculture\n list is the point. A fused challenger that wins both axes becomes the build.\n Close the weighing with a verdict per challenger, decided before any\n borrowing is considered: wins (beats the assigned direction on both axes),\n competitive (holds one axis), or declined (loses both). A declined\n challenger is not spent: name the one discipline of its system the assigned\n direction lacks, and raise the assigned direction to match before\n presenting it. A donation transfers ambition and system discipline, never\n the challenger's clothes. A component treatment, such as a button's shadow\n or a display face, is clothes, not discipline; one world owns the page.\n Write each raise as its own named line on the presented direction, and\n carry every verdict, kept line, and raise into the decision page payload.\nWhen you can view images, open the QUALITY BAR board and hero for any\nchallenger you weigh seriously and for the world you build. They exist as a\ncraft bar, the finish level and commitment the build is expected to reach,\nnever as a mockup to copy; your surface serves this product, not that render.\nPRODUCT.md and explicit incumbent brand commitments constrain every direction.\nThe seed never chooses exact colors, fonts, tokens, or a user preference, and\nit never permits the world and first surface to be selected independently.\nThe CREATIVE SPARK is a complete visual system, not a theme or decorative\nreference. Translate every supplied system rule into the product: palette and\nmaterial, type and composition, topology, controls and states, and adaptation.\nKeep the source's visible character, scale, rhythm, and interaction instead of\nreducing vivid grammar to generic nouns. Keep a literal carrier only when it\nbecomes functional.\nAmbitious motion, spatial media, or interaction is welcome when it strengthens\nthe product without weakening semantics, performance, or fallback behavior.\nMODE RULES (persuade, from <REPO>/tests/fixtures/mode-rules-skill/reference/mode-persuade.md). They govern this surface's directions and every comp you write or judge for it, the decision comps included; where shared guidance conflicts, these win.\nDIRECTIONS\n- PERSUADE DIRECTION RULE ONE.\n- PERSUADE DIRECTION RULE TWO.\nCOMPS\n- PERSUADE COMP RULE.\nA user- or brief-pinned decision beats the roll, always.\nASSIGNED INDEX (restated for truncated readers): 6. Build candidate\n6 of your own grounded list; seed key oracle-key-1.\nPRESENTATION (the decision round, condensed from new-work.md; follow it even when your read of that file came back cut):\n- Present this hand on the decision page: write the options payload (`<IMPECCABLE> serve-question --schema` prints its shape), run `<IMPECCABLE> serve-question --start --payload <file>`, and open the URL it prints for the user.\n- With image generation, every card declares a comp under .impeccable/mocks/decision/, canon included, declined challengers excepted. Serve first, then generate each comp in reading order (assigned, pick, full-card hand, canon), writing its prompt sidecar as it lands (a.png gets a.png.json).\n- After the last comp lands (at once when this round generates none), hold `<IMPECCABLE> serve-question --wait --key <key>`. If your shell hands back a session before --wait exits, keep polling that session until it exits; rerun --wait only after it exits 3 with no answer.\n- Build path: none recorded in .impeccable/config.json or .impeccable/config.local.json, so comp-led whenever image generation exists. Then put \"buildPath\": {\"value\": \"comp\", \"toggle\": true} in the payload; without image generation there is no toggle and the build is code-led. Never ask about the build path during the round; only when the ANSWER returns buildPathFlipped: true, offer once afterwards to keep the flipped value as the default.\n- The structured question tool is the fallback, never the first channel: take it when --start exits 2, when --wait exits 4 after the page closed unanswered, or when your harness cannot hold a blocking --wait at all (say so in your first reply). It carries the same options and asks nothing about the build path.\n",+ "stderr": "",+ "exit": 0,+ "signal": null,+ "files": {+ ".impeccable/questions/roll.json": "{\"scope\":\"direction\",\"key\":\"oracle-key-1\",\"reroll\":0,\"at\": <EPOCH>,\"worlds\":[{\"id\":\"fixture-print-family-banner-press\",\"board\":\"https://cards.example/c/fixture-print-family-banner-press.webp\",\"hero\":\"https://cards.example/c/fixture-print-family-banner-press-hero.webp\"},{\"id\":\"fixture-canon-family-card-index\",\"board\":\"https://cards.example/c/fixture-canon-family-card-index.webp\",\"hero\":\"https://cards.example/c/fixture-canon-family-card-index-hero.webp\"},{\"id\":\"fixture-material-family-reed-basin\",\"board\":\"https://cards.example/c/fixture-material-family-reed-basin.webp\",\"hero\":\"https://cards.example/c/fixture-material-family-reed-basin-hero.webp\"},{\"id\":\"fixture-performed-family-rain-atrium\",\"board\":\"https://cards.example/c/fixture-performed-family-rain-atrium.webp\",\"hero\":\"https://cards.example/c/fixture-performed-family-rain-atrium-hero.webp\"},{\"id\":\"fixture-instruments-family-meter-row\",\"board\":\"https://cards.example/c/fixture-instruments-family-meter-row.webp\",\"hero\":\"https://cards.example/c/fixture-instruments-family-meter-row-hero.webp\"},{\"id\":\"fixture-instruments-family-gauge-bench\",\"board\":\"https://cards.example/c/fixture-instruments-family-gauge-bench.webp\",\"hero\":\"https://cards.example/c/fixture-instruments-family-gauge-bench-hero.webp\"}]}"+ }+}