Skip to content

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

JavaScript

Fix small live-mode and launcher bugs from triage (#1036)

Paul Bakaus6e0a1038043c
diff --git a/crates/live/src/instructions.rs b/crates/live/src/instructions.rs
index d1dd1561a..d0a332853 100644
--- a/crates/live/src/instructions.rs
+++ b/crates/live/src/instructions.rs
@@ -106,7 +106,32 @@ pub fn instructions_for_event(event: &Map<String, Value>, self_cmd: &str) -> Opt
.get("_completionAck")
.and_then(|a| a.get("ok"))
== Some(&Value::Bool(true));
- Some(if ack_ok {
+ let result = event.get("_acceptResult");
+ let refused = result.and_then(|r| r.get("handled")) == Some(&Value::Bool(false));
+ // A refused discard always ends with live-complete --discarded,
+ // which records the discard even when the poll's own completion
+ // never landed. It does not check the source, so the agent
+ // confirms the wrapper is gone first.
+ let complete = format!("{} --id {} --discarded", script_cmd(self_cmd, "live-complete"), id);
+ Some(if refused {
+ let err = match result.and_then(|r| r.get("error")) {
+ Some(v) if truthy(Some(v)) => js_str(Some(v)),
+ _ => "unknown error".to_string(),
+ };
+ if err == "source_locked" {
+ format!(
+ "The source file is briefly locked by a publisher. Re-run {} --id {} --discard (idempotent) until it reports handled; do NOT hand-edit the file. Then run {} and poll again.",
+ script_cmd(self_cmd, "live-accept"),
+ id,
+ complete
+ )
+ } else {
+ format!(
+ "Discard did NOT restore the source: {}. If the impeccable-variants wrapper for {} is still in source, replace it with the original element by hand (the VCS diff shows what it replaced). Once no impeccable-variants marker for {} remains in source, run {} and poll again.",
+ err, id, id, complete
+ )
+ }
+ } else if ack_ok {
"Original restored and durable completion acknowledged; nothing to do. Poll again.".to_string()
} else {
format!(
@@ -432,4 +457,34 @@ mod tests {
assert!(lane.contains("live.md section 4"), "{lane}");
assert!(lane.contains("parameter knobs per section 7"), "{lane}");
}
+
+ #[test]
+ fn a_refused_discard_never_claims_the_original_was_restored() {
+ let event = |result: Value| {
+ let mut m = Map::new();
+ m.insert("type".into(), json!("discard"));
+ m.insert("id".into(), json!("ab12cd34"));
+ m.insert("_acceptResult".into(), result);
+ m.insert("_completionAck".into(), json!({ "ok": true, "type": "error" }));
+ m
+ };
+ let refused = instructions_for_event(
+ &event(json!({ "handled": false, "file": "src/App.tsx", "error": "Original not found" })),
+ "impeccable",
+ )
+ .unwrap();
+ assert!(refused.starts_with("Discard did NOT restore the source: Original not found."), "{refused}");
+ assert!(!refused.contains("Original restored"), "{refused}");
+ assert!(refused.contains("impeccable live-complete --id ab12cd34 --discarded"), "{refused}");
+ let locked = instructions_for_event(
+ &event(json!({ "handled": false, "mode": "error", "file": "src/App.tsx", "error": "source_locked" })),
+ "impeccable",
+ )
+ .unwrap();
+ assert!(locked.contains("Re-run impeccable live-accept --id ab12cd34 --discard"), "{locked}");
+ assert!(locked.contains("do NOT hand-edit"), "{locked}");
+ assert!(locked.contains("impeccable live-complete --id ab12cd34 --discarded"), "{locked}");
+ let restored = instructions_for_event(&event(json!({ "handled": true, "file": "src/App.tsx" })), "impeccable").unwrap();
+ assert!(restored.starts_with("Original restored"), "{restored}");
+ }
}
diff --git a/crates/live/src/live_accept.rs b/crates/live/src/live_accept.rs
index d6a0e6012..77c3cc587 100644
--- a/crates/live/src/live_accept.rs
+++ b/crates/live/src/live_accept.rs
@@ -658,9 +658,10 @@ fn handle_discard_unlocked(id: &str, lines: &[String], target_file: &str) -> Res
let Some(block) = find_marker_block(id, lines) else {
return Err("Markers not found".to_string());
};
- let original = extract_original(lines, &block);
let is_jsx = is_jsx_file(target_file);
let (rs, re) = expand_replace_range(&block, lines, is_jsx, id);
+ let original = original_or_refuse(id, lines, &block, rs, re)
+ .ok_or_else(|| format!("{} Source not modified; replace the wrapper with the original element by hand.", ORIGINAL_MISSING))?;
let indent = leading_ws(&lines[rs]);
let restored = deindent_content(&original, &indent);
let mut new_lines: Vec<String> = Vec::new();
@@ -808,7 +809,10 @@ fn handle_accept_unlocked(
let Some(variant_content) = extract_variant(lines, &block, variant_num) else {
return Err(format!("Variant {} not found", variant_num));
};
- let original_content = extract_original(lines, &block);
+ // Accept writes the chosen variant, not the original; the original only
+ // tells the manual-edit buffer which edits the accept replaced. A wrapper
+ // without the slot therefore accepts normally (only discard needs it).
+ let original_content = extract_original(lines, &block).unwrap_or_default();
let css_content = extract_css(lines, &block, id);
let variant_text = variant_content.join("\n");
let has_helper_attrs = variant_text.contains("data-impeccable-variant");
@@ -1131,13 +1135,60 @@ fn trim_surrounding_blank_lines(lines: Vec<String>) -> Vec<String> {
lines[start..end].to_vec()
}
-/// JS: extractOriginal(lines, block)
-fn extract_original(lines: &[String], block: &MarkerBlock) -> Vec<String> {
+/// JS: extractOriginal(lines, block), with the missing slot kept apart from
+/// an empty one: `None` when the block has no `data-impeccable-variant="original"`
+/// element at all.
+fn extract_original(lines: &[String], block: &MarkerBlock) -> Option<Vec<String>> {
let text = strip_style_and_join(lines, block);
- match extract_inner_by_attr(&text, "data-impeccable-variant=\"original\"") {
- None => Vec::new(),
- Some(inner) => trim_surrounding_blank_lines(inner.split('\n').map(String::from).collect()),
+ extract_inner_by_attr(&text, "data-impeccable-variant=\"original\"")
+ .map(|inner| trim_surrounding_blank_lines(inner.split('\n').map(String::from).collect()))
+}
+
+const ORIGINAL_MISSING: &str = "Original not found: the variants wrapper has no data-impeccable-variant=\"original\" slot, so the element it replaced cannot be restored from it.";
+
+static INSERT_MODE_RE: Lazy<Regex> = Lazy::new(|| {
+ Regex::new(&format!(r#"data-impeccable-mode{ws}*={ws}*(?:"insert"|'insert')"#, ws = WS)).unwrap()
+});
+
+/// The original slot's content for discard, or `None` (refuse, write nothing)
+/// when a wrapper that replaced an element has none (#875): restoring "nothing" there
+/// deletes the element while reporting success. An insert wrapper
+/// (`data-impeccable-mode="insert"`) replaced nothing and legitimately has no
+/// slot, so it restores to nothing.
+fn original_or_refuse(
+ id: &str,
+ lines: &[String],
+ block: &MarkerBlock,
+ rs: usize,
+ re: usize,
+) -> Option<Vec<String>> {
+ if let Some(original) = extract_original(lines, block) {
+ return Some(original);
}
+ // Only this session's own wrapper tag counts, read whole even when a
+ // formatter split its attributes over several lines: a nested insert, or
+ // CSS that names the attribute, must not exempt a replace wrapper.
+ let end = re.min(lines.len().saturating_sub(1));
+ let text = lines[rs..=end].join("\n");
+ wrapper_open_tag(&text, id)
+ .is_some_and(|tag| INSERT_MODE_RE.is_match(tag))
+ .then(Vec::new)
+}
+
+/// The whole opening tag that carries `data-impeccable-variants="<id>"`,
+/// from its `<` to its `>`, across line breaks.
+fn wrapper_open_tag<'a>(text: &'a str, id: &str) -> Option<&'a str> {
+ let e = regex::escape(id);
+ let re = Regex::new(&format!(
+ r#"data-impeccable-variants{ws}*={ws}*(?:"{id}"|'{id}'|\{{["']{id}["']\}})"#,
+ ws = WS,
+ id = e
+ ))
+ .ok()?;
+ let m = re.find(text)?;
+ let start = text[..m.start()].rfind('<')?;
+ let end = m.end() + text[m.end()..].find('>')?;
+ Some(&text[start..=end])
}
/// JS: extractVariant(lines, block, variantNum)
@@ -1330,6 +1381,147 @@ mod discard_tests {
}
}
+#[cfg(test)]
+mod original_slot_tests {
+ use super::*;
+
+ fn scratch(name: &str, src: &[&str]) -> (std::path::PathBuf, String, Vec<String>) {
+ let nanos = std::time::SystemTime::now()
+ .duration_since(std::time::UNIX_EPOCH)
+ .map(|d| d.as_nanos())
+ .unwrap_or(0);
+ let dir = std::env::temp_dir().join(format!(
+ "impeccable-original-slot-{}-{nanos}",
+ std::process::id()
+ ));
+ std::fs::create_dir_all(&dir).unwrap();
+ let file = dir.join(name);
+ let lines: Vec<String> = src.iter().map(|s| s.to_string()).collect();
+ std::fs::write(&file, lines.join("\n")).unwrap();
+ let path = file.to_string_lossy().into_owned();
+ (dir, path, lines)
+ }
+
+ // The hand-written fallback scaffold live.md used to show: no original slot.
+ const NO_ORIGINAL: &[&str] = &[
+ "<main>",
+ " <!-- impeccable-variants-start ab12cd34 -->",
+ " <div data-impeccable-variants=\"ab12cd34\" data-impeccable-variant-count=\"1\" style=\"display: contents\">",
+ " <div data-impeccable-variant=\"1\">",
+ " <h1 class=\"hero\">Bolder</h1>",
+ " </div>",
+ " </div>",
+ " <!-- impeccable-variants-end ab12cd34 -->",
+ "</main>",
+ ];
+
+ #[test]
+ fn discard_without_an_original_slot_refuses_and_writes_nothing() {
+ let (dir, path, lines) = scratch("index.html", NO_ORIGINAL);
+ let err = handle_discard_unlocked("ab12cd34", &lines, &path).unwrap_err();
+ let out = std::fs::read_to_string(&path).unwrap();
+ let _ = std::fs::remove_dir_all(&dir);
+ assert!(err.starts_with("Original not found"), "{err}");
+ assert!(err.contains("Source not modified"), "{err}");
+ assert_eq!(out, NO_ORIGINAL.join("\n"), "the wrapper stays exactly as it was");
+ }
+
+ #[test]
+ fn accept_without_an_original_slot_still_accepts_the_variant() {
+ let (dir, path, lines) = scratch("index.html", NO_ORIGINAL);
+ let result = handle_accept_unlocked("ab12cd34", "1", &lines, &path, None, None);
+ let out = std::fs::read_to_string(&path).unwrap();
+ let _ = std::fs::remove_dir_all(&dir);
+ assert!(result.is_ok(), "{:?}", result.err());
+ assert!(out.contains("<h1 class=\"hero\">Bolder</h1>"), "{out}");
+ assert!(!out.contains("impeccable-variants-start"), "{out}");
+ }
+
+ #[test]
+ fn an_empty_original_slot_still_restores_to_empty() {
+ let src = [
+ "<main>",
+ " <!-- impeccable-variants-start ab12cd34 -->",
+ " <div data-impeccable-variants=\"ab12cd34\" data-impeccable-variant-count=\"1\" style=\"display: contents\">",
+ " <div data-impeccable-variant=\"original\"></div>",
+ " <div data-impeccable-variant=\"1\"><p>New</p></div>",
+ " </div>",
+ " <!-- impeccable-variants-end ab12cd34 -->",
+ "</main>",
+ ];
+ let (dir, path, lines) = scratch("index.html", &src);
+ handle_discard_unlocked("ab12cd34", &lines, &path).unwrap();
+ let out = std::fs::read_to_string(&path).unwrap();
+ let _ = std::fs::remove_dir_all(&dir);
+ assert!(!out.contains("impeccable-variants"), "{out}");
+ }
+
+ #[test]
+ fn only_the_session_wrapper_tag_can_mark_an_insert() {
+ // A nested insert session and CSS naming the attribute both sit inside
+ // this replace wrapper; neither may exempt it from the refusal.
+ let src = [
+ "<main>",
+ " <!-- impeccable-variants-start ab12cd34 -->",
+ " <div data-impeccable-variants=\"ab12cd34\" data-impeccable-variant-count=\"1\" style=\"display: contents\">",
+ " <style data-impeccable-css=\"ab12cd34\">[data-impeccable-mode=\"insert\"] { outline: 0; }</style>",
+ " <div data-impeccable-variant=\"1\">",
+ " <div data-impeccable-variants=\"ef56ab78\" data-impeccable-mode=\"insert\" data-impeccable-variant-count=\"1\"></div>",
+ " </div>",
+ " </div>",
+ " <!-- impeccable-variants-end ab12cd34 -->",
+ "</main>",
+ ];
+ let (dir, path, lines) = scratch("index.html", &src);
+ let err = handle_discard_unlocked("ab12cd34", &lines, &path).unwrap_err();
+ let out = std::fs::read_to_string(&path).unwrap();
+ let _ = std::fs::remove_dir_all(&dir);
+ assert!(err.starts_with("Original not found"), "{err}");
+ assert_eq!(out, src.join("\n"));
+ }
+
+ #[test]
+ fn an_insert_wrapper_split_over_lines_still_discards() {
+ let src = [
+ "<main>",
+ " <!-- impeccable-variants-start ab12cd34 -->",
+ " <div",
+ " data-impeccable-variants=\"ab12cd34\"",
+ " data-impeccable-mode=\"insert\"",
+ " data-impeccable-variant-count=\"1\"",
+ " style=\"display: contents\"",
+ " >",
+ " <div data-impeccable-variant=\"1\"><p>New</p></div>",
+ " </div>",
+ " <!-- impeccable-variants-end ab12cd34 -->",
+ "</main>",
+ ];
+ let (dir, path, lines) = scratch("index.html", &src);
+ handle_discard_unlocked("ab12cd34", &lines, &path).unwrap();
+ let out = std::fs::read_to_string(&path).unwrap();
+ let _ = std::fs::remove_dir_all(&dir);
+ assert_eq!(out, "<main>\n</main>");
+ }
+
+ #[test]
+ fn an_insert_wrapper_has_no_original_and_discards_to_nothing() {
+ let src = [
+ "<main>",
+ " <!-- impeccable-variants-start ab12cd34 -->",
+ " <div data-impeccable-variants=\"ab12cd34\" data-impeccable-mode=\"insert\" data-impeccable-variant-count=\"1\" style=\"display: contents\">",
+ " <div data-impeccable-variant=\"1\"><p>New</p></div>",
+ " </div>",
+ " <!-- impeccable-variants-end ab12cd34 -->",
+ "</main>",
+ ];
+ let (dir, path, lines) = scratch("index.html", &src);
+ handle_discard_unlocked("ab12cd34", &lines, &path).unwrap();
+ let out = std::fs::read_to_string(&path).unwrap();
+ let _ = std::fs::remove_dir_all(&dir);
+ assert_eq!(out, "<main>\n</main>");
+ }
+}
+
#[cfg(test)]
mod carbonize_tests {
use super::*;
diff --git a/crates/live/src/live_server.rs b/crates/live/src/live_server.rs
index 3aa3afc67..bca4cd7dd 100644
--- a/crates/live/src/live_server.rs
+++ b/crates/live/src/live_server.rs
@@ -458,7 +458,11 @@ fn stop(argv: &[String], cwd: &str, io: &mut Io) -> i32 {
Some(port) => println(io, &format!("Stopped live server on port {}.", port)),
None => println(io, "No running live server found."),
}
- if !keep_inject {
+ // No live config means nothing was ever injected (inject reads its target
+ // files from that config), so there is no tag to remove and nothing to
+ // report (#951).
+ let injectable = std::path::Path::new(&crate::paths::resolve_live_config_path(cwd, &env)).exists();
+ if !keep_inject && injectable {
// JS: execFileSync(node, [live-inject.mjs, '--remove'], { cwd })
// with the child's stderr inherited.
let (mut child_io, captured) = Io::captured("", std::path::PathBuf::from(cwd), env.clone());
diff --git a/crates/skills/src/bundle.rs b/crates/skills/src/bundle.rs
index 83c6ff810..8ace5eebb 100644
--- a/crates/skills/src/bundle.rs
+++ b/crates/skills/src/bundle.rs
@@ -304,7 +304,7 @@ fn download_remote_bundle(
keys: Result<TrustedKeys, String>,
) -> Result<String, String> {
keys.and_then(|keys| download_and_extract_signed_bundle(sys, fetch, &keys))
- .map_err(|e| format!("{}{e}. Nothing was installed; retry or update the CLI. If this persists, report it at https://github.com/pbakaus/impeccable/issues/479", bundle_signature::ERROR_PREFIX))
+ .map_err(|e| format!("{}{e}. Nothing was installed; retry or update the CLI. If this persists, report it at https://github.com/pbakaus/impeccable/issues/new", bundle_signature::ERROR_PREFIX))
}
fn download_and_extract_signed_bundle(
diff --git a/docs/CLI-CONTRACT.md b/docs/CLI-CONTRACT.md
index cc2f1766b..ec5a38f3f 100644
--- a/docs/CLI-CONTRACT.md
+++ b/docs/CLI-CONTRACT.md
@@ -1764,7 +1764,7 @@ Order in `live-accept.mjs`: receipt check → find `impeccable-variants-start <i
**Svelte-component accept** (under source lock `accept:<id>` on the route file, wait 1000 ms): read `v<N>.svelte` (`{handled:false, error:'Variant N not found', …}`), split script/markup/style; insert manifests → `inlineSvelteComponentInsertAccept` (empty → `Accepted Svelte insert variant is empty`; `data-impeccable-*` attrs → `Accepted Svelte insert variant contains preview-only data-impeccable attributes`; splice markup at `insertLine` reindented, bake+merge CSS). Replace: merge original root's attributes onto variant root (class union, missing attrs appended); restore props→expressions via AST (contract v2) or textual swap (v1); replace source lines `[sourceStartLine, sourceEndLine]` with reindented markup; collect pre-existing unused selectors (compiler warnings `css_unused_selector`); read `params.json[variant]`; sanitize any `data-impeccable-variant`/`@scope`/`:scope` selectors (defensive); `bakeParamValues` (see below); `mergeCssIntoSvelteSource` (reconcile into last `<style>` block, or create one); remove seeded selectors not re-declared and not used by markup outside the replaced region (`superseded`); `pruneUnusedSelectors` (up to 3 compiler passes); postcondition: any pre-accept selector missing that wasn't pruned/superseded → `{handled:false, mode:'error', error:'CSS reconciliation would lose selectors from the existing style block: … . Source not modified; accept the variant manually.'}`; write; remove session dir; `verifyAcceptedSource`. Result `{handled:true, css:{replaced, appended, pruned:[], superseded:[]}, verify:{clean, findings}, file, sourceFile, previewMode:'svelte-component', componentDir, carbonize:false}`. Discard: remove component dir → `{handled:true, file, carbonize:false, previewMode, componentDir}`.
-**HTML/JSX accept**: generated file → `{handled:false, mode:'fallback', file, hint:'Session is in a generated file. Persist the accepted variant in source; do not rely on this script.'}` exit 0. Legacy `data-impeccable-preview="source-shadow"` → `{handled:false, error:'source_shadow_preview_deprecated', hint}`. Under lock: locate marker block (`Markers not found`), for JSX expand replace range to the outer wrapper `<div>` … matching `</div>` (multi-line-aware depth tracking, `<style>` bodies stripped for matching); extract chosen variant inner (`Variant N not found`), original inner, CSS (`<style data-impeccable-css="ID">` body; JSX template-literal `{\`…\`}` wrap stripped; self-closing → none). `needsCarbonize = !!css || variantText.includes('data-impeccable-variant')`. Replacement (indent = wrapper line's indent):
+**HTML/JSX accept**: generated file → `{handled:false, mode:'fallback', file, hint:'Session is in a generated file. Persist the accepted variant in source; do not rely on this script.'}` exit 0. Legacy `data-impeccable-preview="source-shadow"` → `{handled:false, error:'source_shadow_preview_deprecated', hint}`. Under lock: locate marker block (`Markers not found`), for JSX expand replace range to the outer wrapper `<div>` … matching `</div>` (multi-line-aware depth tracking, `<style>` bodies stripped for matching); extract chosen variant inner (`Variant N not found`), original inner (a wrapper with no `data-impeccable-variant="original"` element whose own opening tag, the one carrying `data-impeccable-variants="<id>"` (read whole, across line breaks), does not say `data-impeccable-mode="insert"` refuses discard with `Original not found: the variants wrapper has no data-impeccable-variant="original" slot, so the element it replaced cannot be restored from it. Source not modified; replace the wrapper with the original element by hand.` and writes nothing; accept still writes the chosen variant, since it needs no original; an insert wrapper restores to nothing; an empty slot restores to an empty line), CSS (`<style data-impeccable-css="ID">` body; JSX template-literal `{\`…\`}` wrap stripped; self-closing → none). `needsCarbonize = !!css || variantText.includes('data-impeccable-variant')`. Replacement (indent = wrapper line's indent):
- no CSS: just deindented variant lines.
- HTML with CSS:
```
@@ -1780,7 +1780,7 @@ Order in `live-accept.mjs`: receipt check → find `impeccable-variants-start <i
```
- Astro (`.astro`): as HTML, except the style tag is the file type's own `styleTag`, `<style is:inline data-impeccable-css="ID">`. The variants block it replaces is `is:inline` too, so accept and the cleanup never add or remove a style block that Astro compiles. A bare `<style>` here would become a `?astro&type=style&index=N` module ahead of the page's own, and deleting it again makes Astro's dev server answer the reload of the vanished index with a 500 (Astro 7.3.6+) or serve another block's CSS under the surviving index (earlier versions).
- JSX: everything above wrapped in `<indent><div data-impeccable-carbonize="ID" style={{ display: "contents" }}>` … `</div>` with body indented 2 more, `<style …>{\`` / `\`}</style>`, `{/* … */}` comments, `style={{ display: 'contents' }}` on the variant div.
-Result `{handled:true, file: rel, carbonize:boolean, todo?:'REQUIRED before next poll: carbonize cleanup in <file>. See reference/live.md "Required after accept".', bakeSkipped?}`. Discard: replace range with deindented original → `{handled:true, file, carbonize:false}`.
+Result `{handled:true, file: rel, carbonize:boolean, todo?:'REQUIRED before next poll: carbonize cleanup in <file>. See reference/live.md "Required after accept".', bakeSkipped?}`. Discard: replace range with deindented original → `{handled:true, file, carbonize:false}`; refused → `{handled:false, file, carbonize:false, error}`.
**Mechanical bake** (`bake.rs`): only on `--bake` (never by default and never on `--no-bake`; the generate lane's accept carbonizes exactly like plain live's, so the agent integrates the accepted variant per live.md), a knob-free HTML/JSX accept is made permanent instead of leaving the carbonize block. Refused (falls back to the carbonize block, with `bakeSkipped:<reason>`) when: `--param-values` is non-empty; the accepted variant carries `data-impeccable-*` or `data-p-*` inside it; the preview CSS uses `var(--p-*)`, `data-p-*`, or `data-impeccable-params`; the variant's root is a component (`<PricingGrid>`, `<Card.Root>`: what it renders is unknown, and its `className` or `id` prop may never reach that element) or has neither an id nor a static class (`className={expr}`); the anchor cannot be shown to match the accepted element alone (the journaled generate event's `element.anchor` must be the same selector, the id or the tag and class set, and its `element.anchorMatches` must be 1: `<anchor> matches N elements on the page; a lasting rule on it would restyle them all`, a different anchor, and a missing descriptor or count each name themselves); a `:scope` cannot be rewritten (sibling combinators, `:scope` not at the front, nested `@scope`); the accepted variant declares no rule; or no destination stylesheet exists. The rewrite: the accepted `@scope ([data-impeccable-variant="N"])` block is flattened and every selector re-anchored on the root tag's selector (`#id`, else `tag.class.class`): `:scope > .x` → `<anchor>` merged with `.x` (the wrapper's only child is the element itself, so the child compound rides on the anchor, a class the anchor already has once, a type only when it is the anchor's own; `#id` anchors take any type), `:scope .x` → `<anchor> .x`, `:scope:hover > .x` → `<anchor>.x:hover`, bare `:scope` → `<anchor>`; Astro's `[data-impeccable-variant="N"] > .x` prefix the same way; nested `@media`/`@supports` inside the block keep their prelude; top-level `@keyframes`/`@font-face` are kept, other variants' blocks dropped. Destination: for `.jsx`/`.tsx` the `.css` file under the app root (skipping node_modules/.git/.impeccable/dist/build/coverage/framework caches, depth ≤ 6, `.min.css` and generated or git-ignored files excluded) with the most rules naming the anchor's id or classes, else the only `.css` file; for other files the page's own last `<style>` block when it has one, else the same search. The rules are **appended** under `/* impeccable generate <id>: accepted variant N */` (existing rules are never rewritten; a same-selector rule later in the cascade overrides declaration by declaration). The source is verified clean (`verifyAcceptedSource`) before anything is written; the stylesheet is written first, then the source with the variant unwrapped at the wrapper's indentation. Result `{handled:true, file, carbonize:false, baked:true, variant:'N', css:{file: rel|null (null = the page's own <style>), rules, anchor}, verify:{clean, findings}}`; the poll's completion for it is `complete`, so the session ends without `live-complete`. After accept with `--page-url`, buffered manual-edit ops whose original/new text appears as an exact text segment in the replaced original block are dropped from `pending-manual-edits.json`.
@@ -1837,7 +1837,7 @@ Conventions: every script's "run directly" guard is `process.argv[1]` ending wit
#### `live-server.mjs` -> `impeccable live-server`
- Invoked from live.md Cleanup (`node {{scripts_path}}/live-server.mjs stop`), by `live.mjs` (`--background`), by tests directly.
-- Args: (none) foreground; `--background` (spawn detached child with same args minus flag, wait ≤10 s for a `server.json` whose pid ≠ own, print `{"pid","port","token"}` exit 0; else stderr `Timed out waiting for live server to start.` exit 1); `--port=N`; `stop [--keep-inject]` (fetch `/stop?token=` → stdout `Stopped live server on port P.` or `No running live server found.`; then unless keep-inject run `live-inject.mjs --remove`, print `Removed live script tag from <file>.` when a result line has `removed:true`, else `Note: could not remove live script tag (<first line>)`; exit 0); `--help`.
+- Args: (none) foreground; `--background` (spawn detached child with same args minus flag, wait ≤10 s for a `server.json` whose pid ≠ own, print `{"pid","port","token"}` exit 0; else stderr `Timed out waiting for live server to start.` exit 1); `--port=N`; `stop [--keep-inject]` (fetch `/stop?token=` → stdout `Stopped live server on port P.` or `No running live server found.`; then unless keep-inject, and only when the live config exists (no config means nothing was injected, so stop says nothing about the tag), run `live-inject.mjs --remove`, print `Removed live script tag from <file>.` when a result line has `removed:true`, else `Note: could not remove live script tag (<first line>)`; exit 0); `--help`.
- Env: `IMPECCABLE_LIVE_DEBUG_EVENTS`, `IMPECCABLE_LIVE_COPY_AGENT*`, `IMPECCABLE_LIVE_APPLY_EVENT_{HARD_TIMEOUT,SOFT_DEADLINE}_MS`, `IMPECCABLE_LIVE_MANUAL_EDIT_CHUNK_SIZE`, `IMPECCABLE_LIVE_MANUAL_EDIT_REPAIR_ATTEMPTS`.
- Behavior: shared model sections 3, 5, 6, 8, 10. Console lines: `[live] lease failed for <id>: <msg>`, `[impeccable] Svelte component session cleanup failed: …`, `[impeccable] applied legacy deferred Svelte component accepts: {…}`.
- Tests: `tests/live-server.test.mjs` (integration: /health, /status, events, poll, gitignore), `tests/live-poll-stream.test.mjs`, `tests/live-e2e.test.mjs`, `tests/live-event-validation.test.mjs`, `tests/live-poll-lanes.test.mjs`, `tests/live-session-store.test.mjs`, `tests/live-generation-preflight.test.mjs`.
@@ -1849,7 +1849,7 @@ Conventions: every script's "run directly" guard is `process.argv[1]` ending wit
- One-shot: loops `GET /poll?token&timeout=<slice ≤270000>&leaseMs=600000[&types]` until an event or total deadline; prints one JSON line (`console.log(JSON.stringify(event))`) with `_instructions` added by `instructionsForEvent` (unless already present). For `accept`/`discard`: spawns `node live-accept.mjs --id ID (--discard | --variant N) [--page-url U] [--param-values JSON]` (30 s), sets `event._acceptResult` (parse failure/throw → `{handled:false, mode:'error', error}`), then POSTs completion `{id, type: completionType, sourceEventType: event.type, message: _acceptResult.error, file: _acceptResult.file, data: {carbonize:true}?}` where completionType = discard: `discarded` if handled else `error`; accept: `agent_done` if handled&carbonize, `complete` if handled, `error` if mode error or (svelte-component unhandled), else `agent_done`; sets `event._completionAck = {ok:true, type}` (+ `final:false, requiresComplete:true, nextCommand:'live-complete.mjs --id <id>', message:'Carbonize cleanup must be verified, then the session must be completed explicitly before polling again.'` for carbonize) or `{ok:false, error}`. Stderr banners: manual_edit_apply → 4-line banner starting `Manual Apply action required: edit source, then reply with \`live-poll.mjs --reply <id> done --data '<json>'\`.`; carbonize → `⚠ Carbonize cleanup REQUIRED before next poll. After cleanup, run live-complete.mjs --id <id>. See reference/live.md "Required after accept".`
- Stream: stderr `[impeccable-poll] stream mode: one JSON object per line on stdout; use --reply while this process stays running`; after each reply-needing event waits (poll `/status` every 400 ms) until the id leaves `pendingEvents` (else `Timed out waiting for --reply on event <id>` exit 1); returns on `exit`.
- Errors: 401 → `Authentication failed. The server token may have changed.` + `Try restarting: node "…/live-server.mjs" stop && node "…/live.mjs"` exit 1; ECONNREFUSED → `Live server not running. Start one with: …` exit 1; reply non-2xx → `Reply failed: <error>\n<reason>\n<hint>\n<failures file:line msg…>\n<_instructions>` exit 1; other → `Poll failed: <msg>` exit 1.
-- `_instructions` templates (instructions.mjs; `<S>` = abs scripts dir): `steer` → `Do what the message asks (page edits, navigation help, or a short answer). Then reply exactly once: node <S>/live-poll.mjs --reply <id> steer_done ["optional short toast"] (on failure: --reply <id> error "Short reason"). No pickup ack; poll again immediately after.`; `prefetch`, `variant_mount_failed` (`The browser could NOT render variant N (module: URL): ERR… reply node <S>/live-poll.mjs --reply <id> done --file <manifest or source path>; the browser retries on its own. Poll again after the reply.`), `discard` (`Original restored and durable completion acknowledged; nothing to do. Poll again.` or `Completion was not acknowledged: run node <S>/live-complete.mjs --id <id> --discarded, then poll again.`), `manual_edit_apply` (delegate to `impeccable_manual_edit_applier`; reply `--reply <id> done --data '{"status":"done","appliedEntryIds":[...],"failed":[],"files":[...],"notes":[]}'`), `timeout` (`No event arrived; poll again immediately.`), `exit` (`Session over: kill any background poll, then node <S>/live-server.mjs stop (removes the injected script tag). Sweep leftover impeccable-variants-start / impeccable-carbonize-start markers from source.`), `generate` (numbered steps: screenshot / scaffold branch (svelte-component: edit stubs `<dir>/v1.svelte…`, params in `params.json`, reply `--file <manifest>`; deferred wrapper: splice into `scaffold.wrapperBlock` and replace lines `replaceStartLine-replaceEndLine` in ONE edit; written wrapper: splice at `insertLine`; no scaffold: run `live-wrap.mjs --id … --count … --element-id "…" --classes "a,b" --tag "…" --text "<first ~80 chars>"`) / action reference / `When all N variants are delivered: node <S>/live-poll.mjs --reply <id> done --file <project-root-relative path you wrote>. Then poll again. If generation fails … reply --reply <id> error "Short reason" …`), `accept` (carbonize 5-step text; `Accept was merged into source mechanically; nothing to clean up. Poll again.`; fallback; `source_locked` retry; `accept_receipt_conflict`; generic error; manual merge). Prefix when ack failed: `Completion was NOT acknowledged: run node <S>/live-status.mjs, finish any cleanup, then node <S>/live-complete.mjs --id <id>. `
+- `_instructions` templates (instructions.mjs; `<S>` = abs scripts dir): `steer` → `Do what the message asks (page edits, navigation help, or a short answer). Then reply exactly once: node <S>/live-poll.mjs --reply <id> steer_done ["optional short toast"] (on failure: --reply <id> error "Short reason"). No pickup ack; poll again immediately after.`; `prefetch`, `variant_mount_failed` (`The browser could NOT render variant N (module: URL): ERR… reply node <S>/live-poll.mjs --reply <id> done --file <manifest or source path>; the browser retries on its own. Poll again after the reply.`), `discard` (`_acceptResult.handled === false` with `source_locked` → `The source file is briefly locked by a publisher. Re-run node <S>/live-accept.mjs --id <id> --discard (idempotent) until it reports handled; do NOT hand-edit the file. Then run node <S>/live-complete.mjs --id <id> --discarded and poll again.`; any other refusal → `Discard did NOT restore the source: <error>. If the impeccable-variants wrapper for <id> is still in source, replace it with the original element by hand (the VCS diff shows what it replaced). Once no impeccable-variants marker for <id> remains in source, run node <S>/live-complete.mjs --id <id> --discarded and poll again.`; else `Original restored and durable completion acknowledged; nothing to do. Poll again.` or `Completion was not acknowledged: run node <S>/live-complete.mjs --id <id> --discarded, then poll again.`), `manual_edit_apply` (delegate to `impeccable_manual_edit_applier`; reply `--reply <id> done --data '{"status":"done","appliedEntryIds":[...],"failed":[],"files":[...],"notes":[]}'`), `timeout` (`No event arrived; poll again immediately.`), `exit` (`Session over: kill any background poll, then node <S>/live-server.mjs stop (removes the injected script tag). Sweep leftover impeccable-variants-start / impeccable-carbonize-start markers from source.`), `generate` (numbered steps: screenshot / scaffold branch (svelte-component: edit stubs `<dir>/v1.svelte…`, params in `params.json`, reply `--file <manifest>`; deferred wrapper: splice into `scaffold.wrapperBlock` and replace lines `replaceStartLine-replaceEndLine` in ONE edit; written wrapper: splice at `insertLine`; no scaffold: run `live-wrap.mjs --id … --count … --element-id "…" --classes "a,b" --tag "…" --text "<first ~80 chars>"`) / action reference / `When all N variants are delivered: node <S>/live-poll.mjs --reply <id> done --file <project-root-relative path you wrote>. Then poll again. If generation fails … reply --reply <id> error "Short reason" …`), `accept` (carbonize 5-step text; `Accept was merged into source mechanically; nothing to clean up. Poll again.`; fallback; `source_locked` retry; `accept_receipt_conflict`; generic error; manual merge). Prefix when ack failed: `Completion was NOT acknowledged: run node <S>/live-status.mjs, finish any cleanup, then node <S>/live-complete.mjs --id <id>. `
- Tests: `tests/live-poll.test.mjs`, `tests/live-poll-stream.test.mjs`, `tests/live-completion.test.mjs`, `tests/live-recovery-commands.test.mjs`.
#### `live-status.mjs` -> `impeccable status`
diff --git a/skill/reference/live.md b/skill/reference/live.md
index 5823d3407..d8611acf3 100644
--- a/skill/reference/live.md
+++ b/skill/reference/live.md
@@ -260,7 +260,7 @@ If wrap or generation fails after the browser flipped to GENERATING, tell the **
When wrap returns `fallback: "agent-driven"`, you pick the source file yourself; the goal is unchanged: three preview variants now, and the accepted one persisted where the next build cannot wipe it.
1. **Find where the element really lives** from the error payload: `element_not_in_source` + `generatedMatch` means the served HTML is generated, so find the generator's template or partial; `element_not_found` means runtime-injected, so find the rendering component or data source; `file_is_generated` resolves the same way. A purely visual change may belong in a shared stylesheet rather than a template.
-2. **Preview in the served file**: manually write the same wrapper scaffold `impeccable live-wrap` produces (`<!-- impeccable-variants-start ID --><div data-impeccable-variants="ID" data-impeccable-variant-count="3" style="display: contents">…</div><!-- end -->`) into the file the browser actually loaded, insert your variant divs, `--reply EVENT_ID done --file <served file>`. This edit is temporary; a regen wiping it is fine.
+2. **Preview in the served file**: manually write the same wrapper scaffold `impeccable live-wrap` produces into the file the browser actually loaded, moving the element itself into the original slot: `<!-- impeccable-variants-start ID --><div data-impeccable-variants="ID" data-impeccable-variant-count="3" style="display: contents"><div data-impeccable-variant="original">THE ELEMENT, UNCHANGED</div><!-- Variants: insert below this line --></div><!-- impeccable-variants-end ID -->`. Insert your variant divs after the marker, then `--reply EVENT_ID done --file <served file>`. Never drop the original slot: discard restores the element from it and refuses a wrapper without one. This edit is temporary; a regen wiping it is fine.
3. **On accept, write to true source** (accept refuses generated files, so `_acceptResult.handled` is usually `false` here): structural change → template/component source; visual-only → the right stylesheet; content rendered from data → the data source or render logic. Then remove the temporary wrapper from the served file.
4. **On discard**, just remove the temporary wrapper.
diff --git a/skill/scripts/impeccable.cmd b/skill/scripts/impeccable.cmd
index dc0fd33e5..789a96f4c 100644
--- a/skill/scripts/impeccable.cmd
+++ b/skill/scripts/impeccable.cmd
@@ -74,20 +74,37 @@ if exist "%IMPECCABLE_HOME%\bin\%version%\" goto cache_ready
mkdir "%IMPECCABLE_HOME%\bin\%version%" >nul 2>nul
if errorlevel 1 goto cache_directory_failed
:cache_ready
-rem Check the staging file too: an existing directory may be read-only.
+rem Stage the download in a directory only this run owns, as the sh launcher
+rem does with .impeccable.part.$$: concurrent first runs (parallel hooks, two
+rem agents) must never write, hash or move each other's files. mkdir fails
+rem when the name exists, so it claims the name atomically. RANDOM alone is
+rem not enough because cmd seeds it from the clock in whole seconds; the
+rem timestamp and the retry on collision keep same-second runs apart. A cache
+rem directory that refuses every mkdir is reported as unwritable.
+set "attempt=0"
+:claim_staging
+set /a attempt+=1
+if %attempt% GTR 20 goto cache_write_failed
+set "stamp=%TIME: =0%"
+set "stamp=%stamp::=%"
+set "stamp=%stamp:.=%"
+set "stamp=%stamp:,=%"
+set "staging=%IMPECCABLE_HOME%\bin\%version%\.impeccable.part.%stamp%-%RANDOM%%RANDOM%"
+mkdir "%staging%" >nul 2>nul
+if errorlevel 1 goto claim_staging
+set "part=%staging%\impeccable.exe"
+set "sidecar=%staging%\impeccable.sha256"
rem Redirection failures do not reliably update ERRORLEVEL in cmd.exe;
-rem branch on the command's failure directly. Never treat a directory as a
-rem staging file (later del cleanup would prompt to delete its contents).
-if exist "%cached%.part\" goto cache_write_failed
-(type nul >"%cached%.part") 2>nul || goto cache_write_failed
+rem branch on the command's failure directly.
+(type nul >"%part%") 2>nul || goto staging_write_failed
set "asset=impeccable-windows-%arch%.exe"
set "url=%IMPECCABLE_DOWNLOAD_BASE%/engine-v%version%/%asset%"
-curl.exe -fsSL -o "%cached%.part" "%url%" >nul 2>nul
+curl.exe -fsSL -o "%part%" "%url%" >nul 2>nul
if not errorlevel 1 goto verify
if not "%arch%"=="arm64" goto download_failed
set "asset=impeccable-windows-x64.exe"
set "url=%IMPECCABLE_DOWNLOAD_BASE%/engine-v%version%/%asset%"
-curl.exe -fsSL -o "%cached%.part" "%url%" >nul 2>nul
+curl.exe -fsSL -o "%part%" "%url%" >nul 2>nul
if errorlevel 1 goto download_failed
:verify
@@ -97,61 +114,67 @@ rem Mirrors the sh launcher and fails closed: a freshly downloaded binary
rem runs only after verifying against its .sha256 sidecar. A sidecar that
rem cannot be fetched, or an empty certutil result, refuses the download
rem instead of running an unverified binary.
-curl.exe -fsSL -o "%cached%.sha256" "%url%.sha256" >nul 2>nul
+curl.exe -fsSL -o "%sidecar%" "%url%.sha256" >nul 2>nul
if errorlevel 1 goto verify_refuse
set "expected="
-set /p expected=<"%cached%.sha256"
+set /p expected=<"%sidecar%"
for /f "tokens=1" %%h in ("%expected%") do set "expected=%%h"
call :check_download
if errorlevel 1 exit /b 127
set "actual="
rem Reuse the sidecar staging file after reading expected. Check certutil's
rem status before parsing: its error text on stdout is not a digest.
-certutil -hashfile "%cached%.part" SHA256 >"%cached%.sha256" 2>nul
+certutil -hashfile "%part%" SHA256 >"%sidecar%" 2>nul
if errorlevel 1 goto verify_refuse
call :check_download
if errorlevel 1 exit /b 127
-for /f "usebackq skip=1 delims=" %%h in ("%cached%.sha256") do if not defined actual set "actual=%%h"
-del "%cached%.sha256" >nul 2>nul
+for /f "usebackq skip=1 delims=" %%h in ("%sidecar%") do if not defined actual set "actual=%%h"
+del "%sidecar%" >nul 2>nul
if not defined expected goto verify_refuse
if not defined actual goto verify_refuse
set "actual=%actual: =%"
if /I "%actual%"=="%expected%" goto place
-del "%cached%.part" >nul 2>nul
+call :discard_staging
echo impeccable: checksum mismatch downloading %url% 1>&2
exit /b 127
:verify_refuse
call :check_download
if errorlevel 1 exit /b 127
-del "%cached%.part" >nul 2>nul
-del "%cached%.sha256" >nul 2>nul
+call :discard_staging
echo impeccable: cannot verify %url% against %url%.sha256; refusing the unverified download 1>&2
exit /b 127
:check_download
set "download_file=%~1"
-if not defined download_file set "download_file=%cached%.part"
+if not defined download_file set "download_file=%part%"
if not exist "%download_file%" goto download_missing
for %%f in ("%download_file%") do if %%~zf==0 goto download_empty
exit /b 0
:download_missing
-del "%cached%.sha256" >nul 2>nul
+call :discard_staging
echo impeccable: download completed but the file was removed before execution: %url%; check your antivirus quarantine or logs. Refusing to continue; do not disable protection. 1>&2
exit /b 127
:download_empty
del "%download_file%" >nul 2>nul
-del "%cached%.sha256" >nul 2>nul
+call :discard_staging
echo impeccable: downloaded file is empty: %url%; refusing the unverified download 1>&2
exit /b 127
+:discard_staging
+rem Removes this run's staging directory and whatever is left in it. Never
+rem touches another run's staging directory or the cached binary.
+if defined staging rd /s /q "%staging%" >nul 2>nul
+exit /b 0
+
:place
call :check_download
if errorlevel 1 exit /b 127
-move /y "%cached%.part" "%cached%" >nul 2>nul
+move /y "%part%" "%cached%" >nul 2>nul
if errorlevel 1 goto place_failed
+call :discard_staging
call :check_download "%cached%"
if errorlevel 1 exit /b 127
set "run=%cached%"
@@ -160,7 +183,7 @@ goto run
:place_failed
call :check_download
if errorlevel 1 exit /b 127
-del "%cached%.part" >nul 2>nul
+call :discard_staging
echo impeccable: could not cache the verified download: %url% 1>&2
exit /b 127
@@ -189,6 +212,9 @@ exit /b 0
echo impeccable: engine %version% is not installed; cannot create cache directory: "%IMPECCABLE_HOME%\bin\%version%" 1>&2
goto setup_failed
+:staging_write_failed
+call :discard_staging
+
:cache_write_failed
echo impeccable: engine %version% is not installed; cannot write to cache directory: "%IMPECCABLE_HOME%\bin\%version%" 1>&2
goto setup_failed
@@ -198,7 +224,7 @@ echo impeccable: cannot download engine %version%; curl.exe is unavailable. 1>&2
goto setup_failed
:download_failed
-del "%cached%.part" >nul 2>nul
+call :discard_staging
echo impeccable: could not download engine %version% from %url%; check network access and the release URL. 1>&2
:setup_failed
@@ -208,7 +234,6 @@ echo Alternatively, set IMPECCABLE_HOME to a writable cache location, or IMPECCA
exit /b 127
:fail
-del "%cached%.part" >nul 2>nul
echo impeccable: no engine binary found (looked in %bin%, %cached%, PATH). 1>&2
echo Download impeccable-windows-%arch%.exe from https://github.com/pbakaus/impeccable/releases (tag engine-v%version%) and save it as %cached%, or set IMPECCABLE_BIN to a preinstalled engine binary. Docs: https://impeccable.style 1>&2
exit /b 127
diff --git a/skill/scripts/live-browser.js b/skill/scripts/live-browser.js
index c7eed77fb..f706898e4 100644
--- a/skill/scripts/live-browser.js
+++ b/skill/scripts/live-browser.js
@@ -7120,6 +7120,10 @@
//
function startScrollTracking() {
+ // Idempotent: callers overlap (showBar starts tracking, then the agent
+ // pick path starts it again), and a second loop would never be cancelled
+ // because scrollRaf only remembers the latest one (#1002).
+ stopScrollTracking();
function tick() {
if (state === 'CONFIGURING' || state === 'GENERATING' || state === 'CYCLING') {
if (isInsertGeneratingSession()) ensureInsertPlaceholder();
diff --git a/tests/launcher-download.test.mjs b/tests/launcher-download.test.mjs
index 0f0621f4f..dd023ee9c 100644
--- a/tests/launcher-download.test.mjs
+++ b/tests/launcher-download.test.mjs
@@ -16,6 +16,15 @@ const COMSPEC = process.env.ComSpec || process.env.COMSPEC || 'C:\\Windows\\Syst
const PAYLOAD = WINDOWS ? fs.readFileSync(COMSPEC) : Buffer.from('#!/bin/sh\necho verified-engine\n');
const HASH = createHash('sha256').update(PAYLOAD).digest('hex');
+// The run's in-flight download: a .impeccable.part.<id> file (sh) or the
+// impeccable.exe inside a .impeccable.part.<id> directory (cmd).
+function stagedDownload(cacheDir) {
+ const name = fs.readdirSync(cacheDir).find(file => file.startsWith('.impeccable.part.') && file !== '.impeccable.part.1');
+ assert.ok(name, 'a staging entry exists while the download is in flight');
+ const staged = path.join(cacheDir, name);
+ return fs.statSync(staged).isDirectory() ? path.join(staged, 'impeccable.exe') : staged;
+}
+
async function exercise(t, scenario) {
const root = fs.mkdtempSync(path.join(os.tmpdir(), 'impeccable-launcher-'));
t.after(() => fs.rmSync(root, { recursive: true, force: true }));
@@ -35,15 +44,16 @@ async function exercise(t, scenario) {
fs.mkdirSync(cache);
fs.writeFileSync(path.join(cache, 'bin'), 'blocked');
}
- if (scenario === 'cache-write-failure') {
- fs.mkdirSync(cacheDir, { recursive: true });
- if (WINDOWS) fs.mkdirSync(path.join(cacheDir, 'impeccable.exe.part'));
- }
- if (scenario === 'cache-readonly-file') {
+ if (scenario === 'cache-write-failure') fs.mkdirSync(cacheDir, { recursive: true });
+ if (scenario === 'stale-staging') {
+ // Leftovers from an older launcher (fixed staging names) or a killed run
+ // must not block or be reused by a new download.
fs.mkdirSync(cacheDir, { recursive: true });
- const staging = path.join(cacheDir, 'impeccable.exe.part');
- fs.writeFileSync(staging, 'read-only');
- fs.chmodSync(staging, 0o444);
+ for (const name of ['impeccable.exe.part', 'impeccable.exe.sha256', '.impeccable.part.1']) {
+ const stale = path.join(cacheDir, name);
+ fs.writeFileSync(stale, 'stale');
+ fs.chmodSync(stale, 0o444);
+ }
}
const tools = path.join(root, 'tools');
fs.mkdirSync(tools);
@@ -63,6 +73,14 @@ async function exercise(t, scenario) {
const after = scenario === 'removed-after-move' ? 'rm -f "$3"\n' : scenario === 'emptied-after-move' ? ': > "$3"\n' : '';
fs.writeFileSync(path.join(tools, 'mv'), scenario === 'move-failure' ? '#!/bin/sh\nexit 1\n' : `#!/bin/sh\n${before}/bin/mv "$@" || exit $?\n${after}`, { mode: 0o755 });
}
+ if (WINDOWS && scenario === 'cache-write-failure') {
+ // The cmd launcher claims a fresh staging directory per run, so no
+ // pre-created path can collide with it; fail the claim itself instead.
+ const claim = 'mkdir "%staging%" >nul 2>nul';
+ const source = fs.readFileSync(launcher, 'utf8');
+ assert.equal(source.split(claim).length, 2, 'instrument exactly one claim');
+ fs.writeFileSync(launcher, source.replace(claim, 'cmd /c exit 1'));
+ }
if (WINDOWS && (placementScenarios.includes(scenario) || ['hash-failure', 'removed-during-hash'].includes(scenario))) {
// move is a cmd builtin and certutil is an .exe: PATH shims cannot
// intercept them. Instrument ONLY the external-operation boundary in the
@@ -71,22 +89,22 @@ async function exercise(t, scenario) {
const fault = path.join(tools, 'fault.cmd');
const hashFault = ['hash-failure', 'removed-during-hash'].includes(scenario);
const operation = hashFault
- ? 'certutil -hashfile "%cached%.part" SHA256 >"%cached%.sha256" 2>nul'
- : 'move /y "%cached%.part" "%cached%" >nul 2>nul';
+ ? 'certutil -hashfile "%part%" SHA256 >"%sidecar%" 2>nul'
+ : 'move /y "%part%" "%cached%" >nul 2>nul';
let script;
if (hashFault) {
- script = `@echo off\n${scenario === 'removed-during-hash' ? 'del "%cached%.part" >nul 2>nul\n' : ''}echo hash header\necho ${HASH}\nexit /b 1\n`;
+ script = `@echo off\n${scenario === 'removed-during-hash' ? 'del "%part%" >nul 2>nul\n' : ''}echo hash header\necho ${HASH}\nexit /b 1\n`;
} else if (scenario === 'move-failure') {
script = '@echo off\nexit /b 1\n';
} else {
- const before = scenario === 'removed-before-move' ? 'del "%cached%.part" >nul 2>nul\n' : '';
+ const before = scenario === 'removed-before-move' ? 'del "%part%" >nul 2>nul\n' : '';
const after = scenario === 'removed-after-move' ? 'del "%cached%" >nul 2>nul\n' : scenario === 'emptied-after-move' ? 'type nul >"%cached%"\n' : '';
script = `@echo off\n${before}${operation}\nif errorlevel 1 exit /b 1\n${after}exit /b 0\n`;
}
fs.writeFileSync(fault, script.replaceAll('\n', '\r\n'));
const source = fs.readFileSync(launcher, 'utf8');
assert.equal(source.split(operation).length, 2, 'instrument exactly one operation');
- const replacement = `call "${fault}"${hashFault ? ' >"%cached%.sha256" 2>nul' : ''}`;
+ const replacement = `call "${fault}"${hashFault ? ' >"%sidecar%" 2>nul' : ''}`;
fs.writeFileSync(launcher, source.replace(operation, replacement));
}
const requests = [];
@@ -97,9 +115,9 @@ async function exercise(t, scenario) {
return;
}
if (req.url.endsWith('.sha256')) {
- const part = fs.readdirSync(cacheDir).find(file => file.includes('.part'));
- if (scenario === 'removed') fs.unlinkSync(path.join(cacheDir, part));
- if (scenario === 'emptied') fs.truncateSync(path.join(cacheDir, part));
+ const part = stagedDownload(cacheDir);
+ if (scenario === 'removed') fs.unlinkSync(part);
+ if (scenario === 'emptied') fs.truncateSync(part);
res.writeHead(scenario === 'no-sidecar' ? 404 : 200);
res.end(scenario === 'empty-sidecar' ? '' : `${scenario === 'mismatch' ? '0'.repeat(64) : HASH} engine\n`);
} else {
@@ -145,7 +163,7 @@ async function exercise(t, scenario) {
return { ...result, files: fs.existsSync(cacheDir) ? fs.readdirSync(cacheDir) : [], requests, cacheDir };
}
-for (const scenario of ['cache-directory-failure', 'cache-write-failure', 'download-failure', 'transport-failure', ...(WINDOWS ? ['cache-readonly-file'] : [])]) {
+for (const scenario of ['cache-directory-failure', 'cache-write-failure', 'download-failure', 'transport-failure']) {
test(`launcher explains ${scenario} and how to retry setup`, async t => {
const result = await exercise(t, scenario);
assert.equal(result.status, 127, JSON.stringify(result));
@@ -174,6 +192,23 @@ test('launcher downloads and runs a verified executable', async t => {
assert.equal(result.requests.length, 2);
});
+test('launcher ignores stale staging files from older or killed runs', async t => {
+ const result = await exercise(t, 'stale-staging');
+ assert.equal(result.status, 0, result.stderr);
+ assert.match(result.stdout, /verified-engine/);
+ assert.deepEqual(result.files.sort(),
+ ['.impeccable.part.1', WINDOWS ? 'impeccable.exe' : 'impeccable', 'impeccable.exe.part', 'impeccable.exe.sha256'].sort(),
+ 'the new download lands and leaves the leftovers untouched');
+});
+
+test('cmd launcher stages each run under its own name', () => {
+ // Concurrent first runs used to share %cached%.part and %cached%.sha256 (#1002).
+ const source = fs.readFileSync(path.join(ROOT, 'skill/scripts/impeccable.cmd'), 'utf8');
+ assert.doesNotMatch(source, /%cached%\.(part|sha256)/);
+ assert.match(source, /set "staging=[^"\n]*%RANDOM%/);
+ assert.match(source, /mkdir "%staging%" >nul 2>nul\r?\nif errorlevel 1 goto claim_staging/);
+});
+
test('cmd launcher forwards engine exit code through cmd /c', { skip: WINDOWS ? false : 'Windows-only cmd /c exit-code forwarding' }, async t => {
const root = fs.mkdtempSync(path.join(os.tmpdir(), 'impeccable-launcher-exit-'));
t.after(() => fs.rmSync(root, { recursive: true, force: true }));
diff --git a/tests/live-browser-source.test.mjs b/tests/live-browser-source.test.mjs
index 546301a55..bd9a174ef 100644
--- a/tests/live-browser-source.test.mjs
+++ b/tests/live-browser-source.test.mjs
@@ -1045,6 +1045,27 @@ describe('live-browser source contracts', () => {
);
});
+ it('runs at most one scroll-tracking loop however often tracking starts (#1002)', () => {
+ const start = SOURCE.match(/function startScrollTracking\(\) \{[\s\S]*?\n \}/)?.[0];
+ const stop = SOURCE.match(/function stopScrollTracking\(\) \{[\s\S]*?\n \}/)?.[0];
+ assert.ok(start && stop);
+ const pending = new Map();
+ let next = 0;
+ const context = {
+ scrollRaf: null, state: 'IDLE', annotActive: false, shaderState: null,
+ requestAnimationFrame: (fn) => { pending.set(++next, fn); return next; },
+ cancelAnimationFrame: (id) => { pending.delete(id); },
+ };
+ runInNewContext(`${stop}\n${start}\nstartScrollTracking();\nstartScrollTracking();`, context);
+ assert.equal(pending.size, 1, 'the second start replaces the first loop');
+ const [[, tick]] = pending;
+ pending.clear();
+ tick();
+ assert.equal(pending.size, 1, 'the surviving loop keeps itself scheduled');
+ runInNewContext(`${stop}\nstopScrollTracking();`, context);
+ assert.equal(pending.size, 0, 'stop cancels the only loop');
+ });
+
it('never DOMParser-injects JSX source (#454)', () => {
const isJsxStart = SOURCE.indexOf('function isJsxSourceFile(');
const isJsxEnd = SOURCE.indexOf('function sourceHasSessionWrapper(', isJsxStart);
diff --git a/tests/oracle/DELTAS.md b/tests/oracle/DELTAS.md
index 783b7bc84..973d43d80 100644
--- a/tests/oracle/DELTAS.md
+++ b/tests/oracle/DELTAS.md
@@ -7074,3 +7074,9 @@ The binary printed a hard-coded npm package version that stayed `4.0.0` after 4.
Product decision (maintainer, issue #1015). `AUTONOMY_DIRECTIVE_CHECK` told the agent to probe with the structured question tool or the decision page and gave no way out for an agent that has neither, such as a subagent running a brief. It now names that case as a reason to infer from the brief, and says a subagent states the substitution in its report. `INCUMBENT_WORLD_UNDOCUMENTED` sent any new-surface or redesign request to all of `reference/new-work.md`; it now states the extend rule inline for an in-world change to an existing surface and names `new-work.md` only for shape, a whole new surface, or a redesign that replaces the world.
Re-recorded from the binary and reviewed by hand, 55 goldens. A script check confirmed every changed line in them equals the old line with those two directive sentences substituted, and nothing else moved: the `AUTONOMY_DIRECTIVE_CHECK` line changes in every case that prints it (57 lines across the 55 goldens), and the `INCUMBENT_WORLD_UNDOCUMENTED` line in the ten cases with code and no DESIGN.md.
+
+## Recorded 2026-10-15: discard refuses a wrapper without its original slot; stop is quiet without a live config (#875, #951)
+
+A variants wrapper with no `data-impeccable-variant="original"` element (the hand-written fallback scaffold `live.md` used to show) made discard restore nothing: the element was deleted and the result said `handled: true`. `live-accept --discard` now refuses such a wrapper with `Original not found: ...` and writes nothing, while `--variant N` still accepts it: accept writes the chosen variant and uses the original only to prune buffered manual edits; an insert wrapper (`data-impeccable-mode="insert"`) has no slot by design and still discards to nothing. New cases, recorded from the binary and reviewed by hand: `live-accept-html-no-original-discard` (handled false, `index.html` byte-identical to the staged wrapper, no receipt), `live-accept-html-no-original-accept` (handled, variant 1 carbonized into `index.html`) and `live-accept-html-insert-discard` (live-insert, then discard: the page is back to the fixture, receipt written). No existing accept golden moved.
+
+`live-server stop` ran `live-inject --remove` even with no live config, which echoed `config_missing` and then `Note: could not remove live script tag (...)` though nothing had been injected. With no config it now skips the removal and says nothing about the tag. Re-recorded `live-server-stop-no-config`: stderr goes from those two lines to empty; stdout and exit are unchanged.
diff --git a/tests/oracle/cases/live-accept.mjs b/tests/oracle/cases/live-accept.mjs
index eeeafde00..ac01988fb 100644
--- a/tests/oracle/cases/live-accept.mjs
+++ b/tests/oracle/cases/live-accept.mjs
@@ -45,6 +45,25 @@ export default [
fs.writeFileSync(p, fs.readFileSync(p, 'utf8').replace(/ {8}<style data-impeccable-css="ab12cd34">[\s\S]*?<\/style>\n/, ''));
},
}),
+ // --- A hand-written wrapper without the original slot (#875): discard
+ // refuses and leaves the source untouched instead of deleting the element;
+ // accept needs no original and writes the variant. An insert wrapper has no slot by design and still discards. ---
+ ...['--discard', '--variant'].map(mode => A(`live-accept-html-no-original-${mode === '--discard' ? 'discard' : 'accept'}`, 'live-html',
+ ['--id', ID, ...(mode === '--discard' ? [mode] : [mode, '1'])], {
+ snap: ['index.html'],
+ setup: (ws) => {
+ stageWrappedHtml(ws);
+ const p = path.join(ws, 'index.html');
+ fs.writeFileSync(p, fs.readFileSync(p, 'utf8').replace(/ *<!-- Original -->\n *<div data-impeccable-variant="original">\n.*\n *<\/div>\n/, ''));
+ },
+ })),
+ {
+ id: 'live-accept-html-insert-discard', workspace: 'live-html', files: [...F, 'index.html'],
+ steps: [
+ { verb: 'live-insert', args: ['--id', ID, '--position', 'after', '--element-id', 'features'] },
+ { verb: 'live-accept', args: ['--id', ID, '--discard'] },
+ ],
+ },
// --- Astro: the carbonize style block keeps `is:inline`, so accept never
// adds a compiled style module that the cleanup then removes ---
A('live-accept-astro-variant-2-steps', 'live-astro', ['--id', ID, '--variant', '2', '--param-values', '{"face":"serif"}'], { snap: ['src/**'], setup: stageWrappedAstro }),
diff --git a/tests/oracle/golden/live-accept-html-insert-discard.json b/tests/oracle/golden/live-accept-html-insert-discard.json
new file mode 100644
index 000000000..a267c3493
--- /dev/null
+++ b/tests/oracle/golden/live-accept-html-insert-discard.json
@@ -0,0 +1,21 @@
+{
+ "steps": [
+ {
+ "stdout": "{\"mode\":\"insert\",\"position\":\"after\",\"file\":\"index.html\",\"insertLine\":22,\"commentSyntax\":{\"open\":\"<!--\",\"close\":\"-->\"},\"styleMode\":\"scoped\",\"styleTag\":\"<style data-impeccable-css=\\\"SESSION_ID\\\">\",\"cssSelectorPrefixExamples\":[],\"cssAuthoring\":{\"mode\":\"scoped\",\"styleTag\":\"<style data-impeccable-css=\\\"SESSION_ID\\\">\",\"strategy\":\"scope-rule\",\"rulePattern\":\"@scope ([data-impeccable-variant=\\\"N\\\"]) { :scope > .variant-class { ... } }\",\"selectorExamples\":[\"@scope ([data-impeccable-variant=\\\"1\\\"]) { :scope > .variant-class { ... } }\",\"@scope ([data-impeccable-variant=\\\"2\\\"]) { :scope > .variant-class { ... } }\",\"@scope ([data-impeccable-variant=\\\"3\\\"]) { :scope > .variant-class { ... } }\"],\"requirements\":[\"Use @scope blocks keyed to each [data-impeccable-variant=\\\"N\\\"] wrapper.\",\"Inside each @scope block, make :scope rules step into the replacement element with a descendant combinator.\",\"Use the styleTag exactly; do not add framework-specific style attributes unless this object says to.\"],\"forbidden\":[\"Do not use global [data-impeccable-variant=\\\"N\\\"] selector prefixes for this styleMode.\",\"Do not add is:inline to the style tag for this styleMode.\"]}}\n",
+ "stderr": "",
+ "exit": 0,
+ "signal": null
+ },
+ {
+ "stdout": "{\"handled\":true,\"file\":\"index.html\",\"carbonize\":false}\n",
+ "stderr": "",
+ "exit": 0,
+ "signal": null
+ }
+ ],
+ "files": {
+ ".impeccable/live/accept-receipts/ab12cd34.json": "{\n \"id\": \"ab12cd34\",\n \"operation\": \"discard\",\n \"variantId\": null,\n \"result\": {\n \"handled\": true,\n \"file\": \"index.html\",\n \"carbonize\": false\n },\n \"completedAt\": \"<ISO>\"\n}\n",
+ ".impeccable/live/config.json": "{\n \"files\": [\"index.html\", \"public/**/*.html\"],\n \"insertBefore\": \"</body>\",\n \"commentSyntax\": \"html\"\n}\n",
+ "index.html": "<!DOCTYPE html>\n<html lang=\"en\">\n <head>\n <meta charset=\"UTF-8\" />\n <title>Oracle Live HTML Fixture</title>\n <style>\n .hero-title { font-size: 2rem; }\n .hero-hook { color: #555; }\n </style>\n </head>\n <body>\n <main class=\"page\">\n <h1 id=\"hero\" class=\"hero-title\">Oracle Fixture</h1>\n <p class=\"hero-hook\">Minimal static page for oracle live-mode goldens.</p>\n <section id=\"features\" class=\"feature-grid\">\n <article class=\"feature-card\">One</article>\n <article class=\"feature-card\">Two</article>\n </section>\n <aside class=\"side-note\">\n <h2 class=\"note-title\">Aside</h2>\n <p>Nested content.</p>\n </aside>\n </main>\n </body>\n</html>\n"
+ }
+}
diff --git a/tests/oracle/golden/live-accept-html-no-original-accept.json b/tests/oracle/golden/live-accept-html-no-original-accept.json
new file mode 100644
index 000000000..c73b41a56
--- /dev/null
+++ b/tests/oracle/golden/live-accept-html-no-original-accept.json
@@ -0,0 +1,11 @@
+{
+ "stdout": "{\"handled\":true,\"file\":\"index.html\",\"carbonize\":true,\"todo\":\"REQUIRED before next poll: carbonize cleanup in index.html. See reference/live.md \\\"Required after accept\\\".\"}\n",
+ "stderr": "",
+ "exit": 0,
+ "signal": null,
+ "files": {
+ ".impeccable/live/accept-receipts/ab12cd34.json": "{\n \"id\": \"ab12cd34\",\n \"operation\": \"accept\",\n \"variantId\": \"1\",\n \"result\": {\n \"handled\": true,\n \"file\": \"index.html\",\n \"carbonize\": true,\n \"todo\": \"REQUIRED before next poll: carbonize cleanup in index.html. See reference/live.md \\\"Required after accept\\\".\"\n },\n \"completedAt\": \"<ISO>\"\n}\n",
+ ".impeccable/live/config.json": "{\n \"files\": [\"index.html\", \"public/**/*.html\"],\n \"insertBefore\": \"</body>\",\n \"commentSyntax\": \"html\"\n}\n",
+ "index.html": "<!DOCTYPE html>\n<html lang=\"en\">\n <head>\n <meta charset=\"UTF-8\" />\n <title>Oracle Live HTML Fixture</title>\n <style>\n .hero-title { font-size: 2rem; }\n .hero-hook { color: #555; }\n </style>\n </head>\n <body>\n <main class=\"page\">\n <!-- impeccable-carbonize-start ab12cd34 -->\n <style data-impeccable-css=\"ab12cd34\">\n @scope ([data-impeccable-variant=\"1\"]) {\n :scope > h1 {\n font-weight: 300;\n color: oklch(var(--p-lightness, 0.5) 0.25 25);\n }\n }\n @scope ([data-impeccable-variant=\"2\"]) {\n :scope > h1 { font-weight: 900; }\n :scope[data-p-face=\"serif\"] > h1 { font-family: ui-serif, serif; }\n :scope[data-p-face=\"mono\"] > h1 { font-family: ui-monospace, monospace; }\n }\n @scope ([data-impeccable-variant=\"3\"]) {\n :scope > h1 { font-weight: 600; text-transform: uppercase; letter-spacing: 0.04em; }\n :scope[data-p-italic] > h1 { font-style: italic; }\n }\n </style>\n <!-- impeccable-carbonize-end ab12cd34 -->\n <div data-impeccable-variant=\"1\" style=\"display: contents\">\n <h1 id=\"hero\" class=\"hero-title\">Oracle Fixture</h1>\n </div>\n <p class=\"hero-hook\">Minimal static page for oracle live-mode goldens.</p>\n <section id=\"features\" class=\"feature-grid\">\n <article class=\"feature-card\">One</article>\n <article class=\"feature-card\">Two</article>\n </section>\n <aside class=\"side-note\">\n <h2 class=\"note-title\">Aside</h2>\n <p>Nested content.</p>\n </aside>\n </main>\n </body>\n</html>\n"
+ }
+}
diff --git a/tests/oracle/golden/live-accept-html-no-original-discard.json b/tests/oracle/golden/live-accept-html-no-original-discard.json
new file mode 100644
index 000000000..56abfdc8f
--- /dev/null
+++ b/tests/oracle/golden/live-accept-html-no-original-discard.json
@@ -0,0 +1,10 @@
+{
+ "stdout": "{\"handled\":false,\"file\":\"index.html\",\"carbonize\":false,\"error\":\"Original not found: the variants wrapper has no data-impeccable-variant=\\\"original\\\" slot, so the element it replaced cannot be restored from it. Source not modified; replace the wrapper with the original element by hand.\"}\n",
+ "stderr": "",
+ "exit": 0,
+ "signal": null,
+ "files": {
+ ".impeccable/live/config.json": "{\n \"files\": [\"index.html\", \"public/**/*.html\"],\n \"insertBefore\": \"</body>\",\n \"commentSyntax\": \"html\"\n}\n",
+ "index.html": "<!DOCTYPE html>\n<html lang=\"en\">\n <head>\n <meta charset=\"UTF-8\" />\n <title>Oracle Live HTML Fixture</title>\n <style>\n .hero-title { font-size: 2rem; }\n .hero-hook { color: #555; }\n </style>\n </head>\n <body>\n <main class=\"page\">\n <!-- impeccable-variants-start ab12cd34 -->\n <div data-impeccable-variants=\"ab12cd34\" data-impeccable-variant-count=\"3\" style=\"display: contents\">\n <!-- Variants: insert below this line -->\n <style data-impeccable-css=\"ab12cd34\">\n @scope ([data-impeccable-variant=\"1\"]) {\n :scope > h1 {\n font-weight: 300;\n color: oklch(var(--p-lightness, 0.5) 0.25 25);\n }\n }\n @scope ([data-impeccable-variant=\"2\"]) {\n :scope > h1 { font-weight: 900; }\n :scope[data-p-face=\"serif\"] > h1 { font-family: ui-serif, serif; }\n :scope[data-p-face=\"mono\"] > h1 { font-family: ui-monospace, monospace; }\n }\n @scope ([data-impeccable-variant=\"3\"]) {\n :scope > h1 { font-weight: 600; text-transform: uppercase; letter-spacing: 0.04em; }\n :scope[data-p-italic] > h1 { font-style: italic; }\n }\n </style>\n <!-- Variant 1 -->\n <div data-impeccable-variant=\"1\" data-impeccable-params='[{\"id\":\"lightness\",\"kind\":\"range\",\"min\":0.3,\"max\":0.7,\"step\":0.05,\"default\":0.5,\"label\":\"Lightness\"}]'>\n <h1 id=\"hero\" class=\"hero-title\">Oracle Fixture</h1>\n </div>\n <!-- Variant 2 -->\n <div data-impeccable-variant=\"2\" style=\"display: none\" data-impeccable-params='[{\"id\":\"face\",\"kind\":\"steps\",\"default\":\"sans\",\"label\":\"Face\",\"options\":[{\"value\":\"sans\",\"label\":\"Sans\"},{\"value\":\"serif\",\"label\":\"Serif\"},{\"value\":\"mono\",\"label\":\"Mono\"}]}]'>\n <h1 id=\"hero\" class=\"hero-title\">Oracle Fixture</h1>\n </div>\n <!-- Variant 3 -->\n <div data-impeccable-variant=\"3\" style=\"display: none\" data-impeccable-params='[{\"id\":\"italic\",\"kind\":\"toggle\",\"default\":false,\"label\":\"Italic\"}]'>\n <h1 id=\"hero\" class=\"hero-title\">Oracle Fixture</h1>\n </div>\n </div>\n <!-- impeccable-variants-end ab12cd34 -->\n <p class=\"hero-hook\">Minimal static page for oracle live-mode goldens.</p>\n <section id=\"features\" class=\"feature-grid\">\n <article class=\"feature-card\">One</article>\n <article class=\"feature-card\">Two</article>\n </section>\n <aside class=\"side-note\">\n <h2 class=\"note-title\">Aside</h2>\n <p>Nested content.</p>\n </aside>\n </main>\n </body>\n</html>\n"
+ }
+}
diff --git a/tests/oracle/golden/live-server-stop-no-config.json b/tests/oracle/golden/live-server-stop-no-config.json
index 600477e6b..d8ee22dbe 100644
--- a/tests/oracle/golden/live-server-stop-no-config.json
+++ b/tests/oracle/golden/live-server-stop-no-config.json
@@ -1,6 +1,6 @@
{
"stdout": "No running live server found.\n",
- "stderr": "{\"ok\":false,\"error\":\"config_missing\",\"path\":\"<WS>/.impeccable/live/config.json\"}\nNote: could not remove live script tag ({\"ok\":false,\"error\":\"config_missing\",\"path\":\"<WS>/.impeccable/live/config.json\"})\n",
+ "stderr": "",
"exit": 0,
"signal": null,
"files": {}