The design language that makes your AI harness better at design.
JavaScript
Sync generated provider output
github-actions[bot]381e159040fc
diff --git a/.agents/skills/impeccable/reference/live.md b/.agents/skills/impeccable/reference/live.mdindex bc1e3e9ea..0a8a17658 100644--- a/.agents/skills/impeccable/reference/live.md+++ b/.agents/skills/impeccable/reference/live.md@@ -12,21 +12,24 @@ Execute in order. No step skipped, no step reordered.1. `live.mjs`: boot. If the request names or implies a file, route, or app inside a monorepo, infer the concrete path and run `node .agents/skills/impeccable/scripts/live.mjs --target <path>` instead; then run the rest of this live session from the returned `projectRoot`.2. Open the app URL that serves `pageFile` (infer from `package.json`, docs, terminal output, or an open tab). Never use `serverPort`; it's the helper, not the app. **Cursor:** `browser_navigate` to that URL before polling; do not skip. **Other harnesses:** use the available browser tool; if the URL is uncertain, ask the user once.-3. Poll loop with the default long timeout (600000 ms). After every event or `--reply`, run `live-poll.mjs` again immediately. Never pass a short `--timeout=`.+3. Poll loop with the default long timeout (600000 ms). Run `live-poll.mjs` again immediately after every event or `--reply`; Codex runs this one-shot poll in the foreground. Never pass a short `--timeout=`.The global bar **Impeccable mark** dims and shows a pulsing amber dot when no agent is long-polling `/poll`. Hover the mark for the hint; restart `live-poll.mjs` to reconnect.-4. On `generate`: read screenshot if present; load the action's reference; plan three distinct directions; write all variants in one edit; `--reply done`; poll again.+4. On `generate`: reuse `event.scaffold` when present; read the screenshot if present; load the action's reference; deliver variants using the delivery policy below; `--reply done`; poll again. Generate in this thread. You already hold the project's tokens, conventions, and file layout; that context is the job, not overhead.5. On `steer`: read the message and `pageUrl`; do the work (page edits, navigation help, or a short reply in the `--reply` message); `--reply steer_done`; poll again. No pickup ack. The Steer bar unlocks when `steer_done` arrives over SSE.-6. On `accept` / `discard`: the poll script runs `live-accept.mjs`, acknowledges the delivered event, and prints `_completionAck`. Plain accepts/discards are terminal immediately; carbonize accepts remain recoverable until you finish cleanup, run `live-complete.mjs --id EVENT_ID`, and only then poll again.+6. On `accept` / `discard`: the poll script runs `live-accept.mjs`, acknowledges the delivered event, and prints `_completionAck`. Plain accepts/discards are terminal immediately. Carbonize accepts remain recoverable until the foreground task runs `live-complete.mjs --id EVENT_ID`; finish that cleanup before polling again.7. If interrupted, run `live-status.mjs` or `live-resume.mjs` before guessing. The durable journal replays unacknowledged work after helper restart.8. On `exit`: run the cleanup at the bottom.Harness policy:-- **Claude Code**: run the poll as a **background task** (no short timeout). The harness notifies you when it completes, so the main conversation stays free. Do not block the shell.+- **Claude Code**: run the poll as a **background task** (no short timeout). The harness notifies you when it completes, so the main conversation stays free while you generate and publish in it. Do not block the shell.- **Cursor**: run **one-shot** poll in a **background terminal** with notify on `"type":"(steer|generate|accept|discard|exit)"`. After each event the poll exits; handle it, `--reply`, then start `live-poll.mjs` again. Do **not** use `--stream` on Cursor: incremental stdout notify is slower in practice than exit-based notify (~5s vs sub-second in testing).-- **Codex**: run the poll in the **foreground** (blocking shell; not a background task, not a subagent). Codex background exec sessions do not reliably surface poll stdout back into the conversation at the moment events arrive, so a "fire-and-forget" background poll will stall live mode.+- **Codex**: run the default one-shot poll in a **yielded foreground exec session**. Do not suffix it with `&`, use `--stream`, or leave Live without an active foreground poll. Handle every event in the main task; after each handler/reply, restart the foreground poll.- **Other harnesses**: one-shot foreground unless you know stdout reliably returns to this session when a shell exits.+Generation delivery policy:+- **Default (Cursor and other harnesses):** keep the established atomic single-edit delivery. Do not switch a harness to progressive until its poll loop is known not to block on the extra publish calls. This avoids trading model latency for extra tool-call latency on harnesses with different streaming behavior.+Chat is overhead. No recap, no tutorial output, no pasting PRODUCT / DESIGN bodies. Spend tokens on tools and edits; on failure, one or two short sentences.## Start@@ -94,14 +97,14 @@ Server restart rule: start `live-server.mjs` again, then poll. Startup requeues**Insert mode** (`event.mode === "insert"`): `{id, mode: "insert", count, pageUrl, insert: { position, anchor }, placeholder: { width, height }, freeformPrompt?, screenshotPath?, comments?, strokes?}`. No `action`. Requires a non-empty `freeformPrompt` **or** annotations. Screenshot is sent only when annotations exist (same rule as replace). Use `placeholder` dimensions as a soft size hint for net-new content.-Speed matters; the user is watching a spinner. Minimize tool calls by using the wrap/insert helper and writing all variants in a single edit.+Speed matters; the user is watching the selected element. Reuse server preflight metadata when available, minimize discovery calls, and follow the harness-specific delivery policy above.### Insert mode branchWhen `event.mode === "insert"`:1. Read the screenshot if `event.screenshotPath` is present (annotations only).-2. Run the insert helper instead of wrap:+2. If `event.scaffold` is present, use it as the insert-helper result and do **not** run the helper again. Otherwise run the insert helper instead of wrap:```bashnode .agents/skills/impeccable/scripts/live-insert.mjs --id EVENT_ID --count EVENT_COUNT --position after \@@ -111,7 +114,7 @@ node .agents/skills/impeccable/scripts/live-insert.mjs --id EVENT_ID --count EVE- `--position` ← `event.insert.position` (`before` | `after`)- Anchor flags ← `event.insert.anchor` (same mapping as wrap: id, classes, tag, text)-The scaffold has **no** `data-impeccable-variant="original"`. Variants are net-new HTML+CSS inserted at `insertLine`. Load `brand.md` or `product.md` (freeform only, no action sub-command). Write all variants in one edit, then `--reply done`.+The scaffold has **no** `data-impeccable-variant="original"`. Variants are net-new HTML+CSS inserted at `insertLine`. Load `brand.md` or `product.md` (freeform only, no action sub-command). Deliver using the harness policy, then `--reply done`.For Svelte/SvelteKit targets, `live-insert.mjs` returns `previewMode: "svelte-component"` with `mode: "insert"`, `file` pointing at a temporary `node_modules/.impeccable-live/<id>/manifest.json`, `componentDir` pointing at the variant component files, and `sourceFile` pointing at the real `.svelte` route. Write each inserted variant as a real Svelte component (`v1.svelte`, `v2.svelte`, …) under `componentDir`. Insert variants must be non-empty net-new content with a single top-level root, no `data-impeccable-*` attributes, and CSS in each component's `<style>` block. Do **not** edit the route source during generation; the browser mounts the temporary component before/after the live anchor while the user cycles variants. On Accept, `live-accept.mjs` inserts the selected component markup into `sourceFile` immediately and deletes the temp session after the source write succeeds.@@ -136,6 +139,8 @@ Reading annotations precisely:### 2. Wrap the element+When `event.scaffold` is present, the local helper already found and wrapped the source before the poll returned. Treat `event.scaffold` as the successful helper output and skip this command entirely. `event.scaffoldAttempted` with `scaffoldError` means local preflight could not finish; use the command/fallback path below. This optimization removes a deterministic tool round trip without changing the generated design.+```bashnode .agents/skills/impeccable/scripts/live-wrap.mjs --id EVENT_ID --count EVENT_COUNT --element-id "ELEMENT_ID" --classes "class1,class2" --tag "div" --text "TEXT_SNIPPET"```@@ -155,7 +160,7 @@ Output on success: `{ file, insertLine, commentSyntax, styleMode, styleTag, cssSFor Svelte/SvelteKit targets, `live-wrap.mjs` returns `previewMode: "svelte-component"` with `file` pointing at a temporary `node_modules/.impeccable-live/<id>/manifest.json`, `componentDir` pointing at the variant component files, and `sourceFile` pointing at the real `.svelte` route. Write each variant as a real Svelte component (`v1.svelte`, `v2.svelte`, …) under `componentDir`; use the `propContract` prop names for dynamic text (`{propName}`), not literal snapshot strings. Put variant CSS in each component's `<style>` block with semantic class selectors (no `@scope`, no `data-impeccable-*`). Reply with `--file` set to the manifest path; the browser dynamically imports and mounts the compiled components so Svelte HMR does not reset page state while the user cycles variants. On Accept, `live-accept.mjs` inlines the accepted component back into `sourceFile` immediately after source promotion succeeds.-**Params on the Svelte component path go in a sidecar, never as an attribute.** Svelte parses `{` inside an attribute value as the start of an expression, so a `data-impeccable-params='[{…}]'` attribute on a component element fails to compile (`Expected token }`). Declare params for this path in `componentDir/params.json`, keyed by variant number, using the exact param schema from section 7:+**Params on component-preview paths go in a sidecar, never as an attribute.** Svelte parses `{` inside an attribute value as the start of an expression, and both Svelte/Vue previews mount without an HTML variant wrapper. Declare params in `componentDir/params.json`, keyed by variant number, using the exact param schema from section 7:```json{@@ -293,11 +298,13 @@ In **departure mode**, the prompt narrows the lanes you draw from, not the familWhen the prompt and PRODUCT.md anti-references conflict (the prompt asks for X, the anti-references ban X), the anti-references win; they describe the brand's standing position, the prompt is one moment.-### 6. Write all variants in a single edit+### 6. Deliver variantsComplete HTML replacement of the original element for each variant, not a CSS-only patch. Consider the element's context (computed styles, parent structure, CSS variables from `event.element`).-Write CSS + all variants in ONE edit at the `insertLine` reported by `wrap`. Colocate CSS as a `<style>` tag inside the variant wrapper; `<style>` works anywhere in modern browsers and this ensures CSS and HTML arrive atomically (no FOUC).+Colocate preview CSS as a `<style>` tag inside the variant wrapper; `<style>` works anywhere in modern browsers and keeps each delivered state internally complete (no FOUC).++**Atomic default:** write CSS + all variants + parameter manifests in one edit at `insertLine`, preserving the established behavior.Use the `cssAuthoring` object returned by `live-wrap.mjs` to author the temporary preview CSS. The style opening tag shown below is the common case; replace it with `cssAuthoring.styleTag` when the tool returns a different one. The variant markup shape is otherwise stable:@@ -321,7 +328,7 @@ Use the `cssAuthoring` object returned by `live-wrap.mjs` to author the temporarThe first variant has no `display: none` (visible by default). All others do. If variants use only inline styles and no preview CSS, omit the `<style>` tag entirely.-One edit, all variants; the browser's MutationObserver picks everything up in one pass.+The browser's MutationObserver accepts either delivery shape. On the transactional progressive path it shows arrived variants and pending dots immediately; Accept and Discard are available as soon as one variant exists. Accepting an arrived variant fences the worker before the browser releases the picker, so later publications are rejected.For `styleMode: "scoped"`, author every `:scope` rule with a descendant combinator. The `@scope` boundary is the **variant wrapper `<div data-impeccable-variant="N">`**, not the element you're designing. A bare `:scope { background: cream; }` styles the wrapper, not the inner replacement, so the cream lands on a `display: contents` shell while the actual element keeps page defaults. Always step in: `:scope > .card`, `:scope > section`, `:scope .hero-title`, etc. The fake test agent's CSS in `tests/live-e2e/agent.mjs` is a faithful template; every scoped rule starts `:scope > ...`.@@ -363,7 +370,7 @@ Each variant can expose **coarse** knobs alongside the full HTML/CSS replacement**Hard cap per variant**: at most **four** parameters so the panel stays legible; rare fifth only if the reference explicitly allows it.-**How to declare.** Put a JSON manifest on the variant wrapper (HTML/JSX path). **On the Svelte `svelte-component` path, do not use this attribute** (Svelte can't compile `{` inside an attribute value). Declare params in `componentDir/params.json` keyed by variant number instead (see the Svelte component paragraph in the wrap section). The param schema below is identical for both paths.+**How to declare.** Put a JSON manifest on the variant wrapper (HTML/JSX path). **On the `svelte-component` path, do not use this attribute.** Declare params in `componentDir/params.json` keyed by variant number instead (see the component-preview paragraphs in the wrap section). The param schema below is identical for every path.```html<div data-impeccable-variant="1" data-impeccable-params='[@@ -464,15 +471,19 @@ Event: `{id, variantId, _acceptResult, _completionAck}`. The poll script already- The accept event includes `pageUrl`; the poll script must forward it to `live-accept.mjs --page-url PAGE_URL` so accept-time cleanup only scrubs staged copy edits for the current page.- `_completionAck.ok !== true`: do not poll yet. Run `live-status.mjs` / `live-resume.mjs`, complete the cleanup manually if needed, then run `live-complete.mjs --id EVENT_ID`.- `_acceptResult.handled: true` and `carbonize: false`: nothing to do. Poll again.-- `_acceptResult.handled: true` and `carbonize: true`: **post-accept cleanup is required before the next poll.** See the "Required after accept (carbonize)" section below. The `event._acceptResult.todo` field, `_completionAck.requiresComplete`, and a stderr banner all point at this required follow-up; none are decorative. After cleanup, run `live-complete.mjs --id EVENT_ID`, then poll again.+- `_acceptResult.handled: true` and `carbonize: true`: post-accept cleanup is required, but it must not stall Codex's control lane. See "Required after accept (carbonize)" below. The `event._acceptResult.todo` field, `_completionAck.requiresComplete`, and stderr banner all point at this required follow-up; none are decorative.- `_acceptResult.handled: false, mode: "fallback"`: the session lived in a generated file and the script refused to persist there. You've already written the accepted variant into true source during Handle fallback Step 3; just clean up the temporary wrapper in the served file if any, and poll again.+- `_acceptResult.handled: false, mode: "error"`: the operation genuinely failed. **Do not hand-edit the file**; the source was not touched and editing it yourself would either double-apply or race whoever holds it.+ - `error: "source_locked"`: a generation publish holds the file. Run the same `live-accept.mjs` command again; it is idempotent and will succeed once the publisher releases. Do not poll past it.+ - `error: "accept_receipt_conflict"`: this session already resolved as `priorOperation` (on `priorVariantId` for an accept), so the request contradicts durable truth. Do not edit. Run `live-status.mjs` and tell the user what the session actually resolved to.+ - anything else: report the error briefly and run `live-status.mjs` before continuing.- `_acceptResult.handled: false` without `mode`: manual cleanup: read file, find markers, edit.### Required after accept (carbonize)When `_acceptResult.carbonize === true`, the accepted variant was stitched into source with helper markers and inline CSS so the browser can render it immediately with no visual gap. That stitch-in is **temporary**. The agent must rewrite it into permanent form before doing anything else. Skipping this leaves dead `@scope` rules for unaccepted variants, a pointless `data-impeccable-variant` wrapper, and `impeccable-carbonize-start/end` comment noise in the source file; all of which accumulate across sessions.-Do these five steps in the current thread, synchronously, before the next poll. Do not poll again until the file is clean.+Do these five steps synchronously before the next poll. The source lock, generation epoch, and expected-source hash remain the final safety gates against a generator finishing concurrently with Accept.1. **Locate the carbonize block** in the source file (`_acceptResult.file`). It's bracketed by `<!-- impeccable-carbonize-start SESSION_ID -->` and `<!-- impeccable-carbonize-end SESSION_ID -->` and contains a `<style data-impeccable-css="SESSION_ID">` element. If the variant declared parameters, an `<!-- impeccable-param-values SESSION_ID: {...} -->` comment sits alongside the style tag with the user's chosen values; read it first; it drives steps 3 and 4 below.2. **Move the CSS rules** into the project's real stylesheet. Which stylesheet depends on the project (e.g. `site/styles/workflow.css` for an Astro project, or the component's co-located CSS file for a Vite/Next project; pick whichever already owns styling for the surrounding element).@@ -480,9 +491,7 @@ Do these five steps in the current thread, synchronously, before the next poll.4. **Unwrap the accepted content.** Delete the inner `<div data-impeccable-variant="N" style="display: contents">` that wraps it. On JSX/TSX, also delete the outer `<div data-impeccable-carbonize="SESSION_ID" style={{ display: 'contents' }}>` wrapper if present (accept adds it so ternary/`return` slots keep a single root). Drop `data-impeccable-params` and any `data-p-*` attributes; those are live-mode plumbing, not source.5. **Delete the inline `<style>` block, the `<!-- impeccable-param-values -->` comment if present, and both `<!-- impeccable-carbonize-start/end -->` markers.** Also drop any `@scope` rules for variants other than the accepted one; those are dead code now.-After the file is clean, run `live-complete.mjs --id SESSION_ID`, verify it reports `phase: "completed"`, then poll again.--A background agent may be used for the rewrite, but the current thread is responsible for verifying the five steps are complete before issuing the next poll. In practice, inline is usually faster and less error-prone.+After the file is clean, the cleanup owner runs `live-complete.mjs --id SESSION_ID` and verifies `phase: "completed"`. Poll again only after that verification.## Handle `discard`diff --git a/.agents/skills/impeccable/scripts/lib/impeccable-paths.mjs b/.agents/skills/impeccable/scripts/lib/impeccable-paths.mjsindex 2ccbe7b74..99956c0f3 100644--- a/.agents/skills/impeccable/scripts/lib/impeccable-paths.mjs+++ b/.agents/skills/impeccable/scripts/lib/impeccable-paths.mjs@@ -104,6 +104,20 @@ export function removeLiveServerInfo(cwd = process.cwd(), options = {}) {}}+/**+ * Session IDs become path segments (journals, snapshots, accept receipts,+ * preview manifests, generated component dirs). They arrive from CLI `--id`+ * arguments and HTTP payloads, so anything containing a separator or `..` must+ * be rejected before it reaches path.join, which would happily escape+ * `.impeccable/live/`. Real IDs are 8 hex chars; the tests use short slugs.+ */+export function safeSessionId(id) {+ if (typeof id !== 'string' || !/^[A-Za-z0-9_-]{1,128}$/.test(id)) {+ throw new Error('invalid session id: ' + id);+ }+ return id;+}+export function getLiveSessionsDir(cwd = process.cwd(), options = {}) {return path.join(getLiveDir(cwd, options), 'sessions');}diff --git a/.agents/skills/impeccable/scripts/live-accept.mjs b/.agents/skills/impeccable/scripts/live-accept.mjsindex 278dfbb2e..453ddea35 100644--- a/.agents/skills/impeccable/scripts/live-accept.mjs+++ b/.agents/skills/impeccable/scripts/live-accept.mjs@@ -16,7 +16,9 @@import fs from 'node:fs';import path from 'node:path';import { isGeneratedFile } from './lib/is-generated.mjs';+import { IMPECCABLE_DIR, getLiveDir, safeSessionId } from './lib/impeccable-paths.mjs';import { readBuffer as readManualEditsBuffer, writeBuffer as writeManualEditsBuffer } from './live/manual-edits-buffer.mjs';+import { withSourceLockSync } from './live/source-lock.mjs';import {applyDeferredSvelteComponentAccepts,findSvelteComponentManifest,@@ -25,6 +27,46 @@ import {} from './live/svelte-component.mjs';const EXTENSIONS = ['.html', '.jsx', '.tsx', '.vue', '.svelte', '.astro'];+const ACCEPT_LOCK_WAIT_MS = 1_000;+// Mirrors VARIANT_ID_PATTERN in live/event-validation.mjs, which gates the same+// value arriving over HTTP.+const VARIANT_NUM_PATTERN = /^[0-9]{1,3}$/;++/**+ * A thrown accept/discard is a real failure, not a manual handoff.+ *+ * live/completion.mjs only classifies a result as `error` when it carries+ * `mode: 'error'`; anything else unhandled falls through to `agent_done` with a+ * successful ack, and reference/live.md then tells the agent to finish the edit+ * by hand. That is right for the documented fallback paths and wrong here: a+ * `source_locked` contention needs a retry (hand-editing races the publisher+ * holding the lock), and a crash needs surfacing, not a hand-applied guess.+ */+function operationFailure(err, extra = {}) {+ return { handled: false, mode: 'error', error: err.message, ...extra };+}++/**+ * Mark an unhandled preview-path result as a real failure.+ *+ * operationFailure only covers results built from a *thrown* error. The accept+ * implementations also return `{handled: false, error}` for their own checks+ * (variant missing, template empty, original text ambiguous), and those arrived+ * without `mode`, so completion.mjs classified them as agent_done and+ * reference/live.md routed the agent to "read file, find markers, edit".+ *+ * That handoff only makes sense for a plain wrapper session, which is the one+ * shape with markers in the user's source to edit. Component and isolated+ * artifact previews keep the source clean until Accept, so there is nothing to+ * hand-edit and an unhandled result is always a failure. `previewMode` is+ * exactly that discriminator: only the preview branches set it.+ */+function markPreviewFailure(result) {+ if (result?.handled === false && !result.mode && result.previewMode) {+ return { ...result, mode: 'error' };+ }+ return result;+}// ---------------------------------------------------------------------------// CLI@@ -63,7 +105,52 @@ Output (JSON):const isDiscard = args.includes('--discard');if (!id) { console.error('Missing --id'); process.exit(1); }+ // `id` becomes a path segment (accept receipts, preview manifests, generated+ // component dirs). Reject separators and traversal here so one check covers+ // every downstream sink.+ try { safeSessionId(id); } catch { console.error('Invalid --id'); process.exit(1); }if (!isDiscard && !variantNum) { console.error('Need --discard or --variant N'); process.exit(1); }+ // `variantNum` is interpolated into a RegExp and into the markup written back+ // to source. The browser and the /events schema both constrain it to digits;+ // enforce the same here, or `--variant '.*'` matches the `original` block+ // first and silently accepts the original while reporting success.+ if (!isDiscard && !VARIANT_NUM_PATTERN.test(variantNum)) {+ console.error('Invalid --variant');+ process.exit(1);+ }++ const requestedOperation = isDiscard ? 'discard' : 'accept';+ const priorReceipt = readAcceptReceipt(process.cwd(), id);+ if (priorReceipt) {+ const sameOperation = priorReceipt.operation === requestedOperation+ && (isDiscard || String(priorReceipt.variantId) === String(variantNum));+ console.log(JSON.stringify(sameOperation+ ? { ...priorReceipt.result, handled: true, alreadyApplied: true }+ : {+ // mode: 'error' is what marks this a real failure rather than a manual+ // handoff. Without it, live/completion.mjs classifies the reply as+ // agent_done and reference/live.md tells the agent to "read file, find+ // markers, edit" by hand — which would apply a second, conflicting+ // accept on top of the one the receipt already recorded.+ handled: false,+ mode: 'error',+ error: 'accept_receipt_conflict',+ priorOperation: priorReceipt.operation,+ priorVariantId: priorReceipt.variantId ?? null,+ }));+ return;+ }+ const emitResult = (rawResult) => {+ const result = markPreviewFailure(rawResult);+ if (result?.handled !== false) {+ writeAcceptReceipt(process.cwd(), id, {+ operation: requestedOperation,+ variantId: isDiscard ? null : String(variantNum),+ result,+ });+ }+ console.log(JSON.stringify(result));+ };let paramValues = null;if (paramValuesRaw) {@@ -82,39 +169,55 @@ Output (JSON):if (svelteComponentManifest) {if (isDiscard) {- removeSvelteComponentSession(id, process.cwd());- console.log(JSON.stringify({- handled: true,+ let result;+ try {+ result = withSourceLockSync(+ path.resolve(process.cwd(), svelteComponentManifest.sourceFile),+ 'discard:' + id,+ () => {+ removeSvelteComponentSession(id, process.cwd());+ return { handled: true };+ },+ { waitMs: ACCEPT_LOCK_WAIT_MS },+ );+ } catch (err) {+ result = operationFailure(err);+ }+ emitResult({+ ...result,file: svelteComponentManifest.sourceFile,carbonize: false,previewMode: 'svelte-component',componentDir: svelteComponentManifest.componentDir,- }));+ });return;}let result;try {- result = inlineSvelteComponentAccept(- svelteComponentManifest,- variantNum,- paramValues,- process.cwd(),+ result = withSourceLockSync(+ path.resolve(process.cwd(), svelteComponentManifest.sourceFile),+ 'accept:' + id,+ () => inlineSvelteComponentAccept(+ svelteComponentManifest,+ variantNum,+ paramValues,+ process.cwd(),+ ),+ { waitMs: ACCEPT_LOCK_WAIT_MS },);} catch (err) {- result = {- handled: false,- error: err.message,+ result = operationFailure(err, {file: svelteComponentManifest.sourceFile,sourceFile: svelteComponentManifest.sourceFile,previewMode: 'svelte-component',componentDir: svelteComponentManifest.componentDir,- };+ });}if (result.carbonize) {result.todo = 'REQUIRED before next poll: carbonize cleanup in ' + result.file + '. See reference/live.md "Required after accept".';}- console.log(JSON.stringify({ handled: result.handled !== false, ...result }));+ emitResult({ handled: result.handled !== false, ...result });return;}@@ -145,10 +248,25 @@ Output (JSON):}if (isDiscard) {- const result = handleDiscard(id, lines, targetFile);- console.log(JSON.stringify({ handled: true, file: relFile, carbonize: false, ...result }));+ let result;+ // handleDiscard takes the source lock, which throws SOURCE_LOCKED under+ // contention. Without this catch the CLI exits non-zero with empty stdout+ // and the agent gets no JSON to act on.+ try {+ result = handleDiscard(id, lines, targetFile);+ } catch (err) {+ emitResult(operationFailure(err, { file: relFile }));+ return;+ }+ emitResult({ handled: true, file: relFile, carbonize: false, ...result });} else {- const result = handleAccept(id, variantNum, lines, targetFile, paramValues);+ let result;+ try {+ result = handleAccept(id, variantNum, lines, targetFile, paramValues);+ } catch (err) {+ emitResult(operationFailure(err, { file: relFile }));+ return;+ }const acceptedOriginalText = result.acceptedOriginalText || '';delete result.acceptedOriginalText;// Single-line attention-grabber when cleanup is required. The full@@ -167,7 +285,7 @@ Output (JSON):// Non-fatal; the buffer stays as-is and the user can discard later.}}- console.log(JSON.stringify({ handled: true, file: relFile, ...result }));+ emitResult({ handled: true, file: relFile, ...result });}}@@ -235,7 +353,14 @@ function scrubManualEditsAgainstFile(_targetFile, cwd = process.cwd(), originalB// Discard// ----------------------------------------------------------------------------function handleDiscard(id, lines, targetFile) {+function handleDiscard(id, _lines, targetFile) {+ return withSourceLockSync(targetFile, 'discard:' + id, () => {+ const lines = fs.readFileSync(targetFile, 'utf-8').split('\n');+ return handleDiscardUnlocked(id, lines, targetFile);+ }, { waitMs: ACCEPT_LOCK_WAIT_MS });+}++function handleDiscardUnlocked(id, lines, targetFile) {const block = findMarkerBlock(id, lines);if (!block) return { handled: false, error: 'Markers not found' };@@ -330,7 +455,24 @@ function reindentContent(contentLines, fromIndent, toIndent) {});}-function handleAccept(id, variantNum, lines, targetFile, paramValues) {+function handleAccept(id, variantNum, _lines, targetFile, paramValues) {+ return withSourceLockSync(targetFile, 'accept:' + id, () => {+ const lines = fs.readFileSync(targetFile, 'utf-8').split('\n');+ return handleAcceptUnlocked(id, variantNum, lines, targetFile, paramValues);+ }, { waitMs: ACCEPT_LOCK_WAIT_MS });+}++function handleAcceptUnlocked(id, variantNum, lines, targetFile, paramValues) {+ const built = buildAcceptedWrappedSource(id, variantNum, lines, targetFile, paramValues);+ if (built.handled === false) return built;+ fs.writeFileSync(targetFile, built.content, 'utf-8');+ return {+ carbonize: built.carbonize,+ acceptedOriginalText: built.acceptedOriginalText,+ };+}++function buildAcceptedWrappedSource(id, variantNum, lines, targetFile, paramValues) {const block = findMarkerBlock(id, lines);if (!block) return { handled: false, error: 'Markers not found' };@@ -375,11 +517,14 @@ function handleAccept(id, variantNum, lines, targetFile, paramValues) {...replacement,...lines.slice(replaceRange.end + 1),];- fs.writeFileSync(targetFile, newLines.join('\n'), 'utf-8');-- return { carbonize: needsCarbonize, acceptedOriginalText: originalContent.join('\n') };+ return {+ content: newLines.join('\n'),+ carbonize: needsCarbonize,+ acceptedOriginalText: originalContent.join('\n'),+ };}+function readSourceShadowPreviewMeta(content, id) {const escaped = escapeRegExp(id);const wrapperRe = new RegExp('<[^>]+data-impeccable-variants=(["\'])' + escaped + '\\1[^>]*>');@@ -746,6 +891,21 @@ function detectCommentSyntax(filePath) {// File search (find the file containing session markers)// ---------------------------------------------------------------------------+/**+ * `.impeccable` is the critical entry, and it is not cosmetic.+ *+ * Progressive publication stages each revision as `.impeccable/live/artifacts/+ * <id>-r<n>.<source-ext>`, and those artifacts carry the very marker this search+ * looks for. The walk reaches `.` for any project whose source is not under one+ * of the privileged dirs above (this repo's own site lives in `site/pages/`), and+ * dot-directories sort before letters, so the artifact was found *before* the+ * real file. isGeneratedFile then declined the accept, and the agent fell back to+ * carbonizing several hundred lines of stylesheet by hand.+ *+ * Impeccable's own state directory is never project source. Never search it.+ */+const SEARCH_SKIP_DIRS = new Set(['node_modules', '.git', 'dist', 'build', IMPECCABLE_DIR]);+function findSessionFile(id, cwd) {const marker = 'impeccable-variants-start ' + id;const searchDirs = ['src', 'app', 'pages', 'components', 'public', 'views', 'templates', '.'];@@ -786,7 +946,7 @@ function searchDir(dir, query, seen, depth) {for (const entry of entries) {if (!entry.isDirectory()) continue;- if (['node_modules', '.git', 'dist', 'build'].includes(entry.name)) continue;+ if (SEARCH_SKIP_DIRS.has(entry.name)) continue;const result = searchDir(path.join(dir, entry.name), query, seen, depth + 1);if (result) return result;}@@ -798,6 +958,28 @@ function searchDir(dir, query, seen, depth) {// Utilities// ---------------------------------------------------------------------------+function acceptReceiptPath(cwd, id) {+ return path.join(getLiveDir(cwd), 'accept-receipts', `${safeSessionId(id)}.json`);+}++function readAcceptReceipt(cwd, id) {+ try { return JSON.parse(fs.readFileSync(acceptReceiptPath(cwd, id), 'utf-8')); } catch { return null; }+}++function writeAcceptReceipt(cwd, id, receipt) {+ const file = acceptReceiptPath(cwd, id);+ fs.mkdirSync(path.dirname(file), { recursive: true });+ const value = {+ id,+ ...receipt,+ completedAt: new Date().toISOString(),+ };+ const temporary = `${file}.${process.pid}.${Date.now()}.tmp`;+ fs.writeFileSync(temporary, JSON.stringify(value, null, 2) + '\n', 'utf-8');+ fs.renameSync(temporary, file);+ return value;+}+function argVal(args, flag) {const idx = args.indexOf(flag);return idx !== -1 && idx + 1 < args.length ? args[idx + 1] : null;diff --git a/.agents/skills/impeccable/scripts/live-browser.js b/.agents/skills/impeccable/scripts/live-browser.jsindex 616f1290a..20d875b93 100644--- a/.agents/skills/impeccable/scripts/live-browser.js+++ b/.agents/skills/impeccable/scripts/live-browser.js@@ -126,6 +126,9 @@let expectedVariants = 0;let arrivedVariants = 0;let visibleVariant = 0;+ let generationPhase = null;+ let parameterGenerationState = 'idle';+ let parameterReadyAnnouncedSession = null;let svelteComponentSession = null;let svelteRuntimePromise = null;let pendingSvelteComponentRetryObserver = null;@@ -134,6 +137,7 @@let currentPreviewMode = null;let recoveryWaitingForAnchor = false;let pickedAnchorSnapshot = null;+ let pickedAnchorViewportTop = null;let pendingVariantAnchorRetryObserver = null;let pendingAcceptedSession = null;let variantObserver = null;@@ -151,10 +155,12 @@// startScrollLock / stopScrollLock below.let scrollLockObserver = null;let scrollLockTargetY = null;+ let scrollLockAnchorTop = null;let scrollLockRaf = null;let scrollLockAbort = null;const SCROLL_ANCHOR_LOCK_ID = 'impeccable-scroll-anchor-lock';const VARIANT_STATE_STYLE_ID = 'impeccable-variant-state';+ const DISCARD_STATE_STYLE_ID = 'impeccable-discard-state';// Dedicated key for scroll position - SEPARATE from LS_KEY so that// saveSession's state updates don't clobber a carefully-captured scrollY.@@ -252,6 +258,13 @@barConnected: !!barEl?.isConnected,hasSvelteComponentSession: !!svelteComponentSession,mountedSvelteVariant: svelteComponentSession?.mountedVariant || 0,+ pickActive,+ pendingApplyInFlight,+ hoveredElement: hoveredElement ? {+ tag: hoveredElement.tagName,+ classes: hoveredElement.className,+ pickable: pickable(hoveredElement),+ } : null,pendingSvelteComponentRetry: !!pendingSvelteComponentRetryObserver,recoveryWaitingForAnchor,evtSourceReadyState: evtSource ? evtSource.readyState : null,@@ -1114,14 +1127,15 @@});}- function hideBar() {+ function hideBar(instant) {if (!barEl) return;const hideSeq = ++barHideSeq;stopVoice({ suppressSubmit: true });if (configureKind === 'insert') clearInsertPicking();barEl.style.opacity = '0';- barEl.style.transform = 'translateY(6px)';- setTimeout(() => { if (barEl && hideSeq === barHideSeq) barEl.style.display = 'none'; }, 250);+ barEl.style.transform = instant ? 'translateY(0)' : 'translateY(6px)';+ if (instant) barEl.style.display = 'none';+ else setTimeout(() => { if (barEl && hideSeq === barHideSeq) barEl.style.display = 'none'; }, 250);hideActionPicker();closeTunePopover();hideConfigureBarTooltip();@@ -1966,6 +1980,7 @@*/function setLiveState(next) {state = next;+ window.__IMPECCABLE_LIVE_STATE__ = next;syncPageInteractionCursor();}@@ -2516,18 +2531,27 @@fontSize: '11px', color: BP.textDim, whiteSpace: 'nowrap',marginLeft: 'auto',});- // Variants currently arrive atomically in a single file edit, so a- // per-variant counter would lie. Say what's true.status.textContent = recoveryWaitingForAnchor? 'Variants ready. Reveal the selected element to resume.'- : (arrivedVariants < expectedVariants- ? 'Generating ' + expectedVariants + ' variants...'- : 'Done');+ : generationStatusText();row.appendChild(status);return row;}+ function generationStatusText() {+ if (arrivedVariants >= expectedVariants && expectedVariants > 0) return 'Done';+ if (generationPhase === 'picked_up') return 'Agent picked up the request...';+ if (generationPhase === 'scaffolding') return 'Finding the source...';+ if (generationPhase === 'source_ready') return 'Source ready. Generating...';+ if (generationPhase === 'scaffold_fallback') return 'Agent is locating the source...';+ if (generationPhase === 'first_variant_generating') return 'Designing the first variant...';+ if (generationPhase === 'first_variant_validating') return 'Checking the first variant...';+ if (generationPhase === 'remaining_variants_generating') return 'Exploring two more directions...';+ if (generationPhase === 'remaining_variants_validating') return 'Checking the remaining variants...';+ return 'Generating ' + expectedVariants + ' variants...';+ }+// Cycling rowconst TUNE_ICON_SVG = '<svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" style="flex-shrink:0"><line x1="4" y1="8" x2="20" y2="8"/><circle cx="14" cy="8" r="2.4" fill="currentColor" stroke="none"/><line x1="4" y1="16" x2="20" y2="16"/><circle cx="10" cy="16" r="2.4" fill="currentColor" stroke="none"/></svg>';@@ -2557,7 +2581,7 @@color: BP.textDim, minWidth: '24px', textAlign: 'center',});counter.id = PREFIX + '-variant-counter';- counter.textContent = visibleVariant + '/' + arrivedVariants;+ counter.textContent = visibleVariant + '/' + expectedVariants;row.appendChild(counter);// Next@@ -2567,10 +2591,12 @@if (visibleVariant >= arrivedVariants) next.style.opacity = '0.3';row.appendChild(next);- // Tune chip - only when the visible variant exposes params+ // Tune chip stays visible while the deferred parameter phase is running,+ // then becomes interactive as soon as this variant exposes controls.const visParams = parseVariantParams(getVisibleVariantEl());const hasParams = visParams.length > 0;- if (hasParams) {+ const paramsPending = !hasParams && (parameterGenerationState === 'pending' || parameterGenerationState === 'loading');+ if (hasParams || paramsPending) {const tune = el('button', {display: 'inline-flex', alignItems: 'center', gap: '6px',padding: '4px 10px', borderRadius: '5px',@@ -2578,35 +2604,54 @@background: tuneOpen ? BP.accentSoft : 'transparent',color: tuneOpen ? BP.accent : BP.text,fontFamily: FONT, fontSize: '11px', fontWeight: '500',- cursor: 'pointer',+ cursor: paramsPending ? 'wait' : 'pointer',transition: 'color 0.12s ease, background 0.12s ease',whiteSpace: 'nowrap',});- tune.innerHTML = TUNE_ICON_SVG;+ if (paramsPending) {+ const spinner = el('span', {+ width: '11px', height: '11px', borderRadius: '50%',+ border: '1.5px solid ' + BP.hairline,+ borderTopColor: BP.accent,+ animation: 'impeccable-spin 0.6s linear infinite',+ boxSizing: 'border-box', flexShrink: '0',+ });+ spinner.setAttribute('aria-hidden', 'true');+ tune.appendChild(spinner);+ } else {+ tune.innerHTML = TUNE_ICON_SVG;+ }const tuneLabel = document.createElement('span');tuneLabel.textContent = 'Tune';tune.appendChild(tuneLabel);- const tuneBadge = document.createElement('span');- Object.assign(tuneBadge.style, {- display: 'inline-flex', alignItems: 'center', justifyContent: 'center',- minWidth: '16px', height: '16px', padding: '0 4px',- borderRadius: '999px',- background: tuneOpen ? C.brand : BP.hairline,- color: tuneOpen ? 'oklch(98% 0 0)' : 'inherit',- fontFamily: MONO, fontSize: '9.5px', fontWeight: '600',- lineHeight: '1',- boxSizing: 'border-box',- });- tuneBadge.textContent = String(visParams.length);- tune.appendChild(tuneBadge);- tune.title = 'Tune this variant (' + visParams.length + ' knob' + (visParams.length === 1 ? '' : 's') + ')';- tune.addEventListener('mouseenter', () => {- if (!tuneOpen) tune.style.background = BP.accentSoft;- });- tune.addEventListener('mouseleave', () => {- if (!tuneOpen) tune.style.background = 'transparent';- });- tune.addEventListener('click', (e) => { e.stopPropagation(); toggleTunePopover(); });+ if (hasParams) {+ const tuneBadge = document.createElement('span');+ Object.assign(tuneBadge.style, {+ display: 'inline-flex', alignItems: 'center', justifyContent: 'center',+ minWidth: '16px', height: '16px', padding: '0 4px',+ borderRadius: '999px',+ background: tuneOpen ? C.brand : BP.hairline,+ color: tuneOpen ? 'oklch(98% 0 0)' : 'inherit',+ fontFamily: MONO, fontSize: '9.5px', fontWeight: '600',+ lineHeight: '1',+ boxSizing: 'border-box',+ });+ tuneBadge.textContent = String(visParams.length);+ tune.appendChild(tuneBadge);+ tune.title = 'Tune this variant (' + visParams.length + ' knob' + (visParams.length === 1 ? '' : 's') + ')';+ tune.addEventListener('mouseenter', () => {+ if (!tuneOpen) tune.style.background = BP.accentSoft;+ });+ tune.addEventListener('mouseleave', () => {+ if (!tuneOpen) tune.style.background = 'transparent';+ });+ tune.addEventListener('click', (e) => { e.stopPropagation(); toggleTunePopover(); });+ } else {+ tune.disabled = true;+ tune.setAttribute('aria-label', 'Tune controls are still being prepared');+ tune.title = 'Tune controls are still being prepared';+ tune.style.opacity = '0.72';+ }tune.dataset.iceqTune = '1';row.appendChild(tune);}@@ -2614,6 +2659,15 @@// Spacerrow.appendChild(el('div', { flex: '1' }));+ if (arrivedVariants < expectedVariants) {+ const remaining = expectedVariants - arrivedVariants;+ const progress = el('span', {+ fontSize: '11px', color: BP.textDim, whiteSpace: 'nowrap',+ });+ progress.textContent = remaining + ' more arriving...';+ row.appendChild(progress);+ }+// Accept - primary action, kinpaku gold + lacquer-deep (matches demo .live-demo-ctx-accept)const accept = el('button', {padding: '5px 14px', borderRadius: '5px',@@ -2628,7 +2682,11 @@accept.addEventListener('mousedown', () => accept.style.transform = 'scale(0.97)');accept.addEventListener('mouseup', () => accept.style.transform = 'scale(1)');accept.addEventListener('click', (e) => { e.stopPropagation(); handleAccept(); });- if (arrivedVariants === 0) { accept.style.opacity = '0.3'; accept.style.pointerEvents = 'none'; }+ if (arrivedVariants === 0) {+ accept.style.opacity = '0.3';+ accept.style.pointerEvents = 'none';+ accept.title = 'Accept becomes available when the first variant arrives';+ }row.appendChild(accept);// Discard@@ -4743,6 +4801,32 @@}}+ function mountedParameterCount() {+ if (svelteComponentSession?.sessionId === currentSessionId) {+ return Object.values(svelteComponentSession.paramsByVariant || {})+ .reduce((total, params) => total + (Array.isArray(params) ? params.length : 0), 0);+ }+ const wrapper = document.querySelector('[data-impeccable-variants="' + currentSessionId + '"]');+ if (!wrapper) return 0;+ return [...wrapper.querySelectorAll('[data-impeccable-variant]:not([data-impeccable-variant="original"])')]+ .reduce((total, variant) => total + parseVariantParams(variant).length, 0);+ }++ function completeParameterPublication() {+ if (!currentSessionId) return;+ const ready = mountedParameterCount() > 0;+ parameterGenerationState = ready ? 'ready' : 'none';+ if (ready && parameterReadyAnnouncedSession !== currentSessionId) {+ parameterReadyAnnouncedSession = currentSessionId;+ showToast('Tune controls are ready.', 3000);+ }+ if (state === 'CYCLING') {+ refreshParamsPanel();+ showOrUpdateCyclingBar();+ }+ saveSession();+ }+function toggleTunePopover() {if (pendingApplyInFlight) { showManualApplyBusyToast(); return; }if (tuneOpen) { closeTunePopover(); return; }@@ -4835,6 +4919,10 @@return String(filePath || '').endsWith('manifest.json');}+ function isFrameworkComponentPreviewMode(mode) {+ return mode === 'svelte-component';+ }+function parseOriginalMarkupElement(originalMarkup) {const parser = new DOMParser();const doc = parser.parseFromString('<div id="impeccable-anchor">' + originalMarkup + '</div>', 'text/html');@@ -5029,9 +5117,13 @@}}- function loadSvelteRuntime(runtimeModule) {+ function resolveComponentModuleUrl(manifest, modulePath) {+ return new URL(String(modulePath || ''), location.origin).href;+ }++ function loadSvelteRuntime(runtimeModule, manifest) {const modulePath = runtimeModule || '/src/lib/impeccable/__runtime.js';- const url = new URL(modulePath, location.origin).href;+ const url = resolveComponentModuleUrl(manifest, modulePath);if (!svelteRuntimePromise) {svelteRuntimePromise = import(/* @vite-ignore */ url);}@@ -5065,7 +5157,8 @@async function loadSvelteComponentVariantSource(manifest, variantNum) {const dir = String(manifest?.componentDir || '').replace(/^\/+/, '');if (!dir || !variantNum) return '';- const sourcePath = dir + '/v' + variantNum + '.svelte';+ const extension = manifest.componentExtension || 'svelte';+ const sourcePath = dir + '/v' + variantNum + '.' + extension;const url = 'http://localhost:' + PORT + '/source?token=' + TOKEN + '&path=' + encodeURIComponent(sourcePath);try {const res = await fetch(url);@@ -5221,7 +5314,7 @@if (!sourceOriginal) return values;const map = buildSvelteExpressionTextMap(sourceOriginal, liveEl);for (const entry of contract) {- const token = '{' + entry.expr + '}';+ const token = entry.previewToken || ('{' + entry.expr + '}');values[entry.prop] = map.get(token) || '';}return values;@@ -5233,9 +5326,12 @@try {const previousAnchor = getMountedSvelteComponentAnchor(svelteComponentSession) || selectedElement;svelteComponentSession.swapAnchor = makeFrozenAnchor(previousAnchor) || svelteComponentSession.swapAnchor || null;- const runtime = await loadSvelteRuntime(manifest.runtimeModule);- const modulePath = '/' + String(manifest.componentDir || '').replace(/^\/+/, '') + '/v' + variantNum + '.svelte';- const moduleUrl = new URL(modulePath, location.origin).href + '?t=' + Date.now();+ const runtime = await loadSvelteRuntime(manifest.runtimeModule, manifest);+ const extension = manifest.componentExtension || 'svelte';+ const moduleBase = manifest.componentModuleBase+ || ('/' + String(manifest.componentDir || '').replace(/^\/+/, ''));+ const modulePath = String(moduleBase).replace(/\/+$/, '') + '/v' + variantNum + '.' + extension;+ const moduleUrl = resolveComponentModuleUrl(manifest, modulePath) + '?t=' + Date.now();const mod = await import(/* @vite-ignore */ moduleUrl);const Component = mod.default;if (svelteComponentSession.mountedInstance && runtime.unmount) {@@ -5275,7 +5371,7 @@if (svelteComponentSession?.sessionId === sessionId) {svelteComponentSession.swapAnchor = null;}- console.error('[impeccable] Failed to mount Svelte variant ' + variantNum + ' for ' + sessionId + ':', err);+ console.error('[impeccable] Failed to mount component variant ' + variantNum + ' for ' + sessionId + ':', err);return false;}}@@ -5340,40 +5436,46 @@if (manifest.id !== sessionId) return;const paramsByVariant = await loadSvelteComponentParams(manifest);+ const availableVariants = Number(manifest.arrivedVariants) || Number(manifest.count) || 1;+ const componentPreviewMode = isFrameworkComponentPreviewMode(manifest.previewMode)+ ? manifest.previewMode+ : 'svelte-component';currentSessionId = sessionId;expectedVariants = Number(manifest.count) || expectedVariants || 1;rememberSessionFileMeta({sourceFile: manifest.sourceFile,previewFile: manifestPath,- previewMode: 'svelte-component',+ previewMode: componentPreviewMode,});if (state !== 'CYCLING') setLiveState('GENERATING');const existingWrapper = document.querySelector('[data-impeccable-variants="' + sessionId + '"]');if (existingWrapper && svelteComponentSession?.sessionId === sessionId) {recoveryWaitingForAnchor = false;+ svelteComponentSession.manifest = manifest;svelteComponentSession.paramsByVariant = paramsByVariant;- arrivedVariants = Number(manifest.count) || expectedVariants || 1;- expectedVariants = arrivedVariants;+ arrivedVariants = availableVariants;+ expectedVariants = Number(manifest.count) || expectedVariants || arrivedVariants;visibleVariant = visibleVariant > 0 && visibleVariant <= arrivedVariants ? visibleVariant : 1;await mountSvelteComponentVariant(visibleVariant || 1);setLiveState('CYCLING');showOrUpdateCyclingBar();saveSession();+ if (parameterGenerationState === 'loading') completeParameterPublication();return;}const liveEl = findLiveElementForSvelteManifest(manifest);if (!liveEl?.parentElement) {console.warn('[impeccable] Could not find original element in live DOM.');- arrivedVariants = Number(manifest.count) || expectedVariants || 1;- expectedVariants = arrivedVariants;+ arrivedVariants = availableVariants;+ expectedVariants = Number(manifest.count) || expectedVariants || arrivedVariants;const saved = loadSession();const savedVisibleVariant = saved && saved.id === sessionId ? saved.visible : 0;visibleVariant = visibleVariant > 0 && visibleVariant <= arrivedVariants? visibleVariant: (savedVisibleVariant > 0 && savedVisibleVariant <= arrivedVariants ? savedVisibleVariant : 1);- enterRecoveryWaitingForAnchor({ checkpointReason: 'svelte_component_anchor_missing', trackScroll: true });+ enterRecoveryWaitingForAnchor({ checkpointReason: 'component_preview_anchor_missing', trackScroll: true });waitForSvelteComponentTargetAndRetry({ manifestPath, sessionId, manifest });return;}@@ -5381,7 +5483,7 @@const wrapper = document.createElement('div');wrapper.dataset.impeccableVariants = sessionId;wrapper.dataset.impeccableVariantCount = String(manifest.count || expectedVariants || 1);- wrapper.dataset.impeccablePreview = 'svelte-component';+ wrapper.dataset.impeccablePreview = componentPreviewMode;wrapper.style.display = 'contents';const mountTarget = document.createElement('div');@@ -5419,8 +5521,8 @@recoveryWaitingForAnchor = false;const previousVisibleVariant = currentSessionId === sessionId ? visibleVariant : 0;- arrivedVariants = Number(manifest.count) || expectedVariants || 1;- expectedVariants = arrivedVariants;+ arrivedVariants = availableVariants;+ expectedVariants = Number(manifest.count) || expectedVariants || arrivedVariants;const saved = loadSession();const savedVisibleVariant = saved && saved.id === sessionId ? saved.visible : 0;visibleVariant = previousVisibleVariant > 0 && previousVisibleVariant <= arrivedVariants@@ -5445,9 +5547,10 @@refreshParamsPanel();positionBar();saveSession();- console.log('[impeccable] Mounted ' + arrivedVariants + ' Svelte component variants.');+ if (parameterGenerationState === 'loading') completeParameterPublication();+ console.log('[impeccable] Mounted ' + arrivedVariants + ' ' + manifest.framework + ' component variants.');} catch (err) {- console.error('[impeccable] Failed to mount Svelte component variants:', err);+ console.error('[impeccable] Failed to mount component-preview variants:', err);abortSvelteComponentInjection(sessionId, 'Could not load variants. Fix the error and re-run.');}}@@ -5493,6 +5596,8 @@clearHandled();resetSessionFileMeta();currentSessionId = null;+ parameterGenerationState = 'idle';+ parameterReadyAnnouncedSession = null;expectedVariants = 0;arrivedVariants = 0;visibleVariant = 0;@@ -5502,12 +5607,24 @@if (message) showToast(message, 5000);}+ // How many delayed re-reads a completion-driven source fallback gets when+ // the fetched source still shows only the preflight scaffold, before the+ // failure is surfaced via recoverEmptyCycling.+ const COMPLETED_SOURCE_FALLBACK_RETRIES = 3;+ const COMPLETED_SOURCE_FALLBACK_RETRY_MS = 1200;+/*** No-HMR fallback: fetch the raw source file from the live server,* parse it, extract the variant wrapper, and inject it into the live DOM.* This works even when the dev server caches HTML (Bun, static servers).+ *+ * opts.generationCompleted marks callers that KNOW the agent finished (a+ * `done` arrived or the server reported a completed generation). For them an+ * empty read is a stale source view and no further event is coming, so the+ * read retries a few times and then surfaces recovery. Callers without the+ * flag may be mid-generation and wait indefinitely for the real completion.*/- function injectVariantsFromSource(filePath, sessionId) {+ function injectVariantsFromSource(filePath, sessionId, opts = {}) {if (isSvelteComponentManifestPath(filePath)) {injectSvelteComponentsFromManifest(filePath, sessionId);return;@@ -5573,6 +5690,32 @@arrivedVariants = variants.length;expectedVariants = parseInt(wrapper.dataset.impeccableVariantCount || arrivedVariants);if (arrivedVariants <= 0) {+ if (state === 'GENERATING') {+ // Mid-generation the source legitimately holds a scaffold wrapper+ // with no variants yet (the server-side preflight wraps before the+ // agent writes). Tearing the session down here would destroy an+ // in-flight generation; stay in GENERATING — the variant observer+ // is armed and the server re-delivers a missed `done`.+ if (!opts.generationCompleted) {+ console.log('[impeccable] Source has scaffold but no variants yet; still generating.');+ return;+ }+ // Generation finished, yet the read shows only the scaffold: the+ // source view is stale and no further event will fire. Re-read a+ // few times before surfacing recovery — a single silent return+ // here would strand the tab in GENERATING forever.+ const attempt = opts.attempt || 0;+ if (attempt < COMPLETED_SOURCE_FALLBACK_RETRIES) {+ console.log('[impeccable] Generation is done but source shows no variants yet; retrying read ('+ + (attempt + 1) + '/' + COMPLETED_SOURCE_FALLBACK_RETRIES + ').');+ setTimeout(() => {+ if (state !== 'GENERATING' || currentSessionId !== sessionId) return;+ if (arrivedVariants > 0) return;+ injectVariantsFromSource(filePath, sessionId, { ...opts, attempt: attempt + 1 });+ }, COMPLETED_SOURCE_FALLBACK_RETRY_MS);+ return;+ }+ }recoverEmptyCycling('source-fallback-empty');return;}@@ -5594,6 +5737,7 @@refreshParamsPanel();positionBar();saveSession();+ if (parameterGenerationState === 'loading') completeParameterPublication();console.log('[impeccable] Injected ' + arrivedVariants + ' variants from source file.');}).catch(err => {@@ -5865,13 +6009,36 @@document.getElementById(VARIANT_STATE_STYLE_ID)?.remove();}+ function showOriginalDuringDiscard(sessionId) {+ if (!sessionId) return;+ let styleEl = document.getElementById(DISCARD_STATE_STYLE_ID);+ if (!styleEl) {+ styleEl = document.createElement('style');+ styleEl.id = DISCARD_STATE_STYLE_ID;+ (document.head || document.documentElement).appendChild(styleEl);+ }+ const wrapper = '[data-impeccable-variants="' + sessionId + '"]';+ styleEl.textContent = wrapper + ' > [data-impeccable-variant]:not([data-impeccable-variant="original"]) { display:none !important; }\n'+ + wrapper + ' > [data-impeccable-variant="original"] { display:block !important; }';+ }++ function resolveScrollLockAnchorTop() {+ const anchor = resolveBarAnchor();+ if (!anchor?.isConnected) return null;+ const top = anchor.getBoundingClientRect().top;+ return Number.isFinite(top) ? top : null;+ }+// Hold window.scrollY at a fixed value across DOM mutations inside the// session's wrapper (HMR patches, variant inserts, cycle swaps).- function startScrollLock(sessionId, initialTargetY) {+ function startScrollLock(sessionId, initialTargetY, initialAnchorTop) {stopScrollLock();scrollLockTargetY = typeof initialTargetY === 'number' && isFinite(initialTargetY)? initialTargetY: window.scrollY;+ scrollLockAnchorTop = typeof initialAnchorTop === 'number' && isFinite(initialAnchorTop)+ ? initialAnchorTop+ : resolveScrollLockAnchorTop();try { history.scrollRestoration = 'manual'; } catch {}@@ -5895,6 +6062,17 @@const correct = (why) => {scrollLockRaf = null;if (scrollLockTargetY == null) return;+ const anchor = resolveBarAnchor();+ if (anchor?.isConnected && typeof scrollLockAnchorTop === 'number' && isFinite(scrollLockAnchorTop)) {+ const anchorTop = anchor.getBoundingClientRect().top;+ const anchorDelta = anchorTop - scrollLockAnchorTop;+ if (Math.abs(anchorDelta) >= 0.5) {+ window.scrollTo({ top: window.scrollY + anchorDelta, left: window.scrollX, behavior: 'instant' });+ scrollLockTargetY = window.scrollY;+ writeScrollY(scrollLockTargetY);+ return;+ }+ }const before = window.scrollY;const delta = before - scrollLockTargetY;if (Math.abs(delta) < 0.5) {@@ -5939,6 +6117,7 @@if (scrollLockRaf != null) { cancelAnimationFrame(scrollLockRaf); scrollLockRaf = null; }const prevTarget = scrollLockTargetY;scrollLockTargetY = window.scrollY;+ scrollLockAnchorTop = resolveScrollLockAnchorTop();writeScrollY(scrollLockTargetY);};const markGesture = (why) => {@@ -5976,6 +6155,7 @@if (scrollLockRaf != null) { cancelAnimationFrame(scrollLockRaf); scrollLockRaf = null; }if (scrollLockAbort) { scrollLockAbort.abort(); scrollLockAbort = null; }scrollLockTargetY = null;+ scrollLockAnchorTop = null;// NOTE: do NOT clear the persistent scroll key here. startScrollLock// calls us as a reset, and clearing the key would nuke the Go-time// scrollY that the next resume needs to read.@@ -6049,6 +6229,7 @@updating = true;arrivedVariants = count;+ generationPhase = arrivedVariants >= expectedVariants ? 'variants_ready' : 'variants_progress';if (visibleVariant === 0 && arrivedVariants > 0) {const saved = loadSession();const savedVisibleVariant = saved && saved.id === sessionId ? saved.visible : 0;@@ -6064,7 +6245,7 @@const expected = parseInt(wrapper.dataset.impeccableVariantCount || '0');if (expected > 0) expectedVariants = expected;- if (arrivedVariants >= expectedVariants && expectedVariants > 0) {+ if (arrivedVariants > 0) {setLiveState('CYCLING');recoveryWaitingForAnchor = false;hideShaderOverlay();@@ -6072,13 +6253,18 @@updateSelectedElement();showOrUpdateCyclingBar();disableInlineEdit();- refreshParamsPanel();+ if (arrivedVariants >= expectedVariants && expectedVariants > 0) refreshParamsPanel();+ else hideParamsPanel();positionBar();} else if (state === 'GENERATING') {updateBarContent('generating');}saveSession();- queueCheckpoint(state === 'CYCLING' ? 'variants_ready' : 'variants_progress');+ sendCheckpoint(+ arrivedVariants >= expectedVariants && expectedVariants > 0+ ? 'variants_ready'+ : 'variants_progress',+ );updating = false;});@@ -6151,6 +6337,7 @@syncAgentPollingUi(!!msg.agentPolling);startAgentStatusPoll();restoreFromActiveSessions(msg.activeSessions, 'sse_connected');+ recoverMissedGenerationCompletion(msg.activeSessions);if (state === 'IDLE' && (pickActive || insertActive)) setLiveState('PICKING');syncPageInteractionCursor();syncPageChatFocus('sse-connected');@@ -6158,6 +6345,42 @@case 'agent_polling':syncAgentPollingUi(!!msg.connected);break;+ case 'agent_phase':+ if (msg.id === currentSessionId && (state === 'GENERATING' || state === 'CYCLING')) {+ generationPhase = msg.phase || generationPhase;+ if (msg.phase === 'variant_parameters_generating' || msg.phase === 'variant_parameters_validating') {+ parameterGenerationState = 'loading';+ }+ if (msg.phase === 'parameters_ready' && parameterGenerationState !== 'ready') {+ parameterGenerationState = 'loading';+ }+ updateBarContent(state === 'CYCLING' ? 'cycling' : 'generating');+ saveSession();+ }+ break;+ case 'variant_progress':+ if (msg.id === currentSessionId) {+ if (msg.publicationKind === 'params') parameterGenerationState = 'loading';+ rememberSessionFileMeta(msg);+ if (isFrameworkComponentPreviewMode(msg.previewMode) && msg.previewFile) {+ injectSvelteComponentsFromManifest(msg.previewFile, msg.id);+ } else if ((msg.previewMode === 'source' || !msg.previewMode) && (msg.previewFile || msg.file)) {+ // Give normal framework HMR the first chance to reconcile its+ // own managed tree. Nuxt route-module HMR can skip intermediate+ // revisions, so fall back to source injection only when the+ // advertised progress still has not appeared after a short+ // settle. Immediate injection races React/Vue ownership and can+ // trigger removeChild errors on the next HMR commit.+ const targetArrived = Number(msg.arrivedVariants) || 1;+ setTimeout(() => {+ if (msg.id !== currentSessionId) return;+ if (state !== 'GENERATING' && state !== 'CYCLING') return;+ if (msg.publicationKind !== 'params' && arrivedVariants >= targetArrived) return;+ injectVariantsFromSource(msg.previewFile || msg.file, msg.id);+ }, 150);+ }+ }+ break;case 'steer_done':maybeCompleteSteer(msg);break;@@ -6175,6 +6398,10 @@case 'done':if (maybeCompleteSteer(msg)) break;rememberSessionFileMeta(msg);+ if (msg.id === currentSessionId && isFrameworkComponentPreviewMode(currentPreviewMode) && currentPreviewFile) {+ injectSvelteComponentsFromManifest(currentPreviewFile, msg.id);+ break;+ }// Variants already arrived via HMR → normal transition.if (arrivedVariants >= expectedVariants && expectedVariants > 0) {if (state === 'GENERATING') {@@ -6190,7 +6417,7 @@setTimeout(() => {if (arrivedVariants >= expectedVariants && expectedVariants > 0) return;if (state !== 'GENERATING' || msg.id !== currentSessionId) return;- injectVariantsFromSource(msg.file, msg.id);+ injectVariantsFromSource(msg.file, msg.id, { generationCompleted: true });}, 750);break;}@@ -6215,9 +6442,10 @@if (maybeCompleteAcceptedSession(msg)) break;break;case 'agent_done':- // Carbonize accepts are not terminal until live-complete.mjs sends- // the final complete event. Keep the browser in its recoverable- // saving state while the source cleanup is still in flight.+ // The deterministic accept has already committed the reviewed DOM+ // and fenced generation. Carbonize may continue in the background;+ // it must not hold the foreground picker hostage.+ if (msg.data?.carbonize === true && maybeCompleteAcceptedSession(msg)) break;break;case 'discarded':if (msg.id && msg.id === currentSessionId) {@@ -6306,6 +6534,7 @@type: 'checkpoint',id: currentSessionId,revision: sessionState.nextCheckpointRevision(),+ revisionDomain: 'browser',owner: browserOwner,phase: String(state || '').toLowerCase(),reason,@@ -6331,6 +6560,7 @@type: 'checkpoint',id,revision: sessionState.nextCheckpointRevision(),+ revisionDomain: 'browser',owner: browserOwner,phase: 'steer',reason,@@ -6684,6 +6914,9 @@expectedVariants = selectedCount;arrivedVariants = 0;visibleVariant = 0;+ generationPhase = 'queued';+ parameterGenerationState = 'pending';+ parameterReadyAnnouncedSession = null;resetSessionFileMeta();// Flip to GENERATING immediately so the bar morphs without waiting on@@ -6693,6 +6926,7 @@const elForCapture = selectedElement;pickedAnchorSnapshot = buildPickedAnchorSnapshot(elForCapture);const captureRect = elForCapture.getBoundingClientRect();+ pickedAnchorViewportTop = captureRect.top;const snapshot = {comments: annotState.comments.map(c => ({ x: c.x, y: c.y, text: c.text })),strokes: annotState.strokes.map(s => ({ points: s.points.map(p => [p[0], p[1]]) })),@@ -6724,7 +6958,7 @@writeScrollY(window.scrollY);if (variantObserver) variantObserver.disconnect();variantObserver = startVariantObserver(currentSessionId);- startScrollLock(currentSessionId);+ startScrollLock(currentSessionId, window.scrollY, pickedAnchorViewportTop);captureAndEmit(elForCapture, basePayload, snapshot, captureRect);}@@ -6759,12 +6993,16 @@expectedVariants = selectedCount;arrivedVariants = 0;visibleVariant = 0;+ generationPhase = 'queued';+ parameterGenerationState = 'pending';+ parameterReadyAnnouncedSession = null;resetSessionFileMeta();selectedElement = placeholderElement;insertPlaceholderSnapshot = buildInsertPlaceholderSnapshotFromDom(insertAnchorElement, placeholderElement);const elForCapture = placeholderElement;const captureRect = elForCapture.getBoundingClientRect();+ pickedAnchorViewportTop = captureRect.top;const basePayload = {type: 'generate',mode: 'insert',@@ -6795,7 +7033,7 @@writeScrollY(window.scrollY);if (variantObserver) variantObserver.disconnect();variantObserver = startVariantObserver(currentSessionId);- startScrollLock(currentSessionId);+ startScrollLock(currentSessionId, window.scrollY, pickedAnchorViewportTop);captureAndEmit(elForCapture, basePayload, snapshot, captureRect);}@@ -6975,9 +7213,9 @@// preview mounts are covered by the same shader regression checks.const adapter = String(window.__IMPECCABLE_LIVE_ADAPTER__ || '').toLowerCase();if (adapter === 'svelte' || adapter === 'sveltekit') return true;- if (currentPreviewMode === 'svelte-component' || svelteComponentSession) return true;+ if (isFrameworkComponentPreviewMode(currentPreviewMode) || svelteComponentSession) return true;const wrapper = el?.closest?.('[data-impeccable-variants]');- return wrapper?.dataset?.impeccablePreview === 'svelte-component';+ return isFrameworkComponentPreviewMode(wrapper?.dataset?.impeccablePreview);}function paintsShaderProxySurface(node) {@@ -7105,6 +7343,17 @@}async function captureAndEmit(el, basePayload, snapshot, rect) {+ const hasAnnotations = snapshot && (snapshot.comments.length > 0 || snapshot.strokes.length > 0);++ // Plain requests do not send a screenshot to the agent, so capture is+ // presentation-only. Wait only for the helper to accept the event before+ // starting CPU-heavy capture; this yields the browser task and prevents+ // rasterization from delaying the fetch itself.+ if (!hasAnnotations) {+ basePayload.clientSentAt = Date.now();+ await sendEvent(basePayload);+ }+let screenshotPath;let blob;let paper;@@ -7122,7 +7371,6 @@// are present. Without annotations the image is pure visual anchoring -// it biases the model toward the current rendering and works against the// three-distinct-directions brief.- const hasAnnotations = snapshot && (snapshot.comments.length > 0 || snapshot.strokes.length > 0);if (blob && hasAnnotations) {try {const uploadRes = await fetch(@@ -7140,7 +7388,12 @@console.warn('[impeccable] annotation upload failed:', err);}}- sendEvent(screenshotPath ? { ...basePayload, screenshotPath } : basePayload);+ // Annotated requests must wait for capture + upload because the screenshot+ // is semantic input. Plain requests were already dispatched above.+ if (hasAnnotations) {+ basePayload.clientSentAt = Date.now();+ sendEvent(screenshotPath ? { ...basePayload, screenshotPath } : basePayload);+ }}//@@ -7520,7 +7773,6 @@ void main() {if (variantSelectionPromise) {try { await variantSelectionPromise; } catch { /* failed selection falls back below */ }}- if (!currentSessionId || arrivedVariants === 0) return;const domVisibleVariant = readVisibleVariantFromDOM(currentSessionId);if (domVisibleVariant > 0) visibleVariant = domVisibleVariant;const acceptPayload = {@@ -7528,7 +7780,9 @@ void main() {id: currentSessionId,variantId: String(visibleVariant),pageUrl: location.pathname,+ clientSentAt: Date.now(),};+ if (!currentSessionId || arrivedVariants === 0) return;const acceptWrapper = document.querySelector('[data-impeccable-variants="' + currentSessionId + '"]');if (Object.keys(paramsCurrentValues).length > 0) {acceptPayload.paramValues = { ...paramsCurrentValues };@@ -7542,7 +7796,7 @@ void main() {const acceptedSessionId = currentSessionId;const acceptedVariant = visibleVariant;const acceptedIsSvelteComponent = svelteComponentSession?.sessionId === acceptedSessionId- || acceptWrapper?.dataset?.impeccablePreview === 'svelte-component';+ || isFrameworkComponentPreviewMode(acceptWrapper?.dataset?.impeccablePreview);const acceptedSnapshot = snapshotAcceptedVariantDom(acceptedSessionId, acceptedVariant);setLiveState('SAVING');@@ -7557,7 +7811,17 @@ void main() {saveSession();sendEvent(acceptPayload, { throwOnError: true })- .then(() => {})+ .then(() => {+ const pending = pendingAcceptedSession;+ if (!pending || pending.id !== acceptedSessionId) return;+ // POST /events returns only after the accept intent is durable and the+ // generation epoch is fenced. Source promotion/carbonize can finish in+ // the background; the foreground picker is free immediately.+ markSessionHandled();+ setLiveState('CONFIRMED');+ document.documentElement.dataset.impeccableAcceptToPickingMs = String(Date.now() - acceptPayload.clientSentAt);+ scheduleAcceptCleanup(pending);+ }).catch(() => {if (pendingAcceptedSession?.id === acceptedSessionId) pendingAcceptedSession = null;setLiveState('CYCLING');@@ -7586,17 +7850,26 @@ void main() {}function scheduleAcceptCleanup(accepted) {- setTimeout(function() {- if (!accepted?.isSvelteComponent && !acceptedDomAlreadyClean(accepted)) {- setTimeout(function() {- if (pendingAcceptedSession?.id !== accepted?.id) return;- if (!accepted?.isSvelteComponent) ensureAcceptedDomClean(accepted);- cleanupAcceptedSession();- }, 1800);- return;+ queueMicrotask(function() {+ if (pendingAcceptedSession?.id !== accepted?.id) return;+ // Svelte previews live in an adapter-owned mount rather than in source+ // wrapper markup. Promote the mounted variant before releasing the+ // session so the old adapter instance cannot linger behind the next+ // Pick → Go loop while carbonize finishes in the background.+ if (accepted?.isSvelteComponent) {+ commitAcceptedSvelteComponentToDom(accepted.id);}cleanupAcceptedSession();- }, 1200);+ });+ // Let React/Vue/Svelte own the HMR reconciliation. Mutating their DOM in+ // the same turn as the source update causes removeChild/NotFoundError+ // races. Static servers still need a fallback, but it must not keep Live+ // in SAVING or block the user's next pick.+ if (!accepted?.isSvelteComponent) {+ setTimeout(function() {+ if (!acceptedDomAlreadyClean(accepted)) ensureAcceptedDomClean(accepted);+ }, 1200);+ }}function snapshotAcceptedVariantDom(sessionId, variantId) {@@ -7700,7 +7973,11 @@ void main() {clearSession();resetSessionFileMeta();selectedElement = null;+ hoveredElement = null;+ pagePickSkipClick = false;currentSessionId = null;+ parameterGenerationState = 'idle';+ parameterReadyAnnouncedSession = null;selectedAction = 'impeccable';pendingAcceptedSession = null;renderEditBadge('hidden');@@ -7735,7 +8012,7 @@ void main() {sendEvent({ type: 'discard', id: currentSessionId }, { throwOnError: true }).then(() => {markSessionHandled();- cleanup();+ cleanup({ restoreOriginal: true, instantChrome: true });}).catch(() => showToast('Could not confirm discard with the live server. Session kept for recovery.', 5000));}@@ -7757,6 +8034,7 @@ void main() {currentPreviewMode = null;recoveryWaitingForAnchor = false;pickedAnchorSnapshot = null;+ pickedAnchorViewportTop = null;}function rememberSessionFileMeta(meta = {}) {@@ -7765,8 +8043,8 @@ void main() {const previewFile = normalizeSessionPath(meta.previewFile);const previewMode = meta.previewMode || (isSvelteComponentManifestPath(previewFile || file) ? 'svelte-component' : null);- if (previewMode === 'svelte-component' || isSvelteComponentManifestPath(file)) {- currentPreviewMode = 'svelte-component';+ if (isFrameworkComponentPreviewMode(previewMode) || isSvelteComponentManifestPath(file)) {+ currentPreviewMode = isFrameworkComponentPreviewMode(previewMode) ? previewMode : 'svelte-component';currentPreviewFile = previewFile || (isSvelteComponentManifestPath(file) ? file : currentPreviewFile);currentSourceFile = sourceFile || currentSourceFile;return;@@ -7782,12 +8060,15 @@ void main() {rememberSessionFileMeta(saved);if (saved.insertPlaceholder) insertPlaceholderSnapshot = saved.insertPlaceholder;if (saved.pickedAnchor) pickedAnchorSnapshot = saved.pickedAnchor;+ if (Number.isFinite(saved.pickedAnchorViewportTop)) pickedAnchorViewportTop = saved.pickedAnchorViewportTop;if (saved.action) selectedAction = saved.action;if (saved.count) selectedCount = saved.count;if (saved.previewMode) currentPreviewMode = saved.previewMode;if (saved.paramValues && typeof saved.paramValues === 'object') {paramsCurrentValues = { ...saved.paramValues };}+ if (saved.parameterState) parameterGenerationState = saved.parameterState;+ if (saved.generationPhase) generationPhase = saved.generationPhase;}function normalizePagePath(value) {@@ -7859,7 +8140,7 @@ void main() {saveSession();queueCheckpoint(reason || 'browser_restore_without_wrapper');- const restoreFile = currentPreviewMode === 'svelte-component'+ const restoreFile = isFrameworkComponentPreviewMode(currentPreviewMode)? currentPreviewFile: (currentSourceFile || currentPreviewFile);if (restoreFile) {@@ -7872,11 +8153,41 @@ void main() {function restoreFromActiveSessions(activeSessions, reason) {const wrapper = document.querySelector('[data-impeccable-variants]');- if (wrapper && wrapper.dataset.impeccablePreview !== 'svelte-component') return false;+ if (wrapper && !isFrameworkComponentPreviewMode(wrapper.dataset.impeccablePreview)) return false;if (svelteComponentSession?.sessionId === currentSessionId) return false;return restoreSessionWithoutWrapper(reason || 'sse_connected', activeSessions);}+ // Self-heal on SSE (re)connect. The preflight scaffold write triggers a+ // framework full-reload (Astro reloads pages for any .astro edit); if the+ // agent's variant write + `done` broadcast land while this page is+ // mid-reload, both the done SSE and the second HMR reload are missed and+ // the resumed page would wait in GENERATING at 0/N forever. The server's+ // session summary carries the durable generationCompletedAt marker, so on+ // every connect compare it against our own progress and pull the finished+ // variants from source when behind. Mirrors the `done` handler's source+ // fallback, including its give-HMR-the-first-chance settle delay.+ function recoverMissedGenerationCompletion(activeSessions) {+ if (!currentSessionId || state !== 'GENERATING') return;+ if (!Array.isArray(activeSessions)) return;+ const summary = activeSessions.find((session) => session?.id === currentSessionId);+ if (!summary?.generationCompletedAt || summary.generationCanceled) return;+ if (isTerminalSessionSummary(summary)) return;+ if (arrivedVariants > 0 && arrivedVariants >= expectedVariants) return;+ rememberSessionFileMeta(summary);+ const sessionId = currentSessionId;+ const file = isFrameworkComponentPreviewMode(currentPreviewMode)+ ? currentPreviewFile+ : (summary.sourceFile || summary.previewFile || currentSourceFile || currentPreviewFile);+ if (!file) return;+ console.log('[impeccable] Reconnected after generation completed; recovering variants from source.');+ setTimeout(() => {+ if (sessionId !== currentSessionId || state !== 'GENERATING') return;+ if (arrivedVariants > 0 && arrivedVariants >= expectedVariants) return;+ injectVariantsFromSource(file, sessionId, { generationCompleted: true });+ }, 750);+ }+function saveSession() {if (!currentSessionId) return;// NOTE: scrollY is stored under a separate key (writeScrollY). Storing@@ -7894,8 +8205,12 @@ void main() {previewMode: currentPreviewMode || undefined,pageUrl: location.pathname,paramValues: { ...paramsCurrentValues },+ parameterState: parameterGenerationState,insertPlaceholder: insertPlaceholderSnapshot || undefined,pickedAnchor: pickedAnchorSnapshot || undefined,+ pickedAnchorViewportTop: Number.isFinite(pickedAnchorViewportTop) ? pickedAnchorViewportTop : undefined,+ pageHash: location.hash || undefined,+ pageSearch: location.search || undefined,});}@@ -7923,20 +8238,26 @@ void main() {sessionState.clearHandled();}- function cleanup() {+ function cleanup(options) {+ const restoreOriginal = options?.restoreOriginal === true;+ const instantChrome = options?.instantChrome === true;const cleanupSessionId = currentSessionId;if (svelteComponentSession?.sessionId === cleanupSessionId) {teardownSvelteComponentSession(true);} else if (cleanupSessionId) {- // Hide the wrapper immediately so variants disappear. DON'T structurally- // mutate the DOM yet - HMR from the agent's source rewrite is on its way,+ // Switch visibility immediately without structurally mutating the DOM.+ // HMR from the agent's source rewrite may still be on its way,// and a manual replaceChild under React causes NotFoundError when the// reconciler later tries to remove a wrapper we already removed.// Schedule a 2s fallback that does the manual swap only if HMR hasn't// replaced the wrapper by then (keeps static-server / no-HMR flows alive).const wrapper = document.querySelector('[data-impeccable-variants="' + cleanupSessionId + '"]');- if (wrapper) wrapper.style.display = 'none';+ if (wrapper) {+ if (restoreOriginal) showOriginalDuringDiscard(cleanupSessionId);+ else wrapper.style.display = 'none';+ }setTimeout(function() {+ document.getElementById(DISCARD_STATE_STYLE_ID)?.remove();if (!cleanupSessionId) return;const lateWrapper = document.querySelector('[data-impeccable-variants="' + cleanupSessionId + '"]');if (!lateWrapper) return;@@ -7951,7 +8272,7 @@ void main() {lateWrapper.remove();}, 2000);}- hideBar();+ hideBar(instantChrome);hideHighlight();stopScrollTracking();if (variantObserver) { variantObserver.disconnect(); variantObserver = null; }@@ -7963,7 +8284,11 @@ void main() {clearSession();resetSessionFileMeta();selectedElement = null;+ hoveredElement = null;+ pagePickSkipClick = false;currentSessionId = null;+ parameterGenerationState = 'idle';+ parameterReadyAnnouncedSession = null;selectedAction = 'impeccable';renderEditBadge('hidden');setLiveState('PICKING');@@ -8047,7 +8372,7 @@ void main() {// would strand the bar in CYCLING at 0/0. If there's no live in-memory mount// for this wrapper, it's an orphan (reload / failed mount): drop it and let// the live-server's SSE re-inject the manifest if the session is still live.- if (wrapper.dataset.impeccablePreview === 'svelte-component'+ if (isFrameworkComponentPreviewMode(wrapper.dataset.impeccablePreview)&& svelteComponentSession?.sessionId !== sessionId) {wrapper.remove();if (restoreSessionWithoutWrapper('browser_resumed_svelte_orphan_wrapper')) return true;@@ -8056,7 +8381,7 @@ void main() {return false;}- if (wrapper.dataset.impeccablePreview === 'svelte-component') {+ if (isFrameworkComponentPreviewMode(wrapper.dataset.impeccablePreview)) {if (!svelteComponentSession?.mountedVariant) {return true;}@@ -8104,7 +8429,7 @@ void main() {insertPlaceholderSnapshot = saved.insertPlaceholder;}- const resumedState = arrivedVariants >= expectedVariants ? 'CYCLING' : 'GENERATING';+ const resumedState = arrivedVariants > 0 ? 'CYCLING' : 'GENERATING';// Find the visible variant's content element for highlight positioning.const isInsert = wrapper.dataset.impeccableMode === 'insert';@@ -8128,7 +8453,11 @@ void main() {// hid. Now that state is CYCLING, re-fire.if (state === 'CYCLING') refreshParamsPanel();saveSession();- queueCheckpoint('browser_resumed');+ if (arrivedVariants > 0 && arrivedVariants < expectedVariants) {+ sendCheckpoint('variants_progress');+ } else {+ queueCheckpoint('browser_resumed');+ }// Start observing for more variants AFTER initial setupif (variantObserver) variantObserver.disconnect();@@ -8136,7 +8465,7 @@ void main() {// Hold the target at its saved viewport top through any subsequent// HMR patches, variant inserts, or cycle swaps.- startScrollLock(currentSessionId, readScrollY());+ startScrollLock(currentSessionId, readScrollY(), pickedAnchorViewportTop);// If we reloaded mid-generation (Bun's HTML HMR destroys the shader// canvas), re-capture the original's content and restart the shader so@@ -8171,6 +8500,7 @@ void main() {let globalBarBrandEl = null;let agentPollTooltipEl = null;let agentPollingConnected = false;+ let agentStatusMessage = null;let agentStatusPollTimer = null;let steerFocusSuspended = false;let steerFocusPauseUntil = 0;@@ -8275,6 +8605,13 @@ void main() {const AGENT_STATUS_POLL_MS = 5000;const AGENT_DISCONNECTED_MARK = 'oklch(62% 0 0 / 0.78)';const AGENT_DISCONNECTED_TIP = 'Agent disconnected - run live-poll.mjs to connect';+ // The indicator tracks whether a poll is parked, which is what decides if+ // steering can reach the agent right now. That goes quiet two ways, and they+ // need different copy: nobody is polling at all, or the agent took the work+ // and is busy with it. Under one-shot foreground polling the second case is+ // every normal generation, and telling the user to start a poll loop then is+ // wrong advice about a healthy session.+ const AGENT_BUSY_TIP = 'Agent is working - steering resumes when it finishes';const GLOBAL_BAR_SECTION_GAP = 8;const GLOBAL_BAR_INNER_GAP = 2;const GLOBAL_BAR_INNER_PAD_LEFT = 2;@@ -9295,24 +9632,46 @@ void main() {</svg>`;}+ /**+ * True while the browser is waiting on work it already handed to the agent.+ * In these states a quiet poll indicator means "busy", not "absent".+ */+ function agentHasWorkInFlight() {+ return state === 'GENERATING' || state === 'SAVING';+ }++ /**+ * Derived at read time, not cached: which of the two reasons applies depends on+ * the live state, which moves between the 5s status polls. The truthiness is+ * the same either way, so the indicator's visuals can stay driven by the+ * cached value while the wording stays current.+ */+ function agentStatusText() {+ if (agentPollingConnected) return null;+ return agentHasWorkInFlight() ? AGENT_BUSY_TIP : AGENT_DISCONNECTED_TIP;+ }+function syncAgentPollingUi(connected) {agentPollingConnected = !!connected;if (!globalBarBrandEl) return;const P = barPaletteForTheme(globalBarEl?.dataset.theme || detectPageTheme());+ agentStatusMessage = agentStatusText();globalBarBrandEl.dataset.agentConnected = connected ? 'true' : 'false';- globalBarBrandEl.setAttribute('aria-label', connected- ? 'Impeccable live mode'- : 'Impeccable live mode - agent not polling');+ // The tooltip is mouse-only, so carry the same distinction in the label or+ // screen-reader users are left with the vaguer of the two readings.+ globalBarBrandEl.setAttribute('aria-label', agentStatusMessage+ ? 'Impeccable live mode - ' + (agentHasWorkInFlight() ? 'agent is working' : 'agent not polling')+ : 'Impeccable live mode');globalBarBrandEl.removeAttribute('title');- globalBarBrandEl.style.cursor = connected ? 'default' : 'help';+ globalBarBrandEl.style.cursor = agentStatusMessage ? 'help' : 'default';const mark = globalBarBrandEl.querySelector('[data-brand-mark]');if (mark) {mark.innerHTML = brandMarkSvg(connected ? P.accent : AGENT_DISCONNECTED_MARK, 18);mark.style.opacity = '1';}const dot = globalBarBrandEl.querySelector('[data-agent-dot]');- if (dot) dot.style.display = connected ? 'none' : 'block';- if (connected) hideAgentPollTooltip();+ if (dot) dot.style.display = agentStatusMessage ? 'block' : 'none';+ if (!agentStatusMessage) hideAgentPollTooltip();}function ensureAgentPollTooltip() {@@ -9339,14 +9698,17 @@ void main() {whiteSpace: 'normal',});agentPollTooltipEl.id = PREFIX + '-agent-poll-tooltip';- agentPollTooltipEl.textContent = AGENT_DISCONNECTED_TIP;+ agentPollTooltipEl.textContent = agentStatusText() || AGENT_DISCONNECTED_TIP;uiAppend(agentPollTooltipEl);return agentPollTooltipEl;}function showAgentPollTooltip(anchor) {- if (agentPollingConnected || !anchor) return;+ if (!agentStatusMessage || !anchor) return;const tip = ensureAgentPollTooltip();+ // Re-derive rather than reuse the cached copy: the live state may have moved+ // since the last status poll set it.+ tip.textContent = agentStatusText() || AGENT_DISCONNECTED_TIP;tip.style.transition = 'none';tip.style.display = 'block';tip.style.opacity = '1';@@ -9376,7 +9738,9 @@ void main() {fetch('http://localhost:' + PORT + '/status?token=' + TOKEN, { cache: 'no-store' }).then((res) => (res.ok ? res.json() : null)).then((data) => {- if (data && typeof data.agentPolling === 'boolean') syncAgentPollingUi(data.agentPolling);+ if (data && typeof data.agentPolling === 'boolean') {+ syncAgentPollingUi(data.agentPolling);+ }}).catch(() => { /* server loss handled elsewhere */ });}diff --git a/.agents/skills/impeccable/scripts/live-inject.mjs b/.agents/skills/impeccable/scripts/live-inject.mjsindex 7c8d91182..d99c37fd5 100644--- a/.agents/skills/impeccable/scripts/live-inject.mjs+++ b/.agents/skills/impeccable/scripts/live-inject.mjs@@ -27,6 +27,8 @@ const __dirname = path.dirname(fileURLToPath(import.meta.url));const CONFIG_PATH = resolveLiveConfigPath({ cwd: process.cwd(), scriptsDir: __dirname });const MARKER_OPEN_TEXT = 'impeccable-live-start';const MARKER_CLOSE_TEXT = 'impeccable-live-end';+const NUXT_PLUGIN_MARKER = 'impeccable-live-nuxt-plugin';+const NUXT_PLUGIN_NAME = 'impeccable-live.client.ts';const IGNORE_MARKER_OPEN = '# impeccable-live-ignore-start';const IGNORE_MARKER_CLOSE = '# impeccable-live-ignore-end';@@ -38,6 +40,9 @@ export const LIVE_IGNORE_PATTERNS = Object.freeze(['.impeccable/live/sessions/','.impeccable/live/previews/','.impeccable/live/annotations/',+ '.impeccable/live/artifacts/',+ '.impeccable/live/accept-receipts/',+ '.impeccable/live/locks/','.impeccable/live/cache/','.impeccable/live/manual-edit-apply-transaction.json','.impeccable/live/manual-edit-events.jsonl',@@ -46,10 +51,15 @@ export const LIVE_IGNORE_PATTERNS = Object.freeze(['.impeccable/live/deferred-svelte-component-accepts.json','.impeccable-live.json','.impeccable-live/',+ 'app/.impeccable-live/',+ 'src/.impeccable-live/','node_modules/.impeccable-live/','src/lib/impeccable/ImpeccableLiveRoot.svelte','src/lib/impeccable/__runtime.js','src/lib/impeccable/[0-9a-f]*/',+ 'plugins/impeccable-live.client.ts',+ 'app/plugins/impeccable-live.client.ts',+ 'src/plugins/impeccable-live.client.ts',]);/**@@ -113,6 +123,7 @@ Output (JSON):const resolvedFiles = resolveFiles(process.cwd(), config);const svelteKit = detectSvelteKitProject(process.cwd(), config);+ const nuxt = detectNuxtProject(process.cwd());if (args.includes('--remove')) {if (svelteKit) {@@ -120,6 +131,12 @@ Output (JSON):console.log(JSON.stringify({ ok: true, adapter: 'sveltekit', results: [adapterResult] }));return;}+ if (nuxt) {+ const adapterResult = removeNuxtLiveAdapter({ cwd: process.cwd(), project: nuxt });+ console.log(JSON.stringify({ ok: !adapterResult.error, adapter: 'nuxt', results: [adapterResult] }));+ if (adapterResult.error) process.exitCode = 1;+ return;+ }const results = resolvedFiles.map((relFile) => {const absFile = path.resolve(process.cwd(), relFile);if (!fs.existsSync(absFile)) return { file: relFile, error: 'file_not_found' };@@ -145,13 +162,28 @@ Output (JSON):console.error(JSON.stringify({ ok: false, error: 'missing_port' }));process.exit(1);}- const gitIgnore = ensureLiveGitIgnores(process.cwd());+ const gitIgnore = ensureLiveGitIgnores(+ process.cwd(),+ nuxt ? [nuxt.pluginFile] : [],+ );if (svelteKit) {const adapterResult = applySvelteKitLiveAdapter({ cwd: process.cwd(), port, config });console.log(JSON.stringify({ ok: true, port, adapter: 'sveltekit', gitIgnore, results: [adapterResult] }));return;}+ if (nuxt) {+ const adapterResult = applyNuxtLiveAdapter({ cwd: process.cwd(), port, project: nuxt });+ console.log(JSON.stringify({+ ok: !adapterResult.error,+ port,+ adapter: 'nuxt',+ gitIgnore,+ results: [adapterResult],+ }));+ if (adapterResult.error) process.exitCode = 1;+ return;+ }const results = resolvedFiles.map((relFile) => {const absFile = path.resolve(process.cwd(), relFile);@@ -175,12 +207,12 @@ Output (JSON):if (!anyInserted) process.exit(1);}-export function ensureLiveGitIgnores(cwd = process.cwd()) {+export function ensureLiveGitIgnores(cwd = process.cwd(), extraPatterns = []) {const target = resolveIgnoreTarget(cwd);const existing = fs.existsSync(target.path) ? fs.readFileSync(target.path, 'utf-8') : '';const block = [IGNORE_MARKER_OPEN,- ...LIVE_IGNORE_PATTERNS,+ ...new Set([...LIVE_IGNORE_PATTERNS, ...extraPatterns]),IGNORE_MARKER_CLOSE,].join('\n');const markerRe = new RegExp(`${escapeRegExp(IGNORE_MARKER_OPEN)}[\\s\\S]*?${escapeRegExp(IGNORE_MARKER_CLOSE)}`);@@ -202,10 +234,119 @@ export function ensureLiveGitIgnores(cwd = process.cwd()) {file: path.relative(cwd, target.path).split(path.sep).join('/'),mode: target.mode,changed: updated !== existing,- patterns: [...LIVE_IGNORE_PATTERNS],+ patterns: [...new Set([...LIVE_IGNORE_PATTERNS, ...extraPatterns])],};}+// ---------------------------------------------------------------------------+// Nuxt adapter+//+// A script element placed in app.vue is compiled as Vue-rendered DOM and is+// not executed. Nuxt instead auto-discovers client plugins. Keep the adapter+// generated, dev-only, and outside user-authored source: Live creates one+// marked .client.ts plugin on start and removes it on stop.+// ---------------------------------------------------------------------------++export function detectNuxtProject(cwd = process.cwd()) {+ const configFile = fs.readdirSync(cwd, { withFileTypes: true })+ .find((entry) => entry.isFile() && /^nuxt\.config\.(?:js|mjs|cjs|ts|mts|cts)$/.test(entry.name))+ ?.name;+ if (!configFile) return null;++ const config = fs.readFileSync(path.join(cwd, configFile), 'utf-8');+ const literalSrcDir = config.match(/\bsrcDir\s*:\s*(['"])([^'"]+)\1/);+ let appDir = '';+ if (literalSrcDir) {+ const candidate = literalSrcDir[2]+ .replace(/\\/g, '/')+ .replace(/^\.\//, '')+ .replace(/\/+$/, '');+ const normalized = path.posix.normalize(candidate);+ if (normalized !== '..' && !normalized.startsWith('../') && !path.isAbsolute(normalized)) {+ appDir = normalized === '.' ? '' : normalized;+ }+ } else if (+ fs.existsSync(path.join(cwd, 'app', 'app.vue'))+ || fs.existsSync(path.join(cwd, 'app', 'pages'))+ ) {+ appDir = 'app';+ }++ const pluginFile = [appDir, 'plugins', NUXT_PLUGIN_NAME].filter(Boolean).join('/');+ return { configFile, appDir, pluginFile };+}++export function buildNuxtPlugin(port) {+ return `/* ${NUXT_PLUGIN_MARKER} */+const liveSrc = 'http://localhost:${port}/live.js';+const liveSelector = 'script[data-impeccable-live-nuxt]';++export default defineNuxtPlugin(() => {+ if (!import.meta.dev || typeof document === 'undefined') return;++ const expectedSrc = new URL(liveSrc, window.location.href).href;+ let script = document.querySelector(liveSelector);+ if (script?.src === expectedSrc) return;+ script?.remove();++ script = document.createElement('script');+ script.src = liveSrc;+ script.async = true;+ script.dataset.impeccableLiveNuxt = '';+ document.head.appendChild(script);++ import.meta.hot?.dispose(() => {+ if (script?.isConnected) script.remove();+ });+});+/* /${NUXT_PLUGIN_MARKER} */+`;+}++export function applyNuxtLiveAdapter({ cwd = process.cwd(), port, project = detectNuxtProject(cwd) }) {+ if (!project) return { error: 'nuxt_not_detected' };+ const absFile = path.join(cwd, project.pluginFile);+ const existing = fs.existsSync(absFile) ? fs.readFileSync(absFile, 'utf-8') : null;+ if (existing !== null && !existing.includes(NUXT_PLUGIN_MARKER)) {+ return {+ file: project.pluginFile,+ error: 'nuxt_plugin_conflict',+ hint: `${project.pluginFile} already exists and is not managed by Impeccable Live`,+ };+ }++ const content = buildNuxtPlugin(port);+ fs.mkdirSync(path.dirname(absFile), { recursive: true });+ if (content !== existing) fs.writeFileSync(absFile, content, 'utf-8');+ return {+ file: project.pluginFile,+ inserted: true,+ changed: content !== existing,+ devOnly: true,+ };+}++export function removeNuxtLiveAdapter({ cwd = process.cwd(), project = detectNuxtProject(cwd) }) {+ if (!project) return { error: 'nuxt_not_detected' };+ const absFile = path.join(cwd, project.pluginFile);+ if (!fs.existsSync(absFile)) {+ return { file: project.pluginFile, removed: false, note: 'no adapter present' };+ }+ const content = fs.readFileSync(absFile, 'utf-8');+ if (!content.includes(NUXT_PLUGIN_MARKER)) {+ return {+ file: project.pluginFile,+ removed: false,+ error: 'nuxt_plugin_conflict',+ hint: `${project.pluginFile} is not managed by Impeccable Live`,+ };+ }+ fs.unlinkSync(absFile);+ const pluginDir = path.dirname(absFile);+ if (fs.readdirSync(pluginDir).length === 0) fs.rmdirSync(pluginDir);+ return { file: project.pluginFile, removed: true };+}+function resolveIgnoreTarget(cwd) {const gitExcludePath = resolveGitInfoExcludePath(cwd);if (gitExcludePath) {diff --git a/.agents/skills/impeccable/scripts/live-poll.mjs b/.agents/skills/impeccable/scripts/live-poll.mjsindex 740161e10..19a8b0f9b 100644--- a/.agents/skills/impeccable/scripts/live-poll.mjs+++ b/.agents/skills/impeccable/scripts/live-poll.mjs@@ -27,7 +27,7 @@ const scriptCmd = (name) => `node "${path.join(SELF_DIR, name)}"`;export const PER_REQUEST_TIMEOUT_MS = 270_000;export const DEFAULT_EVENT_LEASE_MS = 600_000;-const EVENT_TYPES_NEEDING_AGENT_REPLY = new Set(['generate', 'steer', 'manual_edit_apply']);+const EVENT_TYPES_NEEDING_AGENT_REPLY = new Set(['generate', 'steer', 'manual_edit_apply', 'carbonize_cleanup']);function readServerInfo() {const record = readLiveServerInfo(process.cwd());@@ -38,8 +38,8 @@ function readServerInfo() {return record.info;}-export function buildPollReplyPayload(token, { id, type, message, file, data }) {- return { token, id, type, message, file, data };+export function buildPollReplyPayload(token, { id, type, message, file, data, sourceEventType }) {+ return { token, id, type, message, file, data, sourceEventType };}export function manualApplyPollBanner(event = {}) {@@ -152,7 +152,14 @@ export async function waitForEventAck(base, token, eventId, {return false;}-export async function fetchNextEvent(base, token, { totalDeadline } = {}) {+export async function fetchNextEvent(base, token, {+ totalDeadline,+ types,+ resolveTypes,+ perRequestTimeoutMs = PER_REQUEST_TIMEOUT_MS,+ leaseMs = DEFAULT_EVENT_LEASE_MS,+ signal,+} = {}) {while (true) {if (totalDeadline && Date.now() >= totalDeadline) {return { type: 'timeout' };@@ -161,8 +168,15 @@ export async function fetchNextEvent(base, token, { totalDeadline } = {}) {const remaining = totalDeadline? totalDeadline - Date.now(): PER_REQUEST_TIMEOUT_MS;- const slice = Math.min(Math.max(remaining, 1000), PER_REQUEST_TIMEOUT_MS);- const res = await fetch(`${base}/poll?token=${token}&timeout=${slice}&leaseMs=${DEFAULT_EVENT_LEASE_MS}`);+ const slice = Math.min(Math.max(remaining, 1000), perRequestTimeoutMs);+ const query = new URLSearchParams({+ token,+ timeout: String(slice),+ leaseMs: String(leaseMs),+ });+ const normalizedTypes = normalizePollTypes(resolveTypes ? await resolveTypes() : types);+ if (normalizedTypes.length > 0) query.set('types', normalizedTypes.join(','));+ const res = await fetch(`${base}/poll?${query}`, { signal });if (res.status === 401) {const err = new Error('Authentication failed. The server token may have changed.');@@ -202,11 +216,17 @@ export async function augmentEventWithAcceptHandling(event, base, token) {event._acceptResult = { handled: false, mode: 'error', error: err.message };}+ await completeAcceptHandling(event, base, token);+ return event;+}++export async function completeAcceptHandling(event, base, token) {const completionType = completionTypeForAcceptResult(event.type, event._acceptResult);try {await postReply(base, token, {id: event.id,type: completionType,+ sourceEventType: event.type,message: event._acceptResult?.error,file: event._acceptResult?.file,data: event._acceptResult?.carbonize === true ? { carbonize: true } : undefined,@@ -217,7 +237,6 @@ export async function augmentEventWithAcceptHandling(event, base, token) {if (!event._completionAck) {event._completionAck = completionAckForAcceptResult(event.id, completionType, event._acceptResult);}-return event;}@@ -245,9 +264,9 @@ export function printPollEvent(event) {console.log(JSON.stringify(event));}-export async function runPollOnce(base, token, { totalTimeout = 600_000 } = {}) {+export async function runPollOnce(base, token, { totalTimeout = 600_000, types, resolveTypes, perRequestTimeoutMs } = {}) {const deadline = Date.now() + totalTimeout;- const event = await fetchNextEvent(base, token, { totalDeadline: deadline });+ const event = await fetchNextEvent(base, token, { totalDeadline: deadline, types, resolveTypes, perRequestTimeoutMs });await augmentEventWithAcceptHandling(event, base, token);writeCarbonizeBanner(event);printPollEvent(event);@@ -258,11 +277,14 @@ export async function runPollStream(base, token, {ackTimeoutMs = 600_000,ackPollIntervalMs = 400,shouldContinue = () => true,+ types,+ resolveTypes,+ perRequestTimeoutMs,} = {}) {process.stderr.write('[impeccable-poll] stream mode: one JSON object per line on stdout; use --reply while this process stays running\n');while (shouldContinue()) {- const event = await fetchNextEvent(base, token);+ const event = await fetchNextEvent(base, token, { types, resolveTypes, perRequestTimeoutMs });await augmentEventWithAcceptHandling(event, base, token);writeCarbonizeBanner(event);printPollEvent(event);@@ -322,14 +344,17 @@ Modes:Options:--timeout=MS One-shot poll timeout in ms (default: 600000). Ignored in --stream mode+ --types=A,B Lease only these event types--ack-timeout=MS Stream mode: max wait for --reply after generate/steer (default: 600000)--file PATH Attach a source file path to the reply (generate/steer flow)--data JSON Attach a JSON result object to the reply (manual_edit_apply flow). Must be valid JSON--help Show this help messageHarness note:- Default one-shot mode is the portable contract for Claude Code, Codex, and Cursor.- --stream is experimental for harnesses with fast incremental stdout; do not use on Cursor.`);+ Default one-shot mode is the primary contract, including Codex foreground polling.+ Claude Code may run it as a background task; Cursor uses a background terminal with exit notification.+ --stream is retained for harnesses with measured, reliable incremental stdout.+ Do not use --stream on Cursor.`);process.exit(0);}@@ -360,23 +385,30 @@ Harness note:}const streamMode = args.includes('--stream');+ const typesArg = args.find((a) => a.startsWith('--types='));+ const types = normalizePollTypes(typesArg ? typesArg.slice('--types='.length) : null);const ackTimeoutArg = args.find((a) => a.startsWith('--ack-timeout='));const ackTimeoutMs = ackTimeoutArg ? parseInt(ackTimeoutArg.split('=')[1], 10) : 600_000;try {if (streamMode) {- await runPollStream(base, info.token, { ackTimeoutMs });+ await runPollStream(base, info.token, { ackTimeoutMs, types });return;}const timeoutArg = args.find((a) => a.startsWith('--timeout='));const totalTimeout = timeoutArg ? parseInt(timeoutArg.split('=')[1], 10) : 600_000;- await runPollOnce(base, info.token, { totalTimeout });+ await runPollOnce(base, info.token, { totalTimeout, types });} catch (err) {handlePollError(err);}}+export function normalizePollTypes(value) {+ const values = Array.isArray(value) ? value : String(value || '').split(',');+ return [...new Set(values.map((type) => String(type).trim()).filter(Boolean))];+}+// Auto-execute when run directlyconst _running = process.argv[1];if (_running?.endsWith('live-poll.mjs') || _running?.endsWith('live-poll.mjs/')) {diff --git a/.agents/skills/impeccable/scripts/live-server.mjs b/.agents/skills/impeccable/scripts/live-server.mjsindex 5735f2aec..c6e951086 100644--- a/.agents/skills/impeccable/scripts/live-server.mjs+++ b/.agents/skills/impeccable/scripts/live-server.mjs@@ -28,8 +28,10 @@ import {readLiveBrowserScriptParts,resolveLiveBrowserScriptParts,} from './live/browser-script-parts.mjs';-import { createLiveSessionStore } from './live/session-store.mjs';+import { createLiveSessionStore, GENERATION_FENCED_PHASES } from './live/session-store.mjs';+import { runGenerationPreflight } from './live/generation-preflight.mjs';import { validateEvent } from './live/event-validation.mjs';+import { selectAvailablePendingEvent } from './live/poll-lanes.mjs';import { createManualEditRoutes } from './live/manual-edit-routes.mjs';import { LIVE_COMMANDS } from './live/vocabulary.mjs';import {@@ -63,6 +65,10 @@ const DESIGN_MD_PATH = PROJECT_CONTEXT.designPath: null;const DEFAULT_POLL_TIMEOUT = 600_000; // 10 min — agent re-polls on timeout anywayconst SSE_HEARTBEAT_INTERVAL = 30_000; // keepalive ping every 30s+// The browser checkpoints for several unrelated reasons (see checkpointPayload+// in live-browser.js). Only these two report that variant availability changed,+// and only they may drive variant_progress / the *_reviewable phases.+const VARIANT_PROGRESS_CHECKPOINT_REASONS = new Set(['variants_progress', 'variants_ready']);// ---------------------------------------------------------------------------// Port detection@@ -156,29 +162,206 @@ function restorePendingEventsFromStore() {}}-function findAvailablePendingEvent(now = Date.now()) {- for (const entry of state.pendingEvents) {- if (entry.leaseUntil && entry.leaseUntil > now) continue;- return entry;- }- return null;+function findAvailablePendingEvent(now = Date.now(), types = null) {+ return selectAvailablePendingEvent(state.pendingEvents, { now, types });}-function leaseEvent(entry, leaseMs) {+async function leaseEvent(entry, leaseMs) {+ // Claim the entry before awaiting anything. prepareGenerateEventForLease+ // yields to the event loop, and selectAvailablePendingEvent only skips+ // entries whose lease is in the future — an unclaimed entry would be handed+ // to a second poll in that window and generated twice.+ entry.leaseUntil = Date.now() + leaseMs;+ await prepareGenerateEventForLease(entry);if (!entry.event?.id) {const idx = state.pendingEvents.indexOf(entry);if (idx !== -1) state.pendingEvents.splice(idx, 1);return entry.event;}+ // Re-stamp so the lease window starts when the agent actually receives the+ // work, not when scaffolding began.entry.leaseUntil = Date.now() + leaseMs;+ recordGenerateDelivery(entry);scheduleLeaseFlush();broadcastAgentPollingIfChanged();return entry.event;}-function acknowledgePendingEvent(id) {+function recordGenerateDelivery(entry) {+ const event = entry?.event;+ if (!event || event.type !== 'generate' || event.generationReadyAt) return;+ const at = Date.now();+ entry.event = { ...event, generationReadyAt: at };+ state.sessionStore?.appendEvent(entry.event);+ recordAgentPhase(event.id, 'generation_ready', { at });+}++async function prepareGenerateEventForLease(entry) {+ const event = entry?.event;+ if (!event || event.type !== 'generate' || event.scaffoldAttempted) return;++ recordAgentPhase(event.id, 'picked_up');+ recordAgentPhase(event.id, 'scaffolding');+ const result = await runGenerationPreflight(event, {+ cwd: process.cwd(),+ scriptsDir: __dirname,+ });+ entry.event = {+ ...event,+ scaffoldAttempted: true,+ scaffoldDurationMs: result.durationMs ?? null,+ ...(result.ok ? { scaffold: result.scaffold } : { scaffoldError: result.error || result.reason }),+ };+ state.sessionStore?.appendEvent(entry.event);+ recordAgentPhase(event.id, result.ok ? 'source_ready' : 'scaffold_fallback', {+ durationMs: result.durationMs ?? null,+ previewMode: result.scaffold?.previewMode || 'source',+ });+}++function recordAgentPhase(id, phase, details = {}) {+ if (!id) return;+ const event = {+ type: 'agent_phase',+ id,+ phase,+ at: Date.now(),+ ...details,+ };+ state.sessionStore?.appendEvent(event);+ broadcast(event);+}++/**+ * Detect a browser that missed the generation `done` broadcast.+ *+ * The preflight scaffold write triggers a framework full-reload (Astro reloads+ * the page for any .astro edit). If the agent's variant write + `done` land+ * while the browser is mid-reload, the new page misses both the second HMR+ * reload and the SSE `done` — it resumes from the scaffold-only source and+ * sits in GENERATING at 0/N forever. That resumed page always checkpoints+ * (`browser_resumed`), so a checkpoint claiming "still generating, variants+ * missing" for a session whose generation already completed is direct+ * evidence of the miss. Rebuild the `done` payload from the snapshot so the+ * caller can re-broadcast it; the browser's done handler is idempotent and+ * falls back to injecting variants from source.+ *+ * Keys on the store's monotone `generationCompletedAt`, not `phase` — the+ * behind checkpoint itself regresses `phase` to `generating`, and a browser+ * that misses the redelivered `done` too (another reload) must still trigger+ * redelivery from its next checkpoint.+ */+function detectMissedGenerationCompletion(event) {+ if (!event?.id || event.type !== 'checkpoint') return null;+ if (event.phase !== 'generating') return null;+ if (!variantCountLooksBehind(event.arrivedVariants, event.expectedVariants)) return null;+ if (!state.sessionStore) return null;+ let snapshot = null;+ try {+ snapshot = state.sessionStore.getSnapshot(event.id);+ } catch {+ return null;+ }+ return missedCompletionFromSnapshot(snapshot);+}++function variantCountLooksBehind(arrivedValue, expectedValue) {+ const arrived = Number(arrivedValue) || 0;+ const expected = Number(expectedValue) || 0;+ return arrived <= 0 || (expected > 0 && arrived < expected);+}++function missedCompletionFromSnapshot(snapshot) {+ if (!snapshot?.id || !snapshot.generationCompletedAt) return null;+ if (snapshot.generationCanceled) return null;+ // Accept/discard already underway: the browser is no longer waiting on+ // generation, and a late `done` there would collide with teardown.+ if (GENERATION_FENCED_PHASES.has(snapshot.phase)) return null;+ const file = snapshot.sourceFile || snapshot.previewFile;+ if (!file) return null;+ return {+ type: 'done',+ id: snapshot.id,+ file,+ sourceFile: snapshot.sourceFile || undefined,+ previewFile: snapshot.previewFile || undefined,+ previewMode: snapshot.previewMode || undefined,+ redelivered: true,+ };+}++function recordGenerationCheckpoint(event) {+ if (!event?.id || event.type !== 'checkpoint') return;+ if (generationIsFenced(event.id)) return;+ // Only checkpoints that report a change in variant availability are+ // generation progress. The browser also checkpoints for durability on Tune+ // slider drags, resumes, and anchor recovery; treating those as progress+ // echoed `variant_progress` straight back to the browser that sent it, which+ // remounts the component preview mid-drag (reverting the user's live param+ // edit and detaching the popover's element), and permanently latched the+ // *_reviewable phases from the wrong trigger, corrupting generation timings.+ if (!VARIANT_PROGRESS_CHECKPOINT_REASONS.has(event.reason)) return;+ const arrived = Number(event.arrivedVariants) || 0;+ const expected = Number(event.expectedVariants) || 0;+ if (arrived <= 0 || expected <= 0) return;+ const previewMode = event.previewMode || 'source';+ const previewFile = event.previewFile || event.file;+ if (previewFile) {+ broadcast({+ type: 'variant_progress',+ id: event.id,+ file: previewFile,+ sourceFile: event.sourceFile || (previewMode === 'source' ? previewFile : undefined),+ previewFile,+ previewMode,+ arrivedVariants: arrived,+ expectedVariants: expected,+ publicationKind: event.publicationKind || 'variants',+ });+ }+ const details = {+ arrivedVariants: arrived,+ expectedVariants: expected,+ checkpointReason: event.reason || null,+ };+ const at = Date.now();+ if (!generationPhaseAlreadyRecorded(event.id, 'first_reviewable')) {+ recordAgentPhase(event.id, 'first_reviewable', { ...details, at });+ }+ if (arrived >= 2 && expected >= 3 && !generationPhaseAlreadyRecorded(event.id, 'second_reviewable')) {+ recordAgentPhase(event.id, 'second_reviewable', { ...details, at });+ }+ if (arrived >= expected && !generationPhaseAlreadyRecorded(event.id, 'all_variants_ready')) {+ recordAgentPhase(event.id, 'all_variants_ready', { ...details, at });+ }+}++function generationIsFenced(id) {+ if (!state.sessionStore || !id) return false;+ try {+ const snapshot = state.sessionStore.getSnapshot(id, { includeCompleted: true });+ return snapshot?.generationCanceled === true;+ } catch {+ return false;+ }+}++function generationPhaseAlreadyRecorded(id, phase) {+ if (!state.sessionStore) return false;+ try {+ const snapshot = state.sessionStore.getSnapshot(id, { includeCompleted: true });+ return !!snapshot?.generationTimings?.[phase];+ } catch {+ return false;+ }+}++function acknowledgePendingEvent(id, sourceEventType) {if (!id) return false;- const idx = state.pendingEvents.findIndex((entry) => entry.event?.id === id);+ const idx = state.pendingEvents.findIndex((entry) => (+ entry.event?.id === id+ && (!sourceEventType || entry.event?.type === sourceEventType)+ ));if (idx === -1) return false;const acknowledged = state.pendingEvents[idx].event;state.pendingEvents.splice(idx, 1);@@ -187,9 +370,39 @@ function acknowledgePendingEvent(id) {return acknowledged;}-function findPendingEventById(id) {+function releasePendingEvent(id, sourceEventType) {+ const entry = state.pendingEvents.find((item) => (+ item.event?.id === id+ && (!sourceEventType || item.event?.type === sourceEventType)+ ));+ if (!entry) return null;+ entry.leaseUntil = 0;+ scheduleLeaseFlush();+ return entry.event;+}++function retirePendingGeneration(id) {+ if (!id) return 0;+ let retired = 0;+ for (let index = state.pendingEvents.length - 1; index >= 0; index -= 1) {+ const event = state.pendingEvents[index]?.event;+ if (event?.id !== id || event.type !== 'generate') continue;+ state.pendingEvents.splice(index, 1);+ retired += 1;+ }+ if (retired > 0) {+ scheduleLeaseFlush();+ broadcastAgentPollingIfChanged();+ }+ return retired;+}++function findPendingEventById(id, sourceEventType) {if (!id) return null;- const entry = state.pendingEvents.find((item) => item.event?.id === id);+ const entry = state.pendingEvents.find((item) => (+ item.event?.id === id+ && (!sourceEventType || item.event?.type === sourceEventType)+ ));return entry?.event || null;}@@ -198,7 +411,7 @@ function summarizePendingEventForStatus(entry) {const summary = {id: event.id,type: event.type,- leased: !!(entry.leaseUntil && entry.leaseUntil > Date.now()),+ leased: isLeased(entry),leaseUntil: entry.leaseUntil || null,};if (event.type === 'manual_edit_apply') {@@ -224,7 +437,13 @@ function summarizeActiveSessionForClient(snapshot = {}) {arrivedVariants: snapshot.arrivedVariants ?? 0,visibleVariant: snapshot.visibleVariant ?? null,checkpointRevision: snapshot.checkpointRevision ?? 0,+ browserCheckpointRevision: snapshot.browserCheckpointRevision ?? snapshot.checkpointRevision ?? 0,+ publicationCheckpointRevision: snapshot.publicationCheckpointRevision ?? 0,paramValues: snapshot.paramValues || {},+ generationPhase: snapshot.generationPhase ?? null,+ generationCompletedAt: snapshot.generationCompletedAt ?? null,+ generationCanceled: snapshot.generationCanceled === true,+ cancelReason: snapshot.cancelReason ?? null,};}@@ -269,24 +488,46 @@ function scheduleLeaseFlush() {function flushPendingPolls() {let changed = false;while (state.pendingPolls.length > 0) {- const entry = findAvailablePendingEvent();+ let pollIndex = -1;+ let entry = null;+ for (let index = 0; index < state.pendingPolls.length; index += 1) {+ const candidate = findAvailablePendingEvent(Date.now(), state.pendingPolls[index].types);+ if (!candidate) continue;+ pollIndex = index;+ entry = candidate;+ break;+ }if (!entry) {scheduleLeaseFlush();broadcastAgentPollingIfChanged();return;}- const poll = state.pendingPolls.shift();- poll.resolve(leaseEvent(entry, poll.leaseMs));+ const [poll] = state.pendingPolls.splice(pollIndex, 1);+ // leaseEvent is async (it may scaffold source), but it claims the entry+ // synchronously, so the next loop iteration will not re-select it. Resolve+ // the poll when the lease settles rather than awaiting here, so one slow+ // scaffold never delays the other parked polls. On the exceptional failure+ // path, answer `timeout` so the agent re-polls; the claim stays until the+ // lease expires, which keeps a deterministic failure from hot-looping.+ leaseEvent(entry, poll.leaseMs).then(poll.resolve, (error) => {+ console.error('[live] lease failed for ' + (entry.event?.id || 'unknown') + ': ' + (error?.message || error));+ poll.resolve({ type: 'timeout' });+ });changed = true;}scheduleLeaseFlush();if (changed) broadcastAgentPollingIfChanged();}+function isLeased(entry) {+ return !!(entry?.leaseUntil && entry.leaseUntil > Date.now());+}+function agentPollingConnected() {- const now = Date.now();- return state.pendingPolls.length > 0- || state.pendingEvents.some((entry) => entry.leaseUntil && entry.leaseUntil > now);+ // A leased event only proves that a poll returned once. The foreground task+ // may have ended immediately afterward, so only an actively waiting poll is+ // evidence that steering can wake the task right now.+ return state.pendingPolls.length > 0;}function broadcastAgentPollingIfChanged() {@@ -689,6 +930,16 @@ function createRequestHandler({ detectScript, liveScriptParts }) {res.end(JSON.stringify({ error }));return;}+ if (msg.type === 'agent_phase') {+ recordAgentPhase(msg.id, msg.phase, {+ ...(Number.isFinite(msg.durationMs) ? { durationMs: msg.durationMs } : {}),+ owner: typeof msg.owner === 'string' ? msg.owner : undefined,+ });+ res.writeHead(200, { 'Content-Type': 'application/json' });+ res.end(JSON.stringify({ ok: true }));+ return;+ }+ const missedCompletion = detectMissedGenerationCompletion(msg);if (state.sessionStore && msg.id) {try {state.sessionStore.appendEvent(msg);@@ -698,6 +949,11 @@ function createRequestHandler({ detectScript, liveScriptParts }) {return;}}+ if (msg.type === 'accept' || msg.type === 'discard') {+ retirePendingGeneration(msg.id);+ }+ recordGenerationCheckpoint(msg);+ if (missedCompletion) broadcast(missedCompletion);if (msg.type === 'exit') {cleanupSvelteComponentSessionsBeforeExit();}@@ -738,6 +994,12 @@ function createRequestHandler({ detectScript, liveScriptParts }) {// Agent poll endpoints (unchanged from WS version)// ---------------------------------------------------------------------------+function parsePollTypes(value) {+ if (!value) return null;+ const types = String(value).split(',').map((type) => type.trim()).filter(Boolean);+ return types.length > 0 ? new Set(types) : null;+}+function handlePollGet(req, res, url) {const token = url.searchParams.get('token');if (token !== state.token) {@@ -748,13 +1010,25 @@ function handlePollGet(req, res, url) {state.lastPollAt = Date.now();const timeout = parseInt(url.searchParams.get('timeout') || DEFAULT_POLL_TIMEOUT, 10);const leaseMs = parseInt(url.searchParams.get('leaseMs') || '30000', 10);- const available = findAvailablePendingEvent();+ const types = parsePollTypes(url.searchParams.get('types'));+ const available = findAvailablePendingEvent(Date.now(), types);if (available) {- res.writeHead(200, { 'Content-Type': 'application/json' });- res.end(JSON.stringify(leaseEvent(available, leaseMs)));+ // Do not await inline: leaseEvent may scaffold source, and this handler runs+ // on the server's only thread. The client can disconnect during that window,+ // so check the socket before replying.+ leaseEvent(available, leaseMs).then((event) => {+ if (res.writableEnded || res.destroyed) return;+ res.writeHead(200, { 'Content-Type': 'application/json' });+ res.end(JSON.stringify(event));+ }, (error) => {+ console.error('[live] lease failed for ' + (available.event?.id || 'unknown') + ': ' + (error?.message || error));+ if (res.writableEnded || res.destroyed) return;+ res.writeHead(200, { 'Content-Type': 'application/json' });+ res.end(JSON.stringify({ type: 'timeout' }));+ });return;}- const poll = { resolve, leaseMs };+ const poll = { resolve, leaseMs, types };const timer = setTimeout(() => {const idx = state.pendingPolls.indexOf(poll);if (idx !== -1) state.pendingPolls.splice(idx, 1);@@ -783,12 +1057,15 @@ function sessionFileMetadataFromPollReply(file) {if (!file || typeof file !== 'string') return { file };const normalized = file.split(path.sep).join('/');const base = { file: normalized };- if (!normalized.endsWith('/manifest.json') && normalized !== 'manifest.json') return base;- if (!normalized.includes('node_modules/.impeccable-live/') && !normalized.includes('src/lib/impeccable/')) return base;+ const metadataFile = normalized;+ if (!metadataFile.endsWith('/manifest.json') && metadataFile !== 'manifest.json') return base;+ if (!metadataFile.includes('node_modules/.impeccable-live/')+ && !metadataFile.includes('src/lib/impeccable/')+ && !metadataFile.includes('/.impeccable-live/')) return base;let full;try {- full = path.resolve(process.cwd(), normalized);+ full = path.resolve(process.cwd(), metadataFile);const rel = path.relative(process.cwd(), full);if (!rel || rel.startsWith('..') || path.isAbsolute(rel)) return base;} catch {@@ -797,18 +1074,47 @@ function sessionFileMetadataFromPollReply(file) {try {const manifest = JSON.parse(fs.readFileSync(full, 'utf-8'));- if (manifest?.previewMode !== 'svelte-component' || !manifest.sourceFile) return base;+ if (manifest?.previewMode !== 'svelte-component'+ || !manifest.sourceFile) return base;return {file: String(manifest.sourceFile).split(path.sep).join('/'),sourceFile: String(manifest.sourceFile).split(path.sep).join('/'),previewFile: normalized,- previewMode: 'svelte-component',+ previewMode: manifest.previewMode,};} catch {return base;}}+function inferSourceEventType(msg = {}, pendingEvents = state.pendingEvents) {+ const entriesForId = pendingEvents.filter((entry) => entry.event?.id === msg.id);+ const pendingTypes = new Set(entriesForId.map((entry) => entry.event?.type));+ if (msg.type === 'discarded' || msg.type === 'discard') return 'discard';+ if (msg.type === 'complete') {+ if (pendingTypes.has('carbonize_cleanup')) return 'carbonize_cleanup';+ return pendingTypes.has('accept') ? 'accept' : (pendingTypes.has('generate') ? 'generate' : undefined);+ }+ if (msg.type === 'steer_done') return 'steer';+ // `agent_done` can be the automatic acknowledgement for a carbonize Accept.+ // New pollers send sourceEventType explicitly; default to generate only for+ // older callers so a late worker cannot acknowledge a queued Accept.+ if (msg.type === 'agent_done' || msg.type === 'done') return 'generate';+ // `error` is reference/live.md's documented failure reply, and parseReplyArgs+ // never sets sourceEventType on it (the poller is a fresh process that cannot+ // know what it leased). Returning undefined here makes acknowledgePendingEvent+ // match *any* event for this id: a stale generate worker's failure silently+ // consumed the user's queued Accept, which was then never delivered to any+ // agent and left the browser in SAVING forever. Attribute the failure to the+ // event this agent actually holds a lease on, and otherwise to `generate` —+ // never to a wildcard. If that generate was already retired by an Accept, the+ // ack simply finds no match, which is the correct outcome for a stale reply.+ if (msg.type === 'error') {+ return entriesForId.find(isLeased)?.event?.type || 'generate';+ }+ return undefined;+}+function handlePollPost(req, res) {let body = '';req.on('data', (c) => { body += c; });@@ -869,7 +1175,23 @@ function handlePollPost(req, res) {res.end(JSON.stringify({ error: 'stale_manual_edit_apply_reply', ...rollback }));return;}- const pendingEventBeforeAck = findPendingEventById(msg.id);+ const sourceEventType = msg.sourceEventType || inferSourceEventType(msg);+ if (msg.type === 'retry') {+ const releasedEvent = releasePendingEvent(msg.id, sourceEventType);+ if (!releasedEvent) {+ res.writeHead(msg.id ? 404 : 400, { 'Content-Type': 'application/json' });+ res.end(JSON.stringify({+ error: msg.id ? 'unknown_poll_retry_id' : 'missing_poll_retry_id',+ id: msg.id,+ }));+ return;+ }+ flushPendingPolls();+ res.writeHead(200, { 'Content-Type': 'application/json' });+ res.end(JSON.stringify({ ok: true, released: true }));+ return;+ }+ const pendingEventBeforeAck = findPendingEventById(msg.id, sourceEventType);if (pendingEventBeforeAck?.type === 'steer' && msg.type === 'steer_done'&& !msg.file && !(typeof msg.message === 'string' && msg.message.trim())) {res.writeHead(400, { 'Content-Type': 'application/json' });@@ -879,7 +1201,7 @@ function handlePollPost(req, res) {}));return;}- const acknowledgedEvent = acknowledgePendingEvent(msg.id);+ const acknowledgedEvent = acknowledgePendingEvent(msg.id, sourceEventType);let skipJournalReply = false;let existingSession = null;if (!acknowledgedEvent && state.sessionStore && msg.id) {@@ -1083,7 +1405,10 @@ if (args.includes('--background')) {process.exit(0);}} catch { /* not ready yet */ }- await new Promise(r => setTimeout(r, 200));+ // The detached child is typically listening in 35-45ms. A 200ms polling+ // floor dominated configured cold Live startup; poll cheaply and return+ // as soon as the child has written its ready record.+ await new Promise(r => setTimeout(r, 5));}console.error('Timed out waiting for live server to start.');process.exit(1);diff --git a/.agents/skills/impeccable/scripts/live-status.mjs b/.agents/skills/impeccable/scripts/live-status.mjsindex f7e464999..dc98b7386 100644--- a/.agents/skills/impeccable/scripts/live-status.mjs+++ b/.agents/skills/impeccable/scripts/live-status.mjs@@ -37,15 +37,19 @@ export async function statusCli() {pendingEvents: server.pendingEvents,} : null,activeSessions: server?.activeSessions || activeSessions,- recoveryHint: manualApply- ? manualApplyResumeHint(manualApply)- : server- ? 'Run live-poll.mjs to continue pending work, or live-complete.mjs --id <session> after manual cleanup.'- : 'Start live-server.mjs to requeue pending durable events, then run live-poll.mjs.',+ recoveryHint: recoveryHint({ server, manualApply }),};console.log(JSON.stringify(payload, null, 2));}+function recoveryHint({ server, manualApply }) {+ if (manualApply) return manualApplyResumeHint(manualApply);+ if (server) {+ return 'Run live-poll.mjs to continue pending work, or live-complete.mjs --id <session> after manual cleanup.';+ }+ return 'Start live-server.mjs to requeue pending durable events, then run live-poll.mjs.';+}+function findPendingManualApply(server, activeSessions) {const fromServer = server?.pendingEvents?.find((event) => event?.type === 'manual_edit_apply');if (fromServer) return fromServer;diff --git a/.agents/skills/impeccable/scripts/live-wrap.mjs b/.agents/skills/impeccable/scripts/live-wrap.mjsindex 438c01b68..48d7f7683 100644--- a/.agents/skills/impeccable/scripts/live-wrap.mjs+++ b/.agents/skills/impeccable/scripts/live-wrap.mjs@@ -160,11 +160,29 @@ The agent should insert variant HTML at insertLine.`);if (filtered.length === 1) {match = filtered[0];} else if (filtered.length === 0) {- // Source uses dynamic content (`<h1>{title}</h1>` etc.) so the- // browser-side textContent doesn't appear literally in source. Fall- // back to first-match rather than refusing — this is the same- // behavior unmodified callers see, just preserved.- match = candidates[0];+ const normalizedText = String(text).replace(/\s+/g, ' ').trim();+ if (normalizedText.length < 8) {+ // Very short labels cannot disambiguate siblings reliably. Preserve+ // the legacy behavior for these low-information picker events.+ match = candidates[0];+ } else {+ // Rendered text that is absent from every candidate usually means+ // the source uses expressions or component props. Picking the first+ // same-class sibling silently edits the wrong instance (observed on+ // Astro result cards), so stop and surface every candidate instead.+ console.error(JSON.stringify({+ error: 'element_ambiguous',+ fallback: 'agent-driven',+ reason: 'rendered_text_not_in_source',+ file: path.relative(process.cwd(), targetFile),+ candidates: candidates.map((c) => ({+ startLine: c.startLine + 1,+ endLine: c.endLine + 1,+ })),+ hint: 'Rendered text does not occur in any matching source branch. The element may use dynamic props or expressions; inspect the candidates and wrap the intended instance manually.',+ }));+ process.exit(1);+ }} else {// Multiple candidates ALSO match the text. Truly ambiguous — refuse// rather than pick wrong, and hand the agent the candidate locations@@ -269,6 +287,7 @@ The agent should insert variant HTML at insertLine.`);const originalIndented = reindentOriginal(' ');const relTargetFile = path.relative(process.cwd(), targetFile).split(path.sep).join('/');const useSvelteComponent = shouldUseSvelteComponentInjection(targetFile);+ const useFrameworkComponent = useSvelteComponent;// Wrapper attributes differ by syntax. HTML allows plain string attrs;// JSX requires object-literal style and parses string attrs as HTML (which@@ -288,7 +307,7 @@ The agent should insert variant HTML at insertLine.`);// replacement range to include the wrapper's `<div>` open / close lines// so the entire scaffold gets removed cleanly.const wrapperLines = isJsx ? [- indent + '<div data-impeccable-variants="' + id + '" data-impeccable-variant-count="' + count + '" ' + styleContents + '>',+ indent + '<div data-impeccable-variants="' + id + '" data-impeccable-variant-count="' + count + '"' + ' ' + styleContents + '>',indent + ' ' + commentSyntax.open + ' impeccable-variants-start ' + id + ' ' + commentSyntax.close,indent + ' ' + commentSyntax.open + ' Original ' + commentSyntax.close,indent + ' <div data-impeccable-variant="original">',@@ -299,7 +318,7 @@ The agent should insert variant HTML at insertLine.`);indent + '</div>',] : [indent + commentSyntax.open + ' impeccable-variants-start ' + id + ' ' + commentSyntax.close,- indent + '<div data-impeccable-variants="' + id + '" data-impeccable-variant-count="' + count + '" ' + styleContents + '>',+ indent + '<div data-impeccable-variants="' + id + '" data-impeccable-variant-count="' + count + '"' + ' ' + styleContents + '>',indent + ' ' + commentSyntax.open + ' Original ' + commentSyntax.close,indent + ' <div data-impeccable-variant="original">',originalIndented,@@ -356,15 +375,18 @@ The agent should insert variant HTML at insertLine.`);const outputRelFile = path.relative(process.cwd(), outputFile).split(path.sep).join('/');const svelteComponentAuthoring = useSvelteComponent ? buildSvelteComponentCssAuthoring(count) : null;+ const componentSession = svelteSession;+ const componentPreviewMode = useSvelteComponent ? 'svelte-component' : undefined;+ const previewMode = componentPreviewMode;console.log(JSON.stringify({file: outputRelFile,- sourceFile: useSvelteComponent ? relTargetFile : undefined,- previewMode: useSvelteComponent ? 'svelte-component' : undefined,- componentDir: svelteSession?.componentDir,- propContract: svelteSession?.propContract,- sourceStartLine: useSvelteComponent ? startLine + 1 : undefined,- sourceEndLine: useSvelteComponent ? endLine + 1 : undefined,+ sourceFile: useFrameworkComponent ? relTargetFile : undefined,+ previewMode,+ componentDir: componentSession?.componentDir,+ propContract: componentSession?.propContract,+ sourceStartLine: useFrameworkComponent ? startLine + 1 : undefined,+ sourceEndLine: useFrameworkComponent ? endLine + 1 : undefined,startLine: outputStartLine, // 1-indexed for the agent// wrapperLines is an array but one element (the original-content slot)// is a `\n`-joined multi-line string, so the actual file-row count is@@ -374,10 +396,10 @@ The agent should insert variant HTML at insertLine.`);endLine: outputEndLine, // 1-indexedinsertLine, // 1-indexed: where variants gocommentSyntax: commentSyntax,- styleMode: useSvelteComponent ? 'svelte-component' : styleMode.mode,- styleTag: useSvelteComponent ? null : styleMode.styleTag,- cssSelectorPrefixExamples: useSvelteComponent ? [] : buildCssSelectorPrefixExamples(styleMode.mode, count),- cssAuthoring: useSvelteComponent ? svelteComponentAuthoring : buildCssAuthoring(styleMode, count),+ styleMode: componentPreviewMode || styleMode.mode,+ styleTag: useFrameworkComponent ? null : styleMode.styleTag,+ cssSelectorPrefixExamples: useFrameworkComponent ? [] : buildCssSelectorPrefixExamples(styleMode.mode, count),+ cssAuthoring: svelteComponentAuthoring || buildCssAuthoring(styleMode, count),originalLineCount: originalLines.length,}));}diff --git a/.agents/skills/impeccable/scripts/live.mjs b/.agents/skills/impeccable/scripts/live.mjsindex e0bd1ad24..b21a71cc4 100644--- a/.agents/skills/impeccable/scripts/live.mjs+++ b/.agents/skills/impeccable/scripts/live.mjs@@ -10,7 +10,7 @@** After this, the agent's only remaining steps are:* - Open the project's live dev/preview URL in the browser (optional, if browser automation exists)—not `serverPort`; that port is the Impeccable helper for /live.js and /poll- * - Enter the poll loop: `node live-poll.mjs`+ * - Enter the harness-native poll loop: `node live-poll.mjs`** Usage:* node live.mjs # Prepare everything, print JSON, exit@@ -40,6 +40,7 @@ Prepare everything for live variant mode in a single command:- Starts (or reuses) the live server in the background- Injects the browser script tag- Reads PRODUCT.md / DESIGN.md for project context+ - Prepares the harness-native foreground/background poll loop- In monorepos, choose a child app first; --target <path> is the fallback/manual pathOn success, prints a JSON blob with:diff --git a/.agents/skills/impeccable/scripts/live/completion.mjs b/.agents/skills/impeccable/scripts/live/completion.mjsindex 986773066..6f539336d 100644--- a/.agents/skills/impeccable/scripts/live/completion.mjs+++ b/.agents/skills/impeccable/scripts/live/completion.mjs@@ -1,9 +1,18 @@+// A preview whose variants live in component modules rather than in the user's+// source. These leave no markers in the real file, so a failed accept gives the+// agent nothing to hand-edit and must be reported as a failure rather than+// reference/live.md's manual-cleanup handoff. Kept as a set: any future+// component-module preview mode belongs here the day it lands.+const PREVIEW_MODES_WITHOUT_SOURCE_MARKERS = new Set([+ 'svelte-component',+]);+export function completionTypeForAcceptResult(eventType, acceptResult) {if (eventType === 'discard') return acceptResult?.handled === true ? 'discarded' : 'error';if (acceptResult?.handled === true && acceptResult?.carbonize === true) return 'agent_done';if (acceptResult?.handled === true) return 'complete';if (acceptResult?.mode === 'error') return 'error';- if (eventType === 'accept' && acceptResult?.previewMode === 'svelte-component') return 'error';+ if (eventType === 'accept' && PREVIEW_MODES_WITHOUT_SOURCE_MARKERS.has(acceptResult?.previewMode)) return 'error';return 'agent_done';}diff --git a/.agents/skills/impeccable/scripts/live/event-validation.mjs b/.agents/skills/impeccable/scripts/live/event-validation.mjsindex 0897b1317..122c29836 100644--- a/.agents/skills/impeccable/scripts/live/event-validation.mjs+++ b/.agents/skills/impeccable/scripts/live/event-validation.mjs@@ -118,6 +118,15 @@ export function validateEvent(msg) {return 'checkpoint: paramValues must be an object';}return null;+ case 'agent_phase':+ if (!isValidId(msg.id)) return 'agent_phase: missing or malformed id';+ if (typeof msg.phase !== 'string' || !/^[a-z][a-z0-9_]{1,63}$/.test(msg.phase)) {+ return 'agent_phase: missing or malformed phase';+ }+ if (msg.durationMs !== undefined && (!Number.isFinite(msg.durationMs) || msg.durationMs < 0)) {+ return 'agent_phase: durationMs must be a non-negative number';+ }+ return null;case 'exit':return null;case 'prefetch':@@ -131,6 +140,12 @@ export function validateEvent(msg) {if (msg.message.length > 4000) return 'steer: message too long';if (msg.pageUrl !== undefined && typeof msg.pageUrl !== 'string') return 'steer: pageUrl must be string';return null;+ case 'carbonize_cleanup':+ if (!isValidId(msg.id)) return 'carbonize_cleanup: missing or malformed id';+ if (!isValidId(msg.sessionId)) return 'carbonize_cleanup: missing or malformed sessionId';+ if (!msg.file || typeof msg.file !== 'string') return 'carbonize_cleanup: missing file';+ if (!isValidVariantId(String(msg.variantId))) return 'carbonize_cleanup: missing or malformed variantId';+ return null;default:return 'Unknown event type: ' + msg.type;}diff --git a/.agents/skills/impeccable/scripts/live/generation-preflight.mjs b/.agents/skills/impeccable/scripts/live/generation-preflight.mjsnew file mode 100644index 000000000..07a5e957e--- /dev/null+++ b/.agents/skills/impeccable/scripts/live/generation-preflight.mjs@@ -0,0 +1,102 @@+import { execFile } from 'node:child_process';+import path from 'node:path';+import { promisify } from 'node:util';++const execFileAsync = promisify(execFile);+const PREFLIGHT_TIMEOUT_MS = 15_000;++export function buildGenerationPreflight(event, scriptsDir) {+ if (!event || event.type !== 'generate' || !event.id) return null;++ const isInsert = event.mode === 'insert';+ const target = isInsert ? insertTarget(event) : replaceTarget(event);+ if (!target.elementId && !target.classes) return null;++ const script = path.join(scriptsDir, isInsert ? 'live-insert.mjs' : 'live-wrap.mjs');+ const args = [script, '--id', event.id, '--count', String(event.count || 3)];+ if (isInsert) args.push('--position', target.position);+ if (target.elementId) args.push('--element-id', target.elementId);+ if (target.classes) args.push('--classes', target.classes);+ if (target.tag) args.push('--tag', target.tag);+ if (target.text) args.push('--text', target.text);+ if (!isInsert && event.pageUrl) args.push('--page-url', event.pageUrl);+ return { script, args, mode: isInsert ? 'insert' : 'replace' };+}++/**+ * Scaffold the source for a generate event before handing it to an agent.+ *+ * Async on purpose. This spawns `live-wrap.mjs`, which walks the project's+ * source tree and can take seconds (measured at ~7.6s on a large repo when the+ * element is not found, with a 15s ceiling). The live server is single-threaded+ * and calls this while leasing a poll, so a synchronous spawn froze the whole+ * server for that entire window: Accept and Discard POSTs, SSE progress+ * broadcasts, and every other poll stalled behind it.+ */+export async function runGenerationPreflight(event, {+ cwd = process.cwd(),+ scriptsDir,+ execFileImpl = execFileAsync,+ timeoutMs = PREFLIGHT_TIMEOUT_MS,+} = {}) {+ const command = buildGenerationPreflight(event, scriptsDir);+ if (!command) {+ return { ok: false, skipped: true, reason: 'insufficient_locator' };+ }++ const startedAt = performance.now();+ try {+ const { stdout } = await execFileImpl(process.execPath, command.args, {+ cwd,+ encoding: 'utf-8',+ timeout: timeoutMs,+ });+ const line = String(stdout).trim().split('\n').filter(Boolean).pop();+ if (!line) throw new Error('preflight returned no scaffold metadata');+ return {+ ok: true,+ mode: command.mode,+ durationMs: performance.now() - startedAt,+ scaffold: JSON.parse(line),+ };+ } catch (error) {+ return {+ ok: false,+ mode: command.mode,+ durationMs: performance.now() - startedAt,+ error: compactError(error),+ };+ }+}++function replaceTarget(event) {+ return normalizeTarget(event.element || {});+}++function insertTarget(event) {+ return {+ ...normalizeTarget(event.insert?.anchor || {}),+ position: event.insert?.position === 'before' ? 'before' : 'after',+ };+}++function normalizeTarget(target) {+ const classes = Array.isArray(target.classes)+ ? target.classes.join(' ')+ : String(target.classes || '').trim();+ const text = typeof target.textContent === 'string'+ ? target.textContent.trim().slice(0, 80)+ : '';+ return {+ elementId: target.id || target.elementId || undefined,+ classes: classes || undefined,+ tag: target.tagName || target.tag || undefined,+ text: text || undefined,+ };+}++function compactError(error) {+ const stderr = error?.stderr ? String(error.stderr).trim() : '';+ const message = stderr.split('\n').filter(Boolean).pop() || error?.message || 'preflight failed';+ return String(message).slice(0, 500);+}diff --git a/.agents/skills/impeccable/scripts/live/poll-lanes.mjs b/.agents/skills/impeccable/scripts/live/poll-lanes.mjsnew file mode 100644index 000000000..65f20a87a--- /dev/null+++ b/.agents/skills/impeccable/scripts/live/poll-lanes.mjs@@ -0,0 +1,14 @@+export function eventPriority(event = {}) {+ if (event.type === 'accept' || event.type === 'discard' || event.type === 'exit') return 0;+ if (event.type === 'manual_edit_apply' || event.type === 'steer' || event.type === 'carbonize_cleanup') return 1;+ if (event.type === 'generate') return 2;+ return 3;+}++export function selectAvailablePendingEvent(entries, { now = Date.now(), types = null } = {}) {+ const allowed = types instanceof Set ? types : (Array.isArray(types) ? new Set(types) : null);+ return entries+ .filter((entry) => !(entry.leaseUntil && entry.leaseUntil > now))+ .filter((entry) => !allowed || allowed.has(entry.event?.type))+ .sort((a, b) => eventPriority(a.event) - eventPriority(b.event) || a.seq - b.seq)[0] || null;+}diff --git a/.agents/skills/impeccable/scripts/live/session-store.mjs b/.agents/skills/impeccable/scripts/live/session-store.mjsindex affba67c9..9d20341dd 100644--- a/.agents/skills/impeccable/scripts/live/session-store.mjs+++ b/.agents/skills/impeccable/scripts/live/session-store.mjs@@ -1,24 +1,26 @@import fs from 'node:fs';import path from 'node:path';-import { getLegacyLiveSessionsDir, getLiveSessionsDir } from '../lib/impeccable-paths.mjs';+import { getLegacyLiveSessionsDir, getLiveSessionsDir, safeSessionId } from '../lib/impeccable-paths.mjs';const COMPLETED_PHASES = new Set(['completed', 'discarded']);+export const GENERATION_FENCED_PHASES = new Set([+ 'accept_requested',+ 'discard_requested',+ 'carbonize_required',+ 'completed',+ 'discarded',+]);export function createLiveSessionStore({ cwd = process.cwd(), sessionId } = {}) {const rootDir = getLiveSessionsDir(cwd);const legacyRootDir = getLegacyLiveSessionsDir(cwd);fs.mkdirSync(rootDir, { recursive: true });- const snapshotCache = new Map();-- function loadCachedOrRebuild(id) {- const cached = snapshotCache.get(id);- if (cached) return cached;- const journalPath = getReadableJournalPath(id);- const rebuilt = rebuildSnapshotFromJournal(journalPath, id);- snapshotCache.set(id, rebuilt);- return rebuilt;- }+ // No snapshot cache on purpose: appendEvent and getSnapshot both rebuild from+ // the journal so sequence numbers and phase fences never come from a stale+ // in-memory copy when the publisher/complete helpers append from another+ // process. A cache written but never read would grow per session for the+ // lifetime of the server without ever saving a rebuild.function getReadableJournalPath(id) {const primary = getJournalPath(rootDir, id);if (fs.existsSync(primary)) return primary;@@ -38,7 +40,10 @@ export function createLiveSessionStore({ cwd = process.cwd(), sessionId } = {})if (!fs.existsSync(journalPath) && fs.existsSync(legacyJournalPath)) {fs.copyFileSync(legacyJournalPath, journalPath);}- const prior = loadCachedOrRebuild(normalized.id);+ // Publisher/complete helpers can append from a separate process while+ // the server is alive. Rebuild here so sequence numbers and phase+ // fences never come from a stale in-memory cache.+ const prior = rebuildSnapshotFromJournal(getReadableJournalPath(normalized.id), normalized.id);const seq = prior.nextSeq;const entry = {seq,@@ -49,7 +54,6 @@ export function createLiveSessionStore({ cwd = process.cwd(), sessionId } = {})};fs.appendFileSync(journalPath, JSON.stringify(entry) + '\n');const next = applyEvent(prior.snapshot, entry, prior.diagnostics);- snapshotCache.set(normalized.id, { snapshot: next, diagnostics: next.diagnostics || [], nextSeq: seq + 1 });writeSnapshot(snapshotPath, next);return next;},@@ -58,7 +62,6 @@ export function createLiveSessionStore({ cwd = process.cwd(), sessionId } = {})const journalPath = getReadableJournalPath(id);const snapshotPath = getSnapshotPath(rootDir, id);const rebuilt = rebuildSnapshotFromJournal(journalPath, id);- snapshotCache.set(id, rebuilt);writeSnapshot(snapshotPath, rebuilt.snapshot);if (!opts.includeCompleted && COMPLETED_PHASES.has(rebuilt.snapshot.phase)) return null;return rebuilt.snapshot;@@ -95,11 +98,6 @@ function getSnapshotPath(rootDir, id) {return path.join(rootDir, safeSessionId(id) + '.snapshot.json');}-function safeSessionId(id) {- if (!/^[A-Za-z0-9_-]{1,128}$/.test(id)) throw new Error('invalid session id: ' + id);- return id;-}-function baseSnapshot(id) {return {id,@@ -116,9 +114,18 @@ function baseSnapshot(id) {pendingEvent: null,deliveryLease: null,checkpointRevision: 0,+ browserCheckpointRevision: 0,+ publicationCheckpointRevision: 0,activeOwner: null,sourceMarkers: {},fallbackMode: null,+ generationPhase: null,+ generationCompletedAt: null,+ generationTimings: {},+ variantPlan: null,+ generationCanceled: false,+ generationCanceledAt: null,+ cancelReason: null,annotationArtifacts: [],diagnostics: [],updatedAt: null,@@ -158,6 +165,8 @@ function applyEvent(snapshot, entry, inheritedDiagnostics = []) {...snapshot,paramValues: { ...(snapshot.paramValues || {}) },sourceMarkers: { ...(snapshot.sourceMarkers || {}) },+ generationTimings: { ...(snapshot.generationTimings || {}) },+ variantPlan: snapshot.variantPlan || null,annotationArtifacts: [...(snapshot.annotationArtifacts || [])],diagnostics: [...(snapshot.diagnostics || [])],updatedAt: entry.ts || new Date().toISOString(),@@ -174,11 +183,48 @@ function applyEvent(snapshot, entry, inheritedDiagnostics = []) {next.expectedVariants = event.count ?? next.expectedVariants;next.pendingEventSeq = entry.seq ?? next.pendingEventSeq;next.pendingEvent = toPendingEvent(event);+ next.variantPlan = null;if (event.screenshotPath) upsertArtifact(next.annotationArtifacts, { type: 'screenshot', path: event.screenshotPath });break;+ case 'variant_plan':+ if (!next.generationCanceled && !GENERATION_FENCED_PHASES.has(next.phase)) {+ next.variantPlan = event.plan ?? next.variantPlan;+ }+ break;+ case 'detector_waivers':+ if (!next.generationCanceled && !GENERATION_FENCED_PHASES.has(next.phase)) {+ next.detectorWaivers = [+ ...(next.detectorWaivers || []),+ ...(Array.isArray(event.waivers) ? event.waivers : []),+ ];+ }+ break;+ case 'agent_phase':+ next.generationPhase = event.phase ?? next.generationPhase;+ if (event.phase) {+ next.generationTimings[event.phase] = {+ at: event.at ?? (Date.parse(entry.ts || '') || null),+ durationMs: event.durationMs ?? null,+ };+ }+ break;case 'variants_ready':case 'agent_done':+ if ((next.generationCanceled || GENERATION_FENCED_PHASES.has(next.phase))+ && !(event.type === 'agent_done' && event.carbonize === true && next.phase === 'accept_requested')) {+ next.diagnostics.push({+ error: 'late_generation_event_ignored',+ type: event.type,+ phase: next.phase,+ });+ break;+ }next.phase = event.carbonize === true ? 'carbonize_required' : 'variants_ready';+ // Durable completion marker: later browser checkpoints (a resumed page+ // reporting phase "generating") regress `phase`, but generation staying+ // finished is monotone — the live server keys missed-`done` redelivery+ // on this field.+ next.generationCompletedAt = event.at ?? (Date.parse(entry.ts || '') || Date.now());next.sourceFile = event.sourceFile ?? event.file ?? next.sourceFile;next.previewFile = event.previewFile ?? next.previewFile;next.previewMode = event.previewMode ?? next.previewMode;@@ -194,27 +240,45 @@ function applyEvent(snapshot, entry, inheritedDiagnostics = []) {}break;case 'checkpoint':- if (COMPLETED_PHASES.has(next.phase)) {+ if (next.generationCanceled || GENERATION_FENCED_PHASES.has(next.phase)) {next.diagnostics.push({ error: 'checkpoint_after_terminal_ignored', phase: event.phase ?? null, revision: event.revision ?? null });break;}- if ((event.revision ?? 0) >= (next.checkpointRevision ?? 0)) {- next.phase = event.phase ?? next.phase;- next.checkpointRevision = event.revision ?? next.checkpointRevision;- next.activeOwner = event.owner ?? next.activeOwner;- next.arrivedVariants = event.arrivedVariants ?? next.arrivedVariants;- next.visibleVariant = event.visibleVariant ?? next.visibleVariant;- next.sourceFile = event.sourceFile ?? next.sourceFile;- next.previewFile = event.previewFile ?? next.previewFile;- next.previewMode = event.previewMode ?? next.previewMode;- if (event.paramValues) next.paramValues = { ...event.paramValues };- } else {- next.diagnostics.push({ error: 'stale_checkpoint_ignored', revision: event.revision });+ {+ const revisionDomain = event.revisionDomain === 'publication'+ || (event.reason === 'variants_progress' && !event.owner)+ ? 'publication'+ : 'browser';+ const revisionField = revisionDomain === 'publication'+ ? 'publicationCheckpointRevision'+ : 'browserCheckpointRevision';+ const currentRevision = next[revisionField]+ ?? (revisionDomain === 'browser' ? next.checkpointRevision : 0)+ ?? 0;+ if ((event.revision ?? 0) >= currentRevision) {+ next.phase = event.phase ?? next.phase;+ next[revisionField] = event.revision ?? currentRevision;+ if (revisionDomain === 'browser') {+ next.checkpointRevision = event.revision ?? next.checkpointRevision;+ next.activeOwner = event.owner ?? next.activeOwner;+ }+ next.arrivedVariants = event.arrivedVariants ?? next.arrivedVariants;+ if (revisionDomain === 'browser') next.visibleVariant = event.visibleVariant ?? next.visibleVariant;+ next.sourceFile = event.sourceFile ?? next.sourceFile;+ next.previewFile = event.previewFile ?? next.previewFile;+ next.previewMode = event.previewMode ?? next.previewMode;+ if (revisionDomain === 'browser' && event.paramValues) next.paramValues = { ...event.paramValues };+ } else {+ next.diagnostics.push({ error: 'stale_checkpoint_ignored', revision: event.revision, revisionDomain });+ }}break;case 'accept':case 'accept_intent':next.phase = 'accept_requested';+ next.generationCanceled = true;+ next.generationCanceledAt = event.at ?? (Date.parse(entry.ts || '') || Date.now());+ next.cancelReason = 'accept';next.visibleVariant = Number(event.variantId ?? next.visibleVariant);if (event.paramValues) next.paramValues = { ...event.paramValues };next.pendingEventSeq = entry.seq ?? next.pendingEventSeq;@@ -232,6 +296,12 @@ function applyEvent(snapshot, entry, inheritedDiagnostics = []) {next.pendingEventSeq = entry.seq ?? next.pendingEventSeq;next.pendingEvent = toPendingEvent(event);break;+ case 'carbonize_cleanup':+ next.phase = 'carbonize_cleanup_requested';+ next.sourceFile = event.file ?? next.sourceFile;+ next.pendingEventSeq = entry.seq ?? next.pendingEventSeq;+ next.pendingEvent = toPendingEvent(event);+ break;case 'steer_done':next.phase = 'steer_done';next.sourceFile = event.sourceFile ?? event.file ?? next.sourceFile;@@ -243,6 +313,9 @@ function applyEvent(snapshot, entry, inheritedDiagnostics = []) {break;case 'discard':next.phase = 'discard_requested';+ next.generationCanceled = true;+ next.generationCanceledAt = event.at ?? (Date.parse(entry.ts || '') || Date.now());+ next.cancelReason = 'discard';next.pendingEventSeq = entry.seq ?? next.pendingEventSeq;next.pendingEvent = toPendingEvent(event);break;@@ -260,6 +333,10 @@ function applyEvent(snapshot, entry, inheritedDiagnostics = []) {next.pendingEvent = null;break;case 'agent_error':+ if (next.generationCanceled && event.sourceEventType === 'generate') {+ next.diagnostics.push({ error: 'late_generation_event_ignored', type: event.type, phase: next.phase });+ break;+ }next.phase = 'agent_error';next.pendingEventSeq = null;next.pendingEvent = null;diff --git a/.agents/skills/impeccable/scripts/live/source-lock.mjs b/.agents/skills/impeccable/scripts/live/source-lock.mjsnew file mode 100644index 000000000..9ccc557be--- /dev/null+++ b/.agents/skills/impeccable/scripts/live/source-lock.mjs@@ -0,0 +1,105 @@+import fs from 'node:fs';+import path from 'node:path';+import { createHash, randomUUID } from 'node:crypto';+import { getLiveDir, isLiveServerPidReachable } from '../lib/impeccable-paths.mjs';++// Only used to retire a lock whose contents we cannot read (empty or truncated+// by a crash mid-write). A readable lock's fate is decided by its owner's+// liveness instead, so a slow critical section is never swept.+const UNREADABLE_LOCK_STALE_MS = 60_000;++export function sourceLockPath(file, cwd = process.cwd()) {+ const digest = createHash('sha256').update(path.resolve(cwd, file)).digest('hex').slice(0, 24);+ return path.join(getLiveDir(cwd), 'locks', digest + '.lock');+}++export function withSourceLockSync(file, owner, fn, {+ cwd = process.cwd(),+ waitMs = 0,+ retryMs = 5,+} = {}) {+ const lockPath = sourceLockPath(file, cwd);+ fs.mkdirSync(path.dirname(lockPath), { recursive: true });+ const deadline = Date.now() + Math.max(0, Number(waitMs) || 0);+ // Identifies this acquisition specifically, so release can tell our own lock+ // from a replacement that some other writer created.+ const token = randomUUID();+ let acquired = false;++ while (!acquired) {+ clearStaleLock(lockPath);+ let fd;+ try {+ fd = fs.openSync(lockPath, 'wx');+ fs.writeFileSync(fd, JSON.stringify({+ owner,+ token,+ pid: process.pid,+ at: Date.now(),+ file: path.resolve(cwd, file),+ }) + '\n');+ acquired = true;+ } catch (error) {+ if (error?.code !== 'EEXIST') throw error;+ if (Date.now() >= deadline) {+ const locked = new Error('source_locked');+ locked.code = 'SOURCE_LOCKED';+ locked.lockPath = lockPath;+ throw locked;+ }+ sleepSync(Math.max(1, Math.min(Number(retryMs) || 5, deadline - Date.now())));+ } finally {+ try { if (fd !== undefined) fs.closeSync(fd); } catch {}+ }+ }++ try {+ return fn();+ } finally {+ releaseOwnLock(lockPath, token);+ }+}++function sleepSync(ms) {+ Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, ms);+}++function readLock(lockPath) {+ try { return JSON.parse(fs.readFileSync(lockPath, 'utf-8')); } catch { return null; }+}++/**+ * Remove the lock only if it is still the one this call created. If a sweeper+ * judged our lock stale and another writer replaced it, unlinking here would+ * end *their* critical section and admit a third writer to the same file.+ */+function releaseOwnLock(lockPath, token) {+ const held = readLock(lockPath);+ if (held && held.token !== token) return;+ try { fs.unlinkSync(lockPath); } catch {}+}++/**+ * A lock is stale when its owner is gone, not when it is old.+ *+ * Age alone cuts both ways: it sweeps a live holder whose critical section+ * outran the timeout (a suspended laptop, a stopped process), letting two+ * writers into the same source file, while still making every accept on a+ * crashed holder's file wait out the full timeout. Asking the OS whether the+ * recorded pid is alive answers both correctly: a dead owner releases at once,+ * and a live owner keeps its lock however long it needs.+ */+function clearStaleLock(lockPath) {+ const held = readLock(lockPath);+ if (!held) {+ // Unreadable: either a crash truncated it, or we caught the brief window+ // between create and write in a live acquisition. mtime distinguishes them.+ try {+ const stat = fs.statSync(lockPath);+ if (Date.now() - stat.mtimeMs > UNREADABLE_LOCK_STALE_MS) fs.unlinkSync(lockPath);+ } catch { /* gone already */ }+ return;+ }+ if (typeof held.pid === 'number' && isLiveServerPidReachable(held.pid)) return;+ try { fs.unlinkSync(lockPath); } catch {}+}diff --git a/.claude/skills/impeccable/reference/live.md b/.claude/skills/impeccable/reference/live.mdindex 8c2cccd0a..295ae28fc 100644--- a/.claude/skills/impeccable/reference/live.md+++ b/.claude/skills/impeccable/reference/live.md@@ -10,21 +10,24 @@ Execute in order. No step skipped, no step reordered.1. `live.mjs`: boot. If the request names or implies a file, route, or app inside a monorepo, infer the concrete path and run `node .claude/skills/impeccable/scripts/live.mjs --target <path>` instead; then run the rest of this live session from the returned `projectRoot`.2. Open the app URL that serves `pageFile` (infer from `package.json`, docs, terminal output, or an open tab). Never use `serverPort`; it's the helper, not the app. **Cursor:** `browser_navigate` to that URL before polling; do not skip. **Other harnesses:** use the available browser tool; if the URL is uncertain, ask the user once.-3. Poll loop with the default long timeout (600000 ms). After every event or `--reply`, run `live-poll.mjs` again immediately. Never pass a short `--timeout=`.+3. Poll loop with the default long timeout (600000 ms). Run `live-poll.mjs` again immediately after every event or `--reply`; Codex runs this one-shot poll in the foreground. Never pass a short `--timeout=`.The global bar **Impeccable mark** dims and shows a pulsing amber dot when no agent is long-polling `/poll`. Hover the mark for the hint; restart `live-poll.mjs` to reconnect.-4. On `generate`: read screenshot if present; load the action's reference; plan three distinct directions; write all variants in one edit; `--reply done`; poll again.+4. On `generate`: reuse `event.scaffold` when present; read the screenshot if present; load the action's reference; deliver variants using the delivery policy below; `--reply done`; poll again. Generate in this thread. You already hold the project's tokens, conventions, and file layout; that context is the job, not overhead.5. On `steer`: read the message and `pageUrl`; do the work (page edits, navigation help, or a short reply in the `--reply` message); `--reply steer_done`; poll again. No pickup ack. The Steer bar unlocks when `steer_done` arrives over SSE.-6. On `accept` / `discard`: the poll script runs `live-accept.mjs`, acknowledges the delivered event, and prints `_completionAck`. Plain accepts/discards are terminal immediately; carbonize accepts remain recoverable until you finish cleanup, run `live-complete.mjs --id EVENT_ID`, and only then poll again.+6. On `accept` / `discard`: the poll script runs `live-accept.mjs`, acknowledges the delivered event, and prints `_completionAck`. Plain accepts/discards are terminal immediately. Carbonize accepts remain recoverable until the foreground task runs `live-complete.mjs --id EVENT_ID`; finish that cleanup before polling again.7. If interrupted, run `live-status.mjs` or `live-resume.mjs` before guessing. The durable journal replays unacknowledged work after helper restart.8. On `exit`: run the cleanup at the bottom.Harness policy:-- **Claude Code**: run the poll as a **background task** (no short timeout). The harness notifies you when it completes, so the main conversation stays free. Do not block the shell.+- **Claude Code**: run the poll as a **background task** (no short timeout). The harness notifies you when it completes, so the main conversation stays free while you generate and publish in it. Do not block the shell.- **Cursor**: run **one-shot** poll in a **background terminal** with notify on `"type":"(steer|generate|accept|discard|exit)"`. After each event the poll exits; handle it, `--reply`, then start `live-poll.mjs` again. Do **not** use `--stream` on Cursor: incremental stdout notify is slower in practice than exit-based notify (~5s vs sub-second in testing).-- **Codex**: run the poll in the **foreground** (blocking shell; not a background task, not a subagent). Codex background exec sessions do not reliably surface poll stdout back into the conversation at the moment events arrive, so a "fire-and-forget" background poll will stall live mode.+- **Codex**: run the default one-shot poll in a **yielded foreground exec session**. Do not suffix it with `&`, use `--stream`, or leave Live without an active foreground poll. Handle every event in the main task; after each handler/reply, restart the foreground poll.- **Other harnesses**: one-shot foreground unless you know stdout reliably returns to this session when a shell exits.+Generation delivery policy:+- **Default (Cursor and other harnesses):** keep the established atomic single-edit delivery. Do not switch a harness to progressive until its poll loop is known not to block on the extra publish calls. This avoids trading model latency for extra tool-call latency on harnesses with different streaming behavior.+Chat is overhead. No recap, no tutorial output, no pasting PRODUCT / DESIGN bodies. Spend tokens on tools and edits; on failure, one or two short sentences.## Start@@ -92,14 +95,14 @@ Server restart rule: start `live-server.mjs` again, then poll. Startup requeues**Insert mode** (`event.mode === "insert"`): `{id, mode: "insert", count, pageUrl, insert: { position, anchor }, placeholder: { width, height }, freeformPrompt?, screenshotPath?, comments?, strokes?}`. No `action`. Requires a non-empty `freeformPrompt` **or** annotations. Screenshot is sent only when annotations exist (same rule as replace). Use `placeholder` dimensions as a soft size hint for net-new content.-Speed matters; the user is watching a spinner. Minimize tool calls by using the wrap/insert helper and writing all variants in a single edit.+Speed matters; the user is watching the selected element. Reuse server preflight metadata when available, minimize discovery calls, and follow the harness-specific delivery policy above.### Insert mode branchWhen `event.mode === "insert"`:1. Read the screenshot if `event.screenshotPath` is present (annotations only).-2. Run the insert helper instead of wrap:+2. If `event.scaffold` is present, use it as the insert-helper result and do **not** run the helper again. Otherwise run the insert helper instead of wrap:```bashnode .claude/skills/impeccable/scripts/live-insert.mjs --id EVENT_ID --count EVENT_COUNT --position after \@@ -109,7 +112,7 @@ node .claude/skills/impeccable/scripts/live-insert.mjs --id EVENT_ID --count EVE- `--position` ← `event.insert.position` (`before` | `after`)- Anchor flags ← `event.insert.anchor` (same mapping as wrap: id, classes, tag, text)-The scaffold has **no** `data-impeccable-variant="original"`. Variants are net-new HTML+CSS inserted at `insertLine`. Load `brand.md` or `product.md` (freeform only, no action sub-command). Write all variants in one edit, then `--reply done`.+The scaffold has **no** `data-impeccable-variant="original"`. Variants are net-new HTML+CSS inserted at `insertLine`. Load `brand.md` or `product.md` (freeform only, no action sub-command). Deliver using the harness policy, then `--reply done`.For Svelte/SvelteKit targets, `live-insert.mjs` returns `previewMode: "svelte-component"` with `mode: "insert"`, `file` pointing at a temporary `node_modules/.impeccable-live/<id>/manifest.json`, `componentDir` pointing at the variant component files, and `sourceFile` pointing at the real `.svelte` route. Write each inserted variant as a real Svelte component (`v1.svelte`, `v2.svelte`, …) under `componentDir`. Insert variants must be non-empty net-new content with a single top-level root, no `data-impeccable-*` attributes, and CSS in each component's `<style>` block. Do **not** edit the route source during generation; the browser mounts the temporary component before/after the live anchor while the user cycles variants. On Accept, `live-accept.mjs` inserts the selected component markup into `sourceFile` immediately and deletes the temp session after the source write succeeds.@@ -134,6 +137,8 @@ Reading annotations precisely:### 2. Wrap the element+When `event.scaffold` is present, the local helper already found and wrapped the source before the poll returned. Treat `event.scaffold` as the successful helper output and skip this command entirely. `event.scaffoldAttempted` with `scaffoldError` means local preflight could not finish; use the command/fallback path below. This optimization removes a deterministic tool round trip without changing the generated design.+```bashnode .claude/skills/impeccable/scripts/live-wrap.mjs --id EVENT_ID --count EVENT_COUNT --element-id "ELEMENT_ID" --classes "class1,class2" --tag "div" --text "TEXT_SNIPPET"```@@ -153,7 +158,7 @@ Output on success: `{ file, insertLine, commentSyntax, styleMode, styleTag, cssSFor Svelte/SvelteKit targets, `live-wrap.mjs` returns `previewMode: "svelte-component"` with `file` pointing at a temporary `node_modules/.impeccable-live/<id>/manifest.json`, `componentDir` pointing at the variant component files, and `sourceFile` pointing at the real `.svelte` route. Write each variant as a real Svelte component (`v1.svelte`, `v2.svelte`, …) under `componentDir`; use the `propContract` prop names for dynamic text (`{propName}`), not literal snapshot strings. Put variant CSS in each component's `<style>` block with semantic class selectors (no `@scope`, no `data-impeccable-*`). Reply with `--file` set to the manifest path; the browser dynamically imports and mounts the compiled components so Svelte HMR does not reset page state while the user cycles variants. On Accept, `live-accept.mjs` inlines the accepted component back into `sourceFile` immediately after source promotion succeeds.-**Params on the Svelte component path go in a sidecar, never as an attribute.** Svelte parses `{` inside an attribute value as the start of an expression, so a `data-impeccable-params='[{…}]'` attribute on a component element fails to compile (`Expected token }`). Declare params for this path in `componentDir/params.json`, keyed by variant number, using the exact param schema from section 7:+**Params on component-preview paths go in a sidecar, never as an attribute.** Svelte parses `{` inside an attribute value as the start of an expression, and both Svelte/Vue previews mount without an HTML variant wrapper. Declare params in `componentDir/params.json`, keyed by variant number, using the exact param schema from section 7:```json{@@ -291,11 +296,13 @@ In **departure mode**, the prompt narrows the lanes you draw from, not the familWhen the prompt and PRODUCT.md anti-references conflict (the prompt asks for X, the anti-references ban X), the anti-references win; they describe the brand's standing position, the prompt is one moment.-### 6. Write all variants in a single edit+### 6. Deliver variantsComplete HTML replacement of the original element for each variant, not a CSS-only patch. Consider the element's context (computed styles, parent structure, CSS variables from `event.element`).-Write CSS + all variants in ONE edit at the `insertLine` reported by `wrap`. Colocate CSS as a `<style>` tag inside the variant wrapper; `<style>` works anywhere in modern browsers and this ensures CSS and HTML arrive atomically (no FOUC).+Colocate preview CSS as a `<style>` tag inside the variant wrapper; `<style>` works anywhere in modern browsers and keeps each delivered state internally complete (no FOUC).++**Atomic default:** write CSS + all variants + parameter manifests in one edit at `insertLine`, preserving the established behavior.Use the `cssAuthoring` object returned by `live-wrap.mjs` to author the temporary preview CSS. The style opening tag shown below is the common case; replace it with `cssAuthoring.styleTag` when the tool returns a different one. The variant markup shape is otherwise stable:@@ -319,7 +326,7 @@ Use the `cssAuthoring` object returned by `live-wrap.mjs` to author the temporarThe first variant has no `display: none` (visible by default). All others do. If variants use only inline styles and no preview CSS, omit the `<style>` tag entirely.-One edit, all variants; the browser's MutationObserver picks everything up in one pass.+The browser's MutationObserver accepts either delivery shape. On the transactional progressive path it shows arrived variants and pending dots immediately; Accept and Discard are available as soon as one variant exists. Accepting an arrived variant fences the worker before the browser releases the picker, so later publications are rejected.For `styleMode: "scoped"`, author every `:scope` rule with a descendant combinator. The `@scope` boundary is the **variant wrapper `<div data-impeccable-variant="N">`**, not the element you're designing. A bare `:scope { background: cream; }` styles the wrapper, not the inner replacement, so the cream lands on a `display: contents` shell while the actual element keeps page defaults. Always step in: `:scope > .card`, `:scope > section`, `:scope .hero-title`, etc. The fake test agent's CSS in `tests/live-e2e/agent.mjs` is a faithful template; every scoped rule starts `:scope > ...`.@@ -361,7 +368,7 @@ Each variant can expose **coarse** knobs alongside the full HTML/CSS replacement**Hard cap per variant**: at most **four** parameters so the panel stays legible; rare fifth only if the reference explicitly allows it.-**How to declare.** Put a JSON manifest on the variant wrapper (HTML/JSX path). **On the Svelte `svelte-component` path, do not use this attribute** (Svelte can't compile `{` inside an attribute value). Declare params in `componentDir/params.json` keyed by variant number instead (see the Svelte component paragraph in the wrap section). The param schema below is identical for both paths.+**How to declare.** Put a JSON manifest on the variant wrapper (HTML/JSX path). **On the `svelte-component` path, do not use this attribute.** Declare params in `componentDir/params.json` keyed by variant number instead (see the component-preview paragraphs in the wrap section). The param schema below is identical for every path.```html<div data-impeccable-variant="1" data-impeccable-params='[@@ -462,15 +469,19 @@ Event: `{id, variantId, _acceptResult, _completionAck}`. The poll script already- The accept event includes `pageUrl`; the poll script must forward it to `live-accept.mjs --page-url PAGE_URL` so accept-time cleanup only scrubs staged copy edits for the current page.- `_completionAck.ok !== true`: do not poll yet. Run `live-status.mjs` / `live-resume.mjs`, complete the cleanup manually if needed, then run `live-complete.mjs --id EVENT_ID`.- `_acceptResult.handled: true` and `carbonize: false`: nothing to do. Poll again.-- `_acceptResult.handled: true` and `carbonize: true`: **post-accept cleanup is required before the next poll.** See the "Required after accept (carbonize)" section below. The `event._acceptResult.todo` field, `_completionAck.requiresComplete`, and a stderr banner all point at this required follow-up; none are decorative. After cleanup, run `live-complete.mjs --id EVENT_ID`, then poll again.+- `_acceptResult.handled: true` and `carbonize: true`: post-accept cleanup is required, but it must not stall Codex's control lane. See "Required after accept (carbonize)" below. The `event._acceptResult.todo` field, `_completionAck.requiresComplete`, and stderr banner all point at this required follow-up; none are decorative.- `_acceptResult.handled: false, mode: "fallback"`: the session lived in a generated file and the script refused to persist there. You've already written the accepted variant into true source during Handle fallback Step 3; just clean up the temporary wrapper in the served file if any, and poll again.+- `_acceptResult.handled: false, mode: "error"`: the operation genuinely failed. **Do not hand-edit the file**; the source was not touched and editing it yourself would either double-apply or race whoever holds it.+ - `error: "source_locked"`: a generation publish holds the file. Run the same `live-accept.mjs` command again; it is idempotent and will succeed once the publisher releases. Do not poll past it.+ - `error: "accept_receipt_conflict"`: this session already resolved as `priorOperation` (on `priorVariantId` for an accept), so the request contradicts durable truth. Do not edit. Run `live-status.mjs` and tell the user what the session actually resolved to.+ - anything else: report the error briefly and run `live-status.mjs` before continuing.- `_acceptResult.handled: false` without `mode`: manual cleanup: read file, find markers, edit.### Required after accept (carbonize)When `_acceptResult.carbonize === true`, the accepted variant was stitched into source with helper markers and inline CSS so the browser can render it immediately with no visual gap. That stitch-in is **temporary**. The agent must rewrite it into permanent form before doing anything else. Skipping this leaves dead `@scope` rules for unaccepted variants, a pointless `data-impeccable-variant` wrapper, and `impeccable-carbonize-start/end` comment noise in the source file; all of which accumulate across sessions.-Do these five steps in the current thread, synchronously, before the next poll. Do not poll again until the file is clean.+Do these five steps synchronously before the next poll. The source lock, generation epoch, and expected-source hash remain the final safety gates against a generator finishing concurrently with Accept.1. **Locate the carbonize block** in the source file (`_acceptResult.file`). It's bracketed by `<!-- impeccable-carbonize-start SESSION_ID -->` and `<!-- impeccable-carbonize-end SESSION_ID -->` and contains a `<style data-impeccable-css="SESSION_ID">` element. If the variant declared parameters, an `<!-- impeccable-param-values SESSION_ID: {...} -->` comment sits alongside the style tag with the user's chosen values; read it first; it drives steps 3 and 4 below.2. **Move the CSS rules** into the project's real stylesheet. Which stylesheet depends on the project (e.g. `site/styles/workflow.css` for an Astro project, or the component's co-located CSS file for a Vite/Next project; pick whichever already owns styling for the surrounding element).@@ -478,9 +489,7 @@ Do these five steps in the current thread, synchronously, before the next poll.4. **Unwrap the accepted content.** Delete the inner `<div data-impeccable-variant="N" style="display: contents">` that wraps it. On JSX/TSX, also delete the outer `<div data-impeccable-carbonize="SESSION_ID" style={{ display: 'contents' }}>` wrapper if present (accept adds it so ternary/`return` slots keep a single root). Drop `data-impeccable-params` and any `data-p-*` attributes; those are live-mode plumbing, not source.5. **Delete the inline `<style>` block, the `<!-- impeccable-param-values -->` comment if present, and both `<!-- impeccable-carbonize-start/end -->` markers.** Also drop any `@scope` rules for variants other than the accepted one; those are dead code now.-After the file is clean, run `live-complete.mjs --id SESSION_ID`, verify it reports `phase: "completed"`, then poll again.--A background agent may be used for the rewrite, but the current thread is responsible for verifying the five steps are complete before issuing the next poll. In practice, inline is usually faster and less error-prone.+After the file is clean, the cleanup owner runs `live-complete.mjs --id SESSION_ID` and verifies `phase: "completed"`. Poll again only after that verification.## Handle `discard`diff --git a/.claude/skills/impeccable/scripts/lib/impeccable-paths.mjs b/.claude/skills/impeccable/scripts/lib/impeccable-paths.mjsindex 2ccbe7b74..99956c0f3 100644--- a/.claude/skills/impeccable/scripts/lib/impeccable-paths.mjs+++ b/.claude/skills/impeccable/scripts/lib/impeccable-paths.mjs@@ -104,6 +104,20 @@ export function removeLiveServerInfo(cwd = process.cwd(), options = {}) {}}+/**+ * Session IDs become path segments (journals, snapshots, accept receipts,+ * preview manifests, generated component dirs). They arrive from CLI `--id`+ * arguments and HTTP payloads, so anything containing a separator or `..` must+ * be rejected before it reaches path.join, which would happily escape+ * `.impeccable/live/`. Real IDs are 8 hex chars; the tests use short slugs.+ */+export function safeSessionId(id) {+ if (typeof id !== 'string' || !/^[A-Za-z0-9_-]{1,128}$/.test(id)) {+ throw new Error('invalid session id: ' + id);+ }+ return id;+}+export function getLiveSessionsDir(cwd = process.cwd(), options = {}) {return path.join(getLiveDir(cwd, options), 'sessions');}diff --git a/.claude/skills/impeccable/scripts/live-accept.mjs b/.claude/skills/impeccable/scripts/live-accept.mjsindex 278dfbb2e..453ddea35 100644--- a/.claude/skills/impeccable/scripts/live-accept.mjs+++ b/.claude/skills/impeccable/scripts/live-accept.mjs@@ -16,7 +16,9 @@import fs from 'node:fs';import path from 'node:path';import { isGeneratedFile } from './lib/is-generated.mjs';+import { IMPECCABLE_DIR, getLiveDir, safeSessionId } from './lib/impeccable-paths.mjs';import { readBuffer as readManualEditsBuffer, writeBuffer as writeManualEditsBuffer } from './live/manual-edits-buffer.mjs';+import { withSourceLockSync } from './live/source-lock.mjs';import {applyDeferredSvelteComponentAccepts,findSvelteComponentManifest,@@ -25,6 +27,46 @@ import {} from './live/svelte-component.mjs';const EXTENSIONS = ['.html', '.jsx', '.tsx', '.vue', '.svelte', '.astro'];+const ACCEPT_LOCK_WAIT_MS = 1_000;+// Mirrors VARIANT_ID_PATTERN in live/event-validation.mjs, which gates the same+// value arriving over HTTP.+const VARIANT_NUM_PATTERN = /^[0-9]{1,3}$/;++/**+ * A thrown accept/discard is a real failure, not a manual handoff.+ *+ * live/completion.mjs only classifies a result as `error` when it carries+ * `mode: 'error'`; anything else unhandled falls through to `agent_done` with a+ * successful ack, and reference/live.md then tells the agent to finish the edit+ * by hand. That is right for the documented fallback paths and wrong here: a+ * `source_locked` contention needs a retry (hand-editing races the publisher+ * holding the lock), and a crash needs surfacing, not a hand-applied guess.+ */+function operationFailure(err, extra = {}) {+ return { handled: false, mode: 'error', error: err.message, ...extra };+}++/**+ * Mark an unhandled preview-path result as a real failure.+ *+ * operationFailure only covers results built from a *thrown* error. The accept+ * implementations also return `{handled: false, error}` for their own checks+ * (variant missing, template empty, original text ambiguous), and those arrived+ * without `mode`, so completion.mjs classified them as agent_done and+ * reference/live.md routed the agent to "read file, find markers, edit".+ *+ * That handoff only makes sense for a plain wrapper session, which is the one+ * shape with markers in the user's source to edit. Component and isolated+ * artifact previews keep the source clean until Accept, so there is nothing to+ * hand-edit and an unhandled result is always a failure. `previewMode` is+ * exactly that discriminator: only the preview branches set it.+ */+function markPreviewFailure(result) {+ if (result?.handled === false && !result.mode && result.previewMode) {+ return { ...result, mode: 'error' };+ }+ return result;+}// ---------------------------------------------------------------------------// CLI@@ -63,7 +105,52 @@ Output (JSON):const isDiscard = args.includes('--discard');if (!id) { console.error('Missing --id'); process.exit(1); }+ // `id` becomes a path segment (accept receipts, preview manifests, generated+ // component dirs). Reject separators and traversal here so one check covers+ // every downstream sink.+ try { safeSessionId(id); } catch { console.error('Invalid --id'); process.exit(1); }if (!isDiscard && !variantNum) { console.error('Need --discard or --variant N'); process.exit(1); }+ // `variantNum` is interpolated into a RegExp and into the markup written back+ // to source. The browser and the /events schema both constrain it to digits;+ // enforce the same here, or `--variant '.*'` matches the `original` block+ // first and silently accepts the original while reporting success.+ if (!isDiscard && !VARIANT_NUM_PATTERN.test(variantNum)) {+ console.error('Invalid --variant');+ process.exit(1);+ }++ const requestedOperation = isDiscard ? 'discard' : 'accept';+ const priorReceipt = readAcceptReceipt(process.cwd(), id);+ if (priorReceipt) {+ const sameOperation = priorReceipt.operation === requestedOperation+ && (isDiscard || String(priorReceipt.variantId) === String(variantNum));+ console.log(JSON.stringify(sameOperation+ ? { ...priorReceipt.result, handled: true, alreadyApplied: true }+ : {+ // mode: 'error' is what marks this a real failure rather than a manual+ // handoff. Without it, live/completion.mjs classifies the reply as+ // agent_done and reference/live.md tells the agent to "read file, find+ // markers, edit" by hand — which would apply a second, conflicting+ // accept on top of the one the receipt already recorded.+ handled: false,+ mode: 'error',+ error: 'accept_receipt_conflict',+ priorOperation: priorReceipt.operation,+ priorVariantId: priorReceipt.variantId ?? null,+ }));+ return;+ }+ const emitResult = (rawResult) => {+ const result = markPreviewFailure(rawResult);+ if (result?.handled !== false) {+ writeAcceptReceipt(process.cwd(), id, {+ operation: requestedOperation,+ variantId: isDiscard ? null : String(variantNum),+ result,+ });+ }+ console.log(JSON.stringify(result));+ };let paramValues = null;if (paramValuesRaw) {@@ -82,39 +169,55 @@ Output (JSON):if (svelteComponentManifest) {if (isDiscard) {- removeSvelteComponentSession(id, process.cwd());- console.log(JSON.stringify({- handled: true,+ let result;+ try {+ result = withSourceLockSync(+ path.resolve(process.cwd(), svelteComponentManifest.sourceFile),+ 'discard:' + id,+ () => {+ removeSvelteComponentSession(id, process.cwd());+ return { handled: true };+ },+ { waitMs: ACCEPT_LOCK_WAIT_MS },+ );+ } catch (err) {+ result = operationFailure(err);+ }+ emitResult({+ ...result,file: svelteComponentManifest.sourceFile,carbonize: false,previewMode: 'svelte-component',componentDir: svelteComponentManifest.componentDir,- }));+ });return;}let result;try {- result = inlineSvelteComponentAccept(- svelteComponentManifest,- variantNum,- paramValues,- process.cwd(),+ result = withSourceLockSync(+ path.resolve(process.cwd(), svelteComponentManifest.sourceFile),+ 'accept:' + id,+ () => inlineSvelteComponentAccept(+ svelteComponentManifest,+ variantNum,+ paramValues,+ process.cwd(),+ ),+ { waitMs: ACCEPT_LOCK_WAIT_MS },);} catch (err) {- result = {- handled: false,- error: err.message,+ result = operationFailure(err, {file: svelteComponentManifest.sourceFile,sourceFile: svelteComponentManifest.sourceFile,previewMode: 'svelte-component',componentDir: svelteComponentManifest.componentDir,- };+ });}if (result.carbonize) {result.todo = 'REQUIRED before next poll: carbonize cleanup in ' + result.file + '. See reference/live.md "Required after accept".';}- console.log(JSON.stringify({ handled: result.handled !== false, ...result }));+ emitResult({ handled: result.handled !== false, ...result });return;}@@ -145,10 +248,25 @@ Output (JSON):}if (isDiscard) {- const result = handleDiscard(id, lines, targetFile);- console.log(JSON.stringify({ handled: true, file: relFile, carbonize: false, ...result }));+ let result;+ // handleDiscard takes the source lock, which throws SOURCE_LOCKED under+ // contention. Without this catch the CLI exits non-zero with empty stdout+ // and the agent gets no JSON to act on.+ try {+ result = handleDiscard(id, lines, targetFile);+ } catch (err) {+ emitResult(operationFailure(err, { file: relFile }));+ return;+ }+ emitResult({ handled: true, file: relFile, carbonize: false, ...result });} else {- const result = handleAccept(id, variantNum, lines, targetFile, paramValues);+ let result;+ try {+ result = handleAccept(id, variantNum, lines, targetFile, paramValues);+ } catch (err) {+ emitResult(operationFailure(err, { file: relFile }));+ return;+ }const acceptedOriginalText = result.acceptedOriginalText || '';delete result.acceptedOriginalText;// Single-line attention-grabber when cleanup is required. The full@@ -167,7 +285,7 @@ Output (JSON):// Non-fatal; the buffer stays as-is and the user can discard later.}}- console.log(JSON.stringify({ handled: true, file: relFile, ...result }));+ emitResult({ handled: true, file: relFile, ...result });}}@@ -235,7 +353,14 @@ function scrubManualEditsAgainstFile(_targetFile, cwd = process.cwd(), originalB// Discard// ----------------------------------------------------------------------------function handleDiscard(id, lines, targetFile) {+function handleDiscard(id, _lines, targetFile) {+ return withSourceLockSync(targetFile, 'discard:' + id, () => {+ const lines = fs.readFileSync(targetFile, 'utf-8').split('\n');+ return handleDiscardUnlocked(id, lines, targetFile);+ }, { waitMs: ACCEPT_LOCK_WAIT_MS });+}++function handleDiscardUnlocked(id, lines, targetFile) {const block = findMarkerBlock(id, lines);if (!block) return { handled: false, error: 'Markers not found' };@@ -330,7 +455,24 @@ function reindentContent(contentLines, fromIndent, toIndent) {});}-function handleAccept(id, variantNum, lines, targetFile, paramValues) {+function handleAccept(id, variantNum, _lines, targetFile, paramValues) {+ return withSourceLockSync(targetFile, 'accept:' + id, () => {+ const lines = fs.readFileSync(targetFile, 'utf-8').split('\n');+ return handleAcceptUnlocked(id, variantNum, lines, targetFile, paramValues);+ }, { waitMs: ACCEPT_LOCK_WAIT_MS });+}++function handleAcceptUnlocked(id, variantNum, lines, targetFile, paramValues) {+ const built = buildAcceptedWrappedSource(id, variantNum, lines, targetFile, paramValues);+ if (built.handled === false) return built;+ fs.writeFileSync(targetFile, built.content, 'utf-8');+ return {+ carbonize: built.carbonize,+ acceptedOriginalText: built.acceptedOriginalText,+ };+}++function buildAcceptedWrappedSource(id, variantNum, lines, targetFile, paramValues) {const block = findMarkerBlock(id, lines);if (!block) return { handled: false, error: 'Markers not found' };@@ -375,11 +517,14 @@ function handleAccept(id, variantNum, lines, targetFile, paramValues) {...replacement,...lines.slice(replaceRange.end + 1),];- fs.writeFileSync(targetFile, newLines.join('\n'), 'utf-8');-- return { carbonize: needsCarbonize, acceptedOriginalText: originalContent.join('\n') };+ return {+ content: newLines.join('\n'),+ carbonize: needsCarbonize,+ acceptedOriginalText: originalContent.join('\n'),+ };}+function readSourceShadowPreviewMeta(content, id) {const escaped = escapeRegExp(id);const wrapperRe = new RegExp('<[^>]+data-impeccable-variants=(["\'])' + escaped + '\\1[^>]*>');@@ -746,6 +891,21 @@ function detectCommentSyntax(filePath) {// File search (find the file containing session markers)// ---------------------------------------------------------------------------+/**+ * `.impeccable` is the critical entry, and it is not cosmetic.+ *+ * Progressive publication stages each revision as `.impeccable/live/artifacts/+ * <id>-r<n>.<source-ext>`, and those artifacts carry the very marker this search+ * looks for. The walk reaches `.` for any project whose source is not under one+ * of the privileged dirs above (this repo's own site lives in `site/pages/`), and+ * dot-directories sort before letters, so the artifact was found *before* the+ * real file. isGeneratedFile then declined the accept, and the agent fell back to+ * carbonizing several hundred lines of stylesheet by hand.+ *+ * Impeccable's own state directory is never project source. Never search it.+ */+const SEARCH_SKIP_DIRS = new Set(['node_modules', '.git', 'dist', 'build', IMPECCABLE_DIR]);+function findSessionFile(id, cwd) {const marker = 'impeccable-variants-start ' + id;const searchDirs = ['src', 'app', 'pages', 'components', 'public', 'views', 'templates', '.'];@@ -786,7 +946,7 @@ function searchDir(dir, query, seen, depth) {for (const entry of entries) {if (!entry.isDirectory()) continue;- if (['node_modules', '.git', 'dist', 'build'].includes(entry.name)) continue;+ if (SEARCH_SKIP_DIRS.has(entry.name)) continue;const result = searchDir(path.join(dir, entry.name), query, seen, depth + 1);if (result) return result;}@@ -798,6 +958,28 @@ function searchDir(dir, query, seen, depth) {// Utilities// ---------------------------------------------------------------------------+function acceptReceiptPath(cwd, id) {+ return path.join(getLiveDir(cwd), 'accept-receipts', `${safeSessionId(id)}.json`);+}++function readAcceptReceipt(cwd, id) {+ try { return JSON.parse(fs.readFileSync(acceptReceiptPath(cwd, id), 'utf-8')); } catch { return null; }+}++function writeAcceptReceipt(cwd, id, receipt) {+ const file = acceptReceiptPath(cwd, id);+ fs.mkdirSync(path.dirname(file), { recursive: true });+ const value = {+ id,+ ...receipt,+ completedAt: new Date().toISOString(),+ };+ const temporary = `${file}.${process.pid}.${Date.now()}.tmp`;+ fs.writeFileSync(temporary, JSON.stringify(value, null, 2) + '\n', 'utf-8');+ fs.renameSync(temporary, file);+ return value;+}+function argVal(args, flag) {const idx = args.indexOf(flag);return idx !== -1 && idx + 1 < args.length ? args[idx + 1] : null;diff --git a/.claude/skills/impeccable/scripts/live-browser.js b/.claude/skills/impeccable/scripts/live-browser.jsindex 616f1290a..20d875b93 100644--- a/.claude/skills/impeccable/scripts/live-browser.js+++ b/.claude/skills/impeccable/scripts/live-browser.js@@ -126,6 +126,9 @@let expectedVariants = 0;let arrivedVariants = 0;let visibleVariant = 0;+ let generationPhase = null;+ let parameterGenerationState = 'idle';+ let parameterReadyAnnouncedSession = null;let svelteComponentSession = null;let svelteRuntimePromise = null;let pendingSvelteComponentRetryObserver = null;@@ -134,6 +137,7 @@let currentPreviewMode = null;let recoveryWaitingForAnchor = false;let pickedAnchorSnapshot = null;+ let pickedAnchorViewportTop = null;let pendingVariantAnchorRetryObserver = null;let pendingAcceptedSession = null;let variantObserver = null;@@ -151,10 +155,12 @@// startScrollLock / stopScrollLock below.let scrollLockObserver = null;let scrollLockTargetY = null;+ let scrollLockAnchorTop = null;let scrollLockRaf = null;let scrollLockAbort = null;const SCROLL_ANCHOR_LOCK_ID = 'impeccable-scroll-anchor-lock';const VARIANT_STATE_STYLE_ID = 'impeccable-variant-state';+ const DISCARD_STATE_STYLE_ID = 'impeccable-discard-state';// Dedicated key for scroll position - SEPARATE from LS_KEY so that// saveSession's state updates don't clobber a carefully-captured scrollY.@@ -252,6 +258,13 @@barConnected: !!barEl?.isConnected,hasSvelteComponentSession: !!svelteComponentSession,mountedSvelteVariant: svelteComponentSession?.mountedVariant || 0,+ pickActive,+ pendingApplyInFlight,+ hoveredElement: hoveredElement ? {+ tag: hoveredElement.tagName,+ classes: hoveredElement.className,+ pickable: pickable(hoveredElement),+ } : null,pendingSvelteComponentRetry: !!pendingSvelteComponentRetryObserver,recoveryWaitingForAnchor,evtSourceReadyState: evtSource ? evtSource.readyState : null,@@ -1114,14 +1127,15 @@});}- function hideBar() {+ function hideBar(instant) {if (!barEl) return;const hideSeq = ++barHideSeq;stopVoice({ suppressSubmit: true });if (configureKind === 'insert') clearInsertPicking();barEl.style.opacity = '0';- barEl.style.transform = 'translateY(6px)';- setTimeout(() => { if (barEl && hideSeq === barHideSeq) barEl.style.display = 'none'; }, 250);+ barEl.style.transform = instant ? 'translateY(0)' : 'translateY(6px)';+ if (instant) barEl.style.display = 'none';+ else setTimeout(() => { if (barEl && hideSeq === barHideSeq) barEl.style.display = 'none'; }, 250);hideActionPicker();closeTunePopover();hideConfigureBarTooltip();@@ -1966,6 +1980,7 @@*/function setLiveState(next) {state = next;+ window.__IMPECCABLE_LIVE_STATE__ = next;syncPageInteractionCursor();}@@ -2516,18 +2531,27 @@fontSize: '11px', color: BP.textDim, whiteSpace: 'nowrap',marginLeft: 'auto',});- // Variants currently arrive atomically in a single file edit, so a- // per-variant counter would lie. Say what's true.status.textContent = recoveryWaitingForAnchor? 'Variants ready. Reveal the selected element to resume.'- : (arrivedVariants < expectedVariants- ? 'Generating ' + expectedVariants + ' variants...'- : 'Done');+ : generationStatusText();row.appendChild(status);return row;}+ function generationStatusText() {+ if (arrivedVariants >= expectedVariants && expectedVariants > 0) return 'Done';+ if (generationPhase === 'picked_up') return 'Agent picked up the request...';+ if (generationPhase === 'scaffolding') return 'Finding the source...';+ if (generationPhase === 'source_ready') return 'Source ready. Generating...';+ if (generationPhase === 'scaffold_fallback') return 'Agent is locating the source...';+ if (generationPhase === 'first_variant_generating') return 'Designing the first variant...';+ if (generationPhase === 'first_variant_validating') return 'Checking the first variant...';+ if (generationPhase === 'remaining_variants_generating') return 'Exploring two more directions...';+ if (generationPhase === 'remaining_variants_validating') return 'Checking the remaining variants...';+ return 'Generating ' + expectedVariants + ' variants...';+ }+// Cycling rowconst TUNE_ICON_SVG = '<svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" style="flex-shrink:0"><line x1="4" y1="8" x2="20" y2="8"/><circle cx="14" cy="8" r="2.4" fill="currentColor" stroke="none"/><line x1="4" y1="16" x2="20" y2="16"/><circle cx="10" cy="16" r="2.4" fill="currentColor" stroke="none"/></svg>';@@ -2557,7 +2581,7 @@color: BP.textDim, minWidth: '24px', textAlign: 'center',});counter.id = PREFIX + '-variant-counter';- counter.textContent = visibleVariant + '/' + arrivedVariants;+ counter.textContent = visibleVariant + '/' + expectedVariants;row.appendChild(counter);// Next@@ -2567,10 +2591,12 @@if (visibleVariant >= arrivedVariants) next.style.opacity = '0.3';row.appendChild(next);- // Tune chip - only when the visible variant exposes params+ // Tune chip stays visible while the deferred parameter phase is running,+ // then becomes interactive as soon as this variant exposes controls.const visParams = parseVariantParams(getVisibleVariantEl());const hasParams = visParams.length > 0;- if (hasParams) {+ const paramsPending = !hasParams && (parameterGenerationState === 'pending' || parameterGenerationState === 'loading');+ if (hasParams || paramsPending) {const tune = el('button', {display: 'inline-flex', alignItems: 'center', gap: '6px',padding: '4px 10px', borderRadius: '5px',@@ -2578,35 +2604,54 @@background: tuneOpen ? BP.accentSoft : 'transparent',color: tuneOpen ? BP.accent : BP.text,fontFamily: FONT, fontSize: '11px', fontWeight: '500',- cursor: 'pointer',+ cursor: paramsPending ? 'wait' : 'pointer',transition: 'color 0.12s ease, background 0.12s ease',whiteSpace: 'nowrap',});- tune.innerHTML = TUNE_ICON_SVG;+ if (paramsPending) {+ const spinner = el('span', {+ width: '11px', height: '11px', borderRadius: '50%',+ border: '1.5px solid ' + BP.hairline,+ borderTopColor: BP.accent,+ animation: 'impeccable-spin 0.6s linear infinite',+ boxSizing: 'border-box', flexShrink: '0',+ });+ spinner.setAttribute('aria-hidden', 'true');+ tune.appendChild(spinner);+ } else {+ tune.innerHTML = TUNE_ICON_SVG;+ }const tuneLabel = document.createElement('span');tuneLabel.textContent = 'Tune';tune.appendChild(tuneLabel);- const tuneBadge = document.createElement('span');- Object.assign(tuneBadge.style, {- display: 'inline-flex', alignItems: 'center', justifyContent: 'center',- minWidth: '16px', height: '16px', padding: '0 4px',- borderRadius: '999px',- background: tuneOpen ? C.brand : BP.hairline,- color: tuneOpen ? 'oklch(98% 0 0)' : 'inherit',- fontFamily: MONO, fontSize: '9.5px', fontWeight: '600',- lineHeight: '1',- boxSizing: 'border-box',- });- tuneBadge.textContent = String(visParams.length);- tune.appendChild(tuneBadge);- tune.title = 'Tune this variant (' + visParams.length + ' knob' + (visParams.length === 1 ? '' : 's') + ')';- tune.addEventListener('mouseenter', () => {- if (!tuneOpen) tune.style.background = BP.accentSoft;- });- tune.addEventListener('mouseleave', () => {- if (!tuneOpen) tune.style.background = 'transparent';- });- tune.addEventListener('click', (e) => { e.stopPropagation(); toggleTunePopover(); });+ if (hasParams) {+ const tuneBadge = document.createElement('span');+ Object.assign(tuneBadge.style, {+ display: 'inline-flex', alignItems: 'center', justifyContent: 'center',+ minWidth: '16px', height: '16px', padding: '0 4px',+ borderRadius: '999px',+ background: tuneOpen ? C.brand : BP.hairline,+ color: tuneOpen ? 'oklch(98% 0 0)' : 'inherit',+ fontFamily: MONO, fontSize: '9.5px', fontWeight: '600',+ lineHeight: '1',+ boxSizing: 'border-box',+ });+ tuneBadge.textContent = String(visParams.length);+ tune.appendChild(tuneBadge);+ tune.title = 'Tune this variant (' + visParams.length + ' knob' + (visParams.length === 1 ? '' : 's') + ')';+ tune.addEventListener('mouseenter', () => {+ if (!tuneOpen) tune.style.background = BP.accentSoft;+ });+ tune.addEventListener('mouseleave', () => {+ if (!tuneOpen) tune.style.background = 'transparent';+ });+ tune.addEventListener('click', (e) => { e.stopPropagation(); toggleTunePopover(); });+ } else {+ tune.disabled = true;+ tune.setAttribute('aria-label', 'Tune controls are still being prepared');+ tune.title = 'Tune controls are still being prepared';+ tune.style.opacity = '0.72';+ }tune.dataset.iceqTune = '1';row.appendChild(tune);}@@ -2614,6 +2659,15 @@// Spacerrow.appendChild(el('div', { flex: '1' }));+ if (arrivedVariants < expectedVariants) {+ const remaining = expectedVariants - arrivedVariants;+ const progress = el('span', {+ fontSize: '11px', color: BP.textDim, whiteSpace: 'nowrap',+ });+ progress.textContent = remaining + ' more arriving...';+ row.appendChild(progress);+ }+// Accept - primary action, kinpaku gold + lacquer-deep (matches demo .live-demo-ctx-accept)const accept = el('button', {padding: '5px 14px', borderRadius: '5px',@@ -2628,7 +2682,11 @@accept.addEventListener('mousedown', () => accept.style.transform = 'scale(0.97)');accept.addEventListener('mouseup', () => accept.style.transform = 'scale(1)');accept.addEventListener('click', (e) => { e.stopPropagation(); handleAccept(); });- if (arrivedVariants === 0) { accept.style.opacity = '0.3'; accept.style.pointerEvents = 'none'; }+ if (arrivedVariants === 0) {+ accept.style.opacity = '0.3';+ accept.style.pointerEvents = 'none';+ accept.title = 'Accept becomes available when the first variant arrives';+ }row.appendChild(accept);// Discard@@ -4743,6 +4801,32 @@}}+ function mountedParameterCount() {+ if (svelteComponentSession?.sessionId === currentSessionId) {+ return Object.values(svelteComponentSession.paramsByVariant || {})+ .reduce((total, params) => total + (Array.isArray(params) ? params.length : 0), 0);+ }+ const wrapper = document.querySelector('[data-impeccable-variants="' + currentSessionId + '"]');+ if (!wrapper) return 0;+ return [...wrapper.querySelectorAll('[data-impeccable-variant]:not([data-impeccable-variant="original"])')]+ .reduce((total, variant) => total + parseVariantParams(variant).length, 0);+ }++ function completeParameterPublication() {+ if (!currentSessionId) return;+ const ready = mountedParameterCount() > 0;+ parameterGenerationState = ready ? 'ready' : 'none';+ if (ready && parameterReadyAnnouncedSession !== currentSessionId) {+ parameterReadyAnnouncedSession = currentSessionId;+ showToast('Tune controls are ready.', 3000);+ }+ if (state === 'CYCLING') {+ refreshParamsPanel();+ showOrUpdateCyclingBar();+ }+ saveSession();+ }+function toggleTunePopover() {if (pendingApplyInFlight) { showManualApplyBusyToast(); return; }if (tuneOpen) { closeTunePopover(); return; }@@ -4835,6 +4919,10 @@return String(filePath || '').endsWith('manifest.json');}+ function isFrameworkComponentPreviewMode(mode) {+ return mode === 'svelte-component';+ }+function parseOriginalMarkupElement(originalMarkup) {const parser = new DOMParser();const doc = parser.parseFromString('<div id="impeccable-anchor">' + originalMarkup + '</div>', 'text/html');@@ -5029,9 +5117,13 @@}}- function loadSvelteRuntime(runtimeModule) {+ function resolveComponentModuleUrl(manifest, modulePath) {+ return new URL(String(modulePath || ''), location.origin).href;+ }++ function loadSvelteRuntime(runtimeModule, manifest) {const modulePath = runtimeModule || '/src/lib/impeccable/__runtime.js';- const url = new URL(modulePath, location.origin).href;+ const url = resolveComponentModuleUrl(manifest, modulePath);if (!svelteRuntimePromise) {svelteRuntimePromise = import(/* @vite-ignore */ url);}@@ -5065,7 +5157,8 @@async function loadSvelteComponentVariantSource(manifest, variantNum) {const dir = String(manifest?.componentDir || '').replace(/^\/+/, '');if (!dir || !variantNum) return '';- const sourcePath = dir + '/v' + variantNum + '.svelte';+ const extension = manifest.componentExtension || 'svelte';+ const sourcePath = dir + '/v' + variantNum + '.' + extension;const url = 'http://localhost:' + PORT + '/source?token=' + TOKEN + '&path=' + encodeURIComponent(sourcePath);try {const res = await fetch(url);@@ -5221,7 +5314,7 @@if (!sourceOriginal) return values;const map = buildSvelteExpressionTextMap(sourceOriginal, liveEl);for (const entry of contract) {- const token = '{' + entry.expr + '}';+ const token = entry.previewToken || ('{' + entry.expr + '}');values[entry.prop] = map.get(token) || '';}return values;@@ -5233,9 +5326,12 @@try {const previousAnchor = getMountedSvelteComponentAnchor(svelteComponentSession) || selectedElement;svelteComponentSession.swapAnchor = makeFrozenAnchor(previousAnchor) || svelteComponentSession.swapAnchor || null;- const runtime = await loadSvelteRuntime(manifest.runtimeModule);- const modulePath = '/' + String(manifest.componentDir || '').replace(/^\/+/, '') + '/v' + variantNum + '.svelte';- const moduleUrl = new URL(modulePath, location.origin).href + '?t=' + Date.now();+ const runtime = await loadSvelteRuntime(manifest.runtimeModule, manifest);+ const extension = manifest.componentExtension || 'svelte';+ const moduleBase = manifest.componentModuleBase+ || ('/' + String(manifest.componentDir || '').replace(/^\/+/, ''));+ const modulePath = String(moduleBase).replace(/\/+$/, '') + '/v' + variantNum + '.' + extension;+ const moduleUrl = resolveComponentModuleUrl(manifest, modulePath) + '?t=' + Date.now();const mod = await import(/* @vite-ignore */ moduleUrl);const Component = mod.default;if (svelteComponentSession.mountedInstance && runtime.unmount) {@@ -5275,7 +5371,7 @@if (svelteComponentSession?.sessionId === sessionId) {svelteComponentSession.swapAnchor = null;}- console.error('[impeccable] Failed to mount Svelte variant ' + variantNum + ' for ' + sessionId + ':', err);+ console.error('[impeccable] Failed to mount component variant ' + variantNum + ' for ' + sessionId + ':', err);return false;}}@@ -5340,40 +5436,46 @@if (manifest.id !== sessionId) return;const paramsByVariant = await loadSvelteComponentParams(manifest);+ const availableVariants = Number(manifest.arrivedVariants) || Number(manifest.count) || 1;+ const componentPreviewMode = isFrameworkComponentPreviewMode(manifest.previewMode)+ ? manifest.previewMode+ : 'svelte-component';currentSessionId = sessionId;expectedVariants = Number(manifest.count) || expectedVariants || 1;rememberSessionFileMeta({sourceFile: manifest.sourceFile,previewFile: manifestPath,- previewMode: 'svelte-component',+ previewMode: componentPreviewMode,});if (state !== 'CYCLING') setLiveState('GENERATING');const existingWrapper = document.querySelector('[data-impeccable-variants="' + sessionId + '"]');if (existingWrapper && svelteComponentSession?.sessionId === sessionId) {recoveryWaitingForAnchor = false;+ svelteComponentSession.manifest = manifest;svelteComponentSession.paramsByVariant = paramsByVariant;- arrivedVariants = Number(manifest.count) || expectedVariants || 1;- expectedVariants = arrivedVariants;+ arrivedVariants = availableVariants;+ expectedVariants = Number(manifest.count) || expectedVariants || arrivedVariants;visibleVariant = visibleVariant > 0 && visibleVariant <= arrivedVariants ? visibleVariant : 1;await mountSvelteComponentVariant(visibleVariant || 1);setLiveState('CYCLING');showOrUpdateCyclingBar();saveSession();+ if (parameterGenerationState === 'loading') completeParameterPublication();return;}const liveEl = findLiveElementForSvelteManifest(manifest);if (!liveEl?.parentElement) {console.warn('[impeccable] Could not find original element in live DOM.');- arrivedVariants = Number(manifest.count) || expectedVariants || 1;- expectedVariants = arrivedVariants;+ arrivedVariants = availableVariants;+ expectedVariants = Number(manifest.count) || expectedVariants || arrivedVariants;const saved = loadSession();const savedVisibleVariant = saved && saved.id === sessionId ? saved.visible : 0;visibleVariant = visibleVariant > 0 && visibleVariant <= arrivedVariants? visibleVariant: (savedVisibleVariant > 0 && savedVisibleVariant <= arrivedVariants ? savedVisibleVariant : 1);- enterRecoveryWaitingForAnchor({ checkpointReason: 'svelte_component_anchor_missing', trackScroll: true });+ enterRecoveryWaitingForAnchor({ checkpointReason: 'component_preview_anchor_missing', trackScroll: true });waitForSvelteComponentTargetAndRetry({ manifestPath, sessionId, manifest });return;}@@ -5381,7 +5483,7 @@const wrapper = document.createElement('div');wrapper.dataset.impeccableVariants = sessionId;wrapper.dataset.impeccableVariantCount = String(manifest.count || expectedVariants || 1);- wrapper.dataset.impeccablePreview = 'svelte-component';+ wrapper.dataset.impeccablePreview = componentPreviewMode;wrapper.style.display = 'contents';const mountTarget = document.createElement('div');@@ -5419,8 +5521,8 @@recoveryWaitingForAnchor = false;const previousVisibleVariant = currentSessionId === sessionId ? visibleVariant : 0;- arrivedVariants = Number(manifest.count) || expectedVariants || 1;- expectedVariants = arrivedVariants;+ arrivedVariants = availableVariants;+ expectedVariants = Number(manifest.count) || expectedVariants || arrivedVariants;const saved = loadSession();const savedVisibleVariant = saved && saved.id === sessionId ? saved.visible : 0;visibleVariant = previousVisibleVariant > 0 && previousVisibleVariant <= arrivedVariants@@ -5445,9 +5547,10 @@refreshParamsPanel();positionBar();saveSession();- console.log('[impeccable] Mounted ' + arrivedVariants + ' Svelte component variants.');+ if (parameterGenerationState === 'loading') completeParameterPublication();+ console.log('[impeccable] Mounted ' + arrivedVariants + ' ' + manifest.framework + ' component variants.');} catch (err) {- console.error('[impeccable] Failed to mount Svelte component variants:', err);+ console.error('[impeccable] Failed to mount component-preview variants:', err);abortSvelteComponentInjection(sessionId, 'Could not load variants. Fix the error and re-run.');}}@@ -5493,6 +5596,8 @@clearHandled();resetSessionFileMeta();currentSessionId = null;+ parameterGenerationState = 'idle';+ parameterReadyAnnouncedSession = null;expectedVariants = 0;arrivedVariants = 0;visibleVariant = 0;@@ -5502,12 +5607,24 @@if (message) showToast(message, 5000);}+ // How many delayed re-reads a completion-driven source fallback gets when+ // the fetched source still shows only the preflight scaffold, before the+ // failure is surfaced via recoverEmptyCycling.+ const COMPLETED_SOURCE_FALLBACK_RETRIES = 3;+ const COMPLETED_SOURCE_FALLBACK_RETRY_MS = 1200;+/*** No-HMR fallback: fetch the raw source file from the live server,* parse it, extract the variant wrapper, and inject it into the live DOM.* This works even when the dev server caches HTML (Bun, static servers).+ *+ * opts.generationCompleted marks callers that KNOW the agent finished (a+ * `done` arrived or the server reported a completed generation). For them an+ * empty read is a stale source view and no further event is coming, so the+ * read retries a few times and then surfaces recovery. Callers without the+ * flag may be mid-generation and wait indefinitely for the real completion.*/- function injectVariantsFromSource(filePath, sessionId) {+ function injectVariantsFromSource(filePath, sessionId, opts = {}) {if (isSvelteComponentManifestPath(filePath)) {injectSvelteComponentsFromManifest(filePath, sessionId);return;@@ -5573,6 +5690,32 @@arrivedVariants = variants.length;expectedVariants = parseInt(wrapper.dataset.impeccableVariantCount || arrivedVariants);if (arrivedVariants <= 0) {+ if (state === 'GENERATING') {+ // Mid-generation the source legitimately holds a scaffold wrapper+ // with no variants yet (the server-side preflight wraps before the+ // agent writes). Tearing the session down here would destroy an+ // in-flight generation; stay in GENERATING — the variant observer+ // is armed and the server re-delivers a missed `done`.+ if (!opts.generationCompleted) {+ console.log('[impeccable] Source has scaffold but no variants yet; still generating.');+ return;+ }+ // Generation finished, yet the read shows only the scaffold: the+ // source view is stale and no further event will fire. Re-read a+ // few times before surfacing recovery — a single silent return+ // here would strand the tab in GENERATING forever.+ const attempt = opts.attempt || 0;+ if (attempt < COMPLETED_SOURCE_FALLBACK_RETRIES) {+ console.log('[impeccable] Generation is done but source shows no variants yet; retrying read ('+ + (attempt + 1) + '/' + COMPLETED_SOURCE_FALLBACK_RETRIES + ').');+ setTimeout(() => {+ if (state !== 'GENERATING' || currentSessionId !== sessionId) return;+ if (arrivedVariants > 0) return;+ injectVariantsFromSource(filePath, sessionId, { ...opts, attempt: attempt + 1 });+ }, COMPLETED_SOURCE_FALLBACK_RETRY_MS);+ return;+ }+ }recoverEmptyCycling('source-fallback-empty');return;}@@ -5594,6 +5737,7 @@refreshParamsPanel();positionBar();saveSession();+ if (parameterGenerationState === 'loading') completeParameterPublication();console.log('[impeccable] Injected ' + arrivedVariants + ' variants from source file.');}).catch(err => {@@ -5865,13 +6009,36 @@document.getElementById(VARIANT_STATE_STYLE_ID)?.remove();}+ function showOriginalDuringDiscard(sessionId) {+ if (!sessionId) return;+ let styleEl = document.getElementById(DISCARD_STATE_STYLE_ID);+ if (!styleEl) {+ styleEl = document.createElement('style');+ styleEl.id = DISCARD_STATE_STYLE_ID;+ (document.head || document.documentElement).appendChild(styleEl);+ }+ const wrapper = '[data-impeccable-variants="' + sessionId + '"]';+ styleEl.textContent = wrapper + ' > [data-impeccable-variant]:not([data-impeccable-variant="original"]) { display:none !important; }\n'+ + wrapper + ' > [data-impeccable-variant="original"] { display:block !important; }';+ }++ function resolveScrollLockAnchorTop() {+ const anchor = resolveBarAnchor();+ if (!anchor?.isConnected) return null;+ const top = anchor.getBoundingClientRect().top;+ return Number.isFinite(top) ? top : null;+ }+// Hold window.scrollY at a fixed value across DOM mutations inside the// session's wrapper (HMR patches, variant inserts, cycle swaps).- function startScrollLock(sessionId, initialTargetY) {+ function startScrollLock(sessionId, initialTargetY, initialAnchorTop) {stopScrollLock();scrollLockTargetY = typeof initialTargetY === 'number' && isFinite(initialTargetY)? initialTargetY: window.scrollY;+ scrollLockAnchorTop = typeof initialAnchorTop === 'number' && isFinite(initialAnchorTop)+ ? initialAnchorTop+ : resolveScrollLockAnchorTop();try { history.scrollRestoration = 'manual'; } catch {}@@ -5895,6 +6062,17 @@const correct = (why) => {scrollLockRaf = null;if (scrollLockTargetY == null) return;+ const anchor = resolveBarAnchor();+ if (anchor?.isConnected && typeof scrollLockAnchorTop === 'number' && isFinite(scrollLockAnchorTop)) {+ const anchorTop = anchor.getBoundingClientRect().top;+ const anchorDelta = anchorTop - scrollLockAnchorTop;+ if (Math.abs(anchorDelta) >= 0.5) {+ window.scrollTo({ top: window.scrollY + anchorDelta, left: window.scrollX, behavior: 'instant' });+ scrollLockTargetY = window.scrollY;+ writeScrollY(scrollLockTargetY);+ return;+ }+ }const before = window.scrollY;const delta = before - scrollLockTargetY;if (Math.abs(delta) < 0.5) {@@ -5939,6 +6117,7 @@if (scrollLockRaf != null) { cancelAnimationFrame(scrollLockRaf); scrollLockRaf = null; }const prevTarget = scrollLockTargetY;scrollLockTargetY = window.scrollY;+ scrollLockAnchorTop = resolveScrollLockAnchorTop();writeScrollY(scrollLockTargetY);};const markGesture = (why) => {@@ -5976,6 +6155,7 @@if (scrollLockRaf != null) { cancelAnimationFrame(scrollLockRaf); scrollLockRaf = null; }if (scrollLockAbort) { scrollLockAbort.abort(); scrollLockAbort = null; }scrollLockTargetY = null;+ scrollLockAnchorTop = null;// NOTE: do NOT clear the persistent scroll key here. startScrollLock// calls us as a reset, and clearing the key would nuke the Go-time// scrollY that the next resume needs to read.@@ -6049,6 +6229,7 @@updating = true;arrivedVariants = count;+ generationPhase = arrivedVariants >= expectedVariants ? 'variants_ready' : 'variants_progress';if (visibleVariant === 0 && arrivedVariants > 0) {const saved = loadSession();const savedVisibleVariant = saved && saved.id === sessionId ? saved.visible : 0;@@ -6064,7 +6245,7 @@const expected = parseInt(wrapper.dataset.impeccableVariantCount || '0');if (expected > 0) expectedVariants = expected;- if (arrivedVariants >= expectedVariants && expectedVariants > 0) {+ if (arrivedVariants > 0) {setLiveState('CYCLING');recoveryWaitingForAnchor = false;hideShaderOverlay();@@ -6072,13 +6253,18 @@updateSelectedElement();showOrUpdateCyclingBar();disableInlineEdit();- refreshParamsPanel();+ if (arrivedVariants >= expectedVariants && expectedVariants > 0) refreshParamsPanel();+ else hideParamsPanel();positionBar();} else if (state === 'GENERATING') {updateBarContent('generating');}saveSession();- queueCheckpoint(state === 'CYCLING' ? 'variants_ready' : 'variants_progress');+ sendCheckpoint(+ arrivedVariants >= expectedVariants && expectedVariants > 0+ ? 'variants_ready'+ : 'variants_progress',+ );updating = false;});@@ -6151,6 +6337,7 @@syncAgentPollingUi(!!msg.agentPolling);startAgentStatusPoll();restoreFromActiveSessions(msg.activeSessions, 'sse_connected');+ recoverMissedGenerationCompletion(msg.activeSessions);if (state === 'IDLE' && (pickActive || insertActive)) setLiveState('PICKING');syncPageInteractionCursor();syncPageChatFocus('sse-connected');@@ -6158,6 +6345,42 @@case 'agent_polling':syncAgentPollingUi(!!msg.connected);break;+ case 'agent_phase':+ if (msg.id === currentSessionId && (state === 'GENERATING' || state === 'CYCLING')) {+ generationPhase = msg.phase || generationPhase;+ if (msg.phase === 'variant_parameters_generating' || msg.phase === 'variant_parameters_validating') {+ parameterGenerationState = 'loading';+ }+ if (msg.phase === 'parameters_ready' && parameterGenerationState !== 'ready') {+ parameterGenerationState = 'loading';+ }+ updateBarContent(state === 'CYCLING' ? 'cycling' : 'generating');+ saveSession();+ }+ break;+ case 'variant_progress':+ if (msg.id === currentSessionId) {+ if (msg.publicationKind === 'params') parameterGenerationState = 'loading';+ rememberSessionFileMeta(msg);+ if (isFrameworkComponentPreviewMode(msg.previewMode) && msg.previewFile) {+ injectSvelteComponentsFromManifest(msg.previewFile, msg.id);+ } else if ((msg.previewMode === 'source' || !msg.previewMode) && (msg.previewFile || msg.file)) {+ // Give normal framework HMR the first chance to reconcile its+ // own managed tree. Nuxt route-module HMR can skip intermediate+ // revisions, so fall back to source injection only when the+ // advertised progress still has not appeared after a short+ // settle. Immediate injection races React/Vue ownership and can+ // trigger removeChild errors on the next HMR commit.+ const targetArrived = Number(msg.arrivedVariants) || 1;+ setTimeout(() => {+ if (msg.id !== currentSessionId) return;+ if (state !== 'GENERATING' && state !== 'CYCLING') return;+ if (msg.publicationKind !== 'params' && arrivedVariants >= targetArrived) return;+ injectVariantsFromSource(msg.previewFile || msg.file, msg.id);+ }, 150);+ }+ }+ break;case 'steer_done':maybeCompleteSteer(msg);break;@@ -6175,6 +6398,10 @@case 'done':if (maybeCompleteSteer(msg)) break;rememberSessionFileMeta(msg);+ if (msg.id === currentSessionId && isFrameworkComponentPreviewMode(currentPreviewMode) && currentPreviewFile) {+ injectSvelteComponentsFromManifest(currentPreviewFile, msg.id);+ break;+ }// Variants already arrived via HMR → normal transition.if (arrivedVariants >= expectedVariants && expectedVariants > 0) {if (state === 'GENERATING') {@@ -6190,7 +6417,7 @@setTimeout(() => {if (arrivedVariants >= expectedVariants && expectedVariants > 0) return;if (state !== 'GENERATING' || msg.id !== currentSessionId) return;- injectVariantsFromSource(msg.file, msg.id);+ injectVariantsFromSource(msg.file, msg.id, { generationCompleted: true });}, 750);break;}@@ -6215,9 +6442,10 @@if (maybeCompleteAcceptedSession(msg)) break;break;case 'agent_done':- // Carbonize accepts are not terminal until live-complete.mjs sends- // the final complete event. Keep the browser in its recoverable- // saving state while the source cleanup is still in flight.+ // The deterministic accept has already committed the reviewed DOM+ // and fenced generation. Carbonize may continue in the background;+ // it must not hold the foreground picker hostage.+ if (msg.data?.carbonize === true && maybeCompleteAcceptedSession(msg)) break;break;case 'discarded':if (msg.id && msg.id === currentSessionId) {@@ -6306,6 +6534,7 @@type: 'checkpoint',id: currentSessionId,revision: sessionState.nextCheckpointRevision(),+ revisionDomain: 'browser',owner: browserOwner,phase: String(state || '').toLowerCase(),reason,@@ -6331,6 +6560,7 @@type: 'checkpoint',id,revision: sessionState.nextCheckpointRevision(),+ revisionDomain: 'browser',owner: browserOwner,phase: 'steer',reason,@@ -6684,6 +6914,9 @@expectedVariants = selectedCount;arrivedVariants = 0;visibleVariant = 0;+ generationPhase = 'queued';+ parameterGenerationState = 'pending';+ parameterReadyAnnouncedSession = null;resetSessionFileMeta();// Flip to GENERATING immediately so the bar morphs without waiting on@@ -6693,6 +6926,7 @@const elForCapture = selectedElement;pickedAnchorSnapshot = buildPickedAnchorSnapshot(elForCapture);const captureRect = elForCapture.getBoundingClientRect();+ pickedAnchorViewportTop = captureRect.top;const snapshot = {comments: annotState.comments.map(c => ({ x: c.x, y: c.y, text: c.text })),strokes: annotState.strokes.map(s => ({ points: s.points.map(p => [p[0], p[1]]) })),@@ -6724,7 +6958,7 @@writeScrollY(window.scrollY);if (variantObserver) variantObserver.disconnect();variantObserver = startVariantObserver(currentSessionId);- startScrollLock(currentSessionId);+ startScrollLock(currentSessionId, window.scrollY, pickedAnchorViewportTop);captureAndEmit(elForCapture, basePayload, snapshot, captureRect);}@@ -6759,12 +6993,16 @@expectedVariants = selectedCount;arrivedVariants = 0;visibleVariant = 0;+ generationPhase = 'queued';+ parameterGenerationState = 'pending';+ parameterReadyAnnouncedSession = null;resetSessionFileMeta();selectedElement = placeholderElement;insertPlaceholderSnapshot = buildInsertPlaceholderSnapshotFromDom(insertAnchorElement, placeholderElement);const elForCapture = placeholderElement;const captureRect = elForCapture.getBoundingClientRect();+ pickedAnchorViewportTop = captureRect.top;const basePayload = {type: 'generate',mode: 'insert',@@ -6795,7 +7033,7 @@writeScrollY(window.scrollY);if (variantObserver) variantObserver.disconnect();variantObserver = startVariantObserver(currentSessionId);- startScrollLock(currentSessionId);+ startScrollLock(currentSessionId, window.scrollY, pickedAnchorViewportTop);captureAndEmit(elForCapture, basePayload, snapshot, captureRect);}@@ -6975,9 +7213,9 @@// preview mounts are covered by the same shader regression checks.const adapter = String(window.__IMPECCABLE_LIVE_ADAPTER__ || '').toLowerCase();if (adapter === 'svelte' || adapter === 'sveltekit') return true;- if (currentPreviewMode === 'svelte-component' || svelteComponentSession) return true;+ if (isFrameworkComponentPreviewMode(currentPreviewMode) || svelteComponentSession) return true;const wrapper = el?.closest?.('[data-impeccable-variants]');- return wrapper?.dataset?.impeccablePreview === 'svelte-component';+ return isFrameworkComponentPreviewMode(wrapper?.dataset?.impeccablePreview);}function paintsShaderProxySurface(node) {@@ -7105,6 +7343,17 @@}async function captureAndEmit(el, basePayload, snapshot, rect) {+ const hasAnnotations = snapshot && (snapshot.comments.length > 0 || snapshot.strokes.length > 0);++ // Plain requests do not send a screenshot to the agent, so capture is+ // presentation-only. Wait only for the helper to accept the event before+ // starting CPU-heavy capture; this yields the browser task and prevents+ // rasterization from delaying the fetch itself.+ if (!hasAnnotations) {+ basePayload.clientSentAt = Date.now();+ await sendEvent(basePayload);+ }+let screenshotPath;let blob;let paper;@@ -7122,7 +7371,6 @@// are present. Without annotations the image is pure visual anchoring -// it biases the model toward the current rendering and works against the// three-distinct-directions brief.- const hasAnnotations = snapshot && (snapshot.comments.length > 0 || snapshot.strokes.length > 0);if (blob && hasAnnotations) {try {const uploadRes = await fetch(@@ -7140,7 +7388,12 @@console.warn('[impeccable] annotation upload failed:', err);}}- sendEvent(screenshotPath ? { ...basePayload, screenshotPath } : basePayload);+ // Annotated requests must wait for capture + upload because the screenshot+ // is semantic input. Plain requests were already dispatched above.+ if (hasAnnotations) {+ basePayload.clientSentAt = Date.now();+ sendEvent(screenshotPath ? { ...basePayload, screenshotPath } : basePayload);+ }}//@@ -7520,7 +7773,6 @@ void main() {if (variantSelectionPromise) {try { await variantSelectionPromise; } catch { /* failed selection falls back below */ }}- if (!currentSessionId || arrivedVariants === 0) return;const domVisibleVariant = readVisibleVariantFromDOM(currentSessionId);if (domVisibleVariant > 0) visibleVariant = domVisibleVariant;const acceptPayload = {@@ -7528,7 +7780,9 @@ void main() {id: currentSessionId,variantId: String(visibleVariant),pageUrl: location.pathname,+ clientSentAt: Date.now(),};+ if (!currentSessionId || arrivedVariants === 0) return;const acceptWrapper = document.querySelector('[data-impeccable-variants="' + currentSessionId + '"]');if (Object.keys(paramsCurrentValues).length > 0) {acceptPayload.paramValues = { ...paramsCurrentValues };@@ -7542,7 +7796,7 @@ void main() {const acceptedSessionId = currentSessionId;const acceptedVariant = visibleVariant;const acceptedIsSvelteComponent = svelteComponentSession?.sessionId === acceptedSessionId- || acceptWrapper?.dataset?.impeccablePreview === 'svelte-component';+ || isFrameworkComponentPreviewMode(acceptWrapper?.dataset?.impeccablePreview);const acceptedSnapshot = snapshotAcceptedVariantDom(acceptedSessionId, acceptedVariant);setLiveState('SAVING');@@ -7557,7 +7811,17 @@ void main() {saveSession();sendEvent(acceptPayload, { throwOnError: true })- .then(() => {})+ .then(() => {+ const pending = pendingAcceptedSession;+ if (!pending || pending.id !== acceptedSessionId) return;+ // POST /events returns only after the accept intent is durable and the+ // generation epoch is fenced. Source promotion/carbonize can finish in+ // the background; the foreground picker is free immediately.+ markSessionHandled();+ setLiveState('CONFIRMED');+ document.documentElement.dataset.impeccableAcceptToPickingMs = String(Date.now() - acceptPayload.clientSentAt);+ scheduleAcceptCleanup(pending);+ }).catch(() => {if (pendingAcceptedSession?.id === acceptedSessionId) pendingAcceptedSession = null;setLiveState('CYCLING');@@ -7586,17 +7850,26 @@ void main() {}function scheduleAcceptCleanup(accepted) {- setTimeout(function() {- if (!accepted?.isSvelteComponent && !acceptedDomAlreadyClean(accepted)) {- setTimeout(function() {- if (pendingAcceptedSession?.id !== accepted?.id) return;- if (!accepted?.isSvelteComponent) ensureAcceptedDomClean(accepted);- cleanupAcceptedSession();- }, 1800);- return;+ queueMicrotask(function() {+ if (pendingAcceptedSession?.id !== accepted?.id) return;+ // Svelte previews live in an adapter-owned mount rather than in source+ // wrapper markup. Promote the mounted variant before releasing the+ // session so the old adapter instance cannot linger behind the next+ // Pick → Go loop while carbonize finishes in the background.+ if (accepted?.isSvelteComponent) {+ commitAcceptedSvelteComponentToDom(accepted.id);}cleanupAcceptedSession();- }, 1200);+ });+ // Let React/Vue/Svelte own the HMR reconciliation. Mutating their DOM in+ // the same turn as the source update causes removeChild/NotFoundError+ // races. Static servers still need a fallback, but it must not keep Live+ // in SAVING or block the user's next pick.+ if (!accepted?.isSvelteComponent) {+ setTimeout(function() {+ if (!acceptedDomAlreadyClean(accepted)) ensureAcceptedDomClean(accepted);+ }, 1200);+ }}function snapshotAcceptedVariantDom(sessionId, variantId) {@@ -7700,7 +7973,11 @@ void main() {clearSession();resetSessionFileMeta();selectedElement = null;+ hoveredElement = null;+ pagePickSkipClick = false;currentSessionId = null;+ parameterGenerationState = 'idle';+ parameterReadyAnnouncedSession = null;selectedAction = 'impeccable';pendingAcceptedSession = null;renderEditBadge('hidden');@@ -7735,7 +8012,7 @@ void main() {sendEvent({ type: 'discard', id: currentSessionId }, { throwOnError: true }).then(() => {markSessionHandled();- cleanup();+ cleanup({ restoreOriginal: true, instantChrome: true });}).catch(() => showToast('Could not confirm discard with the live server. Session kept for recovery.', 5000));}@@ -7757,6 +8034,7 @@ void main() {currentPreviewMode = null;recoveryWaitingForAnchor = false;pickedAnchorSnapshot = null;+ pickedAnchorViewportTop = null;}function rememberSessionFileMeta(meta = {}) {@@ -7765,8 +8043,8 @@ void main() {const previewFile = normalizeSessionPath(meta.previewFile);const previewMode = meta.previewMode || (isSvelteComponentManifestPath(previewFile || file) ? 'svelte-component' : null);- if (previewMode === 'svelte-component' || isSvelteComponentManifestPath(file)) {- currentPreviewMode = 'svelte-component';+ if (isFrameworkComponentPreviewMode(previewMode) || isSvelteComponentManifestPath(file)) {+ currentPreviewMode = isFrameworkComponentPreviewMode(previewMode) ? previewMode : 'svelte-component';currentPreviewFile = previewFile || (isSvelteComponentManifestPath(file) ? file : currentPreviewFile);currentSourceFile = sourceFile || currentSourceFile;return;@@ -7782,12 +8060,15 @@ void main() {rememberSessionFileMeta(saved);if (saved.insertPlaceholder) insertPlaceholderSnapshot = saved.insertPlaceholder;if (saved.pickedAnchor) pickedAnchorSnapshot = saved.pickedAnchor;+ if (Number.isFinite(saved.pickedAnchorViewportTop)) pickedAnchorViewportTop = saved.pickedAnchorViewportTop;if (saved.action) selectedAction = saved.action;if (saved.count) selectedCount = saved.count;if (saved.previewMode) currentPreviewMode = saved.previewMode;if (saved.paramValues && typeof saved.paramValues === 'object') {paramsCurrentValues = { ...saved.paramValues };}+ if (saved.parameterState) parameterGenerationState = saved.parameterState;+ if (saved.generationPhase) generationPhase = saved.generationPhase;}function normalizePagePath(value) {@@ -7859,7 +8140,7 @@ void main() {saveSession();queueCheckpoint(reason || 'browser_restore_without_wrapper');- const restoreFile = currentPreviewMode === 'svelte-component'+ const restoreFile = isFrameworkComponentPreviewMode(currentPreviewMode)? currentPreviewFile: (currentSourceFile || currentPreviewFile);if (restoreFile) {@@ -7872,11 +8153,41 @@ void main() {function restoreFromActiveSessions(activeSessions, reason) {const wrapper = document.querySelector('[data-impeccable-variants]');- if (wrapper && wrapper.dataset.impeccablePreview !== 'svelte-component') return false;+ if (wrapper && !isFrameworkComponentPreviewMode(wrapper.dataset.impeccablePreview)) return false;if (svelteComponentSession?.sessionId === currentSessionId) return false;return restoreSessionWithoutWrapper(reason || 'sse_connected', activeSessions);}+ // Self-heal on SSE (re)connect. The preflight scaffold write triggers a+ // framework full-reload (Astro reloads pages for any .astro edit); if the+ // agent's variant write + `done` broadcast land while this page is+ // mid-reload, both the done SSE and the second HMR reload are missed and+ // the resumed page would wait in GENERATING at 0/N forever. The server's+ // session summary carries the durable generationCompletedAt marker, so on+ // every connect compare it against our own progress and pull the finished+ // variants from source when behind. Mirrors the `done` handler's source+ // fallback, including its give-HMR-the-first-chance settle delay.+ function recoverMissedGenerationCompletion(activeSessions) {+ if (!currentSessionId || state !== 'GENERATING') return;+ if (!Array.isArray(activeSessions)) return;+ const summary = activeSessions.find((session) => session?.id === currentSessionId);+ if (!summary?.generationCompletedAt || summary.generationCanceled) return;+ if (isTerminalSessionSummary(summary)) return;+ if (arrivedVariants > 0 && arrivedVariants >= expectedVariants) return;+ rememberSessionFileMeta(summary);+ const sessionId = currentSessionId;+ const file = isFrameworkComponentPreviewMode(currentPreviewMode)+ ? currentPreviewFile+ : (summary.sourceFile || summary.previewFile || currentSourceFile || currentPreviewFile);+ if (!file) return;+ console.log('[impeccable] Reconnected after generation completed; recovering variants from source.');+ setTimeout(() => {+ if (sessionId !== currentSessionId || state !== 'GENERATING') return;+ if (arrivedVariants > 0 && arrivedVariants >= expectedVariants) return;+ injectVariantsFromSource(file, sessionId, { generationCompleted: true });+ }, 750);+ }+function saveSession() {if (!currentSessionId) return;// NOTE: scrollY is stored under a separate key (writeScrollY). Storing@@ -7894,8 +8205,12 @@ void main() {previewMode: currentPreviewMode || undefined,pageUrl: location.pathname,paramValues: { ...paramsCurrentValues },+ parameterState: parameterGenerationState,insertPlaceholder: insertPlaceholderSnapshot || undefined,pickedAnchor: pickedAnchorSnapshot || undefined,+ pickedAnchorViewportTop: Number.isFinite(pickedAnchorViewportTop) ? pickedAnchorViewportTop : undefined,+ pageHash: location.hash || undefined,+ pageSearch: location.search || undefined,});}@@ -7923,20 +8238,26 @@ void main() {sessionState.clearHandled();}- function cleanup() {+ function cleanup(options) {+ const restoreOriginal = options?.restoreOriginal === true;+ const instantChrome = options?.instantChrome === true;const cleanupSessionId = currentSessionId;if (svelteComponentSession?.sessionId === cleanupSessionId) {teardownSvelteComponentSession(true);} else if (cleanupSessionId) {- // Hide the wrapper immediately so variants disappear. DON'T structurally- // mutate the DOM yet - HMR from the agent's source rewrite is on its way,+ // Switch visibility immediately without structurally mutating the DOM.+ // HMR from the agent's source rewrite may still be on its way,// and a manual replaceChild under React causes NotFoundError when the// reconciler later tries to remove a wrapper we already removed.// Schedule a 2s fallback that does the manual swap only if HMR hasn't// replaced the wrapper by then (keeps static-server / no-HMR flows alive).const wrapper = document.querySelector('[data-impeccable-variants="' + cleanupSessionId + '"]');- if (wrapper) wrapper.style.display = 'none';+ if (wrapper) {+ if (restoreOriginal) showOriginalDuringDiscard(cleanupSessionId);+ else wrapper.style.display = 'none';+ }setTimeout(function() {+ document.getElementById(DISCARD_STATE_STYLE_ID)?.remove();if (!cleanupSessionId) return;const lateWrapper = document.querySelector('[data-impeccable-variants="' + cleanupSessionId + '"]');if (!lateWrapper) return;@@ -7951,7 +8272,7 @@ void main() {lateWrapper.remove();}, 2000);}- hideBar();+ hideBar(instantChrome);hideHighlight();stopScrollTracking();if (variantObserver) { variantObserver.disconnect(); variantObserver = null; }@@ -7963,7 +8284,11 @@ void main() {clearSession();resetSessionFileMeta();selectedElement = null;+ hoveredElement = null;+ pagePickSkipClick = false;currentSessionId = null;+ parameterGenerationState = 'idle';+ parameterReadyAnnouncedSession = null;selectedAction = 'impeccable';renderEditBadge('hidden');setLiveState('PICKING');@@ -8047,7 +8372,7 @@ void main() {// would strand the bar in CYCLING at 0/0. If there's no live in-memory mount// for this wrapper, it's an orphan (reload / failed mount): drop it and let// the live-server's SSE re-inject the manifest if the session is still live.- if (wrapper.dataset.impeccablePreview === 'svelte-component'+ if (isFrameworkComponentPreviewMode(wrapper.dataset.impeccablePreview)&& svelteComponentSession?.sessionId !== sessionId) {wrapper.remove();if (restoreSessionWithoutWrapper('browser_resumed_svelte_orphan_wrapper')) return true;@@ -8056,7 +8381,7 @@ void main() {return false;}- if (wrapper.dataset.impeccablePreview === 'svelte-component') {+ if (isFrameworkComponentPreviewMode(wrapper.dataset.impeccablePreview)) {if (!svelteComponentSession?.mountedVariant) {return true;}@@ -8104,7 +8429,7 @@ void main() {insertPlaceholderSnapshot = saved.insertPlaceholder;}- const resumedState = arrivedVariants >= expectedVariants ? 'CYCLING' : 'GENERATING';+ const resumedState = arrivedVariants > 0 ? 'CYCLING' : 'GENERATING';// Find the visible variant's content element for highlight positioning.const isInsert = wrapper.dataset.impeccableMode === 'insert';@@ -8128,7 +8453,11 @@ void main() {// hid. Now that state is CYCLING, re-fire.if (state === 'CYCLING') refreshParamsPanel();saveSession();- queueCheckpoint('browser_resumed');+ if (arrivedVariants > 0 && arrivedVariants < expectedVariants) {+ sendCheckpoint('variants_progress');+ } else {+ queueCheckpoint('browser_resumed');+ }// Start observing for more variants AFTER initial setupif (variantObserver) variantObserver.disconnect();@@ -8136,7 +8465,7 @@ void main() {// Hold the target at its saved viewport top through any subsequent// HMR patches, variant inserts, or cycle swaps.- startScrollLock(currentSessionId, readScrollY());+ startScrollLock(currentSessionId, readScrollY(), pickedAnchorViewportTop);// If we reloaded mid-generation (Bun's HTML HMR destroys the shader// canvas), re-capture the original's content and restart the shader so@@ -8171,6 +8500,7 @@ void main() {let globalBarBrandEl = null;let agentPollTooltipEl = null;let agentPollingConnected = false;+ let agentStatusMessage = null;let agentStatusPollTimer = null;let steerFocusSuspended = false;let steerFocusPauseUntil = 0;@@ -8275,6 +8605,13 @@ void main() {const AGENT_STATUS_POLL_MS = 5000;const AGENT_DISCONNECTED_MARK = 'oklch(62% 0 0 / 0.78)';const AGENT_DISCONNECTED_TIP = 'Agent disconnected - run live-poll.mjs to connect';+ // The indicator tracks whether a poll is parked, which is what decides if+ // steering can reach the agent right now. That goes quiet two ways, and they+ // need different copy: nobody is polling at all, or the agent took the work+ // and is busy with it. Under one-shot foreground polling the second case is+ // every normal generation, and telling the user to start a poll loop then is+ // wrong advice about a healthy session.+ const AGENT_BUSY_TIP = 'Agent is working - steering resumes when it finishes';const GLOBAL_BAR_SECTION_GAP = 8;const GLOBAL_BAR_INNER_GAP = 2;const GLOBAL_BAR_INNER_PAD_LEFT = 2;@@ -9295,24 +9632,46 @@ void main() {</svg>`;}+ /**+ * True while the browser is waiting on work it already handed to the agent.+ * In these states a quiet poll indicator means "busy", not "absent".+ */+ function agentHasWorkInFlight() {+ return state === 'GENERATING' || state === 'SAVING';+ }++ /**+ * Derived at read time, not cached: which of the two reasons applies depends on+ * the live state, which moves between the 5s status polls. The truthiness is+ * the same either way, so the indicator's visuals can stay driven by the+ * cached value while the wording stays current.+ */+ function agentStatusText() {+ if (agentPollingConnected) return null;+ return agentHasWorkInFlight() ? AGENT_BUSY_TIP : AGENT_DISCONNECTED_TIP;+ }+function syncAgentPollingUi(connected) {agentPollingConnected = !!connected;if (!globalBarBrandEl) return;const P = barPaletteForTheme(globalBarEl?.dataset.theme || detectPageTheme());+ agentStatusMessage = agentStatusText();globalBarBrandEl.dataset.agentConnected = connected ? 'true' : 'false';- globalBarBrandEl.setAttribute('aria-label', connected- ? 'Impeccable live mode'- : 'Impeccable live mode - agent not polling');+ // The tooltip is mouse-only, so carry the same distinction in the label or+ // screen-reader users are left with the vaguer of the two readings.+ globalBarBrandEl.setAttribute('aria-label', agentStatusMessage+ ? 'Impeccable live mode - ' + (agentHasWorkInFlight() ? 'agent is working' : 'agent not polling')+ : 'Impeccable live mode');globalBarBrandEl.removeAttribute('title');- globalBarBrandEl.style.cursor = connected ? 'default' : 'help';+ globalBarBrandEl.style.cursor = agentStatusMessage ? 'help' : 'default';const mark = globalBarBrandEl.querySelector('[data-brand-mark]');if (mark) {mark.innerHTML = brandMarkSvg(connected ? P.accent : AGENT_DISCONNECTED_MARK, 18);mark.style.opacity = '1';}const dot = globalBarBrandEl.querySelector('[data-agent-dot]');- if (dot) dot.style.display = connected ? 'none' : 'block';- if (connected) hideAgentPollTooltip();+ if (dot) dot.style.display = agentStatusMessage ? 'block' : 'none';+ if (!agentStatusMessage) hideAgentPollTooltip();}function ensureAgentPollTooltip() {@@ -9339,14 +9698,17 @@ void main() {whiteSpace: 'normal',});agentPollTooltipEl.id = PREFIX + '-agent-poll-tooltip';- agentPollTooltipEl.textContent = AGENT_DISCONNECTED_TIP;+ agentPollTooltipEl.textContent = agentStatusText() || AGENT_DISCONNECTED_TIP;uiAppend(agentPollTooltipEl);return agentPollTooltipEl;}function showAgentPollTooltip(anchor) {- if (agentPollingConnected || !anchor) return;+ if (!agentStatusMessage || !anchor) return;const tip = ensureAgentPollTooltip();+ // Re-derive rather than reuse the cached copy: the live state may have moved+ // since the last status poll set it.+ tip.textContent = agentStatusText() || AGENT_DISCONNECTED_TIP;tip.style.transition = 'none';tip.style.display = 'block';tip.style.opacity = '1';@@ -9376,7 +9738,9 @@ void main() {fetch('http://localhost:' + PORT + '/status?token=' + TOKEN, { cache: 'no-store' }).then((res) => (res.ok ? res.json() : null)).then((data) => {- if (data && typeof data.agentPolling === 'boolean') syncAgentPollingUi(data.agentPolling);+ if (data && typeof data.agentPolling === 'boolean') {+ syncAgentPollingUi(data.agentPolling);+ }}).catch(() => { /* server loss handled elsewhere */ });}diff --git a/.claude/skills/impeccable/scripts/live-inject.mjs b/.claude/skills/impeccable/scripts/live-inject.mjsindex 7c8d91182..d99c37fd5 100644--- a/.claude/skills/impeccable/scripts/live-inject.mjs+++ b/.claude/skills/impeccable/scripts/live-inject.mjs@@ -27,6 +27,8 @@ const __dirname = path.dirname(fileURLToPath(import.meta.url));const CONFIG_PATH = resolveLiveConfigPath({ cwd: process.cwd(), scriptsDir: __dirname });const MARKER_OPEN_TEXT = 'impeccable-live-start';const MARKER_CLOSE_TEXT = 'impeccable-live-end';+const NUXT_PLUGIN_MARKER = 'impeccable-live-nuxt-plugin';+const NUXT_PLUGIN_NAME = 'impeccable-live.client.ts';const IGNORE_MARKER_OPEN = '# impeccable-live-ignore-start';const IGNORE_MARKER_CLOSE = '# impeccable-live-ignore-end';@@ -38,6 +40,9 @@ export const LIVE_IGNORE_PATTERNS = Object.freeze(['.impeccable/live/sessions/','.impeccable/live/previews/','.impeccable/live/annotations/',+ '.impeccable/live/artifacts/',+ '.impeccable/live/accept-receipts/',+ '.impeccable/live/locks/','.impeccable/live/cache/','.impeccable/live/manual-edit-apply-transaction.json','.impeccable/live/manual-edit-events.jsonl',@@ -46,10 +51,15 @@ export const LIVE_IGNORE_PATTERNS = Object.freeze(['.impeccable/live/deferred-svelte-component-accepts.json','.impeccable-live.json','.impeccable-live/',+ 'app/.impeccable-live/',+ 'src/.impeccable-live/','node_modules/.impeccable-live/','src/lib/impeccable/ImpeccableLiveRoot.svelte','src/lib/impeccable/__runtime.js','src/lib/impeccable/[0-9a-f]*/',+ 'plugins/impeccable-live.client.ts',+ 'app/plugins/impeccable-live.client.ts',+ 'src/plugins/impeccable-live.client.ts',]);/**@@ -113,6 +123,7 @@ Output (JSON):const resolvedFiles = resolveFiles(process.cwd(), config);const svelteKit = detectSvelteKitProject(process.cwd(), config);+ const nuxt = detectNuxtProject(process.cwd());if (args.includes('--remove')) {if (svelteKit) {@@ -120,6 +131,12 @@ Output (JSON):console.log(JSON.stringify({ ok: true, adapter: 'sveltekit', results: [adapterResult] }));return;}+ if (nuxt) {+ const adapterResult = removeNuxtLiveAdapter({ cwd: process.cwd(), project: nuxt });+ console.log(JSON.stringify({ ok: !adapterResult.error, adapter: 'nuxt', results: [adapterResult] }));+ if (adapterResult.error) process.exitCode = 1;+ return;+ }const results = resolvedFiles.map((relFile) => {const absFile = path.resolve(process.cwd(), relFile);if (!fs.existsSync(absFile)) return { file: relFile, error: 'file_not_found' };@@ -145,13 +162,28 @@ Output (JSON):console.error(JSON.stringify({ ok: false, error: 'missing_port' }));process.exit(1);}- const gitIgnore = ensureLiveGitIgnores(process.cwd());+ const gitIgnore = ensureLiveGitIgnores(+ process.cwd(),+ nuxt ? [nuxt.pluginFile] : [],+ );if (svelteKit) {const adapterResult = applySvelteKitLiveAdapter({ cwd: process.cwd(), port, config });console.log(JSON.stringify({ ok: true, port, adapter: 'sveltekit', gitIgnore, results: [adapterResult] }));return;}+ if (nuxt) {+ const adapterResult = applyNuxtLiveAdapter({ cwd: process.cwd(), port, project: nuxt });+ console.log(JSON.stringify({+ ok: !adapterResult.error,+ port,+ adapter: 'nuxt',+ gitIgnore,+ results: [adapterResult],+ }));+ if (adapterResult.error) process.exitCode = 1;+ return;+ }const results = resolvedFiles.map((relFile) => {const absFile = path.resolve(process.cwd(), relFile);@@ -175,12 +207,12 @@ Output (JSON):if (!anyInserted) process.exit(1);}-export function ensureLiveGitIgnores(cwd = process.cwd()) {+export function ensureLiveGitIgnores(cwd = process.cwd(), extraPatterns = []) {const target = resolveIgnoreTarget(cwd);const existing = fs.existsSync(target.path) ? fs.readFileSync(target.path, 'utf-8') : '';const block = [IGNORE_MARKER_OPEN,- ...LIVE_IGNORE_PATTERNS,+ ...new Set([...LIVE_IGNORE_PATTERNS, ...extraPatterns]),IGNORE_MARKER_CLOSE,].join('\n');const markerRe = new RegExp(`${escapeRegExp(IGNORE_MARKER_OPEN)}[\\s\\S]*?${escapeRegExp(IGNORE_MARKER_CLOSE)}`);@@ -202,10 +234,119 @@ export function ensureLiveGitIgnores(cwd = process.cwd()) {file: path.relative(cwd, target.path).split(path.sep).join('/'),mode: target.mode,changed: updated !== existing,- patterns: [...LIVE_IGNORE_PATTERNS],+ patterns: [...new Set([...LIVE_IGNORE_PATTERNS, ...extraPatterns])],};}+// ---------------------------------------------------------------------------+// Nuxt adapter+//+// A script element placed in app.vue is compiled as Vue-rendered DOM and is+// not executed. Nuxt instead auto-discovers client plugins. Keep the adapter+// generated, dev-only, and outside user-authored source: Live creates one+// marked .client.ts plugin on start and removes it on stop.+// ---------------------------------------------------------------------------++export function detectNuxtProject(cwd = process.cwd()) {+ const configFile = fs.readdirSync(cwd, { withFileTypes: true })+ .find((entry) => entry.isFile() && /^nuxt\.config\.(?:js|mjs|cjs|ts|mts|cts)$/.test(entry.name))+ ?.name;+ if (!configFile) return null;++ const config = fs.readFileSync(path.join(cwd, configFile), 'utf-8');+ const literalSrcDir = config.match(/\bsrcDir\s*:\s*(['"])([^'"]+)\1/);+ let appDir = '';+ if (literalSrcDir) {+ const candidate = literalSrcDir[2]+ .replace(/\\/g, '/')+ .replace(/^\.\//, '')+ .replace(/\/+$/, '');+ const normalized = path.posix.normalize(candidate);+ if (normalized !== '..' && !normalized.startsWith('../') && !path.isAbsolute(normalized)) {+ appDir = normalized === '.' ? '' : normalized;+ }+ } else if (+ fs.existsSync(path.join(cwd, 'app', 'app.vue'))+ || fs.existsSync(path.join(cwd, 'app', 'pages'))+ ) {+ appDir = 'app';+ }++ const pluginFile = [appDir, 'plugins', NUXT_PLUGIN_NAME].filter(Boolean).join('/');+ return { configFile, appDir, pluginFile };+}++export function buildNuxtPlugin(port) {+ return `/* ${NUXT_PLUGIN_MARKER} */+const liveSrc = 'http://localhost:${port}/live.js';+const liveSelector = 'script[data-impeccable-live-nuxt]';++export default defineNuxtPlugin(() => {+ if (!import.meta.dev || typeof document === 'undefined') return;++ const expectedSrc = new URL(liveSrc, window.location.href).href;+ let script = document.querySelector(liveSelector);+ if (script?.src === expectedSrc) return;+ script?.remove();++ script = document.createElement('script');+ script.src = liveSrc;+ script.async = true;+ script.dataset.impeccableLiveNuxt = '';+ document.head.appendChild(script);++ import.meta.hot?.dispose(() => {+ if (script?.isConnected) script.remove();+ });+});+/* /${NUXT_PLUGIN_MARKER} */+`;+}++export function applyNuxtLiveAdapter({ cwd = process.cwd(), port, project = detectNuxtProject(cwd) }) {+ if (!project) return { error: 'nuxt_not_detected' };+ const absFile = path.join(cwd, project.pluginFile);+ const existing = fs.existsSync(absFile) ? fs.readFileSync(absFile, 'utf-8') : null;+ if (existing !== null && !existing.includes(NUXT_PLUGIN_MARKER)) {+ return {+ file: project.pluginFile,+ error: 'nuxt_plugin_conflict',+ hint: `${project.pluginFile} already exists and is not managed by Impeccable Live`,+ };+ }++ const content = buildNuxtPlugin(port);+ fs.mkdirSync(path.dirname(absFile), { recursive: true });+ if (content !== existing) fs.writeFileSync(absFile, content, 'utf-8');+ return {+ file: project.pluginFile,+ inserted: true,+ changed: content !== existing,+ devOnly: true,+ };+}++export function removeNuxtLiveAdapter({ cwd = process.cwd(), project = detectNuxtProject(cwd) }) {+ if (!project) return { error: 'nuxt_not_detected' };+ const absFile = path.join(cwd, project.pluginFile);+ if (!fs.existsSync(absFile)) {+ return { file: project.pluginFile, removed: false, note: 'no adapter present' };+ }+ const content = fs.readFileSync(absFile, 'utf-8');+ if (!content.includes(NUXT_PLUGIN_MARKER)) {+ return {+ file: project.pluginFile,+ removed: false,+ error: 'nuxt_plugin_conflict',+ hint: `${project.pluginFile} is not managed by Impeccable Live`,+ };+ }+ fs.unlinkSync(absFile);+ const pluginDir = path.dirname(absFile);+ if (fs.readdirSync(pluginDir).length === 0) fs.rmdirSync(pluginDir);+ return { file: project.pluginFile, removed: true };+}+function resolveIgnoreTarget(cwd) {const gitExcludePath = resolveGitInfoExcludePath(cwd);if (gitExcludePath) {diff --git a/.claude/skills/impeccable/scripts/live-poll.mjs b/.claude/skills/impeccable/scripts/live-poll.mjsindex 740161e10..19a8b0f9b 100644--- a/.claude/skills/impeccable/scripts/live-poll.mjs+++ b/.claude/skills/impeccable/scripts/live-poll.mjs@@ -27,7 +27,7 @@ const scriptCmd = (name) => `node "${path.join(SELF_DIR, name)}"`;export const PER_REQUEST_TIMEOUT_MS = 270_000;export const DEFAULT_EVENT_LEASE_MS = 600_000;-const EVENT_TYPES_NEEDING_AGENT_REPLY = new Set(['generate', 'steer', 'manual_edit_apply']);+const EVENT_TYPES_NEEDING_AGENT_REPLY = new Set(['generate', 'steer', 'manual_edit_apply', 'carbonize_cleanup']);function readServerInfo() {const record = readLiveServerInfo(process.cwd());@@ -38,8 +38,8 @@ function readServerInfo() {return record.info;}-export function buildPollReplyPayload(token, { id, type, message, file, data }) {- return { token, id, type, message, file, data };+export function buildPollReplyPayload(token, { id, type, message, file, data, sourceEventType }) {+ return { token, id, type, message, file, data, sourceEventType };}export function manualApplyPollBanner(event = {}) {@@ -152,7 +152,14 @@ export async function waitForEventAck(base, token, eventId, {return false;}-export async function fetchNextEvent(base, token, { totalDeadline } = {}) {+export async function fetchNextEvent(base, token, {+ totalDeadline,+ types,+ resolveTypes,+ perRequestTimeoutMs = PER_REQUEST_TIMEOUT_MS,+ leaseMs = DEFAULT_EVENT_LEASE_MS,+ signal,+} = {}) {while (true) {if (totalDeadline && Date.now() >= totalDeadline) {return { type: 'timeout' };@@ -161,8 +168,15 @@ export async function fetchNextEvent(base, token, { totalDeadline } = {}) {const remaining = totalDeadline? totalDeadline - Date.now(): PER_REQUEST_TIMEOUT_MS;- const slice = Math.min(Math.max(remaining, 1000), PER_REQUEST_TIMEOUT_MS);- const res = await fetch(`${base}/poll?token=${token}&timeout=${slice}&leaseMs=${DEFAULT_EVENT_LEASE_MS}`);+ const slice = Math.min(Math.max(remaining, 1000), perRequestTimeoutMs);+ const query = new URLSearchParams({+ token,+ timeout: String(slice),+ leaseMs: String(leaseMs),+ });+ const normalizedTypes = normalizePollTypes(resolveTypes ? await resolveTypes() : types);+ if (normalizedTypes.length > 0) query.set('types', normalizedTypes.join(','));+ const res = await fetch(`${base}/poll?${query}`, { signal });if (res.status === 401) {const err = new Error('Authentication failed. The server token may have changed.');@@ -202,11 +216,17 @@ export async function augmentEventWithAcceptHandling(event, base, token) {event._acceptResult = { handled: false, mode: 'error', error: err.message };}+ await completeAcceptHandling(event, base, token);+ return event;+}++export async function completeAcceptHandling(event, base, token) {const completionType = completionTypeForAcceptResult(event.type, event._acceptResult);try {await postReply(base, token, {id: event.id,type: completionType,+ sourceEventType: event.type,message: event._acceptResult?.error,file: event._acceptResult?.file,data: event._acceptResult?.carbonize === true ? { carbonize: true } : undefined,@@ -217,7 +237,6 @@ export async function augmentEventWithAcceptHandling(event, base, token) {if (!event._completionAck) {event._completionAck = completionAckForAcceptResult(event.id, completionType, event._acceptResult);}-return event;}@@ -245,9 +264,9 @@ export function printPollEvent(event) {console.log(JSON.stringify(event));}-export async function runPollOnce(base, token, { totalTimeout = 600_000 } = {}) {+export async function runPollOnce(base, token, { totalTimeout = 600_000, types, resolveTypes, perRequestTimeoutMs } = {}) {const deadline = Date.now() + totalTimeout;- const event = await fetchNextEvent(base, token, { totalDeadline: deadline });+ const event = await fetchNextEvent(base, token, { totalDeadline: deadline, types, resolveTypes, perRequestTimeoutMs });await augmentEventWithAcceptHandling(event, base, token);writeCarbonizeBanner(event);printPollEvent(event);@@ -258,11 +277,14 @@ export async function runPollStream(base, token, {ackTimeoutMs = 600_000,ackPollIntervalMs = 400,shouldContinue = () => true,+ types,+ resolveTypes,+ perRequestTimeoutMs,} = {}) {process.stderr.write('[impeccable-poll] stream mode: one JSON object per line on stdout; use --reply while this process stays running\n');while (shouldContinue()) {- const event = await fetchNextEvent(base, token);+ const event = await fetchNextEvent(base, token, { types, resolveTypes, perRequestTimeoutMs });await augmentEventWithAcceptHandling(event, base, token);writeCarbonizeBanner(event);printPollEvent(event);@@ -322,14 +344,17 @@ Modes:Options:--timeout=MS One-shot poll timeout in ms (default: 600000). Ignored in --stream mode+ --types=A,B Lease only these event types--ack-timeout=MS Stream mode: max wait for --reply after generate/steer (default: 600000)--file PATH Attach a source file path to the reply (generate/steer flow)--data JSON Attach a JSON result object to the reply (manual_edit_apply flow). Must be valid JSON--help Show this help messageHarness note:- Default one-shot mode is the portable contract for Claude Code, Codex, and Cursor.- --stream is experimental for harnesses with fast incremental stdout; do not use on Cursor.`);+ Default one-shot mode is the primary contract, including Codex foreground polling.+ Claude Code may run it as a background task; Cursor uses a background terminal with exit notification.+ --stream is retained for harnesses with measured, reliable incremental stdout.+ Do not use --stream on Cursor.`);process.exit(0);}@@ -360,23 +385,30 @@ Harness note:}const streamMode = args.includes('--stream');+ const typesArg = args.find((a) => a.startsWith('--types='));+ const types = normalizePollTypes(typesArg ? typesArg.slice('--types='.length) : null);const ackTimeoutArg = args.find((a) => a.startsWith('--ack-timeout='));const ackTimeoutMs = ackTimeoutArg ? parseInt(ackTimeoutArg.split('=')[1], 10) : 600_000;try {if (streamMode) {- await runPollStream(base, info.token, { ackTimeoutMs });+ await runPollStream(base, info.token, { ackTimeoutMs, types });return;}const timeoutArg = args.find((a) => a.startsWith('--timeout='));const totalTimeout = timeoutArg ? parseInt(timeoutArg.split('=')[1], 10) : 600_000;- await runPollOnce(base, info.token, { totalTimeout });+ await runPollOnce(base, info.token, { totalTimeout, types });} catch (err) {handlePollError(err);}}+export function normalizePollTypes(value) {+ const values = Array.isArray(value) ? value : String(value || '').split(',');+ return [...new Set(values.map((type) => String(type).trim()).filter(Boolean))];+}+// Auto-execute when run directlyconst _running = process.argv[1];if (_running?.endsWith('live-poll.mjs') || _running?.endsWith('live-poll.mjs/')) {diff --git a/.claude/skills/impeccable/scripts/live-server.mjs b/.claude/skills/impeccable/scripts/live-server.mjsindex 5735f2aec..c6e951086 100644--- a/.claude/skills/impeccable/scripts/live-server.mjs+++ b/.claude/skills/impeccable/scripts/live-server.mjs@@ -28,8 +28,10 @@ import {readLiveBrowserScriptParts,resolveLiveBrowserScriptParts,} from './live/browser-script-parts.mjs';-import { createLiveSessionStore } from './live/session-store.mjs';+import { createLiveSessionStore, GENERATION_FENCED_PHASES } from './live/session-store.mjs';+import { runGenerationPreflight } from './live/generation-preflight.mjs';import { validateEvent } from './live/event-validation.mjs';+import { selectAvailablePendingEvent } from './live/poll-lanes.mjs';import { createManualEditRoutes } from './live/manual-edit-routes.mjs';import { LIVE_COMMANDS } from './live/vocabulary.mjs';import {@@ -63,6 +65,10 @@ const DESIGN_MD_PATH = PROJECT_CONTEXT.designPath: null;const DEFAULT_POLL_TIMEOUT = 600_000; // 10 min — agent re-polls on timeout anywayconst SSE_HEARTBEAT_INTERVAL = 30_000; // keepalive ping every 30s+// The browser checkpoints for several unrelated reasons (see checkpointPayload+// in live-browser.js). Only these two report that variant availability changed,+// and only they may drive variant_progress / the *_reviewable phases.+const VARIANT_PROGRESS_CHECKPOINT_REASONS = new Set(['variants_progress', 'variants_ready']);// ---------------------------------------------------------------------------// Port detection@@ -156,29 +162,206 @@ function restorePendingEventsFromStore() {}}-function findAvailablePendingEvent(now = Date.now()) {- for (const entry of state.pendingEvents) {- if (entry.leaseUntil && entry.leaseUntil > now) continue;- return entry;- }- return null;+function findAvailablePendingEvent(now = Date.now(), types = null) {+ return selectAvailablePendingEvent(state.pendingEvents, { now, types });}-function leaseEvent(entry, leaseMs) {+async function leaseEvent(entry, leaseMs) {+ // Claim the entry before awaiting anything. prepareGenerateEventForLease+ // yields to the event loop, and selectAvailablePendingEvent only skips+ // entries whose lease is in the future — an unclaimed entry would be handed+ // to a second poll in that window and generated twice.+ entry.leaseUntil = Date.now() + leaseMs;+ await prepareGenerateEventForLease(entry);if (!entry.event?.id) {const idx = state.pendingEvents.indexOf(entry);if (idx !== -1) state.pendingEvents.splice(idx, 1);return entry.event;}+ // Re-stamp so the lease window starts when the agent actually receives the+ // work, not when scaffolding began.entry.leaseUntil = Date.now() + leaseMs;+ recordGenerateDelivery(entry);scheduleLeaseFlush();broadcastAgentPollingIfChanged();return entry.event;}-function acknowledgePendingEvent(id) {+function recordGenerateDelivery(entry) {+ const event = entry?.event;+ if (!event || event.type !== 'generate' || event.generationReadyAt) return;+ const at = Date.now();+ entry.event = { ...event, generationReadyAt: at };+ state.sessionStore?.appendEvent(entry.event);+ recordAgentPhase(event.id, 'generation_ready', { at });+}++async function prepareGenerateEventForLease(entry) {+ const event = entry?.event;+ if (!event || event.type !== 'generate' || event.scaffoldAttempted) return;++ recordAgentPhase(event.id, 'picked_up');+ recordAgentPhase(event.id, 'scaffolding');+ const result = await runGenerationPreflight(event, {+ cwd: process.cwd(),+ scriptsDir: __dirname,+ });+ entry.event = {+ ...event,+ scaffoldAttempted: true,+ scaffoldDurationMs: result.durationMs ?? null,+ ...(result.ok ? { scaffold: result.scaffold } : { scaffoldError: result.error || result.reason }),+ };+ state.sessionStore?.appendEvent(entry.event);+ recordAgentPhase(event.id, result.ok ? 'source_ready' : 'scaffold_fallback', {+ durationMs: result.durationMs ?? null,+ previewMode: result.scaffold?.previewMode || 'source',+ });+}++function recordAgentPhase(id, phase, details = {}) {+ if (!id) return;+ const event = {+ type: 'agent_phase',+ id,+ phase,+ at: Date.now(),+ ...details,+ };+ state.sessionStore?.appendEvent(event);+ broadcast(event);+}++/**+ * Detect a browser that missed the generation `done` broadcast.+ *+ * The preflight scaffold write triggers a framework full-reload (Astro reloads+ * the page for any .astro edit). If the agent's variant write + `done` land+ * while the browser is mid-reload, the new page misses both the second HMR+ * reload and the SSE `done` — it resumes from the scaffold-only source and+ * sits in GENERATING at 0/N forever. That resumed page always checkpoints+ * (`browser_resumed`), so a checkpoint claiming "still generating, variants+ * missing" for a session whose generation already completed is direct+ * evidence of the miss. Rebuild the `done` payload from the snapshot so the+ * caller can re-broadcast it; the browser's done handler is idempotent and+ * falls back to injecting variants from source.+ *+ * Keys on the store's monotone `generationCompletedAt`, not `phase` — the+ * behind checkpoint itself regresses `phase` to `generating`, and a browser+ * that misses the redelivered `done` too (another reload) must still trigger+ * redelivery from its next checkpoint.+ */+function detectMissedGenerationCompletion(event) {+ if (!event?.id || event.type !== 'checkpoint') return null;+ if (event.phase !== 'generating') return null;+ if (!variantCountLooksBehind(event.arrivedVariants, event.expectedVariants)) return null;+ if (!state.sessionStore) return null;+ let snapshot = null;+ try {+ snapshot = state.sessionStore.getSnapshot(event.id);+ } catch {+ return null;+ }+ return missedCompletionFromSnapshot(snapshot);+}++function variantCountLooksBehind(arrivedValue, expectedValue) {+ const arrived = Number(arrivedValue) || 0;+ const expected = Number(expectedValue) || 0;+ return arrived <= 0 || (expected > 0 && arrived < expected);+}++function missedCompletionFromSnapshot(snapshot) {+ if (!snapshot?.id || !snapshot.generationCompletedAt) return null;+ if (snapshot.generationCanceled) return null;+ // Accept/discard already underway: the browser is no longer waiting on+ // generation, and a late `done` there would collide with teardown.+ if (GENERATION_FENCED_PHASES.has(snapshot.phase)) return null;+ const file = snapshot.sourceFile || snapshot.previewFile;+ if (!file) return null;+ return {+ type: 'done',+ id: snapshot.id,+ file,+ sourceFile: snapshot.sourceFile || undefined,+ previewFile: snapshot.previewFile || undefined,+ previewMode: snapshot.previewMode || undefined,+ redelivered: true,+ };+}++function recordGenerationCheckpoint(event) {+ if (!event?.id || event.type !== 'checkpoint') return;+ if (generationIsFenced(event.id)) return;+ // Only checkpoints that report a change in variant availability are+ // generation progress. The browser also checkpoints for durability on Tune+ // slider drags, resumes, and anchor recovery; treating those as progress+ // echoed `variant_progress` straight back to the browser that sent it, which+ // remounts the component preview mid-drag (reverting the user's live param+ // edit and detaching the popover's element), and permanently latched the+ // *_reviewable phases from the wrong trigger, corrupting generation timings.+ if (!VARIANT_PROGRESS_CHECKPOINT_REASONS.has(event.reason)) return;+ const arrived = Number(event.arrivedVariants) || 0;+ const expected = Number(event.expectedVariants) || 0;+ if (arrived <= 0 || expected <= 0) return;+ const previewMode = event.previewMode || 'source';+ const previewFile = event.previewFile || event.file;+ if (previewFile) {+ broadcast({+ type: 'variant_progress',+ id: event.id,+ file: previewFile,+ sourceFile: event.sourceFile || (previewMode === 'source' ? previewFile : undefined),+ previewFile,+ previewMode,+ arrivedVariants: arrived,+ expectedVariants: expected,+ publicationKind: event.publicationKind || 'variants',+ });+ }+ const details = {+ arrivedVariants: arrived,+ expectedVariants: expected,+ checkpointReason: event.reason || null,+ };+ const at = Date.now();+ if (!generationPhaseAlreadyRecorded(event.id, 'first_reviewable')) {+ recordAgentPhase(event.id, 'first_reviewable', { ...details, at });+ }+ if (arrived >= 2 && expected >= 3 && !generationPhaseAlreadyRecorded(event.id, 'second_reviewable')) {+ recordAgentPhase(event.id, 'second_reviewable', { ...details, at });+ }+ if (arrived >= expected && !generationPhaseAlreadyRecorded(event.id, 'all_variants_ready')) {+ recordAgentPhase(event.id, 'all_variants_ready', { ...details, at });+ }+}++function generationIsFenced(id) {+ if (!state.sessionStore || !id) return false;+ try {+ const snapshot = state.sessionStore.getSnapshot(id, { includeCompleted: true });+ return snapshot?.generationCanceled === true;+ } catch {+ return false;+ }+}++function generationPhaseAlreadyRecorded(id, phase) {+ if (!state.sessionStore) return false;+ try {+ const snapshot = state.sessionStore.getSnapshot(id, { includeCompleted: true });+ return !!snapshot?.generationTimings?.[phase];+ } catch {+ return false;+ }+}++function acknowledgePendingEvent(id, sourceEventType) {if (!id) return false;- const idx = state.pendingEvents.findIndex((entry) => entry.event?.id === id);+ const idx = state.pendingEvents.findIndex((entry) => (+ entry.event?.id === id+ && (!sourceEventType || entry.event?.type === sourceEventType)+ ));if (idx === -1) return false;const acknowledged = state.pendingEvents[idx].event;state.pendingEvents.splice(idx, 1);@@ -187,9 +370,39 @@ function acknowledgePendingEvent(id) {return acknowledged;}-function findPendingEventById(id) {+function releasePendingEvent(id, sourceEventType) {+ const entry = state.pendingEvents.find((item) => (+ item.event?.id === id+ && (!sourceEventType || item.event?.type === sourceEventType)+ ));+ if (!entry) return null;+ entry.leaseUntil = 0;+ scheduleLeaseFlush();+ return entry.event;+}++function retirePendingGeneration(id) {+ if (!id) return 0;+ let retired = 0;+ for (let index = state.pendingEvents.length - 1; index >= 0; index -= 1) {+ const event = state.pendingEvents[index]?.event;+ if (event?.id !== id || event.type !== 'generate') continue;+ state.pendingEvents.splice(index, 1);+ retired += 1;+ }+ if (retired > 0) {+ scheduleLeaseFlush();+ broadcastAgentPollingIfChanged();+ }+ return retired;+}++function findPendingEventById(id, sourceEventType) {if (!id) return null;- const entry = state.pendingEvents.find((item) => item.event?.id === id);+ const entry = state.pendingEvents.find((item) => (+ item.event?.id === id+ && (!sourceEventType || item.event?.type === sourceEventType)+ ));return entry?.event || null;}@@ -198,7 +411,7 @@ function summarizePendingEventForStatus(entry) {const summary = {id: event.id,type: event.type,- leased: !!(entry.leaseUntil && entry.leaseUntil > Date.now()),+ leased: isLeased(entry),leaseUntil: entry.leaseUntil || null,};if (event.type === 'manual_edit_apply') {@@ -224,7 +437,13 @@ function summarizeActiveSessionForClient(snapshot = {}) {arrivedVariants: snapshot.arrivedVariants ?? 0,visibleVariant: snapshot.visibleVariant ?? null,checkpointRevision: snapshot.checkpointRevision ?? 0,+ browserCheckpointRevision: snapshot.browserCheckpointRevision ?? snapshot.checkpointRevision ?? 0,+ publicationCheckpointRevision: snapshot.publicationCheckpointRevision ?? 0,paramValues: snapshot.paramValues || {},+ generationPhase: snapshot.generationPhase ?? null,+ generationCompletedAt: snapshot.generationCompletedAt ?? null,+ generationCanceled: snapshot.generationCanceled === true,+ cancelReason: snapshot.cancelReason ?? null,};}@@ -269,24 +488,46 @@ function scheduleLeaseFlush() {function flushPendingPolls() {let changed = false;while (state.pendingPolls.length > 0) {- const entry = findAvailablePendingEvent();+ let pollIndex = -1;+ let entry = null;+ for (let index = 0; index < state.pendingPolls.length; index += 1) {+ const candidate = findAvailablePendingEvent(Date.now(), state.pendingPolls[index].types);+ if (!candidate) continue;+ pollIndex = index;+ entry = candidate;+ break;+ }if (!entry) {scheduleLeaseFlush();broadcastAgentPollingIfChanged();return;}- const poll = state.pendingPolls.shift();- poll.resolve(leaseEvent(entry, poll.leaseMs));+ const [poll] = state.pendingPolls.splice(pollIndex, 1);+ // leaseEvent is async (it may scaffold source), but it claims the entry+ // synchronously, so the next loop iteration will not re-select it. Resolve+ // the poll when the lease settles rather than awaiting here, so one slow+ // scaffold never delays the other parked polls. On the exceptional failure+ // path, answer `timeout` so the agent re-polls; the claim stays until the+ // lease expires, which keeps a deterministic failure from hot-looping.+ leaseEvent(entry, poll.leaseMs).then(poll.resolve, (error) => {+ console.error('[live] lease failed for ' + (entry.event?.id || 'unknown') + ': ' + (error?.message || error));+ poll.resolve({ type: 'timeout' });+ });changed = true;}scheduleLeaseFlush();if (changed) broadcastAgentPollingIfChanged();}+function isLeased(entry) {+ return !!(entry?.leaseUntil && entry.leaseUntil > Date.now());+}+function agentPollingConnected() {- const now = Date.now();- return state.pendingPolls.length > 0- || state.pendingEvents.some((entry) => entry.leaseUntil && entry.leaseUntil > now);+ // A leased event only proves that a poll returned once. The foreground task+ // may have ended immediately afterward, so only an actively waiting poll is+ // evidence that steering can wake the task right now.+ return state.pendingPolls.length > 0;}function broadcastAgentPollingIfChanged() {@@ -689,6 +930,16 @@ function createRequestHandler({ detectScript, liveScriptParts }) {res.end(JSON.stringify({ error }));return;}+ if (msg.type === 'agent_phase') {+ recordAgentPhase(msg.id, msg.phase, {+ ...(Number.isFinite(msg.durationMs) ? { durationMs: msg.durationMs } : {}),+ owner: typeof msg.owner === 'string' ? msg.owner : undefined,+ });+ res.writeHead(200, { 'Content-Type': 'application/json' });+ res.end(JSON.stringify({ ok: true }));+ return;+ }+ const missedCompletion = detectMissedGenerationCompletion(msg);if (state.sessionStore && msg.id) {try {state.sessionStore.appendEvent(msg);@@ -698,6 +949,11 @@ function createRequestHandler({ detectScript, liveScriptParts }) {return;}}+ if (msg.type === 'accept' || msg.type === 'discard') {+ retirePendingGeneration(msg.id);+ }+ recordGenerationCheckpoint(msg);+ if (missedCompletion) broadcast(missedCompletion);if (msg.type === 'exit') {cleanupSvelteComponentSessionsBeforeExit();}@@ -738,6 +994,12 @@ function createRequestHandler({ detectScript, liveScriptParts }) {// Agent poll endpoints (unchanged from WS version)// ---------------------------------------------------------------------------+function parsePollTypes(value) {+ if (!value) return null;+ const types = String(value).split(',').map((type) => type.trim()).filter(Boolean);+ return types.length > 0 ? new Set(types) : null;+}+function handlePollGet(req, res, url) {const token = url.searchParams.get('token');if (token !== state.token) {@@ -748,13 +1010,25 @@ function handlePollGet(req, res, url) {state.lastPollAt = Date.now();const timeout = parseInt(url.searchParams.get('timeout') || DEFAULT_POLL_TIMEOUT, 10);const leaseMs = parseInt(url.searchParams.get('leaseMs') || '30000', 10);- const available = findAvailablePendingEvent();+ const types = parsePollTypes(url.searchParams.get('types'));+ const available = findAvailablePendingEvent(Date.now(), types);if (available) {- res.writeHead(200, { 'Content-Type': 'application/json' });- res.end(JSON.stringify(leaseEvent(available, leaseMs)));+ // Do not await inline: leaseEvent may scaffold source, and this handler runs+ // on the server's only thread. The client can disconnect during that window,+ // so check the socket before replying.+ leaseEvent(available, leaseMs).then((event) => {+ if (res.writableEnded || res.destroyed) return;+ res.writeHead(200, { 'Content-Type': 'application/json' });+ res.end(JSON.stringify(event));+ }, (error) => {+ console.error('[live] lease failed for ' + (available.event?.id || 'unknown') + ': ' + (error?.message || error));+ if (res.writableEnded || res.destroyed) return;+ res.writeHead(200, { 'Content-Type': 'application/json' });+ res.end(JSON.stringify({ type: 'timeout' }));+ });return;}- const poll = { resolve, leaseMs };+ const poll = { resolve, leaseMs, types };const timer = setTimeout(() => {const idx = state.pendingPolls.indexOf(poll);if (idx !== -1) state.pendingPolls.splice(idx, 1);@@ -783,12 +1057,15 @@ function sessionFileMetadataFromPollReply(file) {if (!file || typeof file !== 'string') return { file };const normalized = file.split(path.sep).join('/');const base = { file: normalized };- if (!normalized.endsWith('/manifest.json') && normalized !== 'manifest.json') return base;- if (!normalized.includes('node_modules/.impeccable-live/') && !normalized.includes('src/lib/impeccable/')) return base;+ const metadataFile = normalized;+ if (!metadataFile.endsWith('/manifest.json') && metadataFile !== 'manifest.json') return base;+ if (!metadataFile.includes('node_modules/.impeccable-live/')+ && !metadataFile.includes('src/lib/impeccable/')+ && !metadataFile.includes('/.impeccable-live/')) return base;let full;try {- full = path.resolve(process.cwd(), normalized);+ full = path.resolve(process.cwd(), metadataFile);const rel = path.relative(process.cwd(), full);if (!rel || rel.startsWith('..') || path.isAbsolute(rel)) return base;} catch {@@ -797,18 +1074,47 @@ function sessionFileMetadataFromPollReply(file) {try {const manifest = JSON.parse(fs.readFileSync(full, 'utf-8'));- if (manifest?.previewMode !== 'svelte-component' || !manifest.sourceFile) return base;+ if (manifest?.previewMode !== 'svelte-component'+ || !manifest.sourceFile) return base;return {file: String(manifest.sourceFile).split(path.sep).join('/'),sourceFile: String(manifest.sourceFile).split(path.sep).join('/'),previewFile: normalized,- previewMode: 'svelte-component',+ previewMode: manifest.previewMode,};} catch {return base;}}+function inferSourceEventType(msg = {}, pendingEvents = state.pendingEvents) {+ const entriesForId = pendingEvents.filter((entry) => entry.event?.id === msg.id);+ const pendingTypes = new Set(entriesForId.map((entry) => entry.event?.type));+ if (msg.type === 'discarded' || msg.type === 'discard') return 'discard';+ if (msg.type === 'complete') {+ if (pendingTypes.has('carbonize_cleanup')) return 'carbonize_cleanup';+ return pendingTypes.has('accept') ? 'accept' : (pendingTypes.has('generate') ? 'generate' : undefined);+ }+ if (msg.type === 'steer_done') return 'steer';+ // `agent_done` can be the automatic acknowledgement for a carbonize Accept.+ // New pollers send sourceEventType explicitly; default to generate only for+ // older callers so a late worker cannot acknowledge a queued Accept.+ if (msg.type === 'agent_done' || msg.type === 'done') return 'generate';+ // `error` is reference/live.md's documented failure reply, and parseReplyArgs+ // never sets sourceEventType on it (the poller is a fresh process that cannot+ // know what it leased). Returning undefined here makes acknowledgePendingEvent+ // match *any* event for this id: a stale generate worker's failure silently+ // consumed the user's queued Accept, which was then never delivered to any+ // agent and left the browser in SAVING forever. Attribute the failure to the+ // event this agent actually holds a lease on, and otherwise to `generate` —+ // never to a wildcard. If that generate was already retired by an Accept, the+ // ack simply finds no match, which is the correct outcome for a stale reply.+ if (msg.type === 'error') {+ return entriesForId.find(isLeased)?.event?.type || 'generate';+ }+ return undefined;+}+function handlePollPost(req, res) {let body = '';req.on('data', (c) => { body += c; });@@ -869,7 +1175,23 @@ function handlePollPost(req, res) {res.end(JSON.stringify({ error: 'stale_manual_edit_apply_reply', ...rollback }));return;}- const pendingEventBeforeAck = findPendingEventById(msg.id);+ const sourceEventType = msg.sourceEventType || inferSourceEventType(msg);+ if (msg.type === 'retry') {+ const releasedEvent = releasePendingEvent(msg.id, sourceEventType);+ if (!releasedEvent) {+ res.writeHead(msg.id ? 404 : 400, { 'Content-Type': 'application/json' });+ res.end(JSON.stringify({+ error: msg.id ? 'unknown_poll_retry_id' : 'missing_poll_retry_id',+ id: msg.id,+ }));+ return;+ }+ flushPendingPolls();+ res.writeHead(200, { 'Content-Type': 'application/json' });+ res.end(JSON.stringify({ ok: true, released: true }));+ return;+ }+ const pendingEventBeforeAck = findPendingEventById(msg.id, sourceEventType);if (pendingEventBeforeAck?.type === 'steer' && msg.type === 'steer_done'&& !msg.file && !(typeof msg.message === 'string' && msg.message.trim())) {res.writeHead(400, { 'Content-Type': 'application/json' });@@ -879,7 +1201,7 @@ function handlePollPost(req, res) {}));return;}- const acknowledgedEvent = acknowledgePendingEvent(msg.id);+ const acknowledgedEvent = acknowledgePendingEvent(msg.id, sourceEventType);let skipJournalReply = false;let existingSession = null;if (!acknowledgedEvent && state.sessionStore && msg.id) {@@ -1083,7 +1405,10 @@ if (args.includes('--background')) {process.exit(0);}} catch { /* not ready yet */ }- await new Promise(r => setTimeout(r, 200));+ // The detached child is typically listening in 35-45ms. A 200ms polling+ // floor dominated configured cold Live startup; poll cheaply and return+ // as soon as the child has written its ready record.+ await new Promise(r => setTimeout(r, 5));}console.error('Timed out waiting for live server to start.');process.exit(1);diff --git a/.claude/skills/impeccable/scripts/live-status.mjs b/.claude/skills/impeccable/scripts/live-status.mjsindex f7e464999..dc98b7386 100644--- a/.claude/skills/impeccable/scripts/live-status.mjs+++ b/.claude/skills/impeccable/scripts/live-status.mjs@@ -37,15 +37,19 @@ export async function statusCli() {pendingEvents: server.pendingEvents,} : null,activeSessions: server?.activeSessions || activeSessions,- recoveryHint: manualApply- ? manualApplyResumeHint(manualApply)- : server- ? 'Run live-poll.mjs to continue pending work, or live-complete.mjs --id <session> after manual cleanup.'- : 'Start live-server.mjs to requeue pending durable events, then run live-poll.mjs.',+ recoveryHint: recoveryHint({ server, manualApply }),};console.log(JSON.stringify(payload, null, 2));}+function recoveryHint({ server, manualApply }) {+ if (manualApply) return manualApplyResumeHint(manualApply);+ if (server) {+ return 'Run live-poll.mjs to continue pending work, or live-complete.mjs --id <session> after manual cleanup.';+ }+ return 'Start live-server.mjs to requeue pending durable events, then run live-poll.mjs.';+}+function findPendingManualApply(server, activeSessions) {const fromServer = server?.pendingEvents?.find((event) => event?.type === 'manual_edit_apply');if (fromServer) return fromServer;diff --git a/.claude/skills/impeccable/scripts/live-wrap.mjs b/.claude/skills/impeccable/scripts/live-wrap.mjsindex 438c01b68..48d7f7683 100644--- a/.claude/skills/impeccable/scripts/live-wrap.mjs+++ b/.claude/skills/impeccable/scripts/live-wrap.mjs@@ -160,11 +160,29 @@ The agent should insert variant HTML at insertLine.`);if (filtered.length === 1) {match = filtered[0];} else if (filtered.length === 0) {- // Source uses dynamic content (`<h1>{title}</h1>` etc.) so the- // browser-side textContent doesn't appear literally in source. Fall- // back to first-match rather than refusing — this is the same- // behavior unmodified callers see, just preserved.- match = candidates[0];+ const normalizedText = String(text).replace(/\s+/g, ' ').trim();+ if (normalizedText.length < 8) {+ // Very short labels cannot disambiguate siblings reliably. Preserve+ // the legacy behavior for these low-information picker events.+ match = candidates[0];+ } else {+ // Rendered text that is absent from every candidate usually means+ // the source uses expressions or component props. Picking the first+ // same-class sibling silently edits the wrong instance (observed on+ // Astro result cards), so stop and surface every candidate instead.+ console.error(JSON.stringify({+ error: 'element_ambiguous',+ fallback: 'agent-driven',+ reason: 'rendered_text_not_in_source',+ file: path.relative(process.cwd(), targetFile),+ candidates: candidates.map((c) => ({+ startLine: c.startLine + 1,+ endLine: c.endLine + 1,+ })),+ hint: 'Rendered text does not occur in any matching source branch. The element may use dynamic props or expressions; inspect the candidates and wrap the intended instance manually.',+ }));+ process.exit(1);+ }} else {// Multiple candidates ALSO match the text. Truly ambiguous — refuse// rather than pick wrong, and hand the agent the candidate locations@@ -269,6 +287,7 @@ The agent should insert variant HTML at insertLine.`);const originalIndented = reindentOriginal(' ');const relTargetFile = path.relative(process.cwd(), targetFile).split(path.sep).join('/');const useSvelteComponent = shouldUseSvelteComponentInjection(targetFile);+ const useFrameworkComponent = useSvelteComponent;// Wrapper attributes differ by syntax. HTML allows plain string attrs;// JSX requires object-literal style and parses string attrs as HTML (which@@ -288,7 +307,7 @@ The agent should insert variant HTML at insertLine.`);// replacement range to include the wrapper's `<div>` open / close lines// so the entire scaffold gets removed cleanly.const wrapperLines = isJsx ? [- indent + '<div data-impeccable-variants="' + id + '" data-impeccable-variant-count="' + count + '" ' + styleContents + '>',+ indent + '<div data-impeccable-variants="' + id + '" data-impeccable-variant-count="' + count + '"' + ' ' + styleContents + '>',indent + ' ' + commentSyntax.open + ' impeccable-variants-start ' + id + ' ' + commentSyntax.close,indent + ' ' + commentSyntax.open + ' Original ' + commentSyntax.close,indent + ' <div data-impeccable-variant="original">',@@ -299,7 +318,7 @@ The agent should insert variant HTML at insertLine.`);indent + '</div>',] : [indent + commentSyntax.open + ' impeccable-variants-start ' + id + ' ' + commentSyntax.close,- indent + '<div data-impeccable-variants="' + id + '" data-impeccable-variant-count="' + count + '" ' + styleContents + '>',+ indent + '<div data-impeccable-variants="' + id + '" data-impeccable-variant-count="' + count + '"' + ' ' + styleContents + '>',indent + ' ' + commentSyntax.open + ' Original ' + commentSyntax.close,indent + ' <div data-impeccable-variant="original">',originalIndented,@@ -356,15 +375,18 @@ The agent should insert variant HTML at insertLine.`);const outputRelFile = path.relative(process.cwd(), outputFile).split(path.sep).join('/');const svelteComponentAuthoring = useSvelteComponent ? buildSvelteComponentCssAuthoring(count) : null;+ const componentSession = svelteSession;+ const componentPreviewMode = useSvelteComponent ? 'svelte-component' : undefined;+ const previewMode = componentPreviewMode;console.log(JSON.stringify({file: outputRelFile,- sourceFile: useSvelteComponent ? relTargetFile : undefined,- previewMode: useSvelteComponent ? 'svelte-component' : undefined,- componentDir: svelteSession?.componentDir,- propContract: svelteSession?.propContract,- sourceStartLine: useSvelteComponent ? startLine + 1 : undefined,- sourceEndLine: useSvelteComponent ? endLine + 1 : undefined,+ sourceFile: useFrameworkComponent ? relTargetFile : undefined,+ previewMode,+ componentDir: componentSession?.componentDir,+ propContract: componentSession?.propContract,+ sourceStartLine: useFrameworkComponent ? startLine + 1 : undefined,+ sourceEndLine: useFrameworkComponent ? endLine + 1 : undefined,startLine: outputStartLine, // 1-indexed for the agent// wrapperLines is an array but one element (the original-content slot)// is a `\n`-joined multi-line string, so the actual file-row count is@@ -374,10 +396,10 @@ The agent should insert variant HTML at insertLine.`);endLine: outputEndLine, // 1-indexedinsertLine, // 1-indexed: where variants gocommentSyntax: commentSyntax,- styleMode: useSvelteComponent ? 'svelte-component' : styleMode.mode,- styleTag: useSvelteComponent ? null : styleMode.styleTag,- cssSelectorPrefixExamples: useSvelteComponent ? [] : buildCssSelectorPrefixExamples(styleMode.mode, count),- cssAuthoring: useSvelteComponent ? svelteComponentAuthoring : buildCssAuthoring(styleMode, count),+ styleMode: componentPreviewMode || styleMode.mode,+ styleTag: useFrameworkComponent ? null : styleMode.styleTag,+ cssSelectorPrefixExamples: useFrameworkComponent ? [] : buildCssSelectorPrefixExamples(styleMode.mode, count),+ cssAuthoring: svelteComponentAuthoring || buildCssAuthoring(styleMode, count),originalLineCount: originalLines.length,}));}diff --git a/.claude/skills/impeccable/scripts/live.mjs b/.claude/skills/impeccable/scripts/live.mjsindex e0bd1ad24..b21a71cc4 100644--- a/.claude/skills/impeccable/scripts/live.mjs+++ b/.claude/skills/impeccable/scripts/live.mjs@@ -10,7 +10,7 @@** After this, the agent's only remaining steps are:* - Open the project's live dev/preview URL in the browser (optional, if browser automation exists)—not `serverPort`; that port is the Impeccable helper for /live.js and /poll- * - Enter the poll loop: `node live-poll.mjs`+ * - Enter the harness-native poll loop: `node live-poll.mjs`** Usage:* node live.mjs # Prepare everything, print JSON, exit@@ -40,6 +40,7 @@ Prepare everything for live variant mode in a single command:- Starts (or reuses) the live server in the background- Injects the browser script tag- Reads PRODUCT.md / DESIGN.md for project context+ - Prepares the harness-native foreground/background poll loop- In monorepos, choose a child app first; --target <path> is the fallback/manual pathOn success, prints a JSON blob with:diff --git a/.claude/skills/impeccable/scripts/live/completion.mjs b/.claude/skills/impeccable/scripts/live/completion.mjsindex 986773066..6f539336d 100644--- a/.claude/skills/impeccable/scripts/live/completion.mjs+++ b/.claude/skills/impeccable/scripts/live/completion.mjs@@ -1,9 +1,18 @@+// A preview whose variants live in component modules rather than in the user's+// source. These leave no markers in the real file, so a failed accept gives the+// agent nothing to hand-edit and must be reported as a failure rather than+// reference/live.md's manual-cleanup handoff. Kept as a set: any future+// component-module preview mode belongs here the day it lands.+const PREVIEW_MODES_WITHOUT_SOURCE_MARKERS = new Set([+ 'svelte-component',+]);+export function completionTypeForAcceptResult(eventType, acceptResult) {if (eventType === 'discard') return acceptResult?.handled === true ? 'discarded' : 'error';if (acceptResult?.handled === true && acceptResult?.carbonize === true) return 'agent_done';if (acceptResult?.handled === true) return 'complete';if (acceptResult?.mode === 'error') return 'error';- if (eventType === 'accept' && acceptResult?.previewMode === 'svelte-component') return 'error';+ if (eventType === 'accept' && PREVIEW_MODES_WITHOUT_SOURCE_MARKERS.has(acceptResult?.previewMode)) return 'error';return 'agent_done';}diff --git a/.claude/skills/impeccable/scripts/live/event-validation.mjs b/.claude/skills/impeccable/scripts/live/event-validation.mjsindex 0897b1317..122c29836 100644--- a/.claude/skills/impeccable/scripts/live/event-validation.mjs+++ b/.claude/skills/impeccable/scripts/live/event-validation.mjs@@ -118,6 +118,15 @@ export function validateEvent(msg) {return 'checkpoint: paramValues must be an object';}return null;+ case 'agent_phase':+ if (!isValidId(msg.id)) return 'agent_phase: missing or malformed id';+ if (typeof msg.phase !== 'string' || !/^[a-z][a-z0-9_]{1,63}$/.test(msg.phase)) {+ return 'agent_phase: missing or malformed phase';+ }+ if (msg.durationMs !== undefined && (!Number.isFinite(msg.durationMs) || msg.durationMs < 0)) {+ return 'agent_phase: durationMs must be a non-negative number';+ }+ return null;case 'exit':return null;case 'prefetch':@@ -131,6 +140,12 @@ export function validateEvent(msg) {if (msg.message.length > 4000) return 'steer: message too long';if (msg.pageUrl !== undefined && typeof msg.pageUrl !== 'string') return 'steer: pageUrl must be string';return null;+ case 'carbonize_cleanup':+ if (!isValidId(msg.id)) return 'carbonize_cleanup: missing or malformed id';+ if (!isValidId(msg.sessionId)) return 'carbonize_cleanup: missing or malformed sessionId';+ if (!msg.file || typeof msg.file !== 'string') return 'carbonize_cleanup: missing file';+ if (!isValidVariantId(String(msg.variantId))) return 'carbonize_cleanup: missing or malformed variantId';+ return null;default:return 'Unknown event type: ' + msg.type;}diff --git a/.claude/skills/impeccable/scripts/live/generation-preflight.mjs b/.claude/skills/impeccable/scripts/live/generation-preflight.mjsnew file mode 100644index 000000000..07a5e957e--- /dev/null+++ b/.claude/skills/impeccable/scripts/live/generation-preflight.mjs@@ -0,0 +1,102 @@+import { execFile } from 'node:child_process';+import path from 'node:path';+import { promisify } from 'node:util';++const execFileAsync = promisify(execFile);+const PREFLIGHT_TIMEOUT_MS = 15_000;++export function buildGenerationPreflight(event, scriptsDir) {+ if (!event || event.type !== 'generate' || !event.id) return null;++ const isInsert = event.mode === 'insert';+ const target = isInsert ? insertTarget(event) : replaceTarget(event);+ if (!target.elementId && !target.classes) return null;++ const script = path.join(scriptsDir, isInsert ? 'live-insert.mjs' : 'live-wrap.mjs');+ const args = [script, '--id', event.id, '--count', String(event.count || 3)];+ if (isInsert) args.push('--position', target.position);+ if (target.elementId) args.push('--element-id', target.elementId);+ if (target.classes) args.push('--classes', target.classes);+ if (target.tag) args.push('--tag', target.tag);+ if (target.text) args.push('--text', target.text);+ if (!isInsert && event.pageUrl) args.push('--page-url', event.pageUrl);+ return { script, args, mode: isInsert ? 'insert' : 'replace' };+}++/**+ * Scaffold the source for a generate event before handing it to an agent.+ *+ * Async on purpose. This spawns `live-wrap.mjs`, which walks the project's+ * source tree and can take seconds (measured at ~7.6s on a large repo when the+ * element is not found, with a 15s ceiling). The live server is single-threaded+ * and calls this while leasing a poll, so a synchronous spawn froze the whole+ * server for that entire window: Accept and Discard POSTs, SSE progress+ * broadcasts, and every other poll stalled behind it.+ */+export async function runGenerationPreflight(event, {+ cwd = process.cwd(),+ scriptsDir,+ execFileImpl = execFileAsync,+ timeoutMs = PREFLIGHT_TIMEOUT_MS,+} = {}) {+ const command = buildGenerationPreflight(event, scriptsDir);+ if (!command) {+ return { ok: false, skipped: true, reason: 'insufficient_locator' };+ }++ const startedAt = performance.now();+ try {+ const { stdout } = await execFileImpl(process.execPath, command.args, {+ cwd,+ encoding: 'utf-8',+ timeout: timeoutMs,+ });+ const line = String(stdout).trim().split('\n').filter(Boolean).pop();+ if (!line) throw new Error('preflight returned no scaffold metadata');+ return {+ ok: true,+ mode: command.mode,+ durationMs: performance.now() - startedAt,+ scaffold: JSON.parse(line),+ };+ } catch (error) {+ return {+ ok: false,+ mode: command.mode,+ durationMs: performance.now() - startedAt,+ error: compactError(error),+ };+ }+}++function replaceTarget(event) {+ return normalizeTarget(event.element || {});+}++function insertTarget(event) {+ return {+ ...normalizeTarget(event.insert?.anchor || {}),+ position: event.insert?.position === 'before' ? 'before' : 'after',+ };+}++function normalizeTarget(target) {+ const classes = Array.isArray(target.classes)+ ? target.classes.join(' ')+ : String(target.classes || '').trim();+ const text = typeof target.textContent === 'string'+ ? target.textContent.trim().slice(0, 80)+ : '';+ return {+ elementId: target.id || target.elementId || undefined,+ classes: classes || undefined,+ tag: target.tagName || target.tag || undefined,+ text: text || undefined,+ };+}++function compactError(error) {+ const stderr = error?.stderr ? String(error.stderr).trim() : '';+ const message = stderr.split('\n').filter(Boolean).pop() || error?.message || 'preflight failed';+ return String(message).slice(0, 500);+}diff --git a/.claude/skills/impeccable/scripts/live/poll-lanes.mjs b/.claude/skills/impeccable/scripts/live/poll-lanes.mjsnew file mode 100644index 000000000..65f20a87a--- /dev/null+++ b/.claude/skills/impeccable/scripts/live/poll-lanes.mjs@@ -0,0 +1,14 @@+export function eventPriority(event = {}) {+ if (event.type === 'accept' || event.type === 'discard' || event.type === 'exit') return 0;+ if (event.type === 'manual_edit_apply' || event.type === 'steer' || event.type === 'carbonize_cleanup') return 1;+ if (event.type === 'generate') return 2;+ return 3;+}++export function selectAvailablePendingEvent(entries, { now = Date.now(), types = null } = {}) {+ const allowed = types instanceof Set ? types : (Array.isArray(types) ? new Set(types) : null);+ return entries+ .filter((entry) => !(entry.leaseUntil && entry.leaseUntil > now))+ .filter((entry) => !allowed || allowed.has(entry.event?.type))+ .sort((a, b) => eventPriority(a.event) - eventPriority(b.event) || a.seq - b.seq)[0] || null;+}diff --git a/.claude/skills/impeccable/scripts/live/session-store.mjs b/.claude/skills/impeccable/scripts/live/session-store.mjsindex affba67c9..9d20341dd 100644--- a/.claude/skills/impeccable/scripts/live/session-store.mjs+++ b/.claude/skills/impeccable/scripts/live/session-store.mjs@@ -1,24 +1,26 @@import fs from 'node:fs';import path from 'node:path';-import { getLegacyLiveSessionsDir, getLiveSessionsDir } from '../lib/impeccable-paths.mjs';+import { getLegacyLiveSessionsDir, getLiveSessionsDir, safeSessionId } from '../lib/impeccable-paths.mjs';const COMPLETED_PHASES = new Set(['completed', 'discarded']);+export const GENERATION_FENCED_PHASES = new Set([+ 'accept_requested',+ 'discard_requested',+ 'carbonize_required',+ 'completed',+ 'discarded',+]);export function createLiveSessionStore({ cwd = process.cwd(), sessionId } = {}) {const rootDir = getLiveSessionsDir(cwd);const legacyRootDir = getLegacyLiveSessionsDir(cwd);fs.mkdirSync(rootDir, { recursive: true });- const snapshotCache = new Map();-- function loadCachedOrRebuild(id) {- const cached = snapshotCache.get(id);- if (cached) return cached;- const journalPath = getReadableJournalPath(id);- const rebuilt = rebuildSnapshotFromJournal(journalPath, id);- snapshotCache.set(id, rebuilt);- return rebuilt;- }+ // No snapshot cache on purpose: appendEvent and getSnapshot both rebuild from+ // the journal so sequence numbers and phase fences never come from a stale+ // in-memory copy when the publisher/complete helpers append from another+ // process. A cache written but never read would grow per session for the+ // lifetime of the server without ever saving a rebuild.function getReadableJournalPath(id) {const primary = getJournalPath(rootDir, id);if (fs.existsSync(primary)) return primary;@@ -38,7 +40,10 @@ export function createLiveSessionStore({ cwd = process.cwd(), sessionId } = {})if (!fs.existsSync(journalPath) && fs.existsSync(legacyJournalPath)) {fs.copyFileSync(legacyJournalPath, journalPath);}- const prior = loadCachedOrRebuild(normalized.id);+ // Publisher/complete helpers can append from a separate process while+ // the server is alive. Rebuild here so sequence numbers and phase+ // fences never come from a stale in-memory cache.+ const prior = rebuildSnapshotFromJournal(getReadableJournalPath(normalized.id), normalized.id);const seq = prior.nextSeq;const entry = {seq,@@ -49,7 +54,6 @@ export function createLiveSessionStore({ cwd = process.cwd(), sessionId } = {})};fs.appendFileSync(journalPath, JSON.stringify(entry) + '\n');const next = applyEvent(prior.snapshot, entry, prior.diagnostics);- snapshotCache.set(normalized.id, { snapshot: next, diagnostics: next.diagnostics || [], nextSeq: seq + 1 });writeSnapshot(snapshotPath, next);return next;},@@ -58,7 +62,6 @@ export function createLiveSessionStore({ cwd = process.cwd(), sessionId } = {})const journalPath = getReadableJournalPath(id);const snapshotPath = getSnapshotPath(rootDir, id);const rebuilt = rebuildSnapshotFromJournal(journalPath, id);- snapshotCache.set(id, rebuilt);writeSnapshot(snapshotPath, rebuilt.snapshot);if (!opts.includeCompleted && COMPLETED_PHASES.has(rebuilt.snapshot.phase)) return null;return rebuilt.snapshot;@@ -95,11 +98,6 @@ function getSnapshotPath(rootDir, id) {return path.join(rootDir, safeSessionId(id) + '.snapshot.json');}-function safeSessionId(id) {- if (!/^[A-Za-z0-9_-]{1,128}$/.test(id)) throw new Error('invalid session id: ' + id);- return id;-}-function baseSnapshot(id) {return {id,@@ -116,9 +114,18 @@ function baseSnapshot(id) {pendingEvent: null,deliveryLease: null,checkpointRevision: 0,+ browserCheckpointRevision: 0,+ publicationCheckpointRevision: 0,activeOwner: null,sourceMarkers: {},fallbackMode: null,+ generationPhase: null,+ generationCompletedAt: null,+ generationTimings: {},+ variantPlan: null,+ generationCanceled: false,+ generationCanceledAt: null,+ cancelReason: null,annotationArtifacts: [],diagnostics: [],updatedAt: null,@@ -158,6 +165,8 @@ function applyEvent(snapshot, entry, inheritedDiagnostics = []) {...snapshot,paramValues: { ...(snapshot.paramValues || {}) },sourceMarkers: { ...(snapshot.sourceMarkers || {}) },+ generationTimings: { ...(snapshot.generationTimings || {}) },+ variantPlan: snapshot.variantPlan || null,annotationArtifacts: [...(snapshot.annotationArtifacts || [])],diagnostics: [...(snapshot.diagnostics || [])],updatedAt: entry.ts || new Date().toISOString(),@@ -174,11 +183,48 @@ function applyEvent(snapshot, entry, inheritedDiagnostics = []) {next.expectedVariants = event.count ?? next.expectedVariants;next.pendingEventSeq = entry.seq ?? next.pendingEventSeq;next.pendingEvent = toPendingEvent(event);+ next.variantPlan = null;if (event.screenshotPath) upsertArtifact(next.annotationArtifacts, { type: 'screenshot', path: event.screenshotPath });break;+ case 'variant_plan':+ if (!next.generationCanceled && !GENERATION_FENCED_PHASES.has(next.phase)) {+ next.variantPlan = event.plan ?? next.variantPlan;+ }+ break;+ case 'detector_waivers':+ if (!next.generationCanceled && !GENERATION_FENCED_PHASES.has(next.phase)) {+ next.detectorWaivers = [+ ...(next.detectorWaivers || []),+ ...(Array.isArray(event.waivers) ? event.waivers : []),+ ];+ }+ break;+ case 'agent_phase':+ next.generationPhase = event.phase ?? next.generationPhase;+ if (event.phase) {+ next.generationTimings[event.phase] = {+ at: event.at ?? (Date.parse(entry.ts || '') || null),+ durationMs: event.durationMs ?? null,+ };+ }+ break;case 'variants_ready':case 'agent_done':+ if ((next.generationCanceled || GENERATION_FENCED_PHASES.has(next.phase))+ && !(event.type === 'agent_done' && event.carbonize === true && next.phase === 'accept_requested')) {+ next.diagnostics.push({+ error: 'late_generation_event_ignored',+ type: event.type,+ phase: next.phase,+ });+ break;+ }next.phase = event.carbonize === true ? 'carbonize_required' : 'variants_ready';+ // Durable completion marker: later browser checkpoints (a resumed page+ // reporting phase "generating") regress `phase`, but generation staying+ // finished is monotone — the live server keys missed-`done` redelivery+ // on this field.+ next.generationCompletedAt = event.at ?? (Date.parse(entry.ts || '') || Date.now());next.sourceFile = event.sourceFile ?? event.file ?? next.sourceFile;next.previewFile = event.previewFile ?? next.previewFile;next.previewMode = event.previewMode ?? next.previewMode;@@ -194,27 +240,45 @@ function applyEvent(snapshot, entry, inheritedDiagnostics = []) {}break;case 'checkpoint':- if (COMPLETED_PHASES.has(next.phase)) {+ if (next.generationCanceled || GENERATION_FENCED_PHASES.has(next.phase)) {next.diagnostics.push({ error: 'checkpoint_after_terminal_ignored', phase: event.phase ?? null, revision: event.revision ?? null });break;}- if ((event.revision ?? 0) >= (next.checkpointRevision ?? 0)) {- next.phase = event.phase ?? next.phase;- next.checkpointRevision = event.revision ?? next.checkpointRevision;- next.activeOwner = event.owner ?? next.activeOwner;- next.arrivedVariants = event.arrivedVariants ?? next.arrivedVariants;- next.visibleVariant = event.visibleVariant ?? next.visibleVariant;- next.sourceFile = event.sourceFile ?? next.sourceFile;- next.previewFile = event.previewFile ?? next.previewFile;- next.previewMode = event.previewMode ?? next.previewMode;- if (event.paramValues) next.paramValues = { ...event.paramValues };- } else {- next.diagnostics.push({ error: 'stale_checkpoint_ignored', revision: event.revision });+ {+ const revisionDomain = event.revisionDomain === 'publication'+ || (event.reason === 'variants_progress' && !event.owner)+ ? 'publication'+ : 'browser';+ const revisionField = revisionDomain === 'publication'+ ? 'publicationCheckpointRevision'+ : 'browserCheckpointRevision';+ const currentRevision = next[revisionField]+ ?? (revisionDomain === 'browser' ? next.checkpointRevision : 0)+ ?? 0;+ if ((event.revision ?? 0) >= currentRevision) {+ next.phase = event.phase ?? next.phase;+ next[revisionField] = event.revision ?? currentRevision;+ if (revisionDomain === 'browser') {+ next.checkpointRevision = event.revision ?? next.checkpointRevision;+ next.activeOwner = event.owner ?? next.activeOwner;+ }+ next.arrivedVariants = event.arrivedVariants ?? next.arrivedVariants;+ if (revisionDomain === 'browser') next.visibleVariant = event.visibleVariant ?? next.visibleVariant;+ next.sourceFile = event.sourceFile ?? next.sourceFile;+ next.previewFile = event.previewFile ?? next.previewFile;+ next.previewMode = event.previewMode ?? next.previewMode;+ if (revisionDomain === 'browser' && event.paramValues) next.paramValues = { ...event.paramValues };+ } else {+ next.diagnostics.push({ error: 'stale_checkpoint_ignored', revision: event.revision, revisionDomain });+ }}break;case 'accept':case 'accept_intent':next.phase = 'accept_requested';+ next.generationCanceled = true;+ next.generationCanceledAt = event.at ?? (Date.parse(entry.ts || '') || Date.now());+ next.cancelReason = 'accept';next.visibleVariant = Number(event.variantId ?? next.visibleVariant);if (event.paramValues) next.paramValues = { ...event.paramValues };next.pendingEventSeq = entry.seq ?? next.pendingEventSeq;@@ -232,6 +296,12 @@ function applyEvent(snapshot, entry, inheritedDiagnostics = []) {next.pendingEventSeq = entry.seq ?? next.pendingEventSeq;next.pendingEvent = toPendingEvent(event);break;+ case 'carbonize_cleanup':+ next.phase = 'carbonize_cleanup_requested';+ next.sourceFile = event.file ?? next.sourceFile;+ next.pendingEventSeq = entry.seq ?? next.pendingEventSeq;+ next.pendingEvent = toPendingEvent(event);+ break;case 'steer_done':next.phase = 'steer_done';next.sourceFile = event.sourceFile ?? event.file ?? next.sourceFile;@@ -243,6 +313,9 @@ function applyEvent(snapshot, entry, inheritedDiagnostics = []) {break;case 'discard':next.phase = 'discard_requested';+ next.generationCanceled = true;+ next.generationCanceledAt = event.at ?? (Date.parse(entry.ts || '') || Date.now());+ next.cancelReason = 'discard';next.pendingEventSeq = entry.seq ?? next.pendingEventSeq;next.pendingEvent = toPendingEvent(event);break;@@ -260,6 +333,10 @@ function applyEvent(snapshot, entry, inheritedDiagnostics = []) {next.pendingEvent = null;break;case 'agent_error':+ if (next.generationCanceled && event.sourceEventType === 'generate') {+ next.diagnostics.push({ error: 'late_generation_event_ignored', type: event.type, phase: next.phase });+ break;+ }next.phase = 'agent_error';next.pendingEventSeq = null;next.pendingEvent = null;diff --git a/.claude/skills/impeccable/scripts/live/source-lock.mjs b/.claude/skills/impeccable/scripts/live/source-lock.mjsnew file mode 100644index 000000000..9ccc557be--- /dev/null+++ b/.claude/skills/impeccable/scripts/live/source-lock.mjs@@ -0,0 +1,105 @@+import fs from 'node:fs';+import path from 'node:path';+import { createHash, randomUUID } from 'node:crypto';+import { getLiveDir, isLiveServerPidReachable } from '../lib/impeccable-paths.mjs';++// Only used to retire a lock whose contents we cannot read (empty or truncated+// by a crash mid-write). A readable lock's fate is decided by its owner's+// liveness instead, so a slow critical section is never swept.+const UNREADABLE_LOCK_STALE_MS = 60_000;++export function sourceLockPath(file, cwd = process.cwd()) {+ const digest = createHash('sha256').update(path.resolve(cwd, file)).digest('hex').slice(0, 24);+ return path.join(getLiveDir(cwd), 'locks', digest + '.lock');+}++export function withSourceLockSync(file, owner, fn, {+ cwd = process.cwd(),+ waitMs = 0,+ retryMs = 5,+} = {}) {+ const lockPath = sourceLockPath(file, cwd);+ fs.mkdirSync(path.dirname(lockPath), { recursive: true });+ const deadline = Date.now() + Math.max(0, Number(waitMs) || 0);+ // Identifies this acquisition specifically, so release can tell our own lock+ // from a replacement that some other writer created.+ const token = randomUUID();+ let acquired = false;++ while (!acquired) {+ clearStaleLock(lockPath);+ let fd;+ try {+ fd = fs.openSync(lockPath, 'wx');+ fs.writeFileSync(fd, JSON.stringify({+ owner,+ token,+ pid: process.pid,+ at: Date.now(),+ file: path.resolve(cwd, file),+ }) + '\n');+ acquired = true;+ } catch (error) {+ if (error?.code !== 'EEXIST') throw error;+ if (Date.now() >= deadline) {+ const locked = new Error('source_locked');+ locked.code = 'SOURCE_LOCKED';+ locked.lockPath = lockPath;+ throw locked;+ }+ sleepSync(Math.max(1, Math.min(Number(retryMs) || 5, deadline - Date.now())));+ } finally {+ try { if (fd !== undefined) fs.closeSync(fd); } catch {}+ }+ }++ try {+ return fn();+ } finally {+ releaseOwnLock(lockPath, token);+ }+}++function sleepSync(ms) {+ Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, ms);+}++function readLock(lockPath) {+ try { return JSON.parse(fs.readFileSync(lockPath, 'utf-8')); } catch { return null; }+}++/**+ * Remove the lock only if it is still the one this call created. If a sweeper+ * judged our lock stale and another writer replaced it, unlinking here would+ * end *their* critical section and admit a third writer to the same file.+ */+function releaseOwnLock(lockPath, token) {+ const held = readLock(lockPath);+ if (held && held.token !== token) return;+ try { fs.unlinkSync(lockPath); } catch {}+}++/**+ * A lock is stale when its owner is gone, not when it is old.+ *+ * Age alone cuts both ways: it sweeps a live holder whose critical section+ * outran the timeout (a suspended laptop, a stopped process), letting two+ * writers into the same source file, while still making every accept on a+ * crashed holder's file wait out the full timeout. Asking the OS whether the+ * recorded pid is alive answers both correctly: a dead owner releases at once,+ * and a live owner keeps its lock however long it needs.+ */+function clearStaleLock(lockPath) {+ const held = readLock(lockPath);+ if (!held) {+ // Unreadable: either a crash truncated it, or we caught the brief window+ // between create and write in a live acquisition. mtime distinguishes them.+ try {+ const stat = fs.statSync(lockPath);+ if (Date.now() - stat.mtimeMs > UNREADABLE_LOCK_STALE_MS) fs.unlinkSync(lockPath);+ } catch { /* gone already */ }+ return;+ }+ if (typeof held.pid === 'number' && isLiveServerPidReachable(held.pid)) return;+ try { fs.unlinkSync(lockPath); } catch {}+}diff --git a/.cursor/skills/impeccable/reference/live.md b/.cursor/skills/impeccable/reference/live.mdindex 7867eaa03..ff29c2651 100644--- a/.cursor/skills/impeccable/reference/live.md+++ b/.cursor/skills/impeccable/reference/live.md@@ -10,21 +10,24 @@ Execute in order. No step skipped, no step reordered.1. `live.mjs`: boot. If the request names or implies a file, route, or app inside a monorepo, infer the concrete path and run `node .cursor/skills/impeccable/scripts/live.mjs --target <path>` instead; then run the rest of this live session from the returned `projectRoot`.2. Open the app URL that serves `pageFile` (infer from `package.json`, docs, terminal output, or an open tab). Never use `serverPort`; it's the helper, not the app. **Cursor:** `browser_navigate` to that URL before polling; do not skip. **Other harnesses:** use the available browser tool; if the URL is uncertain, ask the user once.-3. Poll loop with the default long timeout (600000 ms). After every event or `--reply`, run `live-poll.mjs` again immediately. Never pass a short `--timeout=`.+3. Poll loop with the default long timeout (600000 ms). Run `live-poll.mjs` again immediately after every event or `--reply`; Codex runs this one-shot poll in the foreground. Never pass a short `--timeout=`.The global bar **Impeccable mark** dims and shows a pulsing amber dot when no agent is long-polling `/poll`. Hover the mark for the hint; restart `live-poll.mjs` to reconnect.-4. On `generate`: read screenshot if present; load the action's reference; plan three distinct directions; write all variants in one edit; `--reply done`; poll again.+4. On `generate`: reuse `event.scaffold` when present; read the screenshot if present; load the action's reference; deliver variants using the delivery policy below; `--reply done`; poll again. Generate in this thread. You already hold the project's tokens, conventions, and file layout; that context is the job, not overhead.5. On `steer`: read the message and `pageUrl`; do the work (page edits, navigation help, or a short reply in the `--reply` message); `--reply steer_done`; poll again. No pickup ack. The Steer bar unlocks when `steer_done` arrives over SSE.-6. On `accept` / `discard`: the poll script runs `live-accept.mjs`, acknowledges the delivered event, and prints `_completionAck`. Plain accepts/discards are terminal immediately; carbonize accepts remain recoverable until you finish cleanup, run `live-complete.mjs --id EVENT_ID`, and only then poll again.+6. On `accept` / `discard`: the poll script runs `live-accept.mjs`, acknowledges the delivered event, and prints `_completionAck`. Plain accepts/discards are terminal immediately. Carbonize accepts remain recoverable until the foreground task runs `live-complete.mjs --id EVENT_ID`; finish that cleanup before polling again.7. If interrupted, run `live-status.mjs` or `live-resume.mjs` before guessing. The durable journal replays unacknowledged work after helper restart.8. On `exit`: run the cleanup at the bottom.Harness policy:-- **Claude Code**: run the poll as a **background task** (no short timeout). The harness notifies you when it completes, so the main conversation stays free. Do not block the shell.+- **Claude Code**: run the poll as a **background task** (no short timeout). The harness notifies you when it completes, so the main conversation stays free while you generate and publish in it. Do not block the shell.- **Cursor**: run **one-shot** poll in a **background terminal** with notify on `"type":"(steer|generate|accept|discard|exit)"`. After each event the poll exits; handle it, `--reply`, then start `live-poll.mjs` again. Do **not** use `--stream` on Cursor: incremental stdout notify is slower in practice than exit-based notify (~5s vs sub-second in testing).-- **Codex**: run the poll in the **foreground** (blocking shell; not a background task, not a subagent). Codex background exec sessions do not reliably surface poll stdout back into the conversation at the moment events arrive, so a "fire-and-forget" background poll will stall live mode.+- **Codex**: run the default one-shot poll in a **yielded foreground exec session**. Do not suffix it with `&`, use `--stream`, or leave Live without an active foreground poll. Handle every event in the main task; after each handler/reply, restart the foreground poll.- **Other harnesses**: one-shot foreground unless you know stdout reliably returns to this session when a shell exits.+Generation delivery policy:+- **Default (Cursor and other harnesses):** keep the established atomic single-edit delivery. Do not switch a harness to progressive until its poll loop is known not to block on the extra publish calls. This avoids trading model latency for extra tool-call latency on harnesses with different streaming behavior.+Chat is overhead. No recap, no tutorial output, no pasting PRODUCT / DESIGN bodies. Spend tokens on tools and edits; on failure, one or two short sentences.## Start@@ -92,14 +95,14 @@ Server restart rule: start `live-server.mjs` again, then poll. Startup requeues**Insert mode** (`event.mode === "insert"`): `{id, mode: "insert", count, pageUrl, insert: { position, anchor }, placeholder: { width, height }, freeformPrompt?, screenshotPath?, comments?, strokes?}`. No `action`. Requires a non-empty `freeformPrompt` **or** annotations. Screenshot is sent only when annotations exist (same rule as replace). Use `placeholder` dimensions as a soft size hint for net-new content.-Speed matters; the user is watching a spinner. Minimize tool calls by using the wrap/insert helper and writing all variants in a single edit.+Speed matters; the user is watching the selected element. Reuse server preflight metadata when available, minimize discovery calls, and follow the harness-specific delivery policy above.### Insert mode branchWhen `event.mode === "insert"`:1. Read the screenshot if `event.screenshotPath` is present (annotations only).-2. Run the insert helper instead of wrap:+2. If `event.scaffold` is present, use it as the insert-helper result and do **not** run the helper again. Otherwise run the insert helper instead of wrap:```bashnode .cursor/skills/impeccable/scripts/live-insert.mjs --id EVENT_ID --count EVENT_COUNT --position after \@@ -109,7 +112,7 @@ node .cursor/skills/impeccable/scripts/live-insert.mjs --id EVENT_ID --count EVE- `--position` ← `event.insert.position` (`before` | `after`)- Anchor flags ← `event.insert.anchor` (same mapping as wrap: id, classes, tag, text)-The scaffold has **no** `data-impeccable-variant="original"`. Variants are net-new HTML+CSS inserted at `insertLine`. Load `brand.md` or `product.md` (freeform only, no action sub-command). Write all variants in one edit, then `--reply done`.+The scaffold has **no** `data-impeccable-variant="original"`. Variants are net-new HTML+CSS inserted at `insertLine`. Load `brand.md` or `product.md` (freeform only, no action sub-command). Deliver using the harness policy, then `--reply done`.For Svelte/SvelteKit targets, `live-insert.mjs` returns `previewMode: "svelte-component"` with `mode: "insert"`, `file` pointing at a temporary `node_modules/.impeccable-live/<id>/manifest.json`, `componentDir` pointing at the variant component files, and `sourceFile` pointing at the real `.svelte` route. Write each inserted variant as a real Svelte component (`v1.svelte`, `v2.svelte`, …) under `componentDir`. Insert variants must be non-empty net-new content with a single top-level root, no `data-impeccable-*` attributes, and CSS in each component's `<style>` block. Do **not** edit the route source during generation; the browser mounts the temporary component before/after the live anchor while the user cycles variants. On Accept, `live-accept.mjs` inserts the selected component markup into `sourceFile` immediately and deletes the temp session after the source write succeeds.@@ -134,6 +137,8 @@ Reading annotations precisely:### 2. Wrap the element+When `event.scaffold` is present, the local helper already found and wrapped the source before the poll returned. Treat `event.scaffold` as the successful helper output and skip this command entirely. `event.scaffoldAttempted` with `scaffoldError` means local preflight could not finish; use the command/fallback path below. This optimization removes a deterministic tool round trip without changing the generated design.+```bashnode .cursor/skills/impeccable/scripts/live-wrap.mjs --id EVENT_ID --count EVENT_COUNT --element-id "ELEMENT_ID" --classes "class1,class2" --tag "div" --text "TEXT_SNIPPET"```@@ -153,7 +158,7 @@ Output on success: `{ file, insertLine, commentSyntax, styleMode, styleTag, cssSFor Svelte/SvelteKit targets, `live-wrap.mjs` returns `previewMode: "svelte-component"` with `file` pointing at a temporary `node_modules/.impeccable-live/<id>/manifest.json`, `componentDir` pointing at the variant component files, and `sourceFile` pointing at the real `.svelte` route. Write each variant as a real Svelte component (`v1.svelte`, `v2.svelte`, …) under `componentDir`; use the `propContract` prop names for dynamic text (`{propName}`), not literal snapshot strings. Put variant CSS in each component's `<style>` block with semantic class selectors (no `@scope`, no `data-impeccable-*`). Reply with `--file` set to the manifest path; the browser dynamically imports and mounts the compiled components so Svelte HMR does not reset page state while the user cycles variants. On Accept, `live-accept.mjs` inlines the accepted component back into `sourceFile` immediately after source promotion succeeds.-**Params on the Svelte component path go in a sidecar, never as an attribute.** Svelte parses `{` inside an attribute value as the start of an expression, so a `data-impeccable-params='[{…}]'` attribute on a component element fails to compile (`Expected token }`). Declare params for this path in `componentDir/params.json`, keyed by variant number, using the exact param schema from section 7:+**Params on component-preview paths go in a sidecar, never as an attribute.** Svelte parses `{` inside an attribute value as the start of an expression, and both Svelte/Vue previews mount without an HTML variant wrapper. Declare params in `componentDir/params.json`, keyed by variant number, using the exact param schema from section 7:```json{@@ -291,11 +296,13 @@ In **departure mode**, the prompt narrows the lanes you draw from, not the familWhen the prompt and PRODUCT.md anti-references conflict (the prompt asks for X, the anti-references ban X), the anti-references win; they describe the brand's standing position, the prompt is one moment.-### 6. Write all variants in a single edit+### 6. Deliver variantsComplete HTML replacement of the original element for each variant, not a CSS-only patch. Consider the element's context (computed styles, parent structure, CSS variables from `event.element`).-Write CSS + all variants in ONE edit at the `insertLine` reported by `wrap`. Colocate CSS as a `<style>` tag inside the variant wrapper; `<style>` works anywhere in modern browsers and this ensures CSS and HTML arrive atomically (no FOUC).+Colocate preview CSS as a `<style>` tag inside the variant wrapper; `<style>` works anywhere in modern browsers and keeps each delivered state internally complete (no FOUC).++**Atomic default:** write CSS + all variants + parameter manifests in one edit at `insertLine`, preserving the established behavior.Use the `cssAuthoring` object returned by `live-wrap.mjs` to author the temporary preview CSS. The style opening tag shown below is the common case; replace it with `cssAuthoring.styleTag` when the tool returns a different one. The variant markup shape is otherwise stable:@@ -319,7 +326,7 @@ Use the `cssAuthoring` object returned by `live-wrap.mjs` to author the temporarThe first variant has no `display: none` (visible by default). All others do. If variants use only inline styles and no preview CSS, omit the `<style>` tag entirely.-One edit, all variants; the browser's MutationObserver picks everything up in one pass.+The browser's MutationObserver accepts either delivery shape. On the transactional progressive path it shows arrived variants and pending dots immediately; Accept and Discard are available as soon as one variant exists. Accepting an arrived variant fences the worker before the browser releases the picker, so later publications are rejected.For `styleMode: "scoped"`, author every `:scope` rule with a descendant combinator. The `@scope` boundary is the **variant wrapper `<div data-impeccable-variant="N">`**, not the element you're designing. A bare `:scope { background: cream; }` styles the wrapper, not the inner replacement, so the cream lands on a `display: contents` shell while the actual element keeps page defaults. Always step in: `:scope > .card`, `:scope > section`, `:scope .hero-title`, etc. The fake test agent's CSS in `tests/live-e2e/agent.mjs` is a faithful template; every scoped rule starts `:scope > ...`.@@ -361,7 +368,7 @@ Each variant can expose **coarse** knobs alongside the full HTML/CSS replacement**Hard cap per variant**: at most **four** parameters so the panel stays legible; rare fifth only if the reference explicitly allows it.-**How to declare.** Put a JSON manifest on the variant wrapper (HTML/JSX path). **On the Svelte `svelte-component` path, do not use this attribute** (Svelte can't compile `{` inside an attribute value). Declare params in `componentDir/params.json` keyed by variant number instead (see the Svelte component paragraph in the wrap section). The param schema below is identical for both paths.+**How to declare.** Put a JSON manifest on the variant wrapper (HTML/JSX path). **On the `svelte-component` path, do not use this attribute.** Declare params in `componentDir/params.json` keyed by variant number instead (see the component-preview paragraphs in the wrap section). The param schema below is identical for every path.```html<div data-impeccable-variant="1" data-impeccable-params='[@@ -462,15 +469,19 @@ Event: `{id, variantId, _acceptResult, _completionAck}`. The poll script already- The accept event includes `pageUrl`; the poll script must forward it to `live-accept.mjs --page-url PAGE_URL` so accept-time cleanup only scrubs staged copy edits for the current page.- `_completionAck.ok !== true`: do not poll yet. Run `live-status.mjs` / `live-resume.mjs`, complete the cleanup manually if needed, then run `live-complete.mjs --id EVENT_ID`.- `_acceptResult.handled: true` and `carbonize: false`: nothing to do. Poll again.-- `_acceptResult.handled: true` and `carbonize: true`: **post-accept cleanup is required before the next poll.** See the "Required after accept (carbonize)" section below. The `event._acceptResult.todo` field, `_completionAck.requiresComplete`, and a stderr banner all point at this required follow-up; none are decorative. After cleanup, run `live-complete.mjs --id EVENT_ID`, then poll again.+- `_acceptResult.handled: true` and `carbonize: true`: post-accept cleanup is required, but it must not stall Codex's control lane. See "Required after accept (carbonize)" below. The `event._acceptResult.todo` field, `_completionAck.requiresComplete`, and stderr banner all point at this required follow-up; none are decorative.- `_acceptResult.handled: false, mode: "fallback"`: the session lived in a generated file and the script refused to persist there. You've already written the accepted variant into true source during Handle fallback Step 3; just clean up the temporary wrapper in the served file if any, and poll again.+- `_acceptResult.handled: false, mode: "error"`: the operation genuinely failed. **Do not hand-edit the file**; the source was not touched and editing it yourself would either double-apply or race whoever holds it.+ - `error: "source_locked"`: a generation publish holds the file. Run the same `live-accept.mjs` command again; it is idempotent and will succeed once the publisher releases. Do not poll past it.+ - `error: "accept_receipt_conflict"`: this session already resolved as `priorOperation` (on `priorVariantId` for an accept), so the request contradicts durable truth. Do not edit. Run `live-status.mjs` and tell the user what the session actually resolved to.+ - anything else: report the error briefly and run `live-status.mjs` before continuing.- `_acceptResult.handled: false` without `mode`: manual cleanup: read file, find markers, edit.### Required after accept (carbonize)When `_acceptResult.carbonize === true`, the accepted variant was stitched into source with helper markers and inline CSS so the browser can render it immediately with no visual gap. That stitch-in is **temporary**. The agent must rewrite it into permanent form before doing anything else. Skipping this leaves dead `@scope` rules for unaccepted variants, a pointless `data-impeccable-variant` wrapper, and `impeccable-carbonize-start/end` comment noise in the source file; all of which accumulate across sessions.-Do these five steps in the current thread, synchronously, before the next poll. Do not poll again until the file is clean.+Do these five steps synchronously before the next poll. The source lock, generation epoch, and expected-source hash remain the final safety gates against a generator finishing concurrently with Accept.1. **Locate the carbonize block** in the source file (`_acceptResult.file`). It's bracketed by `<!-- impeccable-carbonize-start SESSION_ID -->` and `<!-- impeccable-carbonize-end SESSION_ID -->` and contains a `<style data-impeccable-css="SESSION_ID">` element. If the variant declared parameters, an `<!-- impeccable-param-values SESSION_ID: {...} -->` comment sits alongside the style tag with the user's chosen values; read it first; it drives steps 3 and 4 below.2. **Move the CSS rules** into the project's real stylesheet. Which stylesheet depends on the project (e.g. `site/styles/workflow.css` for an Astro project, or the component's co-located CSS file for a Vite/Next project; pick whichever already owns styling for the surrounding element).@@ -478,9 +489,7 @@ Do these five steps in the current thread, synchronously, before the next poll.4. **Unwrap the accepted content.** Delete the inner `<div data-impeccable-variant="N" style="display: contents">` that wraps it. On JSX/TSX, also delete the outer `<div data-impeccable-carbonize="SESSION_ID" style={{ display: 'contents' }}>` wrapper if present (accept adds it so ternary/`return` slots keep a single root). Drop `data-impeccable-params` and any `data-p-*` attributes; those are live-mode plumbing, not source.5. **Delete the inline `<style>` block, the `<!-- impeccable-param-values -->` comment if present, and both `<!-- impeccable-carbonize-start/end -->` markers.** Also drop any `@scope` rules for variants other than the accepted one; those are dead code now.-After the file is clean, run `live-complete.mjs --id SESSION_ID`, verify it reports `phase: "completed"`, then poll again.--A background agent may be used for the rewrite, but the current thread is responsible for verifying the five steps are complete before issuing the next poll. In practice, inline is usually faster and less error-prone.+After the file is clean, the cleanup owner runs `live-complete.mjs --id SESSION_ID` and verifies `phase: "completed"`. Poll again only after that verification.## Handle `discard`diff --git a/.cursor/skills/impeccable/scripts/lib/impeccable-paths.mjs b/.cursor/skills/impeccable/scripts/lib/impeccable-paths.mjsindex 2ccbe7b74..99956c0f3 100644--- a/.cursor/skills/impeccable/scripts/lib/impeccable-paths.mjs+++ b/.cursor/skills/impeccable/scripts/lib/impeccable-paths.mjs@@ -104,6 +104,20 @@ export function removeLiveServerInfo(cwd = process.cwd(), options = {}) {}}+/**+ * Session IDs become path segments (journals, snapshots, accept receipts,+ * preview manifests, generated component dirs). They arrive from CLI `--id`+ * arguments and HTTP payloads, so anything containing a separator or `..` must+ * be rejected before it reaches path.join, which would happily escape+ * `.impeccable/live/`. Real IDs are 8 hex chars; the tests use short slugs.+ */+export function safeSessionId(id) {+ if (typeof id !== 'string' || !/^[A-Za-z0-9_-]{1,128}$/.test(id)) {+ throw new Error('invalid session id: ' + id);+ }+ return id;+}+export function getLiveSessionsDir(cwd = process.cwd(), options = {}) {return path.join(getLiveDir(cwd, options), 'sessions');}diff --git a/.cursor/skills/impeccable/scripts/live-accept.mjs b/.cursor/skills/impeccable/scripts/live-accept.mjsindex 278dfbb2e..453ddea35 100644--- a/.cursor/skills/impeccable/scripts/live-accept.mjs+++ b/.cursor/skills/impeccable/scripts/live-accept.mjs@@ -16,7 +16,9 @@import fs from 'node:fs';import path from 'node:path';import { isGeneratedFile } from './lib/is-generated.mjs';+import { IMPECCABLE_DIR, getLiveDir, safeSessionId } from './lib/impeccable-paths.mjs';import { readBuffer as readManualEditsBuffer, writeBuffer as writeManualEditsBuffer } from './live/manual-edits-buffer.mjs';+import { withSourceLockSync } from './live/source-lock.mjs';import {applyDeferredSvelteComponentAccepts,findSvelteComponentManifest,@@ -25,6 +27,46 @@ import {} from './live/svelte-component.mjs';const EXTENSIONS = ['.html', '.jsx', '.tsx', '.vue', '.svelte', '.astro'];+const ACCEPT_LOCK_WAIT_MS = 1_000;+// Mirrors VARIANT_ID_PATTERN in live/event-validation.mjs, which gates the same+// value arriving over HTTP.+const VARIANT_NUM_PATTERN = /^[0-9]{1,3}$/;++/**+ * A thrown accept/discard is a real failure, not a manual handoff.+ *+ * live/completion.mjs only classifies a result as `error` when it carries+ * `mode: 'error'`; anything else unhandled falls through to `agent_done` with a+ * successful ack, and reference/live.md then tells the agent to finish the edit+ * by hand. That is right for the documented fallback paths and wrong here: a+ * `source_locked` contention needs a retry (hand-editing races the publisher+ * holding the lock), and a crash needs surfacing, not a hand-applied guess.+ */+function operationFailure(err, extra = {}) {+ return { handled: false, mode: 'error', error: err.message, ...extra };+}++/**+ * Mark an unhandled preview-path result as a real failure.+ *+ * operationFailure only covers results built from a *thrown* error. The accept+ * implementations also return `{handled: false, error}` for their own checks+ * (variant missing, template empty, original text ambiguous), and those arrived+ * without `mode`, so completion.mjs classified them as agent_done and+ * reference/live.md routed the agent to "read file, find markers, edit".+ *+ * That handoff only makes sense for a plain wrapper session, which is the one+ * shape with markers in the user's source to edit. Component and isolated+ * artifact previews keep the source clean until Accept, so there is nothing to+ * hand-edit and an unhandled result is always a failure. `previewMode` is+ * exactly that discriminator: only the preview branches set it.+ */+function markPreviewFailure(result) {+ if (result?.handled === false && !result.mode && result.previewMode) {+ return { ...result, mode: 'error' };+ }+ return result;+}// ---------------------------------------------------------------------------// CLI@@ -63,7 +105,52 @@ Output (JSON):const isDiscard = args.includes('--discard');if (!id) { console.error('Missing --id'); process.exit(1); }+ // `id` becomes a path segment (accept receipts, preview manifests, generated+ // component dirs). Reject separators and traversal here so one check covers+ // every downstream sink.+ try { safeSessionId(id); } catch { console.error('Invalid --id'); process.exit(1); }if (!isDiscard && !variantNum) { console.error('Need --discard or --variant N'); process.exit(1); }+ // `variantNum` is interpolated into a RegExp and into the markup written back+ // to source. The browser and the /events schema both constrain it to digits;+ // enforce the same here, or `--variant '.*'` matches the `original` block+ // first and silently accepts the original while reporting success.+ if (!isDiscard && !VARIANT_NUM_PATTERN.test(variantNum)) {+ console.error('Invalid --variant');+ process.exit(1);+ }++ const requestedOperation = isDiscard ? 'discard' : 'accept';+ const priorReceipt = readAcceptReceipt(process.cwd(), id);+ if (priorReceipt) {+ const sameOperation = priorReceipt.operation === requestedOperation+ && (isDiscard || String(priorReceipt.variantId) === String(variantNum));+ console.log(JSON.stringify(sameOperation+ ? { ...priorReceipt.result, handled: true, alreadyApplied: true }+ : {+ // mode: 'error' is what marks this a real failure rather than a manual+ // handoff. Without it, live/completion.mjs classifies the reply as+ // agent_done and reference/live.md tells the agent to "read file, find+ // markers, edit" by hand — which would apply a second, conflicting+ // accept on top of the one the receipt already recorded.+ handled: false,+ mode: 'error',+ error: 'accept_receipt_conflict',+ priorOperation: priorReceipt.operation,+ priorVariantId: priorReceipt.variantId ?? null,+ }));+ return;+ }+ const emitResult = (rawResult) => {+ const result = markPreviewFailure(rawResult);+ if (result?.handled !== false) {+ writeAcceptReceipt(process.cwd(), id, {+ operation: requestedOperation,+ variantId: isDiscard ? null : String(variantNum),+ result,+ });+ }+ console.log(JSON.stringify(result));+ };let paramValues = null;if (paramValuesRaw) {@@ -82,39 +169,55 @@ Output (JSON):if (svelteComponentManifest) {if (isDiscard) {- removeSvelteComponentSession(id, process.cwd());- console.log(JSON.stringify({- handled: true,+ let result;+ try {+ result = withSourceLockSync(+ path.resolve(process.cwd(), svelteComponentManifest.sourceFile),+ 'discard:' + id,+ () => {+ removeSvelteComponentSession(id, process.cwd());+ return { handled: true };+ },+ { waitMs: ACCEPT_LOCK_WAIT_MS },+ );+ } catch (err) {+ result = operationFailure(err);+ }+ emitResult({+ ...result,file: svelteComponentManifest.sourceFile,carbonize: false,previewMode: 'svelte-component',componentDir: svelteComponentManifest.componentDir,- }));+ });return;}let result;try {- result = inlineSvelteComponentAccept(- svelteComponentManifest,- variantNum,- paramValues,- process.cwd(),+ result = withSourceLockSync(+ path.resolve(process.cwd(), svelteComponentManifest.sourceFile),+ 'accept:' + id,+ () => inlineSvelteComponentAccept(+ svelteComponentManifest,+ variantNum,+ paramValues,+ process.cwd(),+ ),+ { waitMs: ACCEPT_LOCK_WAIT_MS },);} catch (err) {- result = {- handled: false,- error: err.message,+ result = operationFailure(err, {file: svelteComponentManifest.sourceFile,sourceFile: svelteComponentManifest.sourceFile,previewMode: 'svelte-component',componentDir: svelteComponentManifest.componentDir,- };+ });}if (result.carbonize) {result.todo = 'REQUIRED before next poll: carbonize cleanup in ' + result.file + '. See reference/live.md "Required after accept".';}- console.log(JSON.stringify({ handled: result.handled !== false, ...result }));+ emitResult({ handled: result.handled !== false, ...result });return;}@@ -145,10 +248,25 @@ Output (JSON):}if (isDiscard) {- const result = handleDiscard(id, lines, targetFile);- console.log(JSON.stringify({ handled: true, file: relFile, carbonize: false, ...result }));+ let result;+ // handleDiscard takes the source lock, which throws SOURCE_LOCKED under+ // contention. Without this catch the CLI exits non-zero with empty stdout+ // and the agent gets no JSON to act on.+ try {+ result = handleDiscard(id, lines, targetFile);+ } catch (err) {+ emitResult(operationFailure(err, { file: relFile }));+ return;+ }+ emitResult({ handled: true, file: relFile, carbonize: false, ...result });} else {- const result = handleAccept(id, variantNum, lines, targetFile, paramValues);+ let result;+ try {+ result = handleAccept(id, variantNum, lines, targetFile, paramValues);+ } catch (err) {+ emitResult(operationFailure(err, { file: relFile }));+ return;+ }const acceptedOriginalText = result.acceptedOriginalText || '';delete result.acceptedOriginalText;// Single-line attention-grabber when cleanup is required. The full@@ -167,7 +285,7 @@ Output (JSON):// Non-fatal; the buffer stays as-is and the user can discard later.}}- console.log(JSON.stringify({ handled: true, file: relFile, ...result }));+ emitResult({ handled: true, file: relFile, ...result });}}@@ -235,7 +353,14 @@ function scrubManualEditsAgainstFile(_targetFile, cwd = process.cwd(), originalB// Discard// ----------------------------------------------------------------------------function handleDiscard(id, lines, targetFile) {+function handleDiscard(id, _lines, targetFile) {+ return withSourceLockSync(targetFile, 'discard:' + id, () => {+ const lines = fs.readFileSync(targetFile, 'utf-8').split('\n');+ return handleDiscardUnlocked(id, lines, targetFile);+ }, { waitMs: ACCEPT_LOCK_WAIT_MS });+}++function handleDiscardUnlocked(id, lines, targetFile) {const block = findMarkerBlock(id, lines);if (!block) return { handled: false, error: 'Markers not found' };@@ -330,7 +455,24 @@ function reindentContent(contentLines, fromIndent, toIndent) {});}-function handleAccept(id, variantNum, lines, targetFile, paramValues) {+function handleAccept(id, variantNum, _lines, targetFile, paramValues) {+ return withSourceLockSync(targetFile, 'accept:' + id, () => {+ const lines = fs.readFileSync(targetFile, 'utf-8').split('\n');+ return handleAcceptUnlocked(id, variantNum, lines, targetFile, paramValues);+ }, { waitMs: ACCEPT_LOCK_WAIT_MS });+}++function handleAcceptUnlocked(id, variantNum, lines, targetFile, paramValues) {+ const built = buildAcceptedWrappedSource(id, variantNum, lines, targetFile, paramValues);+ if (built.handled === false) return built;+ fs.writeFileSync(targetFile, built.content, 'utf-8');+ return {+ carbonize: built.carbonize,+ acceptedOriginalText: built.acceptedOriginalText,+ };+}++function buildAcceptedWrappedSource(id, variantNum, lines, targetFile, paramValues) {const block = findMarkerBlock(id, lines);if (!block) return { handled: false, error: 'Markers not found' };@@ -375,11 +517,14 @@ function handleAccept(id, variantNum, lines, targetFile, paramValues) {...replacement,...lines.slice(replaceRange.end + 1),];- fs.writeFileSync(targetFile, newLines.join('\n'), 'utf-8');-- return { carbonize: needsCarbonize, acceptedOriginalText: originalContent.join('\n') };+ return {+ content: newLines.join('\n'),+ carbonize: needsCarbonize,+ acceptedOriginalText: originalContent.join('\n'),+ };}+function readSourceShadowPreviewMeta(content, id) {const escaped = escapeRegExp(id);const wrapperRe = new RegExp('<[^>]+data-impeccable-variants=(["\'])' + escaped + '\\1[^>]*>');@@ -746,6 +891,21 @@ function detectCommentSyntax(filePath) {// File search (find the file containing session markers)// ---------------------------------------------------------------------------+/**+ * `.impeccable` is the critical entry, and it is not cosmetic.+ *+ * Progressive publication stages each revision as `.impeccable/live/artifacts/+ * <id>-r<n>.<source-ext>`, and those artifacts carry the very marker this search+ * looks for. The walk reaches `.` for any project whose source is not under one+ * of the privileged dirs above (this repo's own site lives in `site/pages/`), and+ * dot-directories sort before letters, so the artifact was found *before* the+ * real file. isGeneratedFile then declined the accept, and the agent fell back to+ * carbonizing several hundred lines of stylesheet by hand.+ *+ * Impeccable's own state directory is never project source. Never search it.+ */+const SEARCH_SKIP_DIRS = new Set(['node_modules', '.git', 'dist', 'build', IMPECCABLE_DIR]);+function findSessionFile(id, cwd) {const marker = 'impeccable-variants-start ' + id;const searchDirs = ['src', 'app', 'pages', 'components', 'public', 'views', 'templates', '.'];@@ -786,7 +946,7 @@ function searchDir(dir, query, seen, depth) {for (const entry of entries) {if (!entry.isDirectory()) continue;- if (['node_modules', '.git', 'dist', 'build'].includes(entry.name)) continue;+ if (SEARCH_SKIP_DIRS.has(entry.name)) continue;const result = searchDir(path.join(dir, entry.name), query, seen, depth + 1);if (result) return result;}@@ -798,6 +958,28 @@ function searchDir(dir, query, seen, depth) {// Utilities// ---------------------------------------------------------------------------+function acceptReceiptPath(cwd, id) {+ return path.join(getLiveDir(cwd), 'accept-receipts', `${safeSessionId(id)}.json`);+}++function readAcceptReceipt(cwd, id) {+ try { return JSON.parse(fs.readFileSync(acceptReceiptPath(cwd, id), 'utf-8')); } catch { return null; }+}++function writeAcceptReceipt(cwd, id, receipt) {+ const file = acceptReceiptPath(cwd, id);+ fs.mkdirSync(path.dirname(file), { recursive: true });+ const value = {+ id,+ ...receipt,+ completedAt: new Date().toISOString(),+ };+ const temporary = `${file}.${process.pid}.${Date.now()}.tmp`;+ fs.writeFileSync(temporary, JSON.stringify(value, null, 2) + '\n', 'utf-8');+ fs.renameSync(temporary, file);+ return value;+}+function argVal(args, flag) {const idx = args.indexOf(flag);return idx !== -1 && idx + 1 < args.length ? args[idx + 1] : null;diff --git a/.cursor/skills/impeccable/scripts/live-browser.js b/.cursor/skills/impeccable/scripts/live-browser.jsindex 616f1290a..20d875b93 100644--- a/.cursor/skills/impeccable/scripts/live-browser.js+++ b/.cursor/skills/impeccable/scripts/live-browser.js@@ -126,6 +126,9 @@let expectedVariants = 0;let arrivedVariants = 0;let visibleVariant = 0;+ let generationPhase = null;+ let parameterGenerationState = 'idle';+ let parameterReadyAnnouncedSession = null;let svelteComponentSession = null;let svelteRuntimePromise = null;let pendingSvelteComponentRetryObserver = null;@@ -134,6 +137,7 @@let currentPreviewMode = null;let recoveryWaitingForAnchor = false;let pickedAnchorSnapshot = null;+ let pickedAnchorViewportTop = null;let pendingVariantAnchorRetryObserver = null;let pendingAcceptedSession = null;let variantObserver = null;@@ -151,10 +155,12 @@// startScrollLock / stopScrollLock below.let scrollLockObserver = null;let scrollLockTargetY = null;+ let scrollLockAnchorTop = null;let scrollLockRaf = null;let scrollLockAbort = null;const SCROLL_ANCHOR_LOCK_ID = 'impeccable-scroll-anchor-lock';const VARIANT_STATE_STYLE_ID = 'impeccable-variant-state';+ const DISCARD_STATE_STYLE_ID = 'impeccable-discard-state';// Dedicated key for scroll position - SEPARATE from LS_KEY so that// saveSession's state updates don't clobber a carefully-captured scrollY.@@ -252,6 +258,13 @@barConnected: !!barEl?.isConnected,hasSvelteComponentSession: !!svelteComponentSession,mountedSvelteVariant: svelteComponentSession?.mountedVariant || 0,+ pickActive,+ pendingApplyInFlight,+ hoveredElement: hoveredElement ? {+ tag: hoveredElement.tagName,+ classes: hoveredElement.className,+ pickable: pickable(hoveredElement),+ } : null,pendingSvelteComponentRetry: !!pendingSvelteComponentRetryObserver,recoveryWaitingForAnchor,evtSourceReadyState: evtSource ? evtSource.readyState : null,@@ -1114,14 +1127,15 @@});}- function hideBar() {+ function hideBar(instant) {if (!barEl) return;const hideSeq = ++barHideSeq;stopVoice({ suppressSubmit: true });if (configureKind === 'insert') clearInsertPicking();barEl.style.opacity = '0';- barEl.style.transform = 'translateY(6px)';- setTimeout(() => { if (barEl && hideSeq === barHideSeq) barEl.style.display = 'none'; }, 250);+ barEl.style.transform = instant ? 'translateY(0)' : 'translateY(6px)';+ if (instant) barEl.style.display = 'none';+ else setTimeout(() => { if (barEl && hideSeq === barHideSeq) barEl.style.display = 'none'; }, 250);hideActionPicker();closeTunePopover();hideConfigureBarTooltip();@@ -1966,6 +1980,7 @@*/function setLiveState(next) {state = next;+ window.__IMPECCABLE_LIVE_STATE__ = next;syncPageInteractionCursor();}@@ -2516,18 +2531,27 @@fontSize: '11px', color: BP.textDim, whiteSpace: 'nowrap',marginLeft: 'auto',});- // Variants currently arrive atomically in a single file edit, so a- // per-variant counter would lie. Say what's true.status.textContent = recoveryWaitingForAnchor? 'Variants ready. Reveal the selected element to resume.'- : (arrivedVariants < expectedVariants- ? 'Generating ' + expectedVariants + ' variants...'- : 'Done');+ : generationStatusText();row.appendChild(status);return row;}+ function generationStatusText() {+ if (arrivedVariants >= expectedVariants && expectedVariants > 0) return 'Done';+ if (generationPhase === 'picked_up') return 'Agent picked up the request...';+ if (generationPhase === 'scaffolding') return 'Finding the source...';+ if (generationPhase === 'source_ready') return 'Source ready. Generating...';+ if (generationPhase === 'scaffold_fallback') return 'Agent is locating the source...';+ if (generationPhase === 'first_variant_generating') return 'Designing the first variant...';+ if (generationPhase === 'first_variant_validating') return 'Checking the first variant...';+ if (generationPhase === 'remaining_variants_generating') return 'Exploring two more directions...';+ if (generationPhase === 'remaining_variants_validating') return 'Checking the remaining variants...';+ return 'Generating ' + expectedVariants + ' variants...';+ }+// Cycling rowconst TUNE_ICON_SVG = '<svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" style="flex-shrink:0"><line x1="4" y1="8" x2="20" y2="8"/><circle cx="14" cy="8" r="2.4" fill="currentColor" stroke="none"/><line x1="4" y1="16" x2="20" y2="16"/><circle cx="10" cy="16" r="2.4" fill="currentColor" stroke="none"/></svg>';@@ -2557,7 +2581,7 @@color: BP.textDim, minWidth: '24px', textAlign: 'center',});counter.id = PREFIX + '-variant-counter';- counter.textContent = visibleVariant + '/' + arrivedVariants;+ counter.textContent = visibleVariant + '/' + expectedVariants;row.appendChild(counter);// Next@@ -2567,10 +2591,12 @@if (visibleVariant >= arrivedVariants) next.style.opacity = '0.3';row.appendChild(next);- // Tune chip - only when the visible variant exposes params+ // Tune chip stays visible while the deferred parameter phase is running,+ // then becomes interactive as soon as this variant exposes controls.const visParams = parseVariantParams(getVisibleVariantEl());const hasParams = visParams.length > 0;- if (hasParams) {+ const paramsPending = !hasParams && (parameterGenerationState === 'pending' || parameterGenerationState === 'loading');+ if (hasParams || paramsPending) {const tune = el('button', {display: 'inline-flex', alignItems: 'center', gap: '6px',padding: '4px 10px', borderRadius: '5px',@@ -2578,35 +2604,54 @@background: tuneOpen ? BP.accentSoft : 'transparent',color: tuneOpen ? BP.accent : BP.text,fontFamily: FONT, fontSize: '11px', fontWeight: '500',- cursor: 'pointer',+ cursor: paramsPending ? 'wait' : 'pointer',transition: 'color 0.12s ease, background 0.12s ease',whiteSpace: 'nowrap',});- tune.innerHTML = TUNE_ICON_SVG;+ if (paramsPending) {+ const spinner = el('span', {+ width: '11px', height: '11px', borderRadius: '50%',+ border: '1.5px solid ' + BP.hairline,+ borderTopColor: BP.accent,+ animation: 'impeccable-spin 0.6s linear infinite',+ boxSizing: 'border-box', flexShrink: '0',+ });+ spinner.setAttribute('aria-hidden', 'true');+ tune.appendChild(spinner);+ } else {+ tune.innerHTML = TUNE_ICON_SVG;+ }const tuneLabel = document.createElement('span');tuneLabel.textContent = 'Tune';tune.appendChild(tuneLabel);- const tuneBadge = document.createElement('span');- Object.assign(tuneBadge.style, {- display: 'inline-flex', alignItems: 'center', justifyContent: 'center',- minWidth: '16px', height: '16px', padding: '0 4px',- borderRadius: '999px',- background: tuneOpen ? C.brand : BP.hairline,- color: tuneOpen ? 'oklch(98% 0 0)' : 'inherit',- fontFamily: MONO, fontSize: '9.5px', fontWeight: '600',- lineHeight: '1',- boxSizing: 'border-box',- });- tuneBadge.textContent = String(visParams.length);- tune.appendChild(tuneBadge);- tune.title = 'Tune this variant (' + visParams.length + ' knob' + (visParams.length === 1 ? '' : 's') + ')';- tune.addEventListener('mouseenter', () => {- if (!tuneOpen) tune.style.background = BP.accentSoft;- });- tune.addEventListener('mouseleave', () => {- if (!tuneOpen) tune.style.background = 'transparent';- });- tune.addEventListener('click', (e) => { e.stopPropagation(); toggleTunePopover(); });+ if (hasParams) {+ const tuneBadge = document.createElement('span');+ Object.assign(tuneBadge.style, {+ display: 'inline-flex', alignItems: 'center', justifyContent: 'center',+ minWidth: '16px', height: '16px', padding: '0 4px',+ borderRadius: '999px',+ background: tuneOpen ? C.brand : BP.hairline,+ color: tuneOpen ? 'oklch(98% 0 0)' : 'inherit',+ fontFamily: MONO, fontSize: '9.5px', fontWeight: '600',+ lineHeight: '1',+ boxSizing: 'border-box',+ });+ tuneBadge.textContent = String(visParams.length);+ tune.appendChild(tuneBadge);+ tune.title = 'Tune this variant (' + visParams.length + ' knob' + (visParams.length === 1 ? '' : 's') + ')';+ tune.addEventListener('mouseenter', () => {+ if (!tuneOpen) tune.style.background = BP.accentSoft;+ });+ tune.addEventListener('mouseleave', () => {+ if (!tuneOpen) tune.style.background = 'transparent';+ });+ tune.addEventListener('click', (e) => { e.stopPropagation(); toggleTunePopover(); });+ } else {+ tune.disabled = true;+ tune.setAttribute('aria-label', 'Tune controls are still being prepared');+ tune.title = 'Tune controls are still being prepared';+ tune.style.opacity = '0.72';+ }tune.dataset.iceqTune = '1';row.appendChild(tune);}@@ -2614,6 +2659,15 @@// Spacerrow.appendChild(el('div', { flex: '1' }));+ if (arrivedVariants < expectedVariants) {+ const remaining = expectedVariants - arrivedVariants;+ const progress = el('span', {+ fontSize: '11px', color: BP.textDim, whiteSpace: 'nowrap',+ });+ progress.textContent = remaining + ' more arriving...';+ row.appendChild(progress);+ }+// Accept - primary action, kinpaku gold + lacquer-deep (matches demo .live-demo-ctx-accept)const accept = el('button', {padding: '5px 14px', borderRadius: '5px',@@ -2628,7 +2682,11 @@accept.addEventListener('mousedown', () => accept.style.transform = 'scale(0.97)');accept.addEventListener('mouseup', () => accept.style.transform = 'scale(1)');accept.addEventListener('click', (e) => { e.stopPropagation(); handleAccept(); });- if (arrivedVariants === 0) { accept.style.opacity = '0.3'; accept.style.pointerEvents = 'none'; }+ if (arrivedVariants === 0) {+ accept.style.opacity = '0.3';+ accept.style.pointerEvents = 'none';+ accept.title = 'Accept becomes available when the first variant arrives';+ }row.appendChild(accept);// Discard@@ -4743,6 +4801,32 @@}}+ function mountedParameterCount() {+ if (svelteComponentSession?.sessionId === currentSessionId) {+ return Object.values(svelteComponentSession.paramsByVariant || {})+ .reduce((total, params) => total + (Array.isArray(params) ? params.length : 0), 0);+ }+ const wrapper = document.querySelector('[data-impeccable-variants="' + currentSessionId + '"]');+ if (!wrapper) return 0;+ return [...wrapper.querySelectorAll('[data-impeccable-variant]:not([data-impeccable-variant="original"])')]+ .reduce((total, variant) => total + parseVariantParams(variant).length, 0);+ }++ function completeParameterPublication() {+ if (!currentSessionId) return;+ const ready = mountedParameterCount() > 0;+ parameterGenerationState = ready ? 'ready' : 'none';+ if (ready && parameterReadyAnnouncedSession !== currentSessionId) {+ parameterReadyAnnouncedSession = currentSessionId;+ showToast('Tune controls are ready.', 3000);+ }+ if (state === 'CYCLING') {+ refreshParamsPanel();+ showOrUpdateCyclingBar();+ }+ saveSession();+ }+function toggleTunePopover() {if (pendingApplyInFlight) { showManualApplyBusyToast(); return; }if (tuneOpen) { closeTunePopover(); return; }@@ -4835,6 +4919,10 @@return String(filePath || '').endsWith('manifest.json');}+ function isFrameworkComponentPreviewMode(mode) {+ return mode === 'svelte-component';+ }+function parseOriginalMarkupElement(originalMarkup) {const parser = new DOMParser();const doc = parser.parseFromString('<div id="impeccable-anchor">' + originalMarkup + '</div>', 'text/html');@@ -5029,9 +5117,13 @@}}- function loadSvelteRuntime(runtimeModule) {+ function resolveComponentModuleUrl(manifest, modulePath) {+ return new URL(String(modulePath || ''), location.origin).href;+ }++ function loadSvelteRuntime(runtimeModule, manifest) {const modulePath = runtimeModule || '/src/lib/impeccable/__runtime.js';- const url = new URL(modulePath, location.origin).href;+ const url = resolveComponentModuleUrl(manifest, modulePath);if (!svelteRuntimePromise) {svelteRuntimePromise = import(/* @vite-ignore */ url);}@@ -5065,7 +5157,8 @@async function loadSvelteComponentVariantSource(manifest, variantNum) {const dir = String(manifest?.componentDir || '').replace(/^\/+/, '');if (!dir || !variantNum) return '';- const sourcePath = dir + '/v' + variantNum + '.svelte';+ const extension = manifest.componentExtension || 'svelte';+ const sourcePath = dir + '/v' + variantNum + '.' + extension;const url = 'http://localhost:' + PORT + '/source?token=' + TOKEN + '&path=' + encodeURIComponent(sourcePath);try {const res = await fetch(url);@@ -5221,7 +5314,7 @@if (!sourceOriginal) return values;const map = buildSvelteExpressionTextMap(sourceOriginal, liveEl);for (const entry of contract) {- const token = '{' + entry.expr + '}';+ const token = entry.previewToken || ('{' + entry.expr + '}');values[entry.prop] = map.get(token) || '';}return values;@@ -5233,9 +5326,12 @@try {const previousAnchor = getMountedSvelteComponentAnchor(svelteComponentSession) || selectedElement;svelteComponentSession.swapAnchor = makeFrozenAnchor(previousAnchor) || svelteComponentSession.swapAnchor || null;- const runtime = await loadSvelteRuntime(manifest.runtimeModule);- const modulePath = '/' + String(manifest.componentDir || '').replace(/^\/+/, '') + '/v' + variantNum + '.svelte';- const moduleUrl = new URL(modulePath, location.origin).href + '?t=' + Date.now();+ const runtime = await loadSvelteRuntime(manifest.runtimeModule, manifest);+ const extension = manifest.componentExtension || 'svelte';+ const moduleBase = manifest.componentModuleBase+ || ('/' + String(manifest.componentDir || '').replace(/^\/+/, ''));+ const modulePath = String(moduleBase).replace(/\/+$/, '') + '/v' + variantNum + '.' + extension;+ const moduleUrl = resolveComponentModuleUrl(manifest, modulePath) + '?t=' + Date.now();const mod = await import(/* @vite-ignore */ moduleUrl);const Component = mod.default;if (svelteComponentSession.mountedInstance && runtime.unmount) {@@ -5275,7 +5371,7 @@if (svelteComponentSession?.sessionId === sessionId) {svelteComponentSession.swapAnchor = null;}- console.error('[impeccable] Failed to mount Svelte variant ' + variantNum + ' for ' + sessionId + ':', err);+ console.error('[impeccable] Failed to mount component variant ' + variantNum + ' for ' + sessionId + ':', err);return false;}}@@ -5340,40 +5436,46 @@if (manifest.id !== sessionId) return;const paramsByVariant = await loadSvelteComponentParams(manifest);+ const availableVariants = Number(manifest.arrivedVariants) || Number(manifest.count) || 1;+ const componentPreviewMode = isFrameworkComponentPreviewMode(manifest.previewMode)+ ? manifest.previewMode+ : 'svelte-component';currentSessionId = sessionId;expectedVariants = Number(manifest.count) || expectedVariants || 1;rememberSessionFileMeta({sourceFile: manifest.sourceFile,previewFile: manifestPath,- previewMode: 'svelte-component',+ previewMode: componentPreviewMode,});if (state !== 'CYCLING') setLiveState('GENERATING');const existingWrapper = document.querySelector('[data-impeccable-variants="' + sessionId + '"]');if (existingWrapper && svelteComponentSession?.sessionId === sessionId) {recoveryWaitingForAnchor = false;+ svelteComponentSession.manifest = manifest;svelteComponentSession.paramsByVariant = paramsByVariant;- arrivedVariants = Number(manifest.count) || expectedVariants || 1;- expectedVariants = arrivedVariants;+ arrivedVariants = availableVariants;+ expectedVariants = Number(manifest.count) || expectedVariants || arrivedVariants;visibleVariant = visibleVariant > 0 && visibleVariant <= arrivedVariants ? visibleVariant : 1;await mountSvelteComponentVariant(visibleVariant || 1);setLiveState('CYCLING');showOrUpdateCyclingBar();saveSession();+ if (parameterGenerationState === 'loading') completeParameterPublication();return;}const liveEl = findLiveElementForSvelteManifest(manifest);if (!liveEl?.parentElement) {console.warn('[impeccable] Could not find original element in live DOM.');- arrivedVariants = Number(manifest.count) || expectedVariants || 1;- expectedVariants = arrivedVariants;+ arrivedVariants = availableVariants;+ expectedVariants = Number(manifest.count) || expectedVariants || arrivedVariants;const saved = loadSession();const savedVisibleVariant = saved && saved.id === sessionId ? saved.visible : 0;visibleVariant = visibleVariant > 0 && visibleVariant <= arrivedVariants? visibleVariant: (savedVisibleVariant > 0 && savedVisibleVariant <= arrivedVariants ? savedVisibleVariant : 1);- enterRecoveryWaitingForAnchor({ checkpointReason: 'svelte_component_anchor_missing', trackScroll: true });+ enterRecoveryWaitingForAnchor({ checkpointReason: 'component_preview_anchor_missing', trackScroll: true });waitForSvelteComponentTargetAndRetry({ manifestPath, sessionId, manifest });return;}@@ -5381,7 +5483,7 @@const wrapper = document.createElement('div');wrapper.dataset.impeccableVariants = sessionId;wrapper.dataset.impeccableVariantCount = String(manifest.count || expectedVariants || 1);- wrapper.dataset.impeccablePreview = 'svelte-component';+ wrapper.dataset.impeccablePreview = componentPreviewMode;wrapper.style.display = 'contents';const mountTarget = document.createElement('div');@@ -5419,8 +5521,8 @@recoveryWaitingForAnchor = false;const previousVisibleVariant = currentSessionId === sessionId ? visibleVariant : 0;- arrivedVariants = Number(manifest.count) || expectedVariants || 1;- expectedVariants = arrivedVariants;+ arrivedVariants = availableVariants;+ expectedVariants = Number(manifest.count) || expectedVariants || arrivedVariants;const saved = loadSession();const savedVisibleVariant = saved && saved.id === sessionId ? saved.visible : 0;visibleVariant = previousVisibleVariant > 0 && previousVisibleVariant <= arrivedVariants@@ -5445,9 +5547,10 @@refreshParamsPanel();positionBar();saveSession();- console.log('[impeccable] Mounted ' + arrivedVariants + ' Svelte component variants.');+ if (parameterGenerationState === 'loading') completeParameterPublication();+ console.log('[impeccable] Mounted ' + arrivedVariants + ' ' + manifest.framework + ' component variants.');} catch (err) {- console.error('[impeccable] Failed to mount Svelte component variants:', err);+ console.error('[impeccable] Failed to mount component-preview variants:', err);abortSvelteComponentInjection(sessionId, 'Could not load variants. Fix the error and re-run.');}}@@ -5493,6 +5596,8 @@clearHandled();resetSessionFileMeta();currentSessionId = null;+ parameterGenerationState = 'idle';+ parameterReadyAnnouncedSession = null;expectedVariants = 0;arrivedVariants = 0;visibleVariant = 0;@@ -5502,12 +5607,24 @@if (message) showToast(message, 5000);}+ // How many delayed re-reads a completion-driven source fallback gets when+ // the fetched source still shows only the preflight scaffold, before the+ // failure is surfaced via recoverEmptyCycling.+ const COMPLETED_SOURCE_FALLBACK_RETRIES = 3;+ const COMPLETED_SOURCE_FALLBACK_RETRY_MS = 1200;+/*** No-HMR fallback: fetch the raw source file from the live server,* parse it, extract the variant wrapper, and inject it into the live DOM.* This works even when the dev server caches HTML (Bun, static servers).+ *+ * opts.generationCompleted marks callers that KNOW the agent finished (a+ * `done` arrived or the server reported a completed generation). For them an+ * empty read is a stale source view and no further event is coming, so the+ * read retries a few times and then surfaces recovery. Callers without the+ * flag may be mid-generation and wait indefinitely for the real completion.*/- function injectVariantsFromSource(filePath, sessionId) {+ function injectVariantsFromSource(filePath, sessionId, opts = {}) {if (isSvelteComponentManifestPath(filePath)) {injectSvelteComponentsFromManifest(filePath, sessionId);return;@@ -5573,6 +5690,32 @@arrivedVariants = variants.length;expectedVariants = parseInt(wrapper.dataset.impeccableVariantCount || arrivedVariants);if (arrivedVariants <= 0) {+ if (state === 'GENERATING') {+ // Mid-generation the source legitimately holds a scaffold wrapper+ // with no variants yet (the server-side preflight wraps before the+ // agent writes). Tearing the session down here would destroy an+ // in-flight generation; stay in GENERATING — the variant observer+ // is armed and the server re-delivers a missed `done`.+ if (!opts.generationCompleted) {+ console.log('[impeccable] Source has scaffold but no variants yet; still generating.');+ return;+ }+ // Generation finished, yet the read shows only the scaffold: the+ // source view is stale and no further event will fire. Re-read a+ // few times before surfacing recovery — a single silent return+ // here would strand the tab in GENERATING forever.+ const attempt = opts.attempt || 0;+ if (attempt < COMPLETED_SOURCE_FALLBACK_RETRIES) {+ console.log('[impeccable] Generation is done but source shows no variants yet; retrying read ('+ + (attempt + 1) + '/' + COMPLETED_SOURCE_FALLBACK_RETRIES + ').');+ setTimeout(() => {+ if (state !== 'GENERATING' || currentSessionId !== sessionId) return;+ if (arrivedVariants > 0) return;+ injectVariantsFromSource(filePath, sessionId, { ...opts, attempt: attempt + 1 });+ }, COMPLETED_SOURCE_FALLBACK_RETRY_MS);+ return;+ }+ }recoverEmptyCycling('source-fallback-empty');return;}@@ -5594,6 +5737,7 @@refreshParamsPanel();positionBar();saveSession();+ if (parameterGenerationState === 'loading') completeParameterPublication();console.log('[impeccable] Injected ' + arrivedVariants + ' variants from source file.');}).catch(err => {@@ -5865,13 +6009,36 @@document.getElementById(VARIANT_STATE_STYLE_ID)?.remove();}+ function showOriginalDuringDiscard(sessionId) {+ if (!sessionId) return;+ let styleEl = document.getElementById(DISCARD_STATE_STYLE_ID);+ if (!styleEl) {+ styleEl = document.createElement('style');+ styleEl.id = DISCARD_STATE_STYLE_ID;+ (document.head || document.documentElement).appendChild(styleEl);+ }+ const wrapper = '[data-impeccable-variants="' + sessionId + '"]';+ styleEl.textContent = wrapper + ' > [data-impeccable-variant]:not([data-impeccable-variant="original"]) { display:none !important; }\n'+ + wrapper + ' > [data-impeccable-variant="original"] { display:block !important; }';+ }++ function resolveScrollLockAnchorTop() {+ const anchor = resolveBarAnchor();+ if (!anchor?.isConnected) return null;+ const top = anchor.getBoundingClientRect().top;+ return Number.isFinite(top) ? top : null;+ }+// Hold window.scrollY at a fixed value across DOM mutations inside the// session's wrapper (HMR patches, variant inserts, cycle swaps).- function startScrollLock(sessionId, initialTargetY) {+ function startScrollLock(sessionId, initialTargetY, initialAnchorTop) {stopScrollLock();scrollLockTargetY = typeof initialTargetY === 'number' && isFinite(initialTargetY)? initialTargetY: window.scrollY;+ scrollLockAnchorTop = typeof initialAnchorTop === 'number' && isFinite(initialAnchorTop)+ ? initialAnchorTop+ : resolveScrollLockAnchorTop();try { history.scrollRestoration = 'manual'; } catch {}@@ -5895,6 +6062,17 @@const correct = (why) => {scrollLockRaf = null;if (scrollLockTargetY == null) return;+ const anchor = resolveBarAnchor();+ if (anchor?.isConnected && typeof scrollLockAnchorTop === 'number' && isFinite(scrollLockAnchorTop)) {+ const anchorTop = anchor.getBoundingClientRect().top;+ const anchorDelta = anchorTop - scrollLockAnchorTop;+ if (Math.abs(anchorDelta) >= 0.5) {+ window.scrollTo({ top: window.scrollY + anchorDelta, left: window.scrollX, behavior: 'instant' });+ scrollLockTargetY = window.scrollY;+ writeScrollY(scrollLockTargetY);+ return;+ }+ }const before = window.scrollY;const delta = before - scrollLockTargetY;if (Math.abs(delta) < 0.5) {@@ -5939,6 +6117,7 @@if (scrollLockRaf != null) { cancelAnimationFrame(scrollLockRaf); scrollLockRaf = null; }const prevTarget = scrollLockTargetY;scrollLockTargetY = window.scrollY;+ scrollLockAnchorTop = resolveScrollLockAnchorTop();writeScrollY(scrollLockTargetY);};const markGesture = (why) => {@@ -5976,6 +6155,7 @@if (scrollLockRaf != null) { cancelAnimationFrame(scrollLockRaf); scrollLockRaf = null; }if (scrollLockAbort) { scrollLockAbort.abort(); scrollLockAbort = null; }scrollLockTargetY = null;+ scrollLockAnchorTop = null;// NOTE: do NOT clear the persistent scroll key here. startScrollLock// calls us as a reset, and clearing the key would nuke the Go-time// scrollY that the next resume needs to read.@@ -6049,6 +6229,7 @@updating = true;arrivedVariants = count;+ generationPhase = arrivedVariants >= expectedVariants ? 'variants_ready' : 'variants_progress';if (visibleVariant === 0 && arrivedVariants > 0) {const saved = loadSession();const savedVisibleVariant = saved && saved.id === sessionId ? saved.visible : 0;@@ -6064,7 +6245,7 @@const expected = parseInt(wrapper.dataset.impeccableVariantCount || '0');if (expected > 0) expectedVariants = expected;- if (arrivedVariants >= expectedVariants && expectedVariants > 0) {+ if (arrivedVariants > 0) {setLiveState('CYCLING');recoveryWaitingForAnchor = false;hideShaderOverlay();@@ -6072,13 +6253,18 @@updateSelectedElement();showOrUpdateCyclingBar();disableInlineEdit();- refreshParamsPanel();+ if (arrivedVariants >= expectedVariants && expectedVariants > 0) refreshParamsPanel();+ else hideParamsPanel();positionBar();} else if (state === 'GENERATING') {updateBarContent('generating');}saveSession();- queueCheckpoint(state === 'CYCLING' ? 'variants_ready' : 'variants_progress');+ sendCheckpoint(+ arrivedVariants >= expectedVariants && expectedVariants > 0+ ? 'variants_ready'+ : 'variants_progress',+ );updating = false;});@@ -6151,6 +6337,7 @@syncAgentPollingUi(!!msg.agentPolling);startAgentStatusPoll();restoreFromActiveSessions(msg.activeSessions, 'sse_connected');+ recoverMissedGenerationCompletion(msg.activeSessions);if (state === 'IDLE' && (pickActive || insertActive)) setLiveState('PICKING');syncPageInteractionCursor();syncPageChatFocus('sse-connected');@@ -6158,6 +6345,42 @@case 'agent_polling':syncAgentPollingUi(!!msg.connected);break;+ case 'agent_phase':+ if (msg.id === currentSessionId && (state === 'GENERATING' || state === 'CYCLING')) {+ generationPhase = msg.phase || generationPhase;+ if (msg.phase === 'variant_parameters_generating' || msg.phase === 'variant_parameters_validating') {+ parameterGenerationState = 'loading';+ }+ if (msg.phase === 'parameters_ready' && parameterGenerationState !== 'ready') {+ parameterGenerationState = 'loading';+ }+ updateBarContent(state === 'CYCLING' ? 'cycling' : 'generating');+ saveSession();+ }+ break;+ case 'variant_progress':+ if (msg.id === currentSessionId) {+ if (msg.publicationKind === 'params') parameterGenerationState = 'loading';+ rememberSessionFileMeta(msg);+ if (isFrameworkComponentPreviewMode(msg.previewMode) && msg.previewFile) {+ injectSvelteComponentsFromManifest(msg.previewFile, msg.id);+ } else if ((msg.previewMode === 'source' || !msg.previewMode) && (msg.previewFile || msg.file)) {+ // Give normal framework HMR the first chance to reconcile its+ // own managed tree. Nuxt route-module HMR can skip intermediate+ // revisions, so fall back to source injection only when the+ // advertised progress still has not appeared after a short+ // settle. Immediate injection races React/Vue ownership and can+ // trigger removeChild errors on the next HMR commit.+ const targetArrived = Number(msg.arrivedVariants) || 1;+ setTimeout(() => {+ if (msg.id !== currentSessionId) return;+ if (state !== 'GENERATING' && state !== 'CYCLING') return;+ if (msg.publicationKind !== 'params' && arrivedVariants >= targetArrived) return;+ injectVariantsFromSource(msg.previewFile || msg.file, msg.id);+ }, 150);+ }+ }+ break;case 'steer_done':maybeCompleteSteer(msg);break;@@ -6175,6 +6398,10 @@case 'done':if (maybeCompleteSteer(msg)) break;rememberSessionFileMeta(msg);+ if (msg.id === currentSessionId && isFrameworkComponentPreviewMode(currentPreviewMode) && currentPreviewFile) {+ injectSvelteComponentsFromManifest(currentPreviewFile, msg.id);+ break;+ }// Variants already arrived via HMR → normal transition.if (arrivedVariants >= expectedVariants && expectedVariants > 0) {if (state === 'GENERATING') {@@ -6190,7 +6417,7 @@setTimeout(() => {if (arrivedVariants >= expectedVariants && expectedVariants > 0) return;if (state !== 'GENERATING' || msg.id !== currentSessionId) return;- injectVariantsFromSource(msg.file, msg.id);+ injectVariantsFromSource(msg.file, msg.id, { generationCompleted: true });}, 750);break;}@@ -6215,9 +6442,10 @@if (maybeCompleteAcceptedSession(msg)) break;break;case 'agent_done':- // Carbonize accepts are not terminal until live-complete.mjs sends- // the final complete event. Keep the browser in its recoverable- // saving state while the source cleanup is still in flight.+ // The deterministic accept has already committed the reviewed DOM+ // and fenced generation. Carbonize may continue in the background;+ // it must not hold the foreground picker hostage.+ if (msg.data?.carbonize === true && maybeCompleteAcceptedSession(msg)) break;break;case 'discarded':if (msg.id && msg.id === currentSessionId) {@@ -6306,6 +6534,7 @@type: 'checkpoint',id: currentSessionId,revision: sessionState.nextCheckpointRevision(),+ revisionDomain: 'browser',owner: browserOwner,phase: String(state || '').toLowerCase(),reason,@@ -6331,6 +6560,7 @@type: 'checkpoint',id,revision: sessionState.nextCheckpointRevision(),+ revisionDomain: 'browser',owner: browserOwner,phase: 'steer',reason,@@ -6684,6 +6914,9 @@expectedVariants = selectedCount;arrivedVariants = 0;visibleVariant = 0;+ generationPhase = 'queued';+ parameterGenerationState = 'pending';+ parameterReadyAnnouncedSession = null;resetSessionFileMeta();// Flip to GENERATING immediately so the bar morphs without waiting on@@ -6693,6 +6926,7 @@const elForCapture = selectedElement;pickedAnchorSnapshot = buildPickedAnchorSnapshot(elForCapture);const captureRect = elForCapture.getBoundingClientRect();+ pickedAnchorViewportTop = captureRect.top;const snapshot = {comments: annotState.comments.map(c => ({ x: c.x, y: c.y, text: c.text })),strokes: annotState.strokes.map(s => ({ points: s.points.map(p => [p[0], p[1]]) })),@@ -6724,7 +6958,7 @@writeScrollY(window.scrollY);if (variantObserver) variantObserver.disconnect();variantObserver = startVariantObserver(currentSessionId);- startScrollLock(currentSessionId);+ startScrollLock(currentSessionId, window.scrollY, pickedAnchorViewportTop);captureAndEmit(elForCapture, basePayload, snapshot, captureRect);}@@ -6759,12 +6993,16 @@expectedVariants = selectedCount;arrivedVariants = 0;visibleVariant = 0;+ generationPhase = 'queued';+ parameterGenerationState = 'pending';+ parameterReadyAnnouncedSession = null;resetSessionFileMeta();selectedElement = placeholderElement;insertPlaceholderSnapshot = buildInsertPlaceholderSnapshotFromDom(insertAnchorElement, placeholderElement);const elForCapture = placeholderElement;const captureRect = elForCapture.getBoundingClientRect();+ pickedAnchorViewportTop = captureRect.top;const basePayload = {type: 'generate',mode: 'insert',@@ -6795,7 +7033,7 @@writeScrollY(window.scrollY);if (variantObserver) variantObserver.disconnect();variantObserver = startVariantObserver(currentSessionId);- startScrollLock(currentSessionId);+ startScrollLock(currentSessionId, window.scrollY, pickedAnchorViewportTop);captureAndEmit(elForCapture, basePayload, snapshot, captureRect);}@@ -6975,9 +7213,9 @@// preview mounts are covered by the same shader regression checks.const adapter = String(window.__IMPECCABLE_LIVE_ADAPTER__ || '').toLowerCase();if (adapter === 'svelte' || adapter === 'sveltekit') return true;- if (currentPreviewMode === 'svelte-component' || svelteComponentSession) return true;+ if (isFrameworkComponentPreviewMode(currentPreviewMode) || svelteComponentSession) return true;const wrapper = el?.closest?.('[data-impeccable-variants]');- return wrapper?.dataset?.impeccablePreview === 'svelte-component';+ return isFrameworkComponentPreviewMode(wrapper?.dataset?.impeccablePreview);}function paintsShaderProxySurface(node) {@@ -7105,6 +7343,17 @@}async function captureAndEmit(el, basePayload, snapshot, rect) {+ const hasAnnotations = snapshot && (snapshot.comments.length > 0 || snapshot.strokes.length > 0);++ // Plain requests do not send a screenshot to the agent, so capture is+ // presentation-only. Wait only for the helper to accept the event before+ // starting CPU-heavy capture; this yields the browser task and prevents+ // rasterization from delaying the fetch itself.+ if (!hasAnnotations) {+ basePayload.clientSentAt = Date.now();+ await sendEvent(basePayload);+ }+let screenshotPath;let blob;let paper;@@ -7122,7 +7371,6 @@// are present. Without annotations the image is pure visual anchoring -// it biases the model toward the current rendering and works against the// three-distinct-directions brief.- const hasAnnotations = snapshot && (snapshot.comments.length > 0 || snapshot.strokes.length > 0);if (blob && hasAnnotations) {try {const uploadRes = await fetch(@@ -7140,7 +7388,12 @@console.warn('[impeccable] annotation upload failed:', err);}}- sendEvent(screenshotPath ? { ...basePayload, screenshotPath } : basePayload);+ // Annotated requests must wait for capture + upload because the screenshot+ // is semantic input. Plain requests were already dispatched above.+ if (hasAnnotations) {+ basePayload.clientSentAt = Date.now();+ sendEvent(screenshotPath ? { ...basePayload, screenshotPath } : basePayload);+ }}//@@ -7520,7 +7773,6 @@ void main() {if (variantSelectionPromise) {try { await variantSelectionPromise; } catch { /* failed selection falls back below */ }}- if (!currentSessionId || arrivedVariants === 0) return;const domVisibleVariant = readVisibleVariantFromDOM(currentSessionId);if (domVisibleVariant > 0) visibleVariant = domVisibleVariant;const acceptPayload = {@@ -7528,7 +7780,9 @@ void main() {id: currentSessionId,variantId: String(visibleVariant),pageUrl: location.pathname,+ clientSentAt: Date.now(),};+ if (!currentSessionId || arrivedVariants === 0) return;const acceptWrapper = document.querySelector('[data-impeccable-variants="' + currentSessionId + '"]');if (Object.keys(paramsCurrentValues).length > 0) {acceptPayload.paramValues = { ...paramsCurrentValues };@@ -7542,7 +7796,7 @@ void main() {const acceptedSessionId = currentSessionId;const acceptedVariant = visibleVariant;const acceptedIsSvelteComponent = svelteComponentSession?.sessionId === acceptedSessionId- || acceptWrapper?.dataset?.impeccablePreview === 'svelte-component';+ || isFrameworkComponentPreviewMode(acceptWrapper?.dataset?.impeccablePreview);const acceptedSnapshot = snapshotAcceptedVariantDom(acceptedSessionId, acceptedVariant);setLiveState('SAVING');@@ -7557,7 +7811,17 @@ void main() {saveSession();sendEvent(acceptPayload, { throwOnError: true })- .then(() => {})+ .then(() => {+ const pending = pendingAcceptedSession;+ if (!pending || pending.id !== acceptedSessionId) return;+ // POST /events returns only after the accept intent is durable and the+ // generation epoch is fenced. Source promotion/carbonize can finish in+ // the background; the foreground picker is free immediately.+ markSessionHandled();+ setLiveState('CONFIRMED');+ document.documentElement.dataset.impeccableAcceptToPickingMs = String(Date.now() - acceptPayload.clientSentAt);+ scheduleAcceptCleanup(pending);+ }).catch(() => {if (pendingAcceptedSession?.id === acceptedSessionId) pendingAcceptedSession = null;setLiveState('CYCLING');@@ -7586,17 +7850,26 @@ void main() {}function scheduleAcceptCleanup(accepted) {- setTimeout(function() {- if (!accepted?.isSvelteComponent && !acceptedDomAlreadyClean(accepted)) {- setTimeout(function() {- if (pendingAcceptedSession?.id !== accepted?.id) return;- if (!accepted?.isSvelteComponent) ensureAcceptedDomClean(accepted);- cleanupAcceptedSession();- }, 1800);- return;+ queueMicrotask(function() {+ if (pendingAcceptedSession?.id !== accepted?.id) return;+ // Svelte previews live in an adapter-owned mount rather than in source+ // wrapper markup. Promote the mounted variant before releasing the+ // session so the old adapter instance cannot linger behind the next+ // Pick → Go loop while carbonize finishes in the background.+ if (accepted?.isSvelteComponent) {+ commitAcceptedSvelteComponentToDom(accepted.id);}cleanupAcceptedSession();- }, 1200);+ });+ // Let React/Vue/Svelte own the HMR reconciliation. Mutating their DOM in+ // the same turn as the source update causes removeChild/NotFoundError+ // races. Static servers still need a fallback, but it must not keep Live+ // in SAVING or block the user's next pick.+ if (!accepted?.isSvelteComponent) {+ setTimeout(function() {+ if (!acceptedDomAlreadyClean(accepted)) ensureAcceptedDomClean(accepted);+ }, 1200);+ }}function snapshotAcceptedVariantDom(sessionId, variantId) {@@ -7700,7 +7973,11 @@ void main() {clearSession();resetSessionFileMeta();selectedElement = null;+ hoveredElement = null;+ pagePickSkipClick = false;currentSessionId = null;+ parameterGenerationState = 'idle';+ parameterReadyAnnouncedSession = null;selectedAction = 'impeccable';pendingAcceptedSession = null;renderEditBadge('hidden');@@ -7735,7 +8012,7 @@ void main() {sendEvent({ type: 'discard', id: currentSessionId }, { throwOnError: true }).then(() => {markSessionHandled();- cleanup();+ cleanup({ restoreOriginal: true, instantChrome: true });}).catch(() => showToast('Could not confirm discard with the live server. Session kept for recovery.', 5000));}@@ -7757,6 +8034,7 @@ void main() {currentPreviewMode = null;recoveryWaitingForAnchor = false;pickedAnchorSnapshot = null;+ pickedAnchorViewportTop = null;}function rememberSessionFileMeta(meta = {}) {@@ -7765,8 +8043,8 @@ void main() {const previewFile = normalizeSessionPath(meta.previewFile);const previewMode = meta.previewMode || (isSvelteComponentManifestPath(previewFile || file) ? 'svelte-component' : null);- if (previewMode === 'svelte-component' || isSvelteComponentManifestPath(file)) {- currentPreviewMode = 'svelte-component';+ if (isFrameworkComponentPreviewMode(previewMode) || isSvelteComponentManifestPath(file)) {+ currentPreviewMode = isFrameworkComponentPreviewMode(previewMode) ? previewMode : 'svelte-component';currentPreviewFile = previewFile || (isSvelteComponentManifestPath(file) ? file : currentPreviewFile);currentSourceFile = sourceFile || currentSourceFile;return;@@ -7782,12 +8060,15 @@ void main() {rememberSessionFileMeta(saved);if (saved.insertPlaceholder) insertPlaceholderSnapshot = saved.insertPlaceholder;if (saved.pickedAnchor) pickedAnchorSnapshot = saved.pickedAnchor;+ if (Number.isFinite(saved.pickedAnchorViewportTop)) pickedAnchorViewportTop = saved.pickedAnchorViewportTop;if (saved.action) selectedAction = saved.action;if (saved.count) selectedCount = saved.count;if (saved.previewMode) currentPreviewMode = saved.previewMode;if (saved.paramValues && typeof saved.paramValues === 'object') {paramsCurrentValues = { ...saved.paramValues };}+ if (saved.parameterState) parameterGenerationState = saved.parameterState;+ if (saved.generationPhase) generationPhase = saved.generationPhase;}function normalizePagePath(value) {@@ -7859,7 +8140,7 @@ void main() {saveSession();queueCheckpoint(reason || 'browser_restore_without_wrapper');- const restoreFile = currentPreviewMode === 'svelte-component'+ const restoreFile = isFrameworkComponentPreviewMode(currentPreviewMode)? currentPreviewFile: (currentSourceFile || currentPreviewFile);if (restoreFile) {@@ -7872,11 +8153,41 @@ void main() {function restoreFromActiveSessions(activeSessions, reason) {const wrapper = document.querySelector('[data-impeccable-variants]');- if (wrapper && wrapper.dataset.impeccablePreview !== 'svelte-component') return false;+ if (wrapper && !isFrameworkComponentPreviewMode(wrapper.dataset.impeccablePreview)) return false;if (svelteComponentSession?.sessionId === currentSessionId) return false;return restoreSessionWithoutWrapper(reason || 'sse_connected', activeSessions);}+ // Self-heal on SSE (re)connect. The preflight scaffold write triggers a+ // framework full-reload (Astro reloads pages for any .astro edit); if the+ // agent's variant write + `done` broadcast land while this page is+ // mid-reload, both the done SSE and the second HMR reload are missed and+ // the resumed page would wait in GENERATING at 0/N forever. The server's+ // session summary carries the durable generationCompletedAt marker, so on+ // every connect compare it against our own progress and pull the finished+ // variants from source when behind. Mirrors the `done` handler's source+ // fallback, including its give-HMR-the-first-chance settle delay.+ function recoverMissedGenerationCompletion(activeSessions) {+ if (!currentSessionId || state !== 'GENERATING') return;+ if (!Array.isArray(activeSessions)) return;+ const summary = activeSessions.find((session) => session?.id === currentSessionId);+ if (!summary?.generationCompletedAt || summary.generationCanceled) return;+ if (isTerminalSessionSummary(summary)) return;+ if (arrivedVariants > 0 && arrivedVariants >= expectedVariants) return;+ rememberSessionFileMeta(summary);+ const sessionId = currentSessionId;+ const file = isFrameworkComponentPreviewMode(currentPreviewMode)+ ? currentPreviewFile+ : (summary.sourceFile || summary.previewFile || currentSourceFile || currentPreviewFile);+ if (!file) return;+ console.log('[impeccable] Reconnected after generation completed; recovering variants from source.');+ setTimeout(() => {+ if (sessionId !== currentSessionId || state !== 'GENERATING') return;+ if (arrivedVariants > 0 && arrivedVariants >= expectedVariants) return;+ injectVariantsFromSource(file, sessionId, { generationCompleted: true });+ }, 750);+ }+function saveSession() {if (!currentSessionId) return;// NOTE: scrollY is stored under a separate key (writeScrollY). Storing@@ -7894,8 +8205,12 @@ void main() {previewMode: currentPreviewMode || undefined,pageUrl: location.pathname,paramValues: { ...paramsCurrentValues },+ parameterState: parameterGenerationState,insertPlaceholder: insertPlaceholderSnapshot || undefined,pickedAnchor: pickedAnchorSnapshot || undefined,+ pickedAnchorViewportTop: Number.isFinite(pickedAnchorViewportTop) ? pickedAnchorViewportTop : undefined,+ pageHash: location.hash || undefined,+ pageSearch: location.search || undefined,});}@@ -7923,20 +8238,26 @@ void main() {sessionState.clearHandled();}- function cleanup() {+ function cleanup(options) {+ const restoreOriginal = options?.restoreOriginal === true;+ const instantChrome = options?.instantChrome === true;const cleanupSessionId = currentSessionId;if (svelteComponentSession?.sessionId === cleanupSessionId) {teardownSvelteComponentSession(true);} else if (cleanupSessionId) {- // Hide the wrapper immediately so variants disappear. DON'T structurally- // mutate the DOM yet - HMR from the agent's source rewrite is on its way,+ // Switch visibility immediately without structurally mutating the DOM.+ // HMR from the agent's source rewrite may still be on its way,// and a manual replaceChild under React causes NotFoundError when the// reconciler later tries to remove a wrapper we already removed.// Schedule a 2s fallback that does the manual swap only if HMR hasn't// replaced the wrapper by then (keeps static-server / no-HMR flows alive).const wrapper = document.querySelector('[data-impeccable-variants="' + cleanupSessionId + '"]');- if (wrapper) wrapper.style.display = 'none';+ if (wrapper) {+ if (restoreOriginal) showOriginalDuringDiscard(cleanupSessionId);+ else wrapper.style.display = 'none';+ }setTimeout(function() {+ document.getElementById(DISCARD_STATE_STYLE_ID)?.remove();if (!cleanupSessionId) return;const lateWrapper = document.querySelector('[data-impeccable-variants="' + cleanupSessionId + '"]');if (!lateWrapper) return;@@ -7951,7 +8272,7 @@ void main() {lateWrapper.remove();}, 2000);}- hideBar();+ hideBar(instantChrome);hideHighlight();stopScrollTracking();if (variantObserver) { variantObserver.disconnect(); variantObserver = null; }@@ -7963,7 +8284,11 @@ void main() {clearSession();resetSessionFileMeta();selectedElement = null;+ hoveredElement = null;+ pagePickSkipClick = false;currentSessionId = null;+ parameterGenerationState = 'idle';+ parameterReadyAnnouncedSession = null;selectedAction = 'impeccable';renderEditBadge('hidden');setLiveState('PICKING');@@ -8047,7 +8372,7 @@ void main() {// would strand the bar in CYCLING at 0/0. If there's no live in-memory mount// for this wrapper, it's an orphan (reload / failed mount): drop it and let// the live-server's SSE re-inject the manifest if the session is still live.- if (wrapper.dataset.impeccablePreview === 'svelte-component'+ if (isFrameworkComponentPreviewMode(wrapper.dataset.impeccablePreview)&& svelteComponentSession?.sessionId !== sessionId) {wrapper.remove();if (restoreSessionWithoutWrapper('browser_resumed_svelte_orphan_wrapper')) return true;@@ -8056,7 +8381,7 @@ void main() {return false;}- if (wrapper.dataset.impeccablePreview === 'svelte-component') {+ if (isFrameworkComponentPreviewMode(wrapper.dataset.impeccablePreview)) {if (!svelteComponentSession?.mountedVariant) {return true;}@@ -8104,7 +8429,7 @@ void main() {insertPlaceholderSnapshot = saved.insertPlaceholder;}- const resumedState = arrivedVariants >= expectedVariants ? 'CYCLING' : 'GENERATING';+ const resumedState = arrivedVariants > 0 ? 'CYCLING' : 'GENERATING';// Find the visible variant's content element for highlight positioning.const isInsert = wrapper.dataset.impeccableMode === 'insert';@@ -8128,7 +8453,11 @@ void main() {// hid. Now that state is CYCLING, re-fire.if (state === 'CYCLING') refreshParamsPanel();saveSession();- queueCheckpoint('browser_resumed');+ if (arrivedVariants > 0 && arrivedVariants < expectedVariants) {+ sendCheckpoint('variants_progress');+ } else {+ queueCheckpoint('browser_resumed');+ }// Start observing for more variants AFTER initial setupif (variantObserver) variantObserver.disconnect();@@ -8136,7 +8465,7 @@ void main() {// Hold the target at its saved viewport top through any subsequent// HMR patches, variant inserts, or cycle swaps.- startScrollLock(currentSessionId, readScrollY());+ startScrollLock(currentSessionId, readScrollY(), pickedAnchorViewportTop);// If we reloaded mid-generation (Bun's HTML HMR destroys the shader// canvas), re-capture the original's content and restart the shader so@@ -8171,6 +8500,7 @@ void main() {let globalBarBrandEl = null;let agentPollTooltipEl = null;let agentPollingConnected = false;+ let agentStatusMessage = null;let agentStatusPollTimer = null;let steerFocusSuspended = false;let steerFocusPauseUntil = 0;@@ -8275,6 +8605,13 @@ void main() {const AGENT_STATUS_POLL_MS = 5000;const AGENT_DISCONNECTED_MARK = 'oklch(62% 0 0 / 0.78)';const AGENT_DISCONNECTED_TIP = 'Agent disconnected - run live-poll.mjs to connect';+ // The indicator tracks whether a poll is parked, which is what decides if+ // steering can reach the agent right now. That goes quiet two ways, and they+ // need different copy: nobody is polling at all, or the agent took the work+ // and is busy with it. Under one-shot foreground polling the second case is+ // every normal generation, and telling the user to start a poll loop then is+ // wrong advice about a healthy session.+ const AGENT_BUSY_TIP = 'Agent is working - steering resumes when it finishes';const GLOBAL_BAR_SECTION_GAP = 8;const GLOBAL_BAR_INNER_GAP = 2;const GLOBAL_BAR_INNER_PAD_LEFT = 2;@@ -9295,24 +9632,46 @@ void main() {</svg>`;}+ /**+ * True while the browser is waiting on work it already handed to the agent.+ * In these states a quiet poll indicator means "busy", not "absent".+ */+ function agentHasWorkInFlight() {+ return state === 'GENERATING' || state === 'SAVING';+ }++ /**+ * Derived at read time, not cached: which of the two reasons applies depends on+ * the live state, which moves between the 5s status polls. The truthiness is+ * the same either way, so the indicator's visuals can stay driven by the+ * cached value while the wording stays current.+ */+ function agentStatusText() {+ if (agentPollingConnected) return null;+ return agentHasWorkInFlight() ? AGENT_BUSY_TIP : AGENT_DISCONNECTED_TIP;+ }+function syncAgentPollingUi(connected) {agentPollingConnected = !!connected;if (!globalBarBrandEl) return;const P = barPaletteForTheme(globalBarEl?.dataset.theme || detectPageTheme());+ agentStatusMessage = agentStatusText();globalBarBrandEl.dataset.agentConnected = connected ? 'true' : 'false';- globalBarBrandEl.setAttribute('aria-label', connected- ? 'Impeccable live mode'- : 'Impeccable live mode - agent not polling');+ // The tooltip is mouse-only, so carry the same distinction in the label or+ // screen-reader users are left with the vaguer of the two readings.+ globalBarBrandEl.setAttribute('aria-label', agentStatusMessage+ ? 'Impeccable live mode - ' + (agentHasWorkInFlight() ? 'agent is working' : 'agent not polling')+ : 'Impeccable live mode');globalBarBrandEl.removeAttribute('title');- globalBarBrandEl.style.cursor = connected ? 'default' : 'help';+ globalBarBrandEl.style.cursor = agentStatusMessage ? 'help' : 'default';const mark = globalBarBrandEl.querySelector('[data-brand-mark]');if (mark) {mark.innerHTML = brandMarkSvg(connected ? P.accent : AGENT_DISCONNECTED_MARK, 18);mark.style.opacity = '1';}const dot = globalBarBrandEl.querySelector('[data-agent-dot]');- if (dot) dot.style.display = connected ? 'none' : 'block';- if (connected) hideAgentPollTooltip();+ if (dot) dot.style.display = agentStatusMessage ? 'block' : 'none';+ if (!agentStatusMessage) hideAgentPollTooltip();}function ensureAgentPollTooltip() {@@ -9339,14 +9698,17 @@ void main() {whiteSpace: 'normal',});agentPollTooltipEl.id = PREFIX + '-agent-poll-tooltip';- agentPollTooltipEl.textContent = AGENT_DISCONNECTED_TIP;+ agentPollTooltipEl.textContent = agentStatusText() || AGENT_DISCONNECTED_TIP;uiAppend(agentPollTooltipEl);return agentPollTooltipEl;}function showAgentPollTooltip(anchor) {- if (agentPollingConnected || !anchor) return;+ if (!agentStatusMessage || !anchor) return;const tip = ensureAgentPollTooltip();+ // Re-derive rather than reuse the cached copy: the live state may have moved+ // since the last status poll set it.+ tip.textContent = agentStatusText() || AGENT_DISCONNECTED_TIP;tip.style.transition = 'none';tip.style.display = 'block';tip.style.opacity = '1';@@ -9376,7 +9738,9 @@ void main() {fetch('http://localhost:' + PORT + '/status?token=' + TOKEN, { cache: 'no-store' }).then((res) => (res.ok ? res.json() : null)).then((data) => {- if (data && typeof data.agentPolling === 'boolean') syncAgentPollingUi(data.agentPolling);+ if (data && typeof data.agentPolling === 'boolean') {+ syncAgentPollingUi(data.agentPolling);+ }}).catch(() => { /* server loss handled elsewhere */ });}diff --git a/.cursor/skills/impeccable/scripts/live-inject.mjs b/.cursor/skills/impeccable/scripts/live-inject.mjsindex 7c8d91182..d99c37fd5 100644--- a/.cursor/skills/impeccable/scripts/live-inject.mjs+++ b/.cursor/skills/impeccable/scripts/live-inject.mjs@@ -27,6 +27,8 @@ const __dirname = path.dirname(fileURLToPath(import.meta.url));const CONFIG_PATH = resolveLiveConfigPath({ cwd: process.cwd(), scriptsDir: __dirname });const MARKER_OPEN_TEXT = 'impeccable-live-start';const MARKER_CLOSE_TEXT = 'impeccable-live-end';+const NUXT_PLUGIN_MARKER = 'impeccable-live-nuxt-plugin';+const NUXT_PLUGIN_NAME = 'impeccable-live.client.ts';const IGNORE_MARKER_OPEN = '# impeccable-live-ignore-start';const IGNORE_MARKER_CLOSE = '# impeccable-live-ignore-end';@@ -38,6 +40,9 @@ export const LIVE_IGNORE_PATTERNS = Object.freeze(['.impeccable/live/sessions/','.impeccable/live/previews/','.impeccable/live/annotations/',+ '.impeccable/live/artifacts/',+ '.impeccable/live/accept-receipts/',+ '.impeccable/live/locks/','.impeccable/live/cache/','.impeccable/live/manual-edit-apply-transaction.json','.impeccable/live/manual-edit-events.jsonl',@@ -46,10 +51,15 @@ export const LIVE_IGNORE_PATTERNS = Object.freeze(['.impeccable/live/deferred-svelte-component-accepts.json','.impeccable-live.json','.impeccable-live/',+ 'app/.impeccable-live/',+ 'src/.impeccable-live/','node_modules/.impeccable-live/','src/lib/impeccable/ImpeccableLiveRoot.svelte','src/lib/impeccable/__runtime.js','src/lib/impeccable/[0-9a-f]*/',+ 'plugins/impeccable-live.client.ts',+ 'app/plugins/impeccable-live.client.ts',+ 'src/plugins/impeccable-live.client.ts',]);/**@@ -113,6 +123,7 @@ Output (JSON):const resolvedFiles = resolveFiles(process.cwd(), config);const svelteKit = detectSvelteKitProject(process.cwd(), config);+ const nuxt = detectNuxtProject(process.cwd());if (args.includes('--remove')) {if (svelteKit) {@@ -120,6 +131,12 @@ Output (JSON):console.log(JSON.stringify({ ok: true, adapter: 'sveltekit', results: [adapterResult] }));return;}+ if (nuxt) {+ const adapterResult = removeNuxtLiveAdapter({ cwd: process.cwd(), project: nuxt });+ console.log(JSON.stringify({ ok: !adapterResult.error, adapter: 'nuxt', results: [adapterResult] }));+ if (adapterResult.error) process.exitCode = 1;+ return;+ }const results = resolvedFiles.map((relFile) => {const absFile = path.resolve(process.cwd(), relFile);if (!fs.existsSync(absFile)) return { file: relFile, error: 'file_not_found' };@@ -145,13 +162,28 @@ Output (JSON):console.error(JSON.stringify({ ok: false, error: 'missing_port' }));process.exit(1);}- const gitIgnore = ensureLiveGitIgnores(process.cwd());+ const gitIgnore = ensureLiveGitIgnores(+ process.cwd(),+ nuxt ? [nuxt.pluginFile] : [],+ );if (svelteKit) {const adapterResult = applySvelteKitLiveAdapter({ cwd: process.cwd(), port, config });console.log(JSON.stringify({ ok: true, port, adapter: 'sveltekit', gitIgnore, results: [adapterResult] }));return;}+ if (nuxt) {+ const adapterResult = applyNuxtLiveAdapter({ cwd: process.cwd(), port, project: nuxt });+ console.log(JSON.stringify({+ ok: !adapterResult.error,+ port,+ adapter: 'nuxt',+ gitIgnore,+ results: [adapterResult],+ }));+ if (adapterResult.error) process.exitCode = 1;+ return;+ }const results = resolvedFiles.map((relFile) => {const absFile = path.resolve(process.cwd(), relFile);@@ -175,12 +207,12 @@ Output (JSON):if (!anyInserted) process.exit(1);}-export function ensureLiveGitIgnores(cwd = process.cwd()) {+export function ensureLiveGitIgnores(cwd = process.cwd(), extraPatterns = []) {const target = resolveIgnoreTarget(cwd);const existing = fs.existsSync(target.path) ? fs.readFileSync(target.path, 'utf-8') : '';const block = [IGNORE_MARKER_OPEN,- ...LIVE_IGNORE_PATTERNS,+ ...new Set([...LIVE_IGNORE_PATTERNS, ...extraPatterns]),IGNORE_MARKER_CLOSE,].join('\n');const markerRe = new RegExp(`${escapeRegExp(IGNORE_MARKER_OPEN)}[\\s\\S]*?${escapeRegExp(IGNORE_MARKER_CLOSE)}`);@@ -202,10 +234,119 @@ export function ensureLiveGitIgnores(cwd = process.cwd()) {file: path.relative(cwd, target.path).split(path.sep).join('/'),mode: target.mode,changed: updated !== existing,- patterns: [...LIVE_IGNORE_PATTERNS],+ patterns: [...new Set([...LIVE_IGNORE_PATTERNS, ...extraPatterns])],};}+// ---------------------------------------------------------------------------+// Nuxt adapter+//+// A script element placed in app.vue is compiled as Vue-rendered DOM and is+// not executed. Nuxt instead auto-discovers client plugins. Keep the adapter+// generated, dev-only, and outside user-authored source: Live creates one+// marked .client.ts plugin on start and removes it on stop.+// ---------------------------------------------------------------------------++export function detectNuxtProject(cwd = process.cwd()) {+ const configFile = fs.readdirSync(cwd, { withFileTypes: true })+ .find((entry) => entry.isFile() && /^nuxt\.config\.(?:js|mjs|cjs|ts|mts|cts)$/.test(entry.name))+ ?.name;+ if (!configFile) return null;++ const config = fs.readFileSync(path.join(cwd, configFile), 'utf-8');+ const literalSrcDir = config.match(/\bsrcDir\s*:\s*(['"])([^'"]+)\1/);+ let appDir = '';+ if (literalSrcDir) {+ const candidate = literalSrcDir[2]+ .replace(/\\/g, '/')+ .replace(/^\.\//, '')+ .replace(/\/+$/, '');+ const normalized = path.posix.normalize(candidate);+ if (normalized !== '..' && !normalized.startsWith('../') && !path.isAbsolute(normalized)) {+ appDir = normalized === '.' ? '' : normalized;+ }+ } else if (+ fs.existsSync(path.join(cwd, 'app', 'app.vue'))+ || fs.existsSync(path.join(cwd, 'app', 'pages'))+ ) {+ appDir = 'app';+ }++ const pluginFile = [appDir, 'plugins', NUXT_PLUGIN_NAME].filter(Boolean).join('/');+ return { configFile, appDir, pluginFile };+}++export function buildNuxtPlugin(port) {+ return `/* ${NUXT_PLUGIN_MARKER} */+const liveSrc = 'http://localhost:${port}/live.js';+const liveSelector = 'script[data-impeccable-live-nuxt]';++export default defineNuxtPlugin(() => {+ if (!import.meta.dev || typeof document === 'undefined') return;++ const expectedSrc = new URL(liveSrc, window.location.href).href;+ let script = document.querySelector(liveSelector);+ if (script?.src === expectedSrc) return;+ script?.remove();++ script = document.createElement('script');+ script.src = liveSrc;+ script.async = true;+ script.dataset.impeccableLiveNuxt = '';+ document.head.appendChild(script);++ import.meta.hot?.dispose(() => {+ if (script?.isConnected) script.remove();+ });+});+/* /${NUXT_PLUGIN_MARKER} */+`;+}++export function applyNuxtLiveAdapter({ cwd = process.cwd(), port, project = detectNuxtProject(cwd) }) {+ if (!project) return { error: 'nuxt_not_detected' };+ const absFile = path.join(cwd, project.pluginFile);+ const existing = fs.existsSync(absFile) ? fs.readFileSync(absFile, 'utf-8') : null;+ if (existing !== null && !existing.includes(NUXT_PLUGIN_MARKER)) {+ return {+ file: project.pluginFile,+ error: 'nuxt_plugin_conflict',+ hint: `${project.pluginFile} already exists and is not managed by Impeccable Live`,+ };+ }++ const content = buildNuxtPlugin(port);+ fs.mkdirSync(path.dirname(absFile), { recursive: true });+ if (content !== existing) fs.writeFileSync(absFile, content, 'utf-8');+ return {+ file: project.pluginFile,+ inserted: true,+ changed: content !== existing,+ devOnly: true,+ };+}++export function removeNuxtLiveAdapter({ cwd = process.cwd(), project = detectNuxtProject(cwd) }) {+ if (!project) return { error: 'nuxt_not_detected' };+ const absFile = path.join(cwd, project.pluginFile);+ if (!fs.existsSync(absFile)) {+ return { file: project.pluginFile, removed: false, note: 'no adapter present' };+ }+ const content = fs.readFileSync(absFile, 'utf-8');+ if (!content.includes(NUXT_PLUGIN_MARKER)) {+ return {+ file: project.pluginFile,+ removed: false,+ error: 'nuxt_plugin_conflict',+ hint: `${project.pluginFile} is not managed by Impeccable Live`,+ };+ }+ fs.unlinkSync(absFile);+ const pluginDir = path.dirname(absFile);+ if (fs.readdirSync(pluginDir).length === 0) fs.rmdirSync(pluginDir);+ return { file: project.pluginFile, removed: true };+}+function resolveIgnoreTarget(cwd) {const gitExcludePath = resolveGitInfoExcludePath(cwd);if (gitExcludePath) {diff --git a/.cursor/skills/impeccable/scripts/live-poll.mjs b/.cursor/skills/impeccable/scripts/live-poll.mjsindex 740161e10..19a8b0f9b 100644--- a/.cursor/skills/impeccable/scripts/live-poll.mjs+++ b/.cursor/skills/impeccable/scripts/live-poll.mjs@@ -27,7 +27,7 @@ const scriptCmd = (name) => `node "${path.join(SELF_DIR, name)}"`;export const PER_REQUEST_TIMEOUT_MS = 270_000;export const DEFAULT_EVENT_LEASE_MS = 600_000;-const EVENT_TYPES_NEEDING_AGENT_REPLY = new Set(['generate', 'steer', 'manual_edit_apply']);+const EVENT_TYPES_NEEDING_AGENT_REPLY = new Set(['generate', 'steer', 'manual_edit_apply', 'carbonize_cleanup']);function readServerInfo() {const record = readLiveServerInfo(process.cwd());@@ -38,8 +38,8 @@ function readServerInfo() {return record.info;}-export function buildPollReplyPayload(token, { id, type, message, file, data }) {- return { token, id, type, message, file, data };+export function buildPollReplyPayload(token, { id, type, message, file, data, sourceEventType }) {+ return { token, id, type, message, file, data, sourceEventType };}export function manualApplyPollBanner(event = {}) {@@ -152,7 +152,14 @@ export async function waitForEventAck(base, token, eventId, {return false;}-export async function fetchNextEvent(base, token, { totalDeadline } = {}) {+export async function fetchNextEvent(base, token, {+ totalDeadline,+ types,+ resolveTypes,+ perRequestTimeoutMs = PER_REQUEST_TIMEOUT_MS,+ leaseMs = DEFAULT_EVENT_LEASE_MS,+ signal,+} = {}) {while (true) {if (totalDeadline && Date.now() >= totalDeadline) {return { type: 'timeout' };@@ -161,8 +168,15 @@ export async function fetchNextEvent(base, token, { totalDeadline } = {}) {const remaining = totalDeadline? totalDeadline - Date.now(): PER_REQUEST_TIMEOUT_MS;- const slice = Math.min(Math.max(remaining, 1000), PER_REQUEST_TIMEOUT_MS);- const res = await fetch(`${base}/poll?token=${token}&timeout=${slice}&leaseMs=${DEFAULT_EVENT_LEASE_MS}`);+ const slice = Math.min(Math.max(remaining, 1000), perRequestTimeoutMs);+ const query = new URLSearchParams({+ token,+ timeout: String(slice),+ leaseMs: String(leaseMs),+ });+ const normalizedTypes = normalizePollTypes(resolveTypes ? await resolveTypes() : types);+ if (normalizedTypes.length > 0) query.set('types', normalizedTypes.join(','));+ const res = await fetch(`${base}/poll?${query}`, { signal });if (res.status === 401) {const err = new Error('Authentication failed. The server token may have changed.');@@ -202,11 +216,17 @@ export async function augmentEventWithAcceptHandling(event, base, token) {event._acceptResult = { handled: false, mode: 'error', error: err.message };}+ await completeAcceptHandling(event, base, token);+ return event;+}++export async function completeAcceptHandling(event, base, token) {const completionType = completionTypeForAcceptResult(event.type, event._acceptResult);try {await postReply(base, token, {id: event.id,type: completionType,+ sourceEventType: event.type,message: event._acceptResult?.error,file: event._acceptResult?.file,data: event._acceptResult?.carbonize === true ? { carbonize: true } : undefined,@@ -217,7 +237,6 @@ export async function augmentEventWithAcceptHandling(event, base, token) {if (!event._completionAck) {event._completionAck = completionAckForAcceptResult(event.id, completionType, event._acceptResult);}-return event;}@@ -245,9 +264,9 @@ export function printPollEvent(event) {console.log(JSON.stringify(event));}-export async function runPollOnce(base, token, { totalTimeout = 600_000 } = {}) {+export async function runPollOnce(base, token, { totalTimeout = 600_000, types, resolveTypes, perRequestTimeoutMs } = {}) {const deadline = Date.now() + totalTimeout;- const event = await fetchNextEvent(base, token, { totalDeadline: deadline });+ const event = await fetchNextEvent(base, token, { totalDeadline: deadline, types, resolveTypes, perRequestTimeoutMs });await augmentEventWithAcceptHandling(event, base, token);writeCarbonizeBanner(event);printPollEvent(event);@@ -258,11 +277,14 @@ export async function runPollStream(base, token, {ackTimeoutMs = 600_000,ackPollIntervalMs = 400,shouldContinue = () => true,+ types,+ resolveTypes,+ perRequestTimeoutMs,} = {}) {process.stderr.write('[impeccable-poll] stream mode: one JSON object per line on stdout; use --reply while this process stays running\n');while (shouldContinue()) {- const event = await fetchNextEvent(base, token);+ const event = await fetchNextEvent(base, token, { types, resolveTypes, perRequestTimeoutMs });await augmentEventWithAcceptHandling(event, base, token);writeCarbonizeBanner(event);printPollEvent(event);@@ -322,14 +344,17 @@ Modes:Options:--timeout=MS One-shot poll timeout in ms (default: 600000). Ignored in --stream mode+ --types=A,B Lease only these event types--ack-timeout=MS Stream mode: max wait for --reply after generate/steer (default: 600000)--file PATH Attach a source file path to the reply (generate/steer flow)--data JSON Attach a JSON result object to the reply (manual_edit_apply flow). Must be valid JSON--help Show this help messageHarness note:- Default one-shot mode is the portable contract for Claude Code, Codex, and Cursor.- --stream is experimental for harnesses with fast incremental stdout; do not use on Cursor.`);+ Default one-shot mode is the primary contract, including Codex foreground polling.+ Claude Code may run it as a background task; Cursor uses a background terminal with exit notification.+ --stream is retained for harnesses with measured, reliable incremental stdout.+ Do not use --stream on Cursor.`);process.exit(0);}@@ -360,23 +385,30 @@ Harness note:}const streamMode = args.includes('--stream');+ const typesArg = args.find((a) => a.startsWith('--types='));+ const types = normalizePollTypes(typesArg ? typesArg.slice('--types='.length) : null);const ackTimeoutArg = args.find((a) => a.startsWith('--ack-timeout='));const ackTimeoutMs = ackTimeoutArg ? parseInt(ackTimeoutArg.split('=')[1], 10) : 600_000;try {if (streamMode) {- await runPollStream(base, info.token, { ackTimeoutMs });+ await runPollStream(base, info.token, { ackTimeoutMs, types });return;}const timeoutArg = args.find((a) => a.startsWith('--timeout='));const totalTimeout = timeoutArg ? parseInt(timeoutArg.split('=')[1], 10) : 600_000;- await runPollOnce(base, info.token, { totalTimeout });+ await runPollOnce(base, info.token, { totalTimeout, types });} catch (err) {handlePollError(err);}}+export function normalizePollTypes(value) {+ const values = Array.isArray(value) ? value : String(value || '').split(',');+ return [...new Set(values.map((type) => String(type).trim()).filter(Boolean))];+}+// Auto-execute when run directlyconst _running = process.argv[1];if (_running?.endsWith('live-poll.mjs') || _running?.endsWith('live-poll.mjs/')) {diff --git a/.cursor/skills/impeccable/scripts/live-server.mjs b/.cursor/skills/impeccable/scripts/live-server.mjsindex 5735f2aec..c6e951086 100644--- a/.cursor/skills/impeccable/scripts/live-server.mjs+++ b/.cursor/skills/impeccable/scripts/live-server.mjs@@ -28,8 +28,10 @@ import {readLiveBrowserScriptParts,resolveLiveBrowserScriptParts,} from './live/browser-script-parts.mjs';-import { createLiveSessionStore } from './live/session-store.mjs';+import { createLiveSessionStore, GENERATION_FENCED_PHASES } from './live/session-store.mjs';+import { runGenerationPreflight } from './live/generation-preflight.mjs';import { validateEvent } from './live/event-validation.mjs';+import { selectAvailablePendingEvent } from './live/poll-lanes.mjs';import { createManualEditRoutes } from './live/manual-edit-routes.mjs';import { LIVE_COMMANDS } from './live/vocabulary.mjs';import {@@ -63,6 +65,10 @@ const DESIGN_MD_PATH = PROJECT_CONTEXT.designPath: null;const DEFAULT_POLL_TIMEOUT = 600_000; // 10 min — agent re-polls on timeout anywayconst SSE_HEARTBEAT_INTERVAL = 30_000; // keepalive ping every 30s+// The browser checkpoints for several unrelated reasons (see checkpointPayload+// in live-browser.js). Only these two report that variant availability changed,+// and only they may drive variant_progress / the *_reviewable phases.+const VARIANT_PROGRESS_CHECKPOINT_REASONS = new Set(['variants_progress', 'variants_ready']);// ---------------------------------------------------------------------------// Port detection@@ -156,29 +162,206 @@ function restorePendingEventsFromStore() {}}-function findAvailablePendingEvent(now = Date.now()) {- for (const entry of state.pendingEvents) {- if (entry.leaseUntil && entry.leaseUntil > now) continue;- return entry;- }- return null;+function findAvailablePendingEvent(now = Date.now(), types = null) {+ return selectAvailablePendingEvent(state.pendingEvents, { now, types });}-function leaseEvent(entry, leaseMs) {+async function leaseEvent(entry, leaseMs) {+ // Claim the entry before awaiting anything. prepareGenerateEventForLease+ // yields to the event loop, and selectAvailablePendingEvent only skips+ // entries whose lease is in the future — an unclaimed entry would be handed+ // to a second poll in that window and generated twice.+ entry.leaseUntil = Date.now() + leaseMs;+ await prepareGenerateEventForLease(entry);if (!entry.event?.id) {const idx = state.pendingEvents.indexOf(entry);if (idx !== -1) state.pendingEvents.splice(idx, 1);return entry.event;}+ // Re-stamp so the lease window starts when the agent actually receives the+ // work, not when scaffolding began.entry.leaseUntil = Date.now() + leaseMs;+ recordGenerateDelivery(entry);scheduleLeaseFlush();broadcastAgentPollingIfChanged();return entry.event;}-function acknowledgePendingEvent(id) {+function recordGenerateDelivery(entry) {+ const event = entry?.event;+ if (!event || event.type !== 'generate' || event.generationReadyAt) return;+ const at = Date.now();+ entry.event = { ...event, generationReadyAt: at };+ state.sessionStore?.appendEvent(entry.event);+ recordAgentPhase(event.id, 'generation_ready', { at });+}++async function prepareGenerateEventForLease(entry) {+ const event = entry?.event;+ if (!event || event.type !== 'generate' || event.scaffoldAttempted) return;++ recordAgentPhase(event.id, 'picked_up');+ recordAgentPhase(event.id, 'scaffolding');+ const result = await runGenerationPreflight(event, {+ cwd: process.cwd(),+ scriptsDir: __dirname,+ });+ entry.event = {+ ...event,+ scaffoldAttempted: true,+ scaffoldDurationMs: result.durationMs ?? null,+ ...(result.ok ? { scaffold: result.scaffold } : { scaffoldError: result.error || result.reason }),+ };+ state.sessionStore?.appendEvent(entry.event);+ recordAgentPhase(event.id, result.ok ? 'source_ready' : 'scaffold_fallback', {+ durationMs: result.durationMs ?? null,+ previewMode: result.scaffold?.previewMode || 'source',+ });+}++function recordAgentPhase(id, phase, details = {}) {+ if (!id) return;+ const event = {+ type: 'agent_phase',+ id,+ phase,+ at: Date.now(),+ ...details,+ };+ state.sessionStore?.appendEvent(event);+ broadcast(event);+}++/**+ * Detect a browser that missed the generation `done` broadcast.+ *+ * The preflight scaffold write triggers a framework full-reload (Astro reloads+ * the page for any .astro edit). If the agent's variant write + `done` land+ * while the browser is mid-reload, the new page misses both the second HMR+ * reload and the SSE `done` — it resumes from the scaffold-only source and+ * sits in GENERATING at 0/N forever. That resumed page always checkpoints+ * (`browser_resumed`), so a checkpoint claiming "still generating, variants+ * missing" for a session whose generation already completed is direct+ * evidence of the miss. Rebuild the `done` payload from the snapshot so the+ * caller can re-broadcast it; the browser's done handler is idempotent and+ * falls back to injecting variants from source.+ *+ * Keys on the store's monotone `generationCompletedAt`, not `phase` — the+ * behind checkpoint itself regresses `phase` to `generating`, and a browser+ * that misses the redelivered `done` too (another reload) must still trigger+ * redelivery from its next checkpoint.+ */+function detectMissedGenerationCompletion(event) {+ if (!event?.id || event.type !== 'checkpoint') return null;+ if (event.phase !== 'generating') return null;+ if (!variantCountLooksBehind(event.arrivedVariants, event.expectedVariants)) return null;+ if (!state.sessionStore) return null;+ let snapshot = null;+ try {+ snapshot = state.sessionStore.getSnapshot(event.id);+ } catch {+ return null;+ }+ return missedCompletionFromSnapshot(snapshot);+}++function variantCountLooksBehind(arrivedValue, expectedValue) {+ const arrived = Number(arrivedValue) || 0;+ const expected = Number(expectedValue) || 0;+ return arrived <= 0 || (expected > 0 && arrived < expected);+}++function missedCompletionFromSnapshot(snapshot) {+ if (!snapshot?.id || !snapshot.generationCompletedAt) return null;+ if (snapshot.generationCanceled) return null;+ // Accept/discard already underway: the browser is no longer waiting on+ // generation, and a late `done` there would collide with teardown.+ if (GENERATION_FENCED_PHASES.has(snapshot.phase)) return null;+ const file = snapshot.sourceFile || snapshot.previewFile;+ if (!file) return null;+ return {+ type: 'done',+ id: snapshot.id,+ file,+ sourceFile: snapshot.sourceFile || undefined,+ previewFile: snapshot.previewFile || undefined,+ previewMode: snapshot.previewMode || undefined,+ redelivered: true,+ };+}++function recordGenerationCheckpoint(event) {+ if (!event?.id || event.type !== 'checkpoint') return;+ if (generationIsFenced(event.id)) return;+ // Only checkpoints that report a change in variant availability are+ // generation progress. The browser also checkpoints for durability on Tune+ // slider drags, resumes, and anchor recovery; treating those as progress+ // echoed `variant_progress` straight back to the browser that sent it, which+ // remounts the component preview mid-drag (reverting the user's live param+ // edit and detaching the popover's element), and permanently latched the+ // *_reviewable phases from the wrong trigger, corrupting generation timings.+ if (!VARIANT_PROGRESS_CHECKPOINT_REASONS.has(event.reason)) return;+ const arrived = Number(event.arrivedVariants) || 0;+ const expected = Number(event.expectedVariants) || 0;+ if (arrived <= 0 || expected <= 0) return;+ const previewMode = event.previewMode || 'source';+ const previewFile = event.previewFile || event.file;+ if (previewFile) {+ broadcast({+ type: 'variant_progress',+ id: event.id,+ file: previewFile,+ sourceFile: event.sourceFile || (previewMode === 'source' ? previewFile : undefined),+ previewFile,+ previewMode,+ arrivedVariants: arrived,+ expectedVariants: expected,+ publicationKind: event.publicationKind || 'variants',+ });+ }+ const details = {+ arrivedVariants: arrived,+ expectedVariants: expected,+ checkpointReason: event.reason || null,+ };+ const at = Date.now();+ if (!generationPhaseAlreadyRecorded(event.id, 'first_reviewable')) {+ recordAgentPhase(event.id, 'first_reviewable', { ...details, at });+ }+ if (arrived >= 2 && expected >= 3 && !generationPhaseAlreadyRecorded(event.id, 'second_reviewable')) {+ recordAgentPhase(event.id, 'second_reviewable', { ...details, at });+ }+ if (arrived >= expected && !generationPhaseAlreadyRecorded(event.id, 'all_variants_ready')) {+ recordAgentPhase(event.id, 'all_variants_ready', { ...details, at });+ }+}++function generationIsFenced(id) {+ if (!state.sessionStore || !id) return false;+ try {+ const snapshot = state.sessionStore.getSnapshot(id, { includeCompleted: true });+ return snapshot?.generationCanceled === true;+ } catch {+ return false;+ }+}++function generationPhaseAlreadyRecorded(id, phase) {+ if (!state.sessionStore) return false;+ try {+ const snapshot = state.sessionStore.getSnapshot(id, { includeCompleted: true });+ return !!snapshot?.generationTimings?.[phase];+ } catch {+ return false;+ }+}++function acknowledgePendingEvent(id, sourceEventType) {if (!id) return false;- const idx = state.pendingEvents.findIndex((entry) => entry.event?.id === id);+ const idx = state.pendingEvents.findIndex((entry) => (+ entry.event?.id === id+ && (!sourceEventType || entry.event?.type === sourceEventType)+ ));if (idx === -1) return false;const acknowledged = state.pendingEvents[idx].event;state.pendingEvents.splice(idx, 1);@@ -187,9 +370,39 @@ function acknowledgePendingEvent(id) {return acknowledged;}-function findPendingEventById(id) {+function releasePendingEvent(id, sourceEventType) {+ const entry = state.pendingEvents.find((item) => (+ item.event?.id === id+ && (!sourceEventType || item.event?.type === sourceEventType)+ ));+ if (!entry) return null;+ entry.leaseUntil = 0;+ scheduleLeaseFlush();+ return entry.event;+}++function retirePendingGeneration(id) {+ if (!id) return 0;+ let retired = 0;+ for (let index = state.pendingEvents.length - 1; index >= 0; index -= 1) {+ const event = state.pendingEvents[index]?.event;+ if (event?.id !== id || event.type !== 'generate') continue;+ state.pendingEvents.splice(index, 1);+ retired += 1;+ }+ if (retired > 0) {+ scheduleLeaseFlush();+ broadcastAgentPollingIfChanged();+ }+ return retired;+}++function findPendingEventById(id, sourceEventType) {if (!id) return null;- const entry = state.pendingEvents.find((item) => item.event?.id === id);+ const entry = state.pendingEvents.find((item) => (+ item.event?.id === id+ && (!sourceEventType || item.event?.type === sourceEventType)+ ));return entry?.event || null;}@@ -198,7 +411,7 @@ function summarizePendingEventForStatus(entry) {const summary = {id: event.id,type: event.type,- leased: !!(entry.leaseUntil && entry.leaseUntil > Date.now()),+ leased: isLeased(entry),leaseUntil: entry.leaseUntil || null,};if (event.type === 'manual_edit_apply') {@@ -224,7 +437,13 @@ function summarizeActiveSessionForClient(snapshot = {}) {arrivedVariants: snapshot.arrivedVariants ?? 0,visibleVariant: snapshot.visibleVariant ?? null,checkpointRevision: snapshot.checkpointRevision ?? 0,+ browserCheckpointRevision: snapshot.browserCheckpointRevision ?? snapshot.checkpointRevision ?? 0,+ publicationCheckpointRevision: snapshot.publicationCheckpointRevision ?? 0,paramValues: snapshot.paramValues || {},+ generationPhase: snapshot.generationPhase ?? null,+ generationCompletedAt: snapshot.generationCompletedAt ?? null,+ generationCanceled: snapshot.generationCanceled === true,+ cancelReason: snapshot.cancelReason ?? null,};}@@ -269,24 +488,46 @@ function scheduleLeaseFlush() {function flushPendingPolls() {let changed = false;while (state.pendingPolls.length > 0) {- const entry = findAvailablePendingEvent();+ let pollIndex = -1;+ let entry = null;+ for (let index = 0; index < state.pendingPolls.length; index += 1) {+ const candidate = findAvailablePendingEvent(Date.now(), state.pendingPolls[index].types);+ if (!candidate) continue;+ pollIndex = index;+ entry = candidate;+ break;+ }if (!entry) {scheduleLeaseFlush();broadcastAgentPollingIfChanged();return;}- const poll = state.pendingPolls.shift();- poll.resolve(leaseEvent(entry, poll.leaseMs));+ const [poll] = state.pendingPolls.splice(pollIndex, 1);+ // leaseEvent is async (it may scaffold source), but it claims the entry+ // synchronously, so the next loop iteration will not re-select it. Resolve+ // the poll when the lease settles rather than awaiting here, so one slow+ // scaffold never delays the other parked polls. On the exceptional failure+ // path, answer `timeout` so the agent re-polls; the claim stays until the+ // lease expires, which keeps a deterministic failure from hot-looping.+ leaseEvent(entry, poll.leaseMs).then(poll.resolve, (error) => {+ console.error('[live] lease failed for ' + (entry.event?.id || 'unknown') + ': ' + (error?.message || error));+ poll.resolve({ type: 'timeout' });+ });changed = true;}scheduleLeaseFlush();if (changed) broadcastAgentPollingIfChanged();}+function isLeased(entry) {+ return !!(entry?.leaseUntil && entry.leaseUntil > Date.now());+}+function agentPollingConnected() {- const now = Date.now();- return state.pendingPolls.length > 0- || state.pendingEvents.some((entry) => entry.leaseUntil && entry.leaseUntil > now);+ // A leased event only proves that a poll returned once. The foreground task+ // may have ended immediately afterward, so only an actively waiting poll is+ // evidence that steering can wake the task right now.+ return state.pendingPolls.length > 0;}function broadcastAgentPollingIfChanged() {@@ -689,6 +930,16 @@ function createRequestHandler({ detectScript, liveScriptParts }) {res.end(JSON.stringify({ error }));return;}+ if (msg.type === 'agent_phase') {+ recordAgentPhase(msg.id, msg.phase, {+ ...(Number.isFinite(msg.durationMs) ? { durationMs: msg.durationMs } : {}),+ owner: typeof msg.owner === 'string' ? msg.owner : undefined,+ });+ res.writeHead(200, { 'Content-Type': 'application/json' });+ res.end(JSON.stringify({ ok: true }));+ return;+ }+ const missedCompletion = detectMissedGenerationCompletion(msg);if (state.sessionStore && msg.id) {try {state.sessionStore.appendEvent(msg);@@ -698,6 +949,11 @@ function createRequestHandler({ detectScript, liveScriptParts }) {return;}}+ if (msg.type === 'accept' || msg.type === 'discard') {+ retirePendingGeneration(msg.id);+ }+ recordGenerationCheckpoint(msg);+ if (missedCompletion) broadcast(missedCompletion);if (msg.type === 'exit') {cleanupSvelteComponentSessionsBeforeExit();}@@ -738,6 +994,12 @@ function createRequestHandler({ detectScript, liveScriptParts }) {// Agent poll endpoints (unchanged from WS version)// ---------------------------------------------------------------------------+function parsePollTypes(value) {+ if (!value) return null;+ const types = String(value).split(',').map((type) => type.trim()).filter(Boolean);+ return types.length > 0 ? new Set(types) : null;+}+function handlePollGet(req, res, url) {const token = url.searchParams.get('token');if (token !== state.token) {@@ -748,13 +1010,25 @@ function handlePollGet(req, res, url) {state.lastPollAt = Date.now();const timeout = parseInt(url.searchParams.get('timeout') || DEFAULT_POLL_TIMEOUT, 10);const leaseMs = parseInt(url.searchParams.get('leaseMs') || '30000', 10);- const available = findAvailablePendingEvent();+ const types = parsePollTypes(url.searchParams.get('types'));+ const available = findAvailablePendingEvent(Date.now(), types);if (available) {- res.writeHead(200, { 'Content-Type': 'application/json' });- res.end(JSON.stringify(leaseEvent(available, leaseMs)));+ // Do not await inline: leaseEvent may scaffold source, and this handler runs+ // on the server's only thread. The client can disconnect during that window,+ // so check the socket before replying.+ leaseEvent(available, leaseMs).then((event) => {+ if (res.writableEnded || res.destroyed) return;+ res.writeHead(200, { 'Content-Type': 'application/json' });+ res.end(JSON.stringify(event));+ }, (error) => {+ console.error('[live] lease failed for ' + (available.event?.id || 'unknown') + ': ' + (error?.message || error));+ if (res.writableEnded || res.destroyed) return;+ res.writeHead(200, { 'Content-Type': 'application/json' });+ res.end(JSON.stringify({ type: 'timeout' }));+ });return;}- const poll = { resolve, leaseMs };+ const poll = { resolve, leaseMs, types };const timer = setTimeout(() => {const idx = state.pendingPolls.indexOf(poll);if (idx !== -1) state.pendingPolls.splice(idx, 1);@@ -783,12 +1057,15 @@ function sessionFileMetadataFromPollReply(file) {if (!file || typeof file !== 'string') return { file };const normalized = file.split(path.sep).join('/');const base = { file: normalized };- if (!normalized.endsWith('/manifest.json') && normalized !== 'manifest.json') return base;- if (!normalized.includes('node_modules/.impeccable-live/') && !normalized.includes('src/lib/impeccable/')) return base;+ const metadataFile = normalized;+ if (!metadataFile.endsWith('/manifest.json') && metadataFile !== 'manifest.json') return base;+ if (!metadataFile.includes('node_modules/.impeccable-live/')+ && !metadataFile.includes('src/lib/impeccable/')+ && !metadataFile.includes('/.impeccable-live/')) return base;let full;try {- full = path.resolve(process.cwd(), normalized);+ full = path.resolve(process.cwd(), metadataFile);const rel = path.relative(process.cwd(), full);if (!rel || rel.startsWith('..') || path.isAbsolute(rel)) return base;} catch {@@ -797,18 +1074,47 @@ function sessionFileMetadataFromPollReply(file) {try {const manifest = JSON.parse(fs.readFileSync(full, 'utf-8'));- if (manifest?.previewMode !== 'svelte-component' || !manifest.sourceFile) return base;+ if (manifest?.previewMode !== 'svelte-component'+ || !manifest.sourceFile) return base;return {file: String(manifest.sourceFile).split(path.sep).join('/'),sourceFile: String(manifest.sourceFile).split(path.sep).join('/'),previewFile: normalized,- previewMode: 'svelte-component',+ previewMode: manifest.previewMode,};} catch {return base;}}+function inferSourceEventType(msg = {}, pendingEvents = state.pendingEvents) {+ const entriesForId = pendingEvents.filter((entry) => entry.event?.id === msg.id);+ const pendingTypes = new Set(entriesForId.map((entry) => entry.event?.type));+ if (msg.type === 'discarded' || msg.type === 'discard') return 'discard';+ if (msg.type === 'complete') {+ if (pendingTypes.has('carbonize_cleanup')) return 'carbonize_cleanup';+ return pendingTypes.has('accept') ? 'accept' : (pendingTypes.has('generate') ? 'generate' : undefined);+ }+ if (msg.type === 'steer_done') return 'steer';+ // `agent_done` can be the automatic acknowledgement for a carbonize Accept.+ // New pollers send sourceEventType explicitly; default to generate only for+ // older callers so a late worker cannot acknowledge a queued Accept.+ if (msg.type === 'agent_done' || msg.type === 'done') return 'generate';+ // `error` is reference/live.md's documented failure reply, and parseReplyArgs+ // never sets sourceEventType on it (the poller is a fresh process that cannot+ // know what it leased). Returning undefined here makes acknowledgePendingEvent+ // match *any* event for this id: a stale generate worker's failure silently+ // consumed the user's queued Accept, which was then never delivered to any+ // agent and left the browser in SAVING forever. Attribute the failure to the+ // event this agent actually holds a lease on, and otherwise to `generate` —+ // never to a wildcard. If that generate was already retired by an Accept, the+ // ack simply finds no match, which is the correct outcome for a stale reply.+ if (msg.type === 'error') {+ return entriesForId.find(isLeased)?.event?.type || 'generate';+ }+ return undefined;+}+function handlePollPost(req, res) {let body = '';req.on('data', (c) => { body += c; });@@ -869,7 +1175,23 @@ function handlePollPost(req, res) {res.end(JSON.stringify({ error: 'stale_manual_edit_apply_reply', ...rollback }));return;}- const pendingEventBeforeAck = findPendingEventById(msg.id);+ const sourceEventType = msg.sourceEventType || inferSourceEventType(msg);+ if (msg.type === 'retry') {+ const releasedEvent = releasePendingEvent(msg.id, sourceEventType);+ if (!releasedEvent) {+ res.writeHead(msg.id ? 404 : 400, { 'Content-Type': 'application/json' });+ res.end(JSON.stringify({+ error: msg.id ? 'unknown_poll_retry_id' : 'missing_poll_retry_id',+ id: msg.id,+ }));+ return;+ }+ flushPendingPolls();+ res.writeHead(200, { 'Content-Type': 'application/json' });+ res.end(JSON.stringify({ ok: true, released: true }));+ return;+ }+ const pendingEventBeforeAck = findPendingEventById(msg.id, sourceEventType);if (pendingEventBeforeAck?.type === 'steer' && msg.type === 'steer_done'&& !msg.file && !(typeof msg.message === 'string' && msg.message.trim())) {res.writeHead(400, { 'Content-Type': 'application/json' });@@ -879,7 +1201,7 @@ function handlePollPost(req, res) {}));return;}- const acknowledgedEvent = acknowledgePendingEvent(msg.id);+ const acknowledgedEvent = acknowledgePendingEvent(msg.id, sourceEventType);let skipJournalReply = false;let existingSession = null;if (!acknowledgedEvent && state.sessionStore && msg.id) {@@ -1083,7 +1405,10 @@ if (args.includes('--background')) {process.exit(0);}} catch { /* not ready yet */ }- await new Promise(r => setTimeout(r, 200));+ // The detached child is typically listening in 35-45ms. A 200ms polling+ // floor dominated configured cold Live startup; poll cheaply and return+ // as soon as the child has written its ready record.+ await new Promise(r => setTimeout(r, 5));}console.error('Timed out waiting for live server to start.');process.exit(1);diff --git a/.cursor/skills/impeccable/scripts/live-status.mjs b/.cursor/skills/impeccable/scripts/live-status.mjsindex f7e464999..dc98b7386 100644--- a/.cursor/skills/impeccable/scripts/live-status.mjs+++ b/.cursor/skills/impeccable/scripts/live-status.mjs@@ -37,15 +37,19 @@ export async function statusCli() {pendingEvents: server.pendingEvents,} : null,activeSessions: server?.activeSessions || activeSessions,- recoveryHint: manualApply- ? manualApplyResumeHint(manualApply)- : server- ? 'Run live-poll.mjs to continue pending work, or live-complete.mjs --id <session> after manual cleanup.'- : 'Start live-server.mjs to requeue pending durable events, then run live-poll.mjs.',+ recoveryHint: recoveryHint({ server, manualApply }),};console.log(JSON.stringify(payload, null, 2));}+function recoveryHint({ server, manualApply }) {+ if (manualApply) return manualApplyResumeHint(manualApply);+ if (server) {+ return 'Run live-poll.mjs to continue pending work, or live-complete.mjs --id <session> after manual cleanup.';+ }+ return 'Start live-server.mjs to requeue pending durable events, then run live-poll.mjs.';+}+function findPendingManualApply(server, activeSessions) {const fromServer = server?.pendingEvents?.find((event) => event?.type === 'manual_edit_apply');if (fromServer) return fromServer;diff --git a/.cursor/skills/impeccable/scripts/live-wrap.mjs b/.cursor/skills/impeccable/scripts/live-wrap.mjsindex 438c01b68..48d7f7683 100644--- a/.cursor/skills/impeccable/scripts/live-wrap.mjs+++ b/.cursor/skills/impeccable/scripts/live-wrap.mjs@@ -160,11 +160,29 @@ The agent should insert variant HTML at insertLine.`);if (filtered.length === 1) {match = filtered[0];} else if (filtered.length === 0) {- // Source uses dynamic content (`<h1>{title}</h1>` etc.) so the- // browser-side textContent doesn't appear literally in source. Fall- // back to first-match rather than refusing — this is the same- // behavior unmodified callers see, just preserved.- match = candidates[0];+ const normalizedText = String(text).replace(/\s+/g, ' ').trim();+ if (normalizedText.length < 8) {+ // Very short labels cannot disambiguate siblings reliably. Preserve+ // the legacy behavior for these low-information picker events.+ match = candidates[0];+ } else {+ // Rendered text that is absent from every candidate usually means+ // the source uses expressions or component props. Picking the first+ // same-class sibling silently edits the wrong instance (observed on+ // Astro result cards), so stop and surface every candidate instead.+ console.error(JSON.stringify({+ error: 'element_ambiguous',+ fallback: 'agent-driven',+ reason: 'rendered_text_not_in_source',+ file: path.relative(process.cwd(), targetFile),+ candidates: candidates.map((c) => ({+ startLine: c.startLine + 1,+ endLine: c.endLine + 1,+ })),+ hint: 'Rendered text does not occur in any matching source branch. The element may use dynamic props or expressions; inspect the candidates and wrap the intended instance manually.',+ }));+ process.exit(1);+ }} else {// Multiple candidates ALSO match the text. Truly ambiguous — refuse// rather than pick wrong, and hand the agent the candidate locations@@ -269,6 +287,7 @@ The agent should insert variant HTML at insertLine.`);const originalIndented = reindentOriginal(' ');const relTargetFile = path.relative(process.cwd(), targetFile).split(path.sep).join('/');const useSvelteComponent = shouldUseSvelteComponentInjection(targetFile);+ const useFrameworkComponent = useSvelteComponent;// Wrapper attributes differ by syntax. HTML allows plain string attrs;// JSX requires object-literal style and parses string attrs as HTML (which@@ -288,7 +307,7 @@ The agent should insert variant HTML at insertLine.`);// replacement range to include the wrapper's `<div>` open / close lines// so the entire scaffold gets removed cleanly.const wrapperLines = isJsx ? [- indent + '<div data-impeccable-variants="' + id + '" data-impeccable-variant-count="' + count + '" ' + styleContents + '>',+ indent + '<div data-impeccable-variants="' + id + '" data-impeccable-variant-count="' + count + '"' + ' ' + styleContents + '>',indent + ' ' + commentSyntax.open + ' impeccable-variants-start ' + id + ' ' + commentSyntax.close,indent + ' ' + commentSyntax.open + ' Original ' + commentSyntax.close,indent + ' <div data-impeccable-variant="original">',@@ -299,7 +318,7 @@ The agent should insert variant HTML at insertLine.`);indent + '</div>',] : [indent + commentSyntax.open + ' impeccable-variants-start ' + id + ' ' + commentSyntax.close,- indent + '<div data-impeccable-variants="' + id + '" data-impeccable-variant-count="' + count + '" ' + styleContents + '>',+ indent + '<div data-impeccable-variants="' + id + '" data-impeccable-variant-count="' + count + '"' + ' ' + styleContents + '>',indent + ' ' + commentSyntax.open + ' Original ' + commentSyntax.close,indent + ' <div data-impeccable-variant="original">',originalIndented,@@ -356,15 +375,18 @@ The agent should insert variant HTML at insertLine.`);const outputRelFile = path.relative(process.cwd(), outputFile).split(path.sep).join('/');const svelteComponentAuthoring = useSvelteComponent ? buildSvelteComponentCssAuthoring(count) : null;+ const componentSession = svelteSession;+ const componentPreviewMode = useSvelteComponent ? 'svelte-component' : undefined;+ const previewMode = componentPreviewMode;console.log(JSON.stringify({file: outputRelFile,- sourceFile: useSvelteComponent ? relTargetFile : undefined,- previewMode: useSvelteComponent ? 'svelte-component' : undefined,- componentDir: svelteSession?.componentDir,- propContract: svelteSession?.propContract,- sourceStartLine: useSvelteComponent ? startLine + 1 : undefined,- sourceEndLine: useSvelteComponent ? endLine + 1 : undefined,+ sourceFile: useFrameworkComponent ? relTargetFile : undefined,+ previewMode,+ componentDir: componentSession?.componentDir,+ propContract: componentSession?.propContract,+ sourceStartLine: useFrameworkComponent ? startLine + 1 : undefined,+ sourceEndLine: useFrameworkComponent ? endLine + 1 : undefined,startLine: outputStartLine, // 1-indexed for the agent// wrapperLines is an array but one element (the original-content slot)// is a `\n`-joined multi-line string, so the actual file-row count is@@ -374,10 +396,10 @@ The agent should insert variant HTML at insertLine.`);endLine: outputEndLine, // 1-indexedinsertLine, // 1-indexed: where variants gocommentSyntax: commentSyntax,- styleMode: useSvelteComponent ? 'svelte-component' : styleMode.mode,- styleTag: useSvelteComponent ? null : styleMode.styleTag,- cssSelectorPrefixExamples: useSvelteComponent ? [] : buildCssSelectorPrefixExamples(styleMode.mode, count),- cssAuthoring: useSvelteComponent ? svelteComponentAuthoring : buildCssAuthoring(styleMode, count),+ styleMode: componentPreviewMode || styleMode.mode,+ styleTag: useFrameworkComponent ? null : styleMode.styleTag,+ cssSelectorPrefixExamples: useFrameworkComponent ? [] : buildCssSelectorPrefixExamples(styleMode.mode, count),+ cssAuthoring: svelteComponentAuthoring || buildCssAuthoring(styleMode, count),originalLineCount: originalLines.length,}));}diff --git a/.cursor/skills/impeccable/scripts/live.mjs b/.cursor/skills/impeccable/scripts/live.mjsindex e0bd1ad24..b21a71cc4 100644--- a/.cursor/skills/impeccable/scripts/live.mjs+++ b/.cursor/skills/impeccable/scripts/live.mjs@@ -10,7 +10,7 @@** After this, the agent's only remaining steps are:* - Open the project's live dev/preview URL in the browser (optional, if browser automation exists)—not `serverPort`; that port is the Impeccable helper for /live.js and /poll- * - Enter the poll loop: `node live-poll.mjs`+ * - Enter the harness-native poll loop: `node live-poll.mjs`** Usage:* node live.mjs # Prepare everything, print JSON, exit@@ -40,6 +40,7 @@ Prepare everything for live variant mode in a single command:- Starts (or reuses) the live server in the background- Injects the browser script tag- Reads PRODUCT.md / DESIGN.md for project context+ - Prepares the harness-native foreground/background poll loop- In monorepos, choose a child app first; --target <path> is the fallback/manual pathOn success, prints a JSON blob with:diff --git a/.cursor/skills/impeccable/scripts/live/completion.mjs b/.cursor/skills/impeccable/scripts/live/completion.mjsindex 986773066..6f539336d 100644--- a/.cursor/skills/impeccable/scripts/live/completion.mjs+++ b/.cursor/skills/impeccable/scripts/live/completion.mjs@@ -1,9 +1,18 @@+// A preview whose variants live in component modules rather than in the user's+// source. These leave no markers in the real file, so a failed accept gives the+// agent nothing to hand-edit and must be reported as a failure rather than+// reference/live.md's manual-cleanup handoff. Kept as a set: any future+// component-module preview mode belongs here the day it lands.+const PREVIEW_MODES_WITHOUT_SOURCE_MARKERS = new Set([+ 'svelte-component',+]);+export function completionTypeForAcceptResult(eventType, acceptResult) {if (eventType === 'discard') return acceptResult?.handled === true ? 'discarded' : 'error';if (acceptResult?.handled === true && acceptResult?.carbonize === true) return 'agent_done';if (acceptResult?.handled === true) return 'complete';if (acceptResult?.mode === 'error') return 'error';- if (eventType === 'accept' && acceptResult?.previewMode === 'svelte-component') return 'error';+ if (eventType === 'accept' && PREVIEW_MODES_WITHOUT_SOURCE_MARKERS.has(acceptResult?.previewMode)) return 'error';return 'agent_done';}diff --git a/.cursor/skills/impeccable/scripts/live/event-validation.mjs b/.cursor/skills/impeccable/scripts/live/event-validation.mjsindex 0897b1317..122c29836 100644--- a/.cursor/skills/impeccable/scripts/live/event-validation.mjs+++ b/.cursor/skills/impeccable/scripts/live/event-validation.mjs@@ -118,6 +118,15 @@ export function validateEvent(msg) {return 'checkpoint: paramValues must be an object';}return null;+ case 'agent_phase':+ if (!isValidId(msg.id)) return 'agent_phase: missing or malformed id';+ if (typeof msg.phase !== 'string' || !/^[a-z][a-z0-9_]{1,63}$/.test(msg.phase)) {+ return 'agent_phase: missing or malformed phase';+ }+ if (msg.durationMs !== undefined && (!Number.isFinite(msg.durationMs) || msg.durationMs < 0)) {+ return 'agent_phase: durationMs must be a non-negative number';+ }+ return null;case 'exit':return null;case 'prefetch':@@ -131,6 +140,12 @@ export function validateEvent(msg) {if (msg.message.length > 4000) return 'steer: message too long';if (msg.pageUrl !== undefined && typeof msg.pageUrl !== 'string') return 'steer: pageUrl must be string';return null;+ case 'carbonize_cleanup':+ if (!isValidId(msg.id)) return 'carbonize_cleanup: missing or malformed id';+ if (!isValidId(msg.sessionId)) return 'carbonize_cleanup: missing or malformed sessionId';+ if (!msg.file || typeof msg.file !== 'string') return 'carbonize_cleanup: missing file';+ if (!isValidVariantId(String(msg.variantId))) return 'carbonize_cleanup: missing or malformed variantId';+ return null;default:return 'Unknown event type: ' + msg.type;}diff --git a/.cursor/skills/impeccable/scripts/live/generation-preflight.mjs b/.cursor/skills/impeccable/scripts/live/generation-preflight.mjsnew file mode 100644index 000000000..07a5e957e--- /dev/null+++ b/.cursor/skills/impeccable/scripts/live/generation-preflight.mjs@@ -0,0 +1,102 @@+import { execFile } from 'node:child_process';+import path from 'node:path';+import { promisify } from 'node:util';++const execFileAsync = promisify(execFile);+const PREFLIGHT_TIMEOUT_MS = 15_000;++export function buildGenerationPreflight(event, scriptsDir) {+ if (!event || event.type !== 'generate' || !event.id) return null;++ const isInsert = event.mode === 'insert';+ const target = isInsert ? insertTarget(event) : replaceTarget(event);+ if (!target.elementId && !target.classes) return null;++ const script = path.join(scriptsDir, isInsert ? 'live-insert.mjs' : 'live-wrap.mjs');+ const args = [script, '--id', event.id, '--count', String(event.count || 3)];+ if (isInsert) args.push('--position', target.position);+ if (target.elementId) args.push('--element-id', target.elementId);+ if (target.classes) args.push('--classes', target.classes);+ if (target.tag) args.push('--tag', target.tag);+ if (target.text) args.push('--text', target.text);+ if (!isInsert && event.pageUrl) args.push('--page-url', event.pageUrl);+ return { script, args, mode: isInsert ? 'insert' : 'replace' };+}++/**+ * Scaffold the source for a generate event before handing it to an agent.+ *+ * Async on purpose. This spawns `live-wrap.mjs`, which walks the project's+ * source tree and can take seconds (measured at ~7.6s on a large repo when the+ * element is not found, with a 15s ceiling). The live server is single-threaded+ * and calls this while leasing a poll, so a synchronous spawn froze the whole+ * server for that entire window: Accept and Discard POSTs, SSE progress+ * broadcasts, and every other poll stalled behind it.+ */+export async function runGenerationPreflight(event, {+ cwd = process.cwd(),+ scriptsDir,+ execFileImpl = execFileAsync,+ timeoutMs = PREFLIGHT_TIMEOUT_MS,+} = {}) {+ const command = buildGenerationPreflight(event, scriptsDir);+ if (!command) {+ return { ok: false, skipped: true, reason: 'insufficient_locator' };+ }++ const startedAt = performance.now();+ try {+ const { stdout } = await execFileImpl(process.execPath, command.args, {+ cwd,+ encoding: 'utf-8',+ timeout: timeoutMs,+ });+ const line = String(stdout).trim().split('\n').filter(Boolean).pop();+ if (!line) throw new Error('preflight returned no scaffold metadata');+ return {+ ok: true,+ mode: command.mode,+ durationMs: performance.now() - startedAt,+ scaffold: JSON.parse(line),+ };+ } catch (error) {+ return {+ ok: false,+ mode: command.mode,+ durationMs: performance.now() - startedAt,+ error: compactError(error),+ };+ }+}++function replaceTarget(event) {+ return normalizeTarget(event.element || {});+}++function insertTarget(event) {+ return {+ ...normalizeTarget(event.insert?.anchor || {}),+ position: event.insert?.position === 'before' ? 'before' : 'after',+ };+}++function normalizeTarget(target) {+ const classes = Array.isArray(target.classes)+ ? target.classes.join(' ')+ : String(target.classes || '').trim();+ const text = typeof target.textContent === 'string'+ ? target.textContent.trim().slice(0, 80)+ : '';+ return {+ elementId: target.id || target.elementId || undefined,+ classes: classes || undefined,+ tag: target.tagName || target.tag || undefined,+ text: text || undefined,+ };+}++function compactError(error) {+ const stderr = error?.stderr ? String(error.stderr).trim() : '';+ const message = stderr.split('\n').filter(Boolean).pop() || error?.message || 'preflight failed';+ return String(message).slice(0, 500);+}diff --git a/.cursor/skills/impeccable/scripts/live/poll-lanes.mjs b/.cursor/skills/impeccable/scripts/live/poll-lanes.mjsnew file mode 100644index 000000000..65f20a87a--- /dev/null+++ b/.cursor/skills/impeccable/scripts/live/poll-lanes.mjs@@ -0,0 +1,14 @@+export function eventPriority(event = {}) {+ if (event.type === 'accept' || event.type === 'discard' || event.type === 'exit') return 0;+ if (event.type === 'manual_edit_apply' || event.type === 'steer' || event.type === 'carbonize_cleanup') return 1;+ if (event.type === 'generate') return 2;+ return 3;+}++export function selectAvailablePendingEvent(entries, { now = Date.now(), types = null } = {}) {+ const allowed = types instanceof Set ? types : (Array.isArray(types) ? new Set(types) : null);+ return entries+ .filter((entry) => !(entry.leaseUntil && entry.leaseUntil > now))+ .filter((entry) => !allowed || allowed.has(entry.event?.type))+ .sort((a, b) => eventPriority(a.event) - eventPriority(b.event) || a.seq - b.seq)[0] || null;+}diff --git a/.cursor/skills/impeccable/scripts/live/session-store.mjs b/.cursor/skills/impeccable/scripts/live/session-store.mjsindex affba67c9..9d20341dd 100644--- a/.cursor/skills/impeccable/scripts/live/session-store.mjs+++ b/.cursor/skills/impeccable/scripts/live/session-store.mjs@@ -1,24 +1,26 @@import fs from 'node:fs';import path from 'node:path';-import { getLegacyLiveSessionsDir, getLiveSessionsDir } from '../lib/impeccable-paths.mjs';+import { getLegacyLiveSessionsDir, getLiveSessionsDir, safeSessionId } from '../lib/impeccable-paths.mjs';const COMPLETED_PHASES = new Set(['completed', 'discarded']);+export const GENERATION_FENCED_PHASES = new Set([+ 'accept_requested',+ 'discard_requested',+ 'carbonize_required',+ 'completed',+ 'discarded',+]);export function createLiveSessionStore({ cwd = process.cwd(), sessionId } = {}) {const rootDir = getLiveSessionsDir(cwd);const legacyRootDir = getLegacyLiveSessionsDir(cwd);fs.mkdirSync(rootDir, { recursive: true });- const snapshotCache = new Map();-- function loadCachedOrRebuild(id) {- const cached = snapshotCache.get(id);- if (cached) return cached;- const journalPath = getReadableJournalPath(id);- const rebuilt = rebuildSnapshotFromJournal(journalPath, id);- snapshotCache.set(id, rebuilt);- return rebuilt;- }+ // No snapshot cache on purpose: appendEvent and getSnapshot both rebuild from+ // the journal so sequence numbers and phase fences never come from a stale+ // in-memory copy when the publisher/complete helpers append from another+ // process. A cache written but never read would grow per session for the+ // lifetime of the server without ever saving a rebuild.function getReadableJournalPath(id) {const primary = getJournalPath(rootDir, id);if (fs.existsSync(primary)) return primary;@@ -38,7 +40,10 @@ export function createLiveSessionStore({ cwd = process.cwd(), sessionId } = {})if (!fs.existsSync(journalPath) && fs.existsSync(legacyJournalPath)) {fs.copyFileSync(legacyJournalPath, journalPath);}- const prior = loadCachedOrRebuild(normalized.id);+ // Publisher/complete helpers can append from a separate process while+ // the server is alive. Rebuild here so sequence numbers and phase+ // fences never come from a stale in-memory cache.+ const prior = rebuildSnapshotFromJournal(getReadableJournalPath(normalized.id), normalized.id);const seq = prior.nextSeq;const entry = {seq,@@ -49,7 +54,6 @@ export function createLiveSessionStore({ cwd = process.cwd(), sessionId } = {})};fs.appendFileSync(journalPath, JSON.stringify(entry) + '\n');const next = applyEvent(prior.snapshot, entry, prior.diagnostics);- snapshotCache.set(normalized.id, { snapshot: next, diagnostics: next.diagnostics || [], nextSeq: seq + 1 });writeSnapshot(snapshotPath, next);return next;},@@ -58,7 +62,6 @@ export function createLiveSessionStore({ cwd = process.cwd(), sessionId } = {})const journalPath = getReadableJournalPath(id);const snapshotPath = getSnapshotPath(rootDir, id);const rebuilt = rebuildSnapshotFromJournal(journalPath, id);- snapshotCache.set(id, rebuilt);writeSnapshot(snapshotPath, rebuilt.snapshot);if (!opts.includeCompleted && COMPLETED_PHASES.has(rebuilt.snapshot.phase)) return null;return rebuilt.snapshot;@@ -95,11 +98,6 @@ function getSnapshotPath(rootDir, id) {return path.join(rootDir, safeSessionId(id) + '.snapshot.json');}-function safeSessionId(id) {- if (!/^[A-Za-z0-9_-]{1,128}$/.test(id)) throw new Error('invalid session id: ' + id);- return id;-}-function baseSnapshot(id) {return {id,@@ -116,9 +114,18 @@ function baseSnapshot(id) {pendingEvent: null,deliveryLease: null,checkpointRevision: 0,+ browserCheckpointRevision: 0,+ publicationCheckpointRevision: 0,activeOwner: null,sourceMarkers: {},fallbackMode: null,+ generationPhase: null,+ generationCompletedAt: null,+ generationTimings: {},+ variantPlan: null,+ generationCanceled: false,+ generationCanceledAt: null,+ cancelReason: null,annotationArtifacts: [],diagnostics: [],updatedAt: null,@@ -158,6 +165,8 @@ function applyEvent(snapshot, entry, inheritedDiagnostics = []) {...snapshot,paramValues: { ...(snapshot.paramValues || {}) },sourceMarkers: { ...(snapshot.sourceMarkers || {}) },+ generationTimings: { ...(snapshot.generationTimings || {}) },+ variantPlan: snapshot.variantPlan || null,annotationArtifacts: [...(snapshot.annotationArtifacts || [])],diagnostics: [...(snapshot.diagnostics || [])],updatedAt: entry.ts || new Date().toISOString(),@@ -174,11 +183,48 @@ function applyEvent(snapshot, entry, inheritedDiagnostics = []) {next.expectedVariants = event.count ?? next.expectedVariants;next.pendingEventSeq = entry.seq ?? next.pendingEventSeq;next.pendingEvent = toPendingEvent(event);+ next.variantPlan = null;if (event.screenshotPath) upsertArtifact(next.annotationArtifacts, { type: 'screenshot', path: event.screenshotPath });break;+ case 'variant_plan':+ if (!next.generationCanceled && !GENERATION_FENCED_PHASES.has(next.phase)) {+ next.variantPlan = event.plan ?? next.variantPlan;+ }+ break;+ case 'detector_waivers':+ if (!next.generationCanceled && !GENERATION_FENCED_PHASES.has(next.phase)) {+ next.detectorWaivers = [+ ...(next.detectorWaivers || []),+ ...(Array.isArray(event.waivers) ? event.waivers : []),+ ];+ }+ break;+ case 'agent_phase':+ next.generationPhase = event.phase ?? next.generationPhase;+ if (event.phase) {+ next.generationTimings[event.phase] = {+ at: event.at ?? (Date.parse(entry.ts || '') || null),+ durationMs: event.durationMs ?? null,+ };+ }+ break;case 'variants_ready':case 'agent_done':+ if ((next.generationCanceled || GENERATION_FENCED_PHASES.has(next.phase))+ && !(event.type === 'agent_done' && event.carbonize === true && next.phase === 'accept_requested')) {+ next.diagnostics.push({+ error: 'late_generation_event_ignored',+ type: event.type,+ phase: next.phase,+ });+ break;+ }next.phase = event.carbonize === true ? 'carbonize_required' : 'variants_ready';+ // Durable completion marker: later browser checkpoints (a resumed page+ // reporting phase "generating") regress `phase`, but generation staying+ // finished is monotone — the live server keys missed-`done` redelivery+ // on this field.+ next.generationCompletedAt = event.at ?? (Date.parse(entry.ts || '') || Date.now());next.sourceFile = event.sourceFile ?? event.file ?? next.sourceFile;next.previewFile = event.previewFile ?? next.previewFile;next.previewMode = event.previewMode ?? next.previewMode;@@ -194,27 +240,45 @@ function applyEvent(snapshot, entry, inheritedDiagnostics = []) {}break;case 'checkpoint':- if (COMPLETED_PHASES.has(next.phase)) {+ if (next.generationCanceled || GENERATION_FENCED_PHASES.has(next.phase)) {next.diagnostics.push({ error: 'checkpoint_after_terminal_ignored', phase: event.phase ?? null, revision: event.revision ?? null });break;}- if ((event.revision ?? 0) >= (next.checkpointRevision ?? 0)) {- next.phase = event.phase ?? next.phase;- next.checkpointRevision = event.revision ?? next.checkpointRevision;- next.activeOwner = event.owner ?? next.activeOwner;- next.arrivedVariants = event.arrivedVariants ?? next.arrivedVariants;- next.visibleVariant = event.visibleVariant ?? next.visibleVariant;- next.sourceFile = event.sourceFile ?? next.sourceFile;- next.previewFile = event.previewFile ?? next.previewFile;- next.previewMode = event.previewMode ?? next.previewMode;- if (event.paramValues) next.paramValues = { ...event.paramValues };- } else {- next.diagnostics.push({ error: 'stale_checkpoint_ignored', revision: event.revision });+ {+ const revisionDomain = event.revisionDomain === 'publication'+ || (event.reason === 'variants_progress' && !event.owner)+ ? 'publication'+ : 'browser';+ const revisionField = revisionDomain === 'publication'+ ? 'publicationCheckpointRevision'+ : 'browserCheckpointRevision';+ const currentRevision = next[revisionField]+ ?? (revisionDomain === 'browser' ? next.checkpointRevision : 0)+ ?? 0;+ if ((event.revision ?? 0) >= currentRevision) {+ next.phase = event.phase ?? next.phase;+ next[revisionField] = event.revision ?? currentRevision;+ if (revisionDomain === 'browser') {+ next.checkpointRevision = event.revision ?? next.checkpointRevision;+ next.activeOwner = event.owner ?? next.activeOwner;+ }+ next.arrivedVariants = event.arrivedVariants ?? next.arrivedVariants;+ if (revisionDomain === 'browser') next.visibleVariant = event.visibleVariant ?? next.visibleVariant;+ next.sourceFile = event.sourceFile ?? next.sourceFile;+ next.previewFile = event.previewFile ?? next.previewFile;+ next.previewMode = event.previewMode ?? next.previewMode;+ if (revisionDomain === 'browser' && event.paramValues) next.paramValues = { ...event.paramValues };+ } else {+ next.diagnostics.push({ error: 'stale_checkpoint_ignored', revision: event.revision, revisionDomain });+ }}break;case 'accept':case 'accept_intent':next.phase = 'accept_requested';+ next.generationCanceled = true;+ next.generationCanceledAt = event.at ?? (Date.parse(entry.ts || '') || Date.now());+ next.cancelReason = 'accept';next.visibleVariant = Number(event.variantId ?? next.visibleVariant);if (event.paramValues) next.paramValues = { ...event.paramValues };next.pendingEventSeq = entry.seq ?? next.pendingEventSeq;@@ -232,6 +296,12 @@ function applyEvent(snapshot, entry, inheritedDiagnostics = []) {next.pendingEventSeq = entry.seq ?? next.pendingEventSeq;next.pendingEvent = toPendingEvent(event);break;+ case 'carbonize_cleanup':+ next.phase = 'carbonize_cleanup_requested';+ next.sourceFile = event.file ?? next.sourceFile;+ next.pendingEventSeq = entry.seq ?? next.pendingEventSeq;+ next.pendingEvent = toPendingEvent(event);+ break;case 'steer_done':next.phase = 'steer_done';next.sourceFile = event.sourceFile ?? event.file ?? next.sourceFile;@@ -243,6 +313,9 @@ function applyEvent(snapshot, entry, inheritedDiagnostics = []) {break;case 'discard':next.phase = 'discard_requested';+ next.generationCanceled = true;+ next.generationCanceledAt = event.at ?? (Date.parse(entry.ts || '') || Date.now());+ next.cancelReason = 'discard';next.pendingEventSeq = entry.seq ?? next.pendingEventSeq;next.pendingEvent = toPendingEvent(event);break;@@ -260,6 +333,10 @@ function applyEvent(snapshot, entry, inheritedDiagnostics = []) {next.pendingEvent = null;break;case 'agent_error':+ if (next.generationCanceled && event.sourceEventType === 'generate') {+ next.diagnostics.push({ error: 'late_generation_event_ignored', type: event.type, phase: next.phase });+ break;+ }next.phase = 'agent_error';next.pendingEventSeq = null;next.pendingEvent = null;diff --git a/.cursor/skills/impeccable/scripts/live/source-lock.mjs b/.cursor/skills/impeccable/scripts/live/source-lock.mjsnew file mode 100644index 000000000..9ccc557be--- /dev/null+++ b/.cursor/skills/impeccable/scripts/live/source-lock.mjs@@ -0,0 +1,105 @@+import fs from 'node:fs';+import path from 'node:path';+import { createHash, randomUUID } from 'node:crypto';+import { getLiveDir, isLiveServerPidReachable } from '../lib/impeccable-paths.mjs';++// Only used to retire a lock whose contents we cannot read (empty or truncated+// by a crash mid-write). A readable lock's fate is decided by its owner's+// liveness instead, so a slow critical section is never swept.+const UNREADABLE_LOCK_STALE_MS = 60_000;++export function sourceLockPath(file, cwd = process.cwd()) {+ const digest = createHash('sha256').update(path.resolve(cwd, file)).digest('hex').slice(0, 24);+ return path.join(getLiveDir(cwd), 'locks', digest + '.lock');+}++export function withSourceLockSync(file, owner, fn, {+ cwd = process.cwd(),+ waitMs = 0,+ retryMs = 5,+} = {}) {+ const lockPath = sourceLockPath(file, cwd);+ fs.mkdirSync(path.dirname(lockPath), { recursive: true });+ const deadline = Date.now() + Math.max(0, Number(waitMs) || 0);+ // Identifies this acquisition specifically, so release can tell our own lock+ // from a replacement that some other writer created.+ const token = randomUUID();+ let acquired = false;++ while (!acquired) {+ clearStaleLock(lockPath);+ let fd;+ try {+ fd = fs.openSync(lockPath, 'wx');+ fs.writeFileSync(fd, JSON.stringify({+ owner,+ token,+ pid: process.pid,+ at: Date.now(),+ file: path.resolve(cwd, file),+ }) + '\n');+ acquired = true;+ } catch (error) {+ if (error?.code !== 'EEXIST') throw error;+ if (Date.now() >= deadline) {+ const locked = new Error('source_locked');+ locked.code = 'SOURCE_LOCKED';+ locked.lockPath = lockPath;+ throw locked;+ }+ sleepSync(Math.max(1, Math.min(Number(retryMs) || 5, deadline - Date.now())));+ } finally {+ try { if (fd !== undefined) fs.closeSync(fd); } catch {}+ }+ }++ try {+ return fn();+ } finally {+ releaseOwnLock(lockPath, token);+ }+}++function sleepSync(ms) {+ Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, ms);+}++function readLock(lockPath) {+ try { return JSON.parse(fs.readFileSync(lockPath, 'utf-8')); } catch { return null; }+}++/**+ * Remove the lock only if it is still the one this call created. If a sweeper+ * judged our lock stale and another writer replaced it, unlinking here would+ * end *their* critical section and admit a third writer to the same file.+ */+function releaseOwnLock(lockPath, token) {+ const held = readLock(lockPath);+ if (held && held.token !== token) return;+ try { fs.unlinkSync(lockPath); } catch {}+}++/**+ * A lock is stale when its owner is gone, not when it is old.+ *+ * Age alone cuts both ways: it sweeps a live holder whose critical section+ * outran the timeout (a suspended laptop, a stopped process), letting two+ * writers into the same source file, while still making every accept on a+ * crashed holder's file wait out the full timeout. Asking the OS whether the+ * recorded pid is alive answers both correctly: a dead owner releases at once,+ * and a live owner keeps its lock however long it needs.+ */+function clearStaleLock(lockPath) {+ const held = readLock(lockPath);+ if (!held) {+ // Unreadable: either a crash truncated it, or we caught the brief window+ // between create and write in a live acquisition. mtime distinguishes them.+ try {+ const stat = fs.statSync(lockPath);+ if (Date.now() - stat.mtimeMs > UNREADABLE_LOCK_STALE_MS) fs.unlinkSync(lockPath);+ } catch { /* gone already */ }+ return;+ }+ if (typeof held.pid === 'number' && isLiveServerPidReachable(held.pid)) return;+ try { fs.unlinkSync(lockPath); } catch {}+}diff --git a/.gemini/skills/impeccable/reference/live.md b/.gemini/skills/impeccable/reference/live.mdindex c405f2833..983cbd960 100644--- a/.gemini/skills/impeccable/reference/live.md+++ b/.gemini/skills/impeccable/reference/live.md@@ -10,21 +10,24 @@ Execute in order. No step skipped, no step reordered.1. `live.mjs`: boot. If the request names or implies a file, route, or app inside a monorepo, infer the concrete path and run `node .gemini/skills/impeccable/scripts/live.mjs --target <path>` instead; then run the rest of this live session from the returned `projectRoot`.2. Open the app URL that serves `pageFile` (infer from `package.json`, docs, terminal output, or an open tab). Never use `serverPort`; it's the helper, not the app. **Cursor:** `browser_navigate` to that URL before polling; do not skip. **Other harnesses:** use the available browser tool; if the URL is uncertain, ask the user once.-3. Poll loop with the default long timeout (600000 ms). After every event or `--reply`, run `live-poll.mjs` again immediately. Never pass a short `--timeout=`.+3. Poll loop with the default long timeout (600000 ms). Run `live-poll.mjs` again immediately after every event or `--reply`; Codex runs this one-shot poll in the foreground. Never pass a short `--timeout=`.The global bar **Impeccable mark** dims and shows a pulsing amber dot when no agent is long-polling `/poll`. Hover the mark for the hint; restart `live-poll.mjs` to reconnect.-4. On `generate`: read screenshot if present; load the action's reference; plan three distinct directions; write all variants in one edit; `--reply done`; poll again.+4. On `generate`: reuse `event.scaffold` when present; read the screenshot if present; load the action's reference; deliver variants using the delivery policy below; `--reply done`; poll again. Generate in this thread. You already hold the project's tokens, conventions, and file layout; that context is the job, not overhead.5. On `steer`: read the message and `pageUrl`; do the work (page edits, navigation help, or a short reply in the `--reply` message); `--reply steer_done`; poll again. No pickup ack. The Steer bar unlocks when `steer_done` arrives over SSE.-6. On `accept` / `discard`: the poll script runs `live-accept.mjs`, acknowledges the delivered event, and prints `_completionAck`. Plain accepts/discards are terminal immediately; carbonize accepts remain recoverable until you finish cleanup, run `live-complete.mjs --id EVENT_ID`, and only then poll again.+6. On `accept` / `discard`: the poll script runs `live-accept.mjs`, acknowledges the delivered event, and prints `_completionAck`. Plain accepts/discards are terminal immediately. Carbonize accepts remain recoverable until the foreground task runs `live-complete.mjs --id EVENT_ID`; finish that cleanup before polling again.7. If interrupted, run `live-status.mjs` or `live-resume.mjs` before guessing. The durable journal replays unacknowledged work after helper restart.8. On `exit`: run the cleanup at the bottom.Harness policy:-- **Claude Code**: run the poll as a **background task** (no short timeout). The harness notifies you when it completes, so the main conversation stays free. Do not block the shell.+- **Claude Code**: run the poll as a **background task** (no short timeout). The harness notifies you when it completes, so the main conversation stays free while you generate and publish in it. Do not block the shell.- **Cursor**: run **one-shot** poll in a **background terminal** with notify on `"type":"(steer|generate|accept|discard|exit)"`. After each event the poll exits; handle it, `--reply`, then start `live-poll.mjs` again. Do **not** use `--stream` on Cursor: incremental stdout notify is slower in practice than exit-based notify (~5s vs sub-second in testing).-- **Codex**: run the poll in the **foreground** (blocking shell; not a background task, not a subagent). Codex background exec sessions do not reliably surface poll stdout back into the conversation at the moment events arrive, so a "fire-and-forget" background poll will stall live mode.+- **Codex**: run the default one-shot poll in a **yielded foreground exec session**. Do not suffix it with `&`, use `--stream`, or leave Live without an active foreground poll. Handle every event in the main task; after each handler/reply, restart the foreground poll.- **Other harnesses**: one-shot foreground unless you know stdout reliably returns to this session when a shell exits.+Generation delivery policy:+- **Default (Cursor and other harnesses):** keep the established atomic single-edit delivery. Do not switch a harness to progressive until its poll loop is known not to block on the extra publish calls. This avoids trading model latency for extra tool-call latency on harnesses with different streaming behavior.+Chat is overhead. No recap, no tutorial output, no pasting PRODUCT / DESIGN bodies. Spend tokens on tools and edits; on failure, one or two short sentences.## Start@@ -92,14 +95,14 @@ Server restart rule: start `live-server.mjs` again, then poll. Startup requeues**Insert mode** (`event.mode === "insert"`): `{id, mode: "insert", count, pageUrl, insert: { position, anchor }, placeholder: { width, height }, freeformPrompt?, screenshotPath?, comments?, strokes?}`. No `action`. Requires a non-empty `freeformPrompt` **or** annotations. Screenshot is sent only when annotations exist (same rule as replace). Use `placeholder` dimensions as a soft size hint for net-new content.-Speed matters; the user is watching a spinner. Minimize tool calls by using the wrap/insert helper and writing all variants in a single edit.+Speed matters; the user is watching the selected element. Reuse server preflight metadata when available, minimize discovery calls, and follow the harness-specific delivery policy above.### Insert mode branchWhen `event.mode === "insert"`:1. Read the screenshot if `event.screenshotPath` is present (annotations only).-2. Run the insert helper instead of wrap:+2. If `event.scaffold` is present, use it as the insert-helper result and do **not** run the helper again. Otherwise run the insert helper instead of wrap:```bashnode .gemini/skills/impeccable/scripts/live-insert.mjs --id EVENT_ID --count EVENT_COUNT --position after \@@ -109,7 +112,7 @@ node .gemini/skills/impeccable/scripts/live-insert.mjs --id EVENT_ID --count EVE- `--position` ← `event.insert.position` (`before` | `after`)- Anchor flags ← `event.insert.anchor` (same mapping as wrap: id, classes, tag, text)-The scaffold has **no** `data-impeccable-variant="original"`. Variants are net-new HTML+CSS inserted at `insertLine`. Load `brand.md` or `product.md` (freeform only, no action sub-command). Write all variants in one edit, then `--reply done`.+The scaffold has **no** `data-impeccable-variant="original"`. Variants are net-new HTML+CSS inserted at `insertLine`. Load `brand.md` or `product.md` (freeform only, no action sub-command). Deliver using the harness policy, then `--reply done`.For Svelte/SvelteKit targets, `live-insert.mjs` returns `previewMode: "svelte-component"` with `mode: "insert"`, `file` pointing at a temporary `node_modules/.impeccable-live/<id>/manifest.json`, `componentDir` pointing at the variant component files, and `sourceFile` pointing at the real `.svelte` route. Write each inserted variant as a real Svelte component (`v1.svelte`, `v2.svelte`, …) under `componentDir`. Insert variants must be non-empty net-new content with a single top-level root, no `data-impeccable-*` attributes, and CSS in each component's `<style>` block. Do **not** edit the route source during generation; the browser mounts the temporary component before/after the live anchor while the user cycles variants. On Accept, `live-accept.mjs` inserts the selected component markup into `sourceFile` immediately and deletes the temp session after the source write succeeds.@@ -134,6 +137,8 @@ Reading annotations precisely:### 2. Wrap the element+When `event.scaffold` is present, the local helper already found and wrapped the source before the poll returned. Treat `event.scaffold` as the successful helper output and skip this command entirely. `event.scaffoldAttempted` with `scaffoldError` means local preflight could not finish; use the command/fallback path below. This optimization removes a deterministic tool round trip without changing the generated design.+```bashnode .gemini/skills/impeccable/scripts/live-wrap.mjs --id EVENT_ID --count EVENT_COUNT --element-id "ELEMENT_ID" --classes "class1,class2" --tag "div" --text "TEXT_SNIPPET"```@@ -153,7 +158,7 @@ Output on success: `{ file, insertLine, commentSyntax, styleMode, styleTag, cssSFor Svelte/SvelteKit targets, `live-wrap.mjs` returns `previewMode: "svelte-component"` with `file` pointing at a temporary `node_modules/.impeccable-live/<id>/manifest.json`, `componentDir` pointing at the variant component files, and `sourceFile` pointing at the real `.svelte` route. Write each variant as a real Svelte component (`v1.svelte`, `v2.svelte`, …) under `componentDir`; use the `propContract` prop names for dynamic text (`{propName}`), not literal snapshot strings. Put variant CSS in each component's `<style>` block with semantic class selectors (no `@scope`, no `data-impeccable-*`). Reply with `--file` set to the manifest path; the browser dynamically imports and mounts the compiled components so Svelte HMR does not reset page state while the user cycles variants. On Accept, `live-accept.mjs` inlines the accepted component back into `sourceFile` immediately after source promotion succeeds.-**Params on the Svelte component path go in a sidecar, never as an attribute.** Svelte parses `{` inside an attribute value as the start of an expression, so a `data-impeccable-params='[{…}]'` attribute on a component element fails to compile (`Expected token }`). Declare params for this path in `componentDir/params.json`, keyed by variant number, using the exact param schema from section 7:+**Params on component-preview paths go in a sidecar, never as an attribute.** Svelte parses `{` inside an attribute value as the start of an expression, and both Svelte/Vue previews mount without an HTML variant wrapper. Declare params in `componentDir/params.json`, keyed by variant number, using the exact param schema from section 7:```json{@@ -291,11 +296,13 @@ In **departure mode**, the prompt narrows the lanes you draw from, not the familWhen the prompt and PRODUCT.md anti-references conflict (the prompt asks for X, the anti-references ban X), the anti-references win; they describe the brand's standing position, the prompt is one moment.-### 6. Write all variants in a single edit+### 6. Deliver variantsComplete HTML replacement of the original element for each variant, not a CSS-only patch. Consider the element's context (computed styles, parent structure, CSS variables from `event.element`).-Write CSS + all variants in ONE edit at the `insertLine` reported by `wrap`. Colocate CSS as a `<style>` tag inside the variant wrapper; `<style>` works anywhere in modern browsers and this ensures CSS and HTML arrive atomically (no FOUC).+Colocate preview CSS as a `<style>` tag inside the variant wrapper; `<style>` works anywhere in modern browsers and keeps each delivered state internally complete (no FOUC).++**Atomic default:** write CSS + all variants + parameter manifests in one edit at `insertLine`, preserving the established behavior.Use the `cssAuthoring` object returned by `live-wrap.mjs` to author the temporary preview CSS. The style opening tag shown below is the common case; replace it with `cssAuthoring.styleTag` when the tool returns a different one. The variant markup shape is otherwise stable:@@ -319,7 +326,7 @@ Use the `cssAuthoring` object returned by `live-wrap.mjs` to author the temporarThe first variant has no `display: none` (visible by default). All others do. If variants use only inline styles and no preview CSS, omit the `<style>` tag entirely.-One edit, all variants; the browser's MutationObserver picks everything up in one pass.+The browser's MutationObserver accepts either delivery shape. On the transactional progressive path it shows arrived variants and pending dots immediately; Accept and Discard are available as soon as one variant exists. Accepting an arrived variant fences the worker before the browser releases the picker, so later publications are rejected.For `styleMode: "scoped"`, author every `:scope` rule with a descendant combinator. The `@scope` boundary is the **variant wrapper `<div data-impeccable-variant="N">`**, not the element you're designing. A bare `:scope { background: cream; }` styles the wrapper, not the inner replacement, so the cream lands on a `display: contents` shell while the actual element keeps page defaults. Always step in: `:scope > .card`, `:scope > section`, `:scope .hero-title`, etc. The fake test agent's CSS in `tests/live-e2e/agent.mjs` is a faithful template; every scoped rule starts `:scope > ...`.@@ -361,7 +368,7 @@ Each variant can expose **coarse** knobs alongside the full HTML/CSS replacement**Hard cap per variant**: at most **four** parameters so the panel stays legible; rare fifth only if the reference explicitly allows it.-**How to declare.** Put a JSON manifest on the variant wrapper (HTML/JSX path). **On the Svelte `svelte-component` path, do not use this attribute** (Svelte can't compile `{` inside an attribute value). Declare params in `componentDir/params.json` keyed by variant number instead (see the Svelte component paragraph in the wrap section). The param schema below is identical for both paths.+**How to declare.** Put a JSON manifest on the variant wrapper (HTML/JSX path). **On the `svelte-component` path, do not use this attribute.** Declare params in `componentDir/params.json` keyed by variant number instead (see the component-preview paragraphs in the wrap section). The param schema below is identical for every path.```html<div data-impeccable-variant="1" data-impeccable-params='[@@ -462,15 +469,19 @@ Event: `{id, variantId, _acceptResult, _completionAck}`. The poll script already- The accept event includes `pageUrl`; the poll script must forward it to `live-accept.mjs --page-url PAGE_URL` so accept-time cleanup only scrubs staged copy edits for the current page.- `_completionAck.ok !== true`: do not poll yet. Run `live-status.mjs` / `live-resume.mjs`, complete the cleanup manually if needed, then run `live-complete.mjs --id EVENT_ID`.- `_acceptResult.handled: true` and `carbonize: false`: nothing to do. Poll again.-- `_acceptResult.handled: true` and `carbonize: true`: **post-accept cleanup is required before the next poll.** See the "Required after accept (carbonize)" section below. The `event._acceptResult.todo` field, `_completionAck.requiresComplete`, and a stderr banner all point at this required follow-up; none are decorative. After cleanup, run `live-complete.mjs --id EVENT_ID`, then poll again.+- `_acceptResult.handled: true` and `carbonize: true`: post-accept cleanup is required, but it must not stall Codex's control lane. See "Required after accept (carbonize)" below. The `event._acceptResult.todo` field, `_completionAck.requiresComplete`, and stderr banner all point at this required follow-up; none are decorative.- `_acceptResult.handled: false, mode: "fallback"`: the session lived in a generated file and the script refused to persist there. You've already written the accepted variant into true source during Handle fallback Step 3; just clean up the temporary wrapper in the served file if any, and poll again.+- `_acceptResult.handled: false, mode: "error"`: the operation genuinely failed. **Do not hand-edit the file**; the source was not touched and editing it yourself would either double-apply or race whoever holds it.+ - `error: "source_locked"`: a generation publish holds the file. Run the same `live-accept.mjs` command again; it is idempotent and will succeed once the publisher releases. Do not poll past it.+ - `error: "accept_receipt_conflict"`: this session already resolved as `priorOperation` (on `priorVariantId` for an accept), so the request contradicts durable truth. Do not edit. Run `live-status.mjs` and tell the user what the session actually resolved to.+ - anything else: report the error briefly and run `live-status.mjs` before continuing.- `_acceptResult.handled: false` without `mode`: manual cleanup: read file, find markers, edit.### Required after accept (carbonize)When `_acceptResult.carbonize === true`, the accepted variant was stitched into source with helper markers and inline CSS so the browser can render it immediately with no visual gap. That stitch-in is **temporary**. The agent must rewrite it into permanent form before doing anything else. Skipping this leaves dead `@scope` rules for unaccepted variants, a pointless `data-impeccable-variant` wrapper, and `impeccable-carbonize-start/end` comment noise in the source file; all of which accumulate across sessions.-Do these five steps in the current thread, synchronously, before the next poll. Do not poll again until the file is clean.+Do these five steps synchronously before the next poll. The source lock, generation epoch, and expected-source hash remain the final safety gates against a generator finishing concurrently with Accept.1. **Locate the carbonize block** in the source file (`_acceptResult.file`). It's bracketed by `<!-- impeccable-carbonize-start SESSION_ID -->` and `<!-- impeccable-carbonize-end SESSION_ID -->` and contains a `<style data-impeccable-css="SESSION_ID">` element. If the variant declared parameters, an `<!-- impeccable-param-values SESSION_ID: {...} -->` comment sits alongside the style tag with the user's chosen values; read it first; it drives steps 3 and 4 below.2. **Move the CSS rules** into the project's real stylesheet. Which stylesheet depends on the project (e.g. `site/styles/workflow.css` for an Astro project, or the component's co-located CSS file for a Vite/Next project; pick whichever already owns styling for the surrounding element).@@ -478,9 +489,7 @@ Do these five steps in the current thread, synchronously, before the next poll.4. **Unwrap the accepted content.** Delete the inner `<div data-impeccable-variant="N" style="display: contents">` that wraps it. On JSX/TSX, also delete the outer `<div data-impeccable-carbonize="SESSION_ID" style={{ display: 'contents' }}>` wrapper if present (accept adds it so ternary/`return` slots keep a single root). Drop `data-impeccable-params` and any `data-p-*` attributes; those are live-mode plumbing, not source.5. **Delete the inline `<style>` block, the `<!-- impeccable-param-values -->` comment if present, and both `<!-- impeccable-carbonize-start/end -->` markers.** Also drop any `@scope` rules for variants other than the accepted one; those are dead code now.-After the file is clean, run `live-complete.mjs --id SESSION_ID`, verify it reports `phase: "completed"`, then poll again.--A background agent may be used for the rewrite, but the current thread is responsible for verifying the five steps are complete before issuing the next poll. In practice, inline is usually faster and less error-prone.+After the file is clean, the cleanup owner runs `live-complete.mjs --id SESSION_ID` and verifies `phase: "completed"`. Poll again only after that verification.## Handle `discard`diff --git a/.gemini/skills/impeccable/scripts/lib/impeccable-paths.mjs b/.gemini/skills/impeccable/scripts/lib/impeccable-paths.mjsindex 2ccbe7b74..99956c0f3 100644--- a/.gemini/skills/impeccable/scripts/lib/impeccable-paths.mjs+++ b/.gemini/skills/impeccable/scripts/lib/impeccable-paths.mjs@@ -104,6 +104,20 @@ export function removeLiveServerInfo(cwd = process.cwd(), options = {}) {}}+/**+ * Session IDs become path segments (journals, snapshots, accept receipts,+ * preview manifests, generated component dirs). They arrive from CLI `--id`+ * arguments and HTTP payloads, so anything containing a separator or `..` must+ * be rejected before it reaches path.join, which would happily escape+ * `.impeccable/live/`. Real IDs are 8 hex chars; the tests use short slugs.+ */+export function safeSessionId(id) {+ if (typeof id !== 'string' || !/^[A-Za-z0-9_-]{1,128}$/.test(id)) {+ throw new Error('invalid session id: ' + id);+ }+ return id;+}+export function getLiveSessionsDir(cwd = process.cwd(), options = {}) {return path.join(getLiveDir(cwd, options), 'sessions');}diff --git a/.gemini/skills/impeccable/scripts/live-accept.mjs b/.gemini/skills/impeccable/scripts/live-accept.mjsindex 278dfbb2e..453ddea35 100644--- a/.gemini/skills/impeccable/scripts/live-accept.mjs+++ b/.gemini/skills/impeccable/scripts/live-accept.mjs@@ -16,7 +16,9 @@import fs from 'node:fs';import path from 'node:path';import { isGeneratedFile } from './lib/is-generated.mjs';+import { IMPECCABLE_DIR, getLiveDir, safeSessionId } from './lib/impeccable-paths.mjs';import { readBuffer as readManualEditsBuffer, writeBuffer as writeManualEditsBuffer } from './live/manual-edits-buffer.mjs';+import { withSourceLockSync } from './live/source-lock.mjs';import {applyDeferredSvelteComponentAccepts,findSvelteComponentManifest,@@ -25,6 +27,46 @@ import {} from './live/svelte-component.mjs';const EXTENSIONS = ['.html', '.jsx', '.tsx', '.vue', '.svelte', '.astro'];+const ACCEPT_LOCK_WAIT_MS = 1_000;+// Mirrors VARIANT_ID_PATTERN in live/event-validation.mjs, which gates the same+// value arriving over HTTP.+const VARIANT_NUM_PATTERN = /^[0-9]{1,3}$/;++/**+ * A thrown accept/discard is a real failure, not a manual handoff.+ *+ * live/completion.mjs only classifies a result as `error` when it carries+ * `mode: 'error'`; anything else unhandled falls through to `agent_done` with a+ * successful ack, and reference/live.md then tells the agent to finish the edit+ * by hand. That is right for the documented fallback paths and wrong here: a+ * `source_locked` contention needs a retry (hand-editing races the publisher+ * holding the lock), and a crash needs surfacing, not a hand-applied guess.+ */+function operationFailure(err, extra = {}) {+ return { handled: false, mode: 'error', error: err.message, ...extra };+}++/**+ * Mark an unhandled preview-path result as a real failure.+ *+ * operationFailure only covers results built from a *thrown* error. The accept+ * implementations also return `{handled: false, error}` for their own checks+ * (variant missing, template empty, original text ambiguous), and those arrived+ * without `mode`, so completion.mjs classified them as agent_done and+ * reference/live.md routed the agent to "read file, find markers, edit".+ *+ * That handoff only makes sense for a plain wrapper session, which is the one+ * shape with markers in the user's source to edit. Component and isolated+ * artifact previews keep the source clean until Accept, so there is nothing to+ * hand-edit and an unhandled result is always a failure. `previewMode` is+ * exactly that discriminator: only the preview branches set it.+ */+function markPreviewFailure(result) {+ if (result?.handled === false && !result.mode && result.previewMode) {+ return { ...result, mode: 'error' };+ }+ return result;+}// ---------------------------------------------------------------------------// CLI@@ -63,7 +105,52 @@ Output (JSON):const isDiscard = args.includes('--discard');if (!id) { console.error('Missing --id'); process.exit(1); }+ // `id` becomes a path segment (accept receipts, preview manifests, generated+ // component dirs). Reject separators and traversal here so one check covers+ // every downstream sink.+ try { safeSessionId(id); } catch { console.error('Invalid --id'); process.exit(1); }if (!isDiscard && !variantNum) { console.error('Need --discard or --variant N'); process.exit(1); }+ // `variantNum` is interpolated into a RegExp and into the markup written back+ // to source. The browser and the /events schema both constrain it to digits;+ // enforce the same here, or `--variant '.*'` matches the `original` block+ // first and silently accepts the original while reporting success.+ if (!isDiscard && !VARIANT_NUM_PATTERN.test(variantNum)) {+ console.error('Invalid --variant');+ process.exit(1);+ }++ const requestedOperation = isDiscard ? 'discard' : 'accept';+ const priorReceipt = readAcceptReceipt(process.cwd(), id);+ if (priorReceipt) {+ const sameOperation = priorReceipt.operation === requestedOperation+ && (isDiscard || String(priorReceipt.variantId) === String(variantNum));+ console.log(JSON.stringify(sameOperation+ ? { ...priorReceipt.result, handled: true, alreadyApplied: true }+ : {+ // mode: 'error' is what marks this a real failure rather than a manual+ // handoff. Without it, live/completion.mjs classifies the reply as+ // agent_done and reference/live.md tells the agent to "read file, find+ // markers, edit" by hand — which would apply a second, conflicting+ // accept on top of the one the receipt already recorded.+ handled: false,+ mode: 'error',+ error: 'accept_receipt_conflict',+ priorOperation: priorReceipt.operation,+ priorVariantId: priorReceipt.variantId ?? null,+ }));+ return;+ }+ const emitResult = (rawResult) => {+ const result = markPreviewFailure(rawResult);+ if (result?.handled !== false) {+ writeAcceptReceipt(process.cwd(), id, {+ operation: requestedOperation,+ variantId: isDiscard ? null : String(variantNum),+ result,+ });+ }+ console.log(JSON.stringify(result));+ };let paramValues = null;if (paramValuesRaw) {@@ -82,39 +169,55 @@ Output (JSON):if (svelteComponentManifest) {if (isDiscard) {- removeSvelteComponentSession(id, process.cwd());- console.log(JSON.stringify({- handled: true,+ let result;+ try {+ result = withSourceLockSync(+ path.resolve(process.cwd(), svelteComponentManifest.sourceFile),+ 'discard:' + id,+ () => {+ removeSvelteComponentSession(id, process.cwd());+ return { handled: true };+ },+ { waitMs: ACCEPT_LOCK_WAIT_MS },+ );+ } catch (err) {+ result = operationFailure(err);+ }+ emitResult({+ ...result,file: svelteComponentManifest.sourceFile,carbonize: false,previewMode: 'svelte-component',componentDir: svelteComponentManifest.componentDir,- }));+ });return;}let result;try {- result = inlineSvelteComponentAccept(- svelteComponentManifest,- variantNum,- paramValues,- process.cwd(),+ result = withSourceLockSync(+ path.resolve(process.cwd(), svelteComponentManifest.sourceFile),+ 'accept:' + id,+ () => inlineSvelteComponentAccept(+ svelteComponentManifest,+ variantNum,+ paramValues,+ process.cwd(),+ ),+ { waitMs: ACCEPT_LOCK_WAIT_MS },);} catch (err) {- result = {- handled: false,- error: err.message,+ result = operationFailure(err, {file: svelteComponentManifest.sourceFile,sourceFile: svelteComponentManifest.sourceFile,previewMode: 'svelte-component',componentDir: svelteComponentManifest.componentDir,- };+ });}if (result.carbonize) {result.todo = 'REQUIRED before next poll: carbonize cleanup in ' + result.file + '. See reference/live.md "Required after accept".';}- console.log(JSON.stringify({ handled: result.handled !== false, ...result }));+ emitResult({ handled: result.handled !== false, ...result });return;}@@ -145,10 +248,25 @@ Output (JSON):}if (isDiscard) {- const result = handleDiscard(id, lines, targetFile);- console.log(JSON.stringify({ handled: true, file: relFile, carbonize: false, ...result }));+ let result;+ // handleDiscard takes the source lock, which throws SOURCE_LOCKED under+ // contention. Without this catch the CLI exits non-zero with empty stdout+ // and the agent gets no JSON to act on.+ try {+ result = handleDiscard(id, lines, targetFile);+ } catch (err) {+ emitResult(operationFailure(err, { file: relFile }));+ return;+ }+ emitResult({ handled: true, file: relFile, carbonize: false, ...result });} else {- const result = handleAccept(id, variantNum, lines, targetFile, paramValues);+ let result;+ try {+ result = handleAccept(id, variantNum, lines, targetFile, paramValues);+ } catch (err) {+ emitResult(operationFailure(err, { file: relFile }));+ return;+ }const acceptedOriginalText = result.acceptedOriginalText || '';delete result.acceptedOriginalText;// Single-line attention-grabber when cleanup is required. The full@@ -167,7 +285,7 @@ Output (JSON):// Non-fatal; the buffer stays as-is and the user can discard later.}}- console.log(JSON.stringify({ handled: true, file: relFile, ...result }));+ emitResult({ handled: true, file: relFile, ...result });}}@@ -235,7 +353,14 @@ function scrubManualEditsAgainstFile(_targetFile, cwd = process.cwd(), originalB// Discard// ----------------------------------------------------------------------------function handleDiscard(id, lines, targetFile) {+function handleDiscard(id, _lines, targetFile) {+ return withSourceLockSync(targetFile, 'discard:' + id, () => {+ const lines = fs.readFileSync(targetFile, 'utf-8').split('\n');+ return handleDiscardUnlocked(id, lines, targetFile);+ }, { waitMs: ACCEPT_LOCK_WAIT_MS });+}++function handleDiscardUnlocked(id, lines, targetFile) {const block = findMarkerBlock(id, lines);if (!block) return { handled: false, error: 'Markers not found' };@@ -330,7 +455,24 @@ function reindentContent(contentLines, fromIndent, toIndent) {});}-function handleAccept(id, variantNum, lines, targetFile, paramValues) {+function handleAccept(id, variantNum, _lines, targetFile, paramValues) {+ return withSourceLockSync(targetFile, 'accept:' + id, () => {+ const lines = fs.readFileSync(targetFile, 'utf-8').split('\n');+ return handleAcceptUnlocked(id, variantNum, lines, targetFile, paramValues);+ }, { waitMs: ACCEPT_LOCK_WAIT_MS });+}++function handleAcceptUnlocked(id, variantNum, lines, targetFile, paramValues) {+ const built = buildAcceptedWrappedSource(id, variantNum, lines, targetFile, paramValues);+ if (built.handled === false) return built;+ fs.writeFileSync(targetFile, built.content, 'utf-8');+ return {+ carbonize: built.carbonize,+ acceptedOriginalText: built.acceptedOriginalText,+ };+}++function buildAcceptedWrappedSource(id, variantNum, lines, targetFile, paramValues) {const block = findMarkerBlock(id, lines);if (!block) return { handled: false, error: 'Markers not found' };@@ -375,11 +517,14 @@ function handleAccept(id, variantNum, lines, targetFile, paramValues) {...replacement,...lines.slice(replaceRange.end + 1),];- fs.writeFileSync(targetFile, newLines.join('\n'), 'utf-8');-- return { carbonize: needsCarbonize, acceptedOriginalText: originalContent.join('\n') };+ return {+ content: newLines.join('\n'),+ carbonize: needsCarbonize,+ acceptedOriginalText: originalContent.join('\n'),+ };}+function readSourceShadowPreviewMeta(content, id) {const escaped = escapeRegExp(id);const wrapperRe = new RegExp('<[^>]+data-impeccable-variants=(["\'])' + escaped + '\\1[^>]*>');@@ -746,6 +891,21 @@ function detectCommentSyntax(filePath) {// File search (find the file containing session markers)// ---------------------------------------------------------------------------+/**+ * `.impeccable` is the critical entry, and it is not cosmetic.+ *+ * Progressive publication stages each revision as `.impeccable/live/artifacts/+ * <id>-r<n>.<source-ext>`, and those artifacts carry the very marker this search+ * looks for. The walk reaches `.` for any project whose source is not under one+ * of the privileged dirs above (this repo's own site lives in `site/pages/`), and+ * dot-directories sort before letters, so the artifact was found *before* the+ * real file. isGeneratedFile then declined the accept, and the agent fell back to+ * carbonizing several hundred lines of stylesheet by hand.+ *+ * Impeccable's own state directory is never project source. Never search it.+ */+const SEARCH_SKIP_DIRS = new Set(['node_modules', '.git', 'dist', 'build', IMPECCABLE_DIR]);+function findSessionFile(id, cwd) {const marker = 'impeccable-variants-start ' + id;const searchDirs = ['src', 'app', 'pages', 'components', 'public', 'views', 'templates', '.'];@@ -786,7 +946,7 @@ function searchDir(dir, query, seen, depth) {for (const entry of entries) {if (!entry.isDirectory()) continue;- if (['node_modules', '.git', 'dist', 'build'].includes(entry.name)) continue;+ if (SEARCH_SKIP_DIRS.has(entry.name)) continue;const result = searchDir(path.join(dir, entry.name), query, seen, depth + 1);if (result) return result;}@@ -798,6 +958,28 @@ function searchDir(dir, query, seen, depth) {// Utilities// ---------------------------------------------------------------------------+function acceptReceiptPath(cwd, id) {+ return path.join(getLiveDir(cwd), 'accept-receipts', `${safeSessionId(id)}.json`);+}++function readAcceptReceipt(cwd, id) {+ try { return JSON.parse(fs.readFileSync(acceptReceiptPath(cwd, id), 'utf-8')); } catch { return null; }+}++function writeAcceptReceipt(cwd, id, receipt) {+ const file = acceptReceiptPath(cwd, id);+ fs.mkdirSync(path.dirname(file), { recursive: true });+ const value = {+ id,+ ...receipt,+ completedAt: new Date().toISOString(),+ };+ const temporary = `${file}.${process.pid}.${Date.now()}.tmp`;+ fs.writeFileSync(temporary, JSON.stringify(value, null, 2) + '\n', 'utf-8');+ fs.renameSync(temporary, file);+ return value;+}+function argVal(args, flag) {const idx = args.indexOf(flag);return idx !== -1 && idx + 1 < args.length ? args[idx + 1] : null;diff --git a/.gemini/skills/impeccable/scripts/live-browser.js b/.gemini/skills/impeccable/scripts/live-browser.jsindex 616f1290a..20d875b93 100644--- a/.gemini/skills/impeccable/scripts/live-browser.js+++ b/.gemini/skills/impeccable/scripts/live-browser.js@@ -126,6 +126,9 @@let expectedVariants = 0;let arrivedVariants = 0;let visibleVariant = 0;+ let generationPhase = null;+ let parameterGenerationState = 'idle';+ let parameterReadyAnnouncedSession = null;let svelteComponentSession = null;let svelteRuntimePromise = null;let pendingSvelteComponentRetryObserver = null;@@ -134,6 +137,7 @@let currentPreviewMode = null;let recoveryWaitingForAnchor = false;let pickedAnchorSnapshot = null;+ let pickedAnchorViewportTop = null;let pendingVariantAnchorRetryObserver = null;let pendingAcceptedSession = null;let variantObserver = null;@@ -151,10 +155,12 @@// startScrollLock / stopScrollLock below.let scrollLockObserver = null;let scrollLockTargetY = null;+ let scrollLockAnchorTop = null;let scrollLockRaf = null;let scrollLockAbort = null;const SCROLL_ANCHOR_LOCK_ID = 'impeccable-scroll-anchor-lock';const VARIANT_STATE_STYLE_ID = 'impeccable-variant-state';+ const DISCARD_STATE_STYLE_ID = 'impeccable-discard-state';// Dedicated key for scroll position - SEPARATE from LS_KEY so that// saveSession's state updates don't clobber a carefully-captured scrollY.@@ -252,6 +258,13 @@barConnected: !!barEl?.isConnected,hasSvelteComponentSession: !!svelteComponentSession,mountedSvelteVariant: svelteComponentSession?.mountedVariant || 0,+ pickActive,+ pendingApplyInFlight,+ hoveredElement: hoveredElement ? {+ tag: hoveredElement.tagName,+ classes: hoveredElement.className,+ pickable: pickable(hoveredElement),+ } : null,pendingSvelteComponentRetry: !!pendingSvelteComponentRetryObserver,recoveryWaitingForAnchor,evtSourceReadyState: evtSource ? evtSource.readyState : null,@@ -1114,14 +1127,15 @@});}- function hideBar() {+ function hideBar(instant) {if (!barEl) return;const hideSeq = ++barHideSeq;stopVoice({ suppressSubmit: true });if (configureKind === 'insert') clearInsertPicking();barEl.style.opacity = '0';- barEl.style.transform = 'translateY(6px)';- setTimeout(() => { if (barEl && hideSeq === barHideSeq) barEl.style.display = 'none'; }, 250);+ barEl.style.transform = instant ? 'translateY(0)' : 'translateY(6px)';+ if (instant) barEl.style.display = 'none';+ else setTimeout(() => { if (barEl && hideSeq === barHideSeq) barEl.style.display = 'none'; }, 250);hideActionPicker();closeTunePopover();hideConfigureBarTooltip();@@ -1966,6 +1980,7 @@*/function setLiveState(next) {state = next;+ window.__IMPECCABLE_LIVE_STATE__ = next;syncPageInteractionCursor();}@@ -2516,18 +2531,27 @@fontSize: '11px', color: BP.textDim, whiteSpace: 'nowrap',marginLeft: 'auto',});- // Variants currently arrive atomically in a single file edit, so a- // per-variant counter would lie. Say what's true.status.textContent = recoveryWaitingForAnchor? 'Variants ready. Reveal the selected element to resume.'- : (arrivedVariants < expectedVariants- ? 'Generating ' + expectedVariants + ' variants...'- : 'Done');+ : generationStatusText();row.appendChild(status);return row;}+ function generationStatusText() {+ if (arrivedVariants >= expectedVariants && expectedVariants > 0) return 'Done';+ if (generationPhase === 'picked_up') return 'Agent picked up the request...';+ if (generationPhase === 'scaffolding') return 'Finding the source...';+ if (generationPhase === 'source_ready') return 'Source ready. Generating...';+ if (generationPhase === 'scaffold_fallback') return 'Agent is locating the source...';+ if (generationPhase === 'first_variant_generating') return 'Designing the first variant...';+ if (generationPhase === 'first_variant_validating') return 'Checking the first variant...';+ if (generationPhase === 'remaining_variants_generating') return 'Exploring two more directions...';+ if (generationPhase === 'remaining_variants_validating') return 'Checking the remaining variants...';+ return 'Generating ' + expectedVariants + ' variants...';+ }+// Cycling rowconst TUNE_ICON_SVG = '<svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" style="flex-shrink:0"><line x1="4" y1="8" x2="20" y2="8"/><circle cx="14" cy="8" r="2.4" fill="currentColor" stroke="none"/><line x1="4" y1="16" x2="20" y2="16"/><circle cx="10" cy="16" r="2.4" fill="currentColor" stroke="none"/></svg>';@@ -2557,7 +2581,7 @@color: BP.textDim, minWidth: '24px', textAlign: 'center',});counter.id = PREFIX + '-variant-counter';- counter.textContent = visibleVariant + '/' + arrivedVariants;+ counter.textContent = visibleVariant + '/' + expectedVariants;row.appendChild(counter);// Next@@ -2567,10 +2591,12 @@if (visibleVariant >= arrivedVariants) next.style.opacity = '0.3';row.appendChild(next);- // Tune chip - only when the visible variant exposes params+ // Tune chip stays visible while the deferred parameter phase is running,+ // then becomes interactive as soon as this variant exposes controls.const visParams = parseVariantParams(getVisibleVariantEl());const hasParams = visParams.length > 0;- if (hasParams) {+ const paramsPending = !hasParams && (parameterGenerationState === 'pending' || parameterGenerationState === 'loading');+ if (hasParams || paramsPending) {const tune = el('button', {display: 'inline-flex', alignItems: 'center', gap: '6px',padding: '4px 10px', borderRadius: '5px',@@ -2578,35 +2604,54 @@background: tuneOpen ? BP.accentSoft : 'transparent',color: tuneOpen ? BP.accent : BP.text,fontFamily: FONT, fontSize: '11px', fontWeight: '500',- cursor: 'pointer',+ cursor: paramsPending ? 'wait' : 'pointer',transition: 'color 0.12s ease, background 0.12s ease',whiteSpace: 'nowrap',});- tune.innerHTML = TUNE_ICON_SVG;+ if (paramsPending) {+ const spinner = el('span', {+ width: '11px', height: '11px', borderRadius: '50%',+ border: '1.5px solid ' + BP.hairline,+ borderTopColor: BP.accent,+ animation: 'impeccable-spin 0.6s linear infinite',+ boxSizing: 'border-box', flexShrink: '0',+ });+ spinner.setAttribute('aria-hidden', 'true');+ tune.appendChild(spinner);+ } else {+ tune.innerHTML = TUNE_ICON_SVG;+ }const tuneLabel = document.createElement('span');tuneLabel.textContent = 'Tune';tune.appendChild(tuneLabel);- const tuneBadge = document.createElement('span');- Object.assign(tuneBadge.style, {- display: 'inline-flex', alignItems: 'center', justifyContent: 'center',- minWidth: '16px', height: '16px', padding: '0 4px',- borderRadius: '999px',- background: tuneOpen ? C.brand : BP.hairline,- color: tuneOpen ? 'oklch(98% 0 0)' : 'inherit',- fontFamily: MONO, fontSize: '9.5px', fontWeight: '600',- lineHeight: '1',- boxSizing: 'border-box',- });- tuneBadge.textContent = String(visParams.length);- tune.appendChild(tuneBadge);- tune.title = 'Tune this variant (' + visParams.length + ' knob' + (visParams.length === 1 ? '' : 's') + ')';- tune.addEventListener('mouseenter', () => {- if (!tuneOpen) tune.style.background = BP.accentSoft;- });- tune.addEventListener('mouseleave', () => {- if (!tuneOpen) tune.style.background = 'transparent';- });- tune.addEventListener('click', (e) => { e.stopPropagation(); toggleTunePopover(); });+ if (hasParams) {+ const tuneBadge = document.createElement('span');+ Object.assign(tuneBadge.style, {+ display: 'inline-flex', alignItems: 'center', justifyContent: 'center',+ minWidth: '16px', height: '16px', padding: '0 4px',+ borderRadius: '999px',+ background: tuneOpen ? C.brand : BP.hairline,+ color: tuneOpen ? 'oklch(98% 0 0)' : 'inherit',+ fontFamily: MONO, fontSize: '9.5px', fontWeight: '600',+ lineHeight: '1',+ boxSizing: 'border-box',+ });+ tuneBadge.textContent = String(visParams.length);+ tune.appendChild(tuneBadge);+ tune.title = 'Tune this variant (' + visParams.length + ' knob' + (visParams.length === 1 ? '' : 's') + ')';+ tune.addEventListener('mouseenter', () => {+ if (!tuneOpen) tune.style.background = BP.accentSoft;+ });+ tune.addEventListener('mouseleave', () => {+ if (!tuneOpen) tune.style.background = 'transparent';+ });+ tune.addEventListener('click', (e) => { e.stopPropagation(); toggleTunePopover(); });+ } else {+ tune.disabled = true;+ tune.setAttribute('aria-label', 'Tune controls are still being prepared');+ tune.title = 'Tune controls are still being prepared';+ tune.style.opacity = '0.72';+ }tune.dataset.iceqTune = '1';row.appendChild(tune);}@@ -2614,6 +2659,15 @@// Spacerrow.appendChild(el('div', { flex: '1' }));+ if (arrivedVariants < expectedVariants) {+ const remaining = expectedVariants - arrivedVariants;+ const progress = el('span', {+ fontSize: '11px', color: BP.textDim, whiteSpace: 'nowrap',+ });+ progress.textContent = remaining + ' more arriving...';+ row.appendChild(progress);+ }+// Accept - primary action, kinpaku gold + lacquer-deep (matches demo .live-demo-ctx-accept)const accept = el('button', {padding: '5px 14px', borderRadius: '5px',@@ -2628,7 +2682,11 @@accept.addEventListener('mousedown', () => accept.style.transform = 'scale(0.97)');accept.addEventListener('mouseup', () => accept.style.transform = 'scale(1)');accept.addEventListener('click', (e) => { e.stopPropagation(); handleAccept(); });- if (arrivedVariants === 0) { accept.style.opacity = '0.3'; accept.style.pointerEvents = 'none'; }+ if (arrivedVariants === 0) {+ accept.style.opacity = '0.3';+ accept.style.pointerEvents = 'none';+ accept.title = 'Accept becomes available when the first variant arrives';+ }row.appendChild(accept);// Discard@@ -4743,6 +4801,32 @@}}+ function mountedParameterCount() {+ if (svelteComponentSession?.sessionId === currentSessionId) {+ return Object.values(svelteComponentSession.paramsByVariant || {})+ .reduce((total, params) => total + (Array.isArray(params) ? params.length : 0), 0);+ }+ const wrapper = document.querySelector('[data-impeccable-variants="' + currentSessionId + '"]');+ if (!wrapper) return 0;+ return [...wrapper.querySelectorAll('[data-impeccable-variant]:not([data-impeccable-variant="original"])')]+ .reduce((total, variant) => total + parseVariantParams(variant).length, 0);+ }++ function completeParameterPublication() {+ if (!currentSessionId) return;+ const ready = mountedParameterCount() > 0;+ parameterGenerationState = ready ? 'ready' : 'none';+ if (ready && parameterReadyAnnouncedSession !== currentSessionId) {+ parameterReadyAnnouncedSession = currentSessionId;+ showToast('Tune controls are ready.', 3000);+ }+ if (state === 'CYCLING') {+ refreshParamsPanel();+ showOrUpdateCyclingBar();+ }+ saveSession();+ }+function toggleTunePopover() {if (pendingApplyInFlight) { showManualApplyBusyToast(); return; }if (tuneOpen) { closeTunePopover(); return; }@@ -4835,6 +4919,10 @@return String(filePath || '').endsWith('manifest.json');}+ function isFrameworkComponentPreviewMode(mode) {+ return mode === 'svelte-component';+ }+function parseOriginalMarkupElement(originalMarkup) {const parser = new DOMParser();const doc = parser.parseFromString('<div id="impeccable-anchor">' + originalMarkup + '</div>', 'text/html');@@ -5029,9 +5117,13 @@}}- function loadSvelteRuntime(runtimeModule) {+ function resolveComponentModuleUrl(manifest, modulePath) {+ return new URL(String(modulePath || ''), location.origin).href;+ }++ function loadSvelteRuntime(runtimeModule, manifest) {const modulePath = runtimeModule || '/src/lib/impeccable/__runtime.js';- const url = new URL(modulePath, location.origin).href;+ const url = resolveComponentModuleUrl(manifest, modulePath);if (!svelteRuntimePromise) {svelteRuntimePromise = import(/* @vite-ignore */ url);}@@ -5065,7 +5157,8 @@async function loadSvelteComponentVariantSource(manifest, variantNum) {const dir = String(manifest?.componentDir || '').replace(/^\/+/, '');if (!dir || !variantNum) return '';- const sourcePath = dir + '/v' + variantNum + '.svelte';+ const extension = manifest.componentExtension || 'svelte';+ const sourcePath = dir + '/v' + variantNum + '.' + extension;const url = 'http://localhost:' + PORT + '/source?token=' + TOKEN + '&path=' + encodeURIComponent(sourcePath);try {const res = await fetch(url);@@ -5221,7 +5314,7 @@if (!sourceOriginal) return values;const map = buildSvelteExpressionTextMap(sourceOriginal, liveEl);for (const entry of contract) {- const token = '{' + entry.expr + '}';+ const token = entry.previewToken || ('{' + entry.expr + '}');values[entry.prop] = map.get(token) || '';}return values;@@ -5233,9 +5326,12 @@try {const previousAnchor = getMountedSvelteComponentAnchor(svelteComponentSession) || selectedElement;svelteComponentSession.swapAnchor = makeFrozenAnchor(previousAnchor) || svelteComponentSession.swapAnchor || null;- const runtime = await loadSvelteRuntime(manifest.runtimeModule);- const modulePath = '/' + String(manifest.componentDir || '').replace(/^\/+/, '') + '/v' + variantNum + '.svelte';- const moduleUrl = new URL(modulePath, location.origin).href + '?t=' + Date.now();+ const runtime = await loadSvelteRuntime(manifest.runtimeModule, manifest);+ const extension = manifest.componentExtension || 'svelte';+ const moduleBase = manifest.componentModuleBase+ || ('/' + String(manifest.componentDir || '').replace(/^\/+/, ''));+ const modulePath = String(moduleBase).replace(/\/+$/, '') + '/v' + variantNum + '.' + extension;+ const moduleUrl = resolveComponentModuleUrl(manifest, modulePath) + '?t=' + Date.now();const mod = await import(/* @vite-ignore */ moduleUrl);const Component = mod.default;if (svelteComponentSession.mountedInstance && runtime.unmount) {@@ -5275,7 +5371,7 @@if (svelteComponentSession?.sessionId === sessionId) {svelteComponentSession.swapAnchor = null;}- console.error('[impeccable] Failed to mount Svelte variant ' + variantNum + ' for ' + sessionId + ':', err);+ console.error('[impeccable] Failed to mount component variant ' + variantNum + ' for ' + sessionId + ':', err);return false;}}@@ -5340,40 +5436,46 @@if (manifest.id !== sessionId) return;const paramsByVariant = await loadSvelteComponentParams(manifest);+ const availableVariants = Number(manifest.arrivedVariants) || Number(manifest.count) || 1;+ const componentPreviewMode = isFrameworkComponentPreviewMode(manifest.previewMode)+ ? manifest.previewMode+ : 'svelte-component';currentSessionId = sessionId;expectedVariants = Number(manifest.count) || expectedVariants || 1;rememberSessionFileMeta({sourceFile: manifest.sourceFile,previewFile: manifestPath,- previewMode: 'svelte-component',+ previewMode: componentPreviewMode,});if (state !== 'CYCLING') setLiveState('GENERATING');const existingWrapper = document.querySelector('[data-impeccable-variants="' + sessionId + '"]');if (existingWrapper && svelteComponentSession?.sessionId === sessionId) {recoveryWaitingForAnchor = false;+ svelteComponentSession.manifest = manifest;svelteComponentSession.paramsByVariant = paramsByVariant;- arrivedVariants = Number(manifest.count) || expectedVariants || 1;- expectedVariants = arrivedVariants;+ arrivedVariants = availableVariants;+ expectedVariants = Number(manifest.count) || expectedVariants || arrivedVariants;visibleVariant = visibleVariant > 0 && visibleVariant <= arrivedVariants ? visibleVariant : 1;await mountSvelteComponentVariant(visibleVariant || 1);setLiveState('CYCLING');showOrUpdateCyclingBar();saveSession();+ if (parameterGenerationState === 'loading') completeParameterPublication();return;}const liveEl = findLiveElementForSvelteManifest(manifest);if (!liveEl?.parentElement) {console.warn('[impeccable] Could not find original element in live DOM.');- arrivedVariants = Number(manifest.count) || expectedVariants || 1;- expectedVariants = arrivedVariants;+ arrivedVariants = availableVariants;+ expectedVariants = Number(manifest.count) || expectedVariants || arrivedVariants;const saved = loadSession();const savedVisibleVariant = saved && saved.id === sessionId ? saved.visible : 0;visibleVariant = visibleVariant > 0 && visibleVariant <= arrivedVariants? visibleVariant: (savedVisibleVariant > 0 && savedVisibleVariant <= arrivedVariants ? savedVisibleVariant : 1);- enterRecoveryWaitingForAnchor({ checkpointReason: 'svelte_component_anchor_missing', trackScroll: true });+ enterRecoveryWaitingForAnchor({ checkpointReason: 'component_preview_anchor_missing', trackScroll: true });waitForSvelteComponentTargetAndRetry({ manifestPath, sessionId, manifest });return;}@@ -5381,7 +5483,7 @@const wrapper = document.createElement('div');wrapper.dataset.impeccableVariants = sessionId;wrapper.dataset.impeccableVariantCount = String(manifest.count || expectedVariants || 1);- wrapper.dataset.impeccablePreview = 'svelte-component';+ wrapper.dataset.impeccablePreview = componentPreviewMode;wrapper.style.display = 'contents';const mountTarget = document.createElement('div');@@ -5419,8 +5521,8 @@recoveryWaitingForAnchor = false;const previousVisibleVariant = currentSessionId === sessionId ? visibleVariant : 0;- arrivedVariants = Number(manifest.count) || expectedVariants || 1;- expectedVariants = arrivedVariants;+ arrivedVariants = availableVariants;+ expectedVariants = Number(manifest.count) || expectedVariants || arrivedVariants;const saved = loadSession();const savedVisibleVariant = saved && saved.id === sessionId ? saved.visible : 0;visibleVariant = previousVisibleVariant > 0 && previousVisibleVariant <= arrivedVariants@@ -5445,9 +5547,10 @@refreshParamsPanel();positionBar();saveSession();- console.log('[impeccable] Mounted ' + arrivedVariants + ' Svelte component variants.');+ if (parameterGenerationState === 'loading') completeParameterPublication();+ console.log('[impeccable] Mounted ' + arrivedVariants + ' ' + manifest.framework + ' component variants.');} catch (err) {- console.error('[impeccable] Failed to mount Svelte component variants:', err);+ console.error('[impeccable] Failed to mount component-preview variants:', err);abortSvelteComponentInjection(sessionId, 'Could not load variants. Fix the error and re-run.');}}@@ -5493,6 +5596,8 @@clearHandled();resetSessionFileMeta();currentSessionId = null;+ parameterGenerationState = 'idle';+ parameterReadyAnnouncedSession = null;expectedVariants = 0;arrivedVariants = 0;visibleVariant = 0;@@ -5502,12 +5607,24 @@if (message) showToast(message, 5000);}+ // How many delayed re-reads a completion-driven source fallback gets when+ // the fetched source still shows only the preflight scaffold, before the+ // failure is surfaced via recoverEmptyCycling.+ const COMPLETED_SOURCE_FALLBACK_RETRIES = 3;+ const COMPLETED_SOURCE_FALLBACK_RETRY_MS = 1200;+/*** No-HMR fallback: fetch the raw source file from the live server,* parse it, extract the variant wrapper, and inject it into the live DOM.* This works even when the dev server caches HTML (Bun, static servers).+ *+ * opts.generationCompleted marks callers that KNOW the agent finished (a+ * `done` arrived or the server reported a completed generation). For them an+ * empty read is a stale source view and no further event is coming, so the+ * read retries a few times and then surfaces recovery. Callers without the+ * flag may be mid-generation and wait indefinitely for the real completion.*/- function injectVariantsFromSource(filePath, sessionId) {+ function injectVariantsFromSource(filePath, sessionId, opts = {}) {if (isSvelteComponentManifestPath(filePath)) {injectSvelteComponentsFromManifest(filePath, sessionId);return;@@ -5573,6 +5690,32 @@arrivedVariants = variants.length;expectedVariants = parseInt(wrapper.dataset.impeccableVariantCount || arrivedVariants);if (arrivedVariants <= 0) {+ if (state === 'GENERATING') {+ // Mid-generation the source legitimately holds a scaffold wrapper+ // with no variants yet (the server-side preflight wraps before the+ // agent writes). Tearing the session down here would destroy an+ // in-flight generation; stay in GENERATING — the variant observer+ // is armed and the server re-delivers a missed `done`.+ if (!opts.generationCompleted) {+ console.log('[impeccable] Source has scaffold but no variants yet; still generating.');+ return;+ }+ // Generation finished, yet the read shows only the scaffold: the+ // source view is stale and no further event will fire. Re-read a+ // few times before surfacing recovery — a single silent return+ // here would strand the tab in GENERATING forever.+ const attempt = opts.attempt || 0;+ if (attempt < COMPLETED_SOURCE_FALLBACK_RETRIES) {+ console.log('[impeccable] Generation is done but source shows no variants yet; retrying read ('+ + (attempt + 1) + '/' + COMPLETED_SOURCE_FALLBACK_RETRIES + ').');+ setTimeout(() => {+ if (state !== 'GENERATING' || currentSessionId !== sessionId) return;+ if (arrivedVariants > 0) return;+ injectVariantsFromSource(filePath, sessionId, { ...opts, attempt: attempt + 1 });+ }, COMPLETED_SOURCE_FALLBACK_RETRY_MS);+ return;+ }+ }recoverEmptyCycling('source-fallback-empty');return;}@@ -5594,6 +5737,7 @@refreshParamsPanel();positionBar();saveSession();+ if (parameterGenerationState === 'loading') completeParameterPublication();console.log('[impeccable] Injected ' + arrivedVariants + ' variants from source file.');}).catch(err => {@@ -5865,13 +6009,36 @@document.getElementById(VARIANT_STATE_STYLE_ID)?.remove();}+ function showOriginalDuringDiscard(sessionId) {+ if (!sessionId) return;+ let styleEl = document.getElementById(DISCARD_STATE_STYLE_ID);+ if (!styleEl) {+ styleEl = document.createElement('style');+ styleEl.id = DISCARD_STATE_STYLE_ID;+ (document.head || document.documentElement).appendChild(styleEl);+ }+ const wrapper = '[data-impeccable-variants="' + sessionId + '"]';+ styleEl.textContent = wrapper + ' > [data-impeccable-variant]:not([data-impeccable-variant="original"]) { display:none !important; }\n'+ + wrapper + ' > [data-impeccable-variant="original"] { display:block !important; }';+ }++ function resolveScrollLockAnchorTop() {+ const anchor = resolveBarAnchor();+ if (!anchor?.isConnected) return null;+ const top = anchor.getBoundingClientRect().top;+ return Number.isFinite(top) ? top : null;+ }+// Hold window.scrollY at a fixed value across DOM mutations inside the// session's wrapper (HMR patches, variant inserts, cycle swaps).- function startScrollLock(sessionId, initialTargetY) {+ function startScrollLock(sessionId, initialTargetY, initialAnchorTop) {stopScrollLock();scrollLockTargetY = typeof initialTargetY === 'number' && isFinite(initialTargetY)? initialTargetY: window.scrollY;+ scrollLockAnchorTop = typeof initialAnchorTop === 'number' && isFinite(initialAnchorTop)+ ? initialAnchorTop+ : resolveScrollLockAnchorTop();try { history.scrollRestoration = 'manual'; } catch {}@@ -5895,6 +6062,17 @@const correct = (why) => {scrollLockRaf = null;if (scrollLockTargetY == null) return;+ const anchor = resolveBarAnchor();+ if (anchor?.isConnected && typeof scrollLockAnchorTop === 'number' && isFinite(scrollLockAnchorTop)) {+ const anchorTop = anchor.getBoundingClientRect().top;+ const anchorDelta = anchorTop - scrollLockAnchorTop;+ if (Math.abs(anchorDelta) >= 0.5) {+ window.scrollTo({ top: window.scrollY + anchorDelta, left: window.scrollX, behavior: 'instant' });+ scrollLockTargetY = window.scrollY;+ writeScrollY(scrollLockTargetY);+ return;+ }+ }const before = window.scrollY;const delta = before - scrollLockTargetY;if (Math.abs(delta) < 0.5) {@@ -5939,6 +6117,7 @@if (scrollLockRaf != null) { cancelAnimationFrame(scrollLockRaf); scrollLockRaf = null; }const prevTarget = scrollLockTargetY;scrollLockTargetY = window.scrollY;+ scrollLockAnchorTop = resolveScrollLockAnchorTop();writeScrollY(scrollLockTargetY);};const markGesture = (why) => {@@ -5976,6 +6155,7 @@if (scrollLockRaf != null) { cancelAnimationFrame(scrollLockRaf); scrollLockRaf = null; }if (scrollLockAbort) { scrollLockAbort.abort(); scrollLockAbort = null; }scrollLockTargetY = null;+ scrollLockAnchorTop = null;// NOTE: do NOT clear the persistent scroll key here. startScrollLock// calls us as a reset, and clearing the key would nuke the Go-time// scrollY that the next resume needs to read.@@ -6049,6 +6229,7 @@updating = true;arrivedVariants = count;+ generationPhase = arrivedVariants >= expectedVariants ? 'variants_ready' : 'variants_progress';if (visibleVariant === 0 && arrivedVariants > 0) {const saved = loadSession();const savedVisibleVariant = saved && saved.id === sessionId ? saved.visible : 0;@@ -6064,7 +6245,7 @@const expected = parseInt(wrapper.dataset.impeccableVariantCount || '0');if (expected > 0) expectedVariants = expected;- if (arrivedVariants >= expectedVariants && expectedVariants > 0) {+ if (arrivedVariants > 0) {setLiveState('CYCLING');recoveryWaitingForAnchor = false;hideShaderOverlay();@@ -6072,13 +6253,18 @@updateSelectedElement();showOrUpdateCyclingBar();disableInlineEdit();- refreshParamsPanel();+ if (arrivedVariants >= expectedVariants && expectedVariants > 0) refreshParamsPanel();+ else hideParamsPanel();positionBar();} else if (state === 'GENERATING') {updateBarContent('generating');}saveSession();- queueCheckpoint(state === 'CYCLING' ? 'variants_ready' : 'variants_progress');+ sendCheckpoint(+ arrivedVariants >= expectedVariants && expectedVariants > 0+ ? 'variants_ready'+ : 'variants_progress',+ );updating = false;});@@ -6151,6 +6337,7 @@syncAgentPollingUi(!!msg.agentPolling);startAgentStatusPoll();restoreFromActiveSessions(msg.activeSessions, 'sse_connected');+ recoverMissedGenerationCompletion(msg.activeSessions);if (state === 'IDLE' && (pickActive || insertActive)) setLiveState('PICKING');syncPageInteractionCursor();syncPageChatFocus('sse-connected');@@ -6158,6 +6345,42 @@case 'agent_polling':syncAgentPollingUi(!!msg.connected);break;+ case 'agent_phase':+ if (msg.id === currentSessionId && (state === 'GENERATING' || state === 'CYCLING')) {+ generationPhase = msg.phase || generationPhase;+ if (msg.phase === 'variant_parameters_generating' || msg.phase === 'variant_parameters_validating') {+ parameterGenerationState = 'loading';+ }+ if (msg.phase === 'parameters_ready' && parameterGenerationState !== 'ready') {+ parameterGenerationState = 'loading';+ }+ updateBarContent(state === 'CYCLING' ? 'cycling' : 'generating');+ saveSession();+ }+ break;+ case 'variant_progress':+ if (msg.id === currentSessionId) {+ if (msg.publicationKind === 'params') parameterGenerationState = 'loading';+ rememberSessionFileMeta(msg);+ if (isFrameworkComponentPreviewMode(msg.previewMode) && msg.previewFile) {+ injectSvelteComponentsFromManifest(msg.previewFile, msg.id);+ } else if ((msg.previewMode === 'source' || !msg.previewMode) && (msg.previewFile || msg.file)) {+ // Give normal framework HMR the first chance to reconcile its+ // own managed tree. Nuxt route-module HMR can skip intermediate+ // revisions, so fall back to source injection only when the+ // advertised progress still has not appeared after a short+ // settle. Immediate injection races React/Vue ownership and can+ // trigger removeChild errors on the next HMR commit.+ const targetArrived = Number(msg.arrivedVariants) || 1;+ setTimeout(() => {+ if (msg.id !== currentSessionId) return;+ if (state !== 'GENERATING' && state !== 'CYCLING') return;+ if (msg.publicationKind !== 'params' && arrivedVariants >= targetArrived) return;+ injectVariantsFromSource(msg.previewFile || msg.file, msg.id);+ }, 150);+ }+ }+ break;case 'steer_done':maybeCompleteSteer(msg);break;@@ -6175,6 +6398,10 @@case 'done':if (maybeCompleteSteer(msg)) break;rememberSessionFileMeta(msg);+ if (msg.id === currentSessionId && isFrameworkComponentPreviewMode(currentPreviewMode) && currentPreviewFile) {+ injectSvelteComponentsFromManifest(currentPreviewFile, msg.id);+ break;+ }// Variants already arrived via HMR → normal transition.if (arrivedVariants >= expectedVariants && expectedVariants > 0) {if (state === 'GENERATING') {@@ -6190,7 +6417,7 @@setTimeout(() => {if (arrivedVariants >= expectedVariants && expectedVariants > 0) return;if (state !== 'GENERATING' || msg.id !== currentSessionId) return;- injectVariantsFromSource(msg.file, msg.id);+ injectVariantsFromSource(msg.file, msg.id, { generationCompleted: true });}, 750);break;}@@ -6215,9 +6442,10 @@if (maybeCompleteAcceptedSession(msg)) break;break;case 'agent_done':- // Carbonize accepts are not terminal until live-complete.mjs sends- // the final complete event. Keep the browser in its recoverable- // saving state while the source cleanup is still in flight.+ // The deterministic accept has already committed the reviewed DOM+ // and fenced generation. Carbonize may continue in the background;+ // it must not hold the foreground picker hostage.+ if (msg.data?.carbonize === true && maybeCompleteAcceptedSession(msg)) break;break;case 'discarded':if (msg.id && msg.id === currentSessionId) {@@ -6306,6 +6534,7 @@type: 'checkpoint',id: currentSessionId,revision: sessionState.nextCheckpointRevision(),+ revisionDomain: 'browser',owner: browserOwner,phase: String(state || '').toLowerCase(),reason,@@ -6331,6 +6560,7 @@type: 'checkpoint',id,revision: sessionState.nextCheckpointRevision(),+ revisionDomain: 'browser',owner: browserOwner,phase: 'steer',reason,@@ -6684,6 +6914,9 @@expectedVariants = selectedCount;arrivedVariants = 0;visibleVariant = 0;+ generationPhase = 'queued';+ parameterGenerationState = 'pending';+ parameterReadyAnnouncedSession = null;resetSessionFileMeta();// Flip to GENERATING immediately so the bar morphs without waiting on@@ -6693,6 +6926,7 @@const elForCapture = selectedElement;pickedAnchorSnapshot = buildPickedAnchorSnapshot(elForCapture);const captureRect = elForCapture.getBoundingClientRect();+ pickedAnchorViewportTop = captureRect.top;const snapshot = {comments: annotState.comments.map(c => ({ x: c.x, y: c.y, text: c.text })),strokes: annotState.strokes.map(s => ({ points: s.points.map(p => [p[0], p[1]]) })),@@ -6724,7 +6958,7 @@writeScrollY(window.scrollY);if (variantObserver) variantObserver.disconnect();variantObserver = startVariantObserver(currentSessionId);- startScrollLock(currentSessionId);+ startScrollLock(currentSessionId, window.scrollY, pickedAnchorViewportTop);captureAndEmit(elForCapture, basePayload, snapshot, captureRect);}@@ -6759,12 +6993,16 @@expectedVariants = selectedCount;arrivedVariants = 0;visibleVariant = 0;+ generationPhase = 'queued';+ parameterGenerationState = 'pending';+ parameterReadyAnnouncedSession = null;resetSessionFileMeta();selectedElement = placeholderElement;insertPlaceholderSnapshot = buildInsertPlaceholderSnapshotFromDom(insertAnchorElement, placeholderElement);const elForCapture = placeholderElement;const captureRect = elForCapture.getBoundingClientRect();+ pickedAnchorViewportTop = captureRect.top;const basePayload = {type: 'generate',mode: 'insert',@@ -6795,7 +7033,7 @@writeScrollY(window.scrollY);if (variantObserver) variantObserver.disconnect();variantObserver = startVariantObserver(currentSessionId);- startScrollLock(currentSessionId);+ startScrollLock(currentSessionId, window.scrollY, pickedAnchorViewportTop);captureAndEmit(elForCapture, basePayload, snapshot, captureRect);}@@ -6975,9 +7213,9 @@// preview mounts are covered by the same shader regression checks.const adapter = String(window.__IMPECCABLE_LIVE_ADAPTER__ || '').toLowerCase();if (adapter === 'svelte' || adapter === 'sveltekit') return true;- if (currentPreviewMode === 'svelte-component' || svelteComponentSession) return true;+ if (isFrameworkComponentPreviewMode(currentPreviewMode) || svelteComponentSession) return true;const wrapper = el?.closest?.('[data-impeccable-variants]');- return wrapper?.dataset?.impeccablePreview === 'svelte-component';+ return isFrameworkComponentPreviewMode(wrapper?.dataset?.impeccablePreview);}function paintsShaderProxySurface(node) {@@ -7105,6 +7343,17 @@}async function captureAndEmit(el, basePayload, snapshot, rect) {+ const hasAnnotations = snapshot && (snapshot.comments.length > 0 || snapshot.strokes.length > 0);++ // Plain requests do not send a screenshot to the agent, so capture is+ // presentation-only. Wait only for the helper to accept the event before+ // starting CPU-heavy capture; this yields the browser task and prevents+ // rasterization from delaying the fetch itself.+ if (!hasAnnotations) {+ basePayload.clientSentAt = Date.now();+ await sendEvent(basePayload);+ }+let screenshotPath;let blob;let paper;@@ -7122,7 +7371,6 @@// are present. Without annotations the image is pure visual anchoring -// it biases the model toward the current rendering and works against the// three-distinct-directions brief.- const hasAnnotations = snapshot && (snapshot.comments.length > 0 || snapshot.strokes.length > 0);if (blob && hasAnnotations) {try {const uploadRes = await fetch(@@ -7140,7 +7388,12 @@console.warn('[impeccable] annotation upload failed:', err);}}- sendEvent(screenshotPath ? { ...basePayload, screenshotPath } : basePayload);+ // Annotated requests must wait for capture + upload because the screenshot+ // is semantic input. Plain requests were already dispatched above.+ if (hasAnnotations) {+ basePayload.clientSentAt = Date.now();+ sendEvent(screenshotPath ? { ...basePayload, screenshotPath } : basePayload);+ }}//@@ -7520,7 +7773,6 @@ void main() {if (variantSelectionPromise) {try { await variantSelectionPromise; } catch { /* failed selection falls back below */ }}- if (!currentSessionId || arrivedVariants === 0) return;const domVisibleVariant = readVisibleVariantFromDOM(currentSessionId);if (domVisibleVariant > 0) visibleVariant = domVisibleVariant;const acceptPayload = {@@ -7528,7 +7780,9 @@ void main() {id: currentSessionId,variantId: String(visibleVariant),pageUrl: location.pathname,+ clientSentAt: Date.now(),};+ if (!currentSessionId || arrivedVariants === 0) return;const acceptWrapper = document.querySelector('[data-impeccable-variants="' + currentSessionId + '"]');if (Object.keys(paramsCurrentValues).length > 0) {acceptPayload.paramValues = { ...paramsCurrentValues };@@ -7542,7 +7796,7 @@ void main() {const acceptedSessionId = currentSessionId;const acceptedVariant = visibleVariant;const acceptedIsSvelteComponent = svelteComponentSession?.sessionId === acceptedSessionId- || acceptWrapper?.dataset?.impeccablePreview === 'svelte-component';+ || isFrameworkComponentPreviewMode(acceptWrapper?.dataset?.impeccablePreview);const acceptedSnapshot = snapshotAcceptedVariantDom(acceptedSessionId, acceptedVariant);setLiveState('SAVING');@@ -7557,7 +7811,17 @@ void main() {saveSession();sendEvent(acceptPayload, { throwOnError: true })- .then(() => {})+ .then(() => {+ const pending = pendingAcceptedSession;+ if (!pending || pending.id !== acceptedSessionId) return;+ // POST /events returns only after the accept intent is durable and the+ // generation epoch is fenced. Source promotion/carbonize can finish in+ // the background; the foreground picker is free immediately.+ markSessionHandled();+ setLiveState('CONFIRMED');+ document.documentElement.dataset.impeccableAcceptToPickingMs = String(Date.now() - acceptPayload.clientSentAt);+ scheduleAcceptCleanup(pending);+ }).catch(() => {if (pendingAcceptedSession?.id === acceptedSessionId) pendingAcceptedSession = null;setLiveState('CYCLING');@@ -7586,17 +7850,26 @@ void main() {}function scheduleAcceptCleanup(accepted) {- setTimeout(function() {- if (!accepted?.isSvelteComponent && !acceptedDomAlreadyClean(accepted)) {- setTimeout(function() {- if (pendingAcceptedSession?.id !== accepted?.id) return;- if (!accepted?.isSvelteComponent) ensureAcceptedDomClean(accepted);- cleanupAcceptedSession();- }, 1800);- return;+ queueMicrotask(function() {+ if (pendingAcceptedSession?.id !== accepted?.id) return;+ // Svelte previews live in an adapter-owned mount rather than in source+ // wrapper markup. Promote the mounted variant before releasing the+ // session so the old adapter instance cannot linger behind the next+ // Pick → Go loop while carbonize finishes in the background.+ if (accepted?.isSvelteComponent) {+ commitAcceptedSvelteComponentToDom(accepted.id);}cleanupAcceptedSession();- }, 1200);+ });+ // Let React/Vue/Svelte own the HMR reconciliation. Mutating their DOM in+ // the same turn as the source update causes removeChild/NotFoundError+ // races. Static servers still need a fallback, but it must not keep Live+ // in SAVING or block the user's next pick.+ if (!accepted?.isSvelteComponent) {+ setTimeout(function() {+ if (!acceptedDomAlreadyClean(accepted)) ensureAcceptedDomClean(accepted);+ }, 1200);+ }}function snapshotAcceptedVariantDom(sessionId, variantId) {@@ -7700,7 +7973,11 @@ void main() {clearSession();resetSessionFileMeta();selectedElement = null;+ hoveredElement = null;+ pagePickSkipClick = false;currentSessionId = null;+ parameterGenerationState = 'idle';+ parameterReadyAnnouncedSession = null;selectedAction = 'impeccable';pendingAcceptedSession = null;renderEditBadge('hidden');@@ -7735,7 +8012,7 @@ void main() {sendEvent({ type: 'discard', id: currentSessionId }, { throwOnError: true }).then(() => {markSessionHandled();- cleanup();+ cleanup({ restoreOriginal: true, instantChrome: true });}).catch(() => showToast('Could not confirm discard with the live server. Session kept for recovery.', 5000));}@@ -7757,6 +8034,7 @@ void main() {currentPreviewMode = null;recoveryWaitingForAnchor = false;pickedAnchorSnapshot = null;+ pickedAnchorViewportTop = null;}function rememberSessionFileMeta(meta = {}) {@@ -7765,8 +8043,8 @@ void main() {const previewFile = normalizeSessionPath(meta.previewFile);const previewMode = meta.previewMode || (isSvelteComponentManifestPath(previewFile || file) ? 'svelte-component' : null);- if (previewMode === 'svelte-component' || isSvelteComponentManifestPath(file)) {- currentPreviewMode = 'svelte-component';+ if (isFrameworkComponentPreviewMode(previewMode) || isSvelteComponentManifestPath(file)) {+ currentPreviewMode = isFrameworkComponentPreviewMode(previewMode) ? previewMode : 'svelte-component';currentPreviewFile = previewFile || (isSvelteComponentManifestPath(file) ? file : currentPreviewFile);currentSourceFile = sourceFile || currentSourceFile;return;@@ -7782,12 +8060,15 @@ void main() {rememberSessionFileMeta(saved);if (saved.insertPlaceholder) insertPlaceholderSnapshot = saved.insertPlaceholder;if (saved.pickedAnchor) pickedAnchorSnapshot = saved.pickedAnchor;+ if (Number.isFinite(saved.pickedAnchorViewportTop)) pickedAnchorViewportTop = saved.pickedAnchorViewportTop;if (saved.action) selectedAction = saved.action;if (saved.count) selectedCount = saved.count;if (saved.previewMode) currentPreviewMode = saved.previewMode;if (saved.paramValues && typeof saved.paramValues === 'object') {paramsCurrentValues = { ...saved.paramValues };}+ if (saved.parameterState) parameterGenerationState = saved.parameterState;+ if (saved.generationPhase) generationPhase = saved.generationPhase;}function normalizePagePath(value) {@@ -7859,7 +8140,7 @@ void main() {saveSession();queueCheckpoint(reason || 'browser_restore_without_wrapper');- const restoreFile = currentPreviewMode === 'svelte-component'+ const restoreFile = isFrameworkComponentPreviewMode(currentPreviewMode)? currentPreviewFile: (currentSourceFile || currentPreviewFile);if (restoreFile) {@@ -7872,11 +8153,41 @@ void main() {function restoreFromActiveSessions(activeSessions, reason) {const wrapper = document.querySelector('[data-impeccable-variants]');- if (wrapper && wrapper.dataset.impeccablePreview !== 'svelte-component') return false;+ if (wrapper && !isFrameworkComponentPreviewMode(wrapper.dataset.impeccablePreview)) return false;if (svelteComponentSession?.sessionId === currentSessionId) return false;return restoreSessionWithoutWrapper(reason || 'sse_connected', activeSessions);}+ // Self-heal on SSE (re)connect. The preflight scaffold write triggers a+ // framework full-reload (Astro reloads pages for any .astro edit); if the+ // agent's variant write + `done` broadcast land while this page is+ // mid-reload, both the done SSE and the second HMR reload are missed and+ // the resumed page would wait in GENERATING at 0/N forever. The server's+ // session summary carries the durable generationCompletedAt marker, so on+ // every connect compare it against our own progress and pull the finished+ // variants from source when behind. Mirrors the `done` handler's source+ // fallback, including its give-HMR-the-first-chance settle delay.+ function recoverMissedGenerationCompletion(activeSessions) {+ if (!currentSessionId || state !== 'GENERATING') return;+ if (!Array.isArray(activeSessions)) return;+ const summary = activeSessions.find((session) => session?.id === currentSessionId);+ if (!summary?.generationCompletedAt || summary.generationCanceled) return;+ if (isTerminalSessionSummary(summary)) return;+ if (arrivedVariants > 0 && arrivedVariants >= expectedVariants) return;+ rememberSessionFileMeta(summary);+ const sessionId = currentSessionId;+ const file = isFrameworkComponentPreviewMode(currentPreviewMode)+ ? currentPreviewFile+ : (summary.sourceFile || summary.previewFile || currentSourceFile || currentPreviewFile);+ if (!file) return;+ console.log('[impeccable] Reconnected after generation completed; recovering variants from source.');+ setTimeout(() => {+ if (sessionId !== currentSessionId || state !== 'GENERATING') return;+ if (arrivedVariants > 0 && arrivedVariants >= expectedVariants) return;+ injectVariantsFromSource(file, sessionId, { generationCompleted: true });+ }, 750);+ }+function saveSession() {if (!currentSessionId) return;// NOTE: scrollY is stored under a separate key (writeScrollY). Storing@@ -7894,8 +8205,12 @@ void main() {previewMode: currentPreviewMode || undefined,pageUrl: location.pathname,paramValues: { ...paramsCurrentValues },+ parameterState: parameterGenerationState,insertPlaceholder: insertPlaceholderSnapshot || undefined,pickedAnchor: pickedAnchorSnapshot || undefined,+ pickedAnchorViewportTop: Number.isFinite(pickedAnchorViewportTop) ? pickedAnchorViewportTop : undefined,+ pageHash: location.hash || undefined,+ pageSearch: location.search || undefined,});}@@ -7923,20 +8238,26 @@ void main() {sessionState.clearHandled();}- function cleanup() {+ function cleanup(options) {+ const restoreOriginal = options?.restoreOriginal === true;+ const instantChrome = options?.instantChrome === true;const cleanupSessionId = currentSessionId;if (svelteComponentSession?.sessionId === cleanupSessionId) {teardownSvelteComponentSession(true);} else if (cleanupSessionId) {- // Hide the wrapper immediately so variants disappear. DON'T structurally- // mutate the DOM yet - HMR from the agent's source rewrite is on its way,+ // Switch visibility immediately without structurally mutating the DOM.+ // HMR from the agent's source rewrite may still be on its way,// and a manual replaceChild under React causes NotFoundError when the// reconciler later tries to remove a wrapper we already removed.// Schedule a 2s fallback that does the manual swap only if HMR hasn't// replaced the wrapper by then (keeps static-server / no-HMR flows alive).const wrapper = document.querySelector('[data-impeccable-variants="' + cleanupSessionId + '"]');- if (wrapper) wrapper.style.display = 'none';+ if (wrapper) {+ if (restoreOriginal) showOriginalDuringDiscard(cleanupSessionId);+ else wrapper.style.display = 'none';+ }setTimeout(function() {+ document.getElementById(DISCARD_STATE_STYLE_ID)?.remove();if (!cleanupSessionId) return;const lateWrapper = document.querySelector('[data-impeccable-variants="' + cleanupSessionId + '"]');if (!lateWrapper) return;@@ -7951,7 +8272,7 @@ void main() {lateWrapper.remove();}, 2000);}- hideBar();+ hideBar(instantChrome);hideHighlight();stopScrollTracking();if (variantObserver) { variantObserver.disconnect(); variantObserver = null; }@@ -7963,7 +8284,11 @@ void main() {clearSession();resetSessionFileMeta();selectedElement = null;+ hoveredElement = null;+ pagePickSkipClick = false;currentSessionId = null;+ parameterGenerationState = 'idle';+ parameterReadyAnnouncedSession = null;selectedAction = 'impeccable';renderEditBadge('hidden');setLiveState('PICKING');@@ -8047,7 +8372,7 @@ void main() {// would strand the bar in CYCLING at 0/0. If there's no live in-memory mount// for this wrapper, it's an orphan (reload / failed mount): drop it and let// the live-server's SSE re-inject the manifest if the session is still live.- if (wrapper.dataset.impeccablePreview === 'svelte-component'+ if (isFrameworkComponentPreviewMode(wrapper.dataset.impeccablePreview)&& svelteComponentSession?.sessionId !== sessionId) {wrapper.remove();if (restoreSessionWithoutWrapper('browser_resumed_svelte_orphan_wrapper')) return true;@@ -8056,7 +8381,7 @@ void main() {return false;}- if (wrapper.dataset.impeccablePreview === 'svelte-component') {+ if (isFrameworkComponentPreviewMode(wrapper.dataset.impeccablePreview)) {if (!svelteComponentSession?.mountedVariant) {return true;}@@ -8104,7 +8429,7 @@ void main() {insertPlaceholderSnapshot = saved.insertPlaceholder;}- const resumedState = arrivedVariants >= expectedVariants ? 'CYCLING' : 'GENERATING';+ const resumedState = arrivedVariants > 0 ? 'CYCLING' : 'GENERATING';// Find the visible variant's content element for highlight positioning.const isInsert = wrapper.dataset.impeccableMode === 'insert';@@ -8128,7 +8453,11 @@ void main() {// hid. Now that state is CYCLING, re-fire.if (state === 'CYCLING') refreshParamsPanel();saveSession();- queueCheckpoint('browser_resumed');+ if (arrivedVariants > 0 && arrivedVariants < expectedVariants) {+ sendCheckpoint('variants_progress');+ } else {+ queueCheckpoint('browser_resumed');+ }// Start observing for more variants AFTER initial setupif (variantObserver) variantObserver.disconnect();@@ -8136,7 +8465,7 @@ void main() {// Hold the target at its saved viewport top through any subsequent// HMR patches, variant inserts, or cycle swaps.- startScrollLock(currentSessionId, readScrollY());+ startScrollLock(currentSessionId, readScrollY(), pickedAnchorViewportTop);// If we reloaded mid-generation (Bun's HTML HMR destroys the shader// canvas), re-capture the original's content and restart the shader so@@ -8171,6 +8500,7 @@ void main() {let globalBarBrandEl = null;let agentPollTooltipEl = null;let agentPollingConnected = false;+ let agentStatusMessage = null;let agentStatusPollTimer = null;let steerFocusSuspended = false;let steerFocusPauseUntil = 0;@@ -8275,6 +8605,13 @@ void main() {const AGENT_STATUS_POLL_MS = 5000;const AGENT_DISCONNECTED_MARK = 'oklch(62% 0 0 / 0.78)';const AGENT_DISCONNECTED_TIP = 'Agent disconnected - run live-poll.mjs to connect';+ // The indicator tracks whether a poll is parked, which is what decides if+ // steering can reach the agent right now. That goes quiet two ways, and they+ // need different copy: nobody is polling at all, or the agent took the work+ // and is busy with it. Under one-shot foreground polling the second case is+ // every normal generation, and telling the user to start a poll loop then is+ // wrong advice about a healthy session.+ const AGENT_BUSY_TIP = 'Agent is working - steering resumes when it finishes';const GLOBAL_BAR_SECTION_GAP = 8;const GLOBAL_BAR_INNER_GAP = 2;const GLOBAL_BAR_INNER_PAD_LEFT = 2;@@ -9295,24 +9632,46 @@ void main() {</svg>`;}+ /**+ * True while the browser is waiting on work it already handed to the agent.+ * In these states a quiet poll indicator means "busy", not "absent".+ */+ function agentHasWorkInFlight() {+ return state === 'GENERATING' || state === 'SAVING';+ }++ /**+ * Derived at read time, not cached: which of the two reasons applies depends on+ * the live state, which moves between the 5s status polls. The truthiness is+ * the same either way, so the indicator's visuals can stay driven by the+ * cached value while the wording stays current.+ */+ function agentStatusText() {+ if (agentPollingConnected) return null;+ return agentHasWorkInFlight() ? AGENT_BUSY_TIP : AGENT_DISCONNECTED_TIP;+ }+function syncAgentPollingUi(connected) {agentPollingConnected = !!connected;if (!globalBarBrandEl) return;const P = barPaletteForTheme(globalBarEl?.dataset.theme || detectPageTheme());+ agentStatusMessage = agentStatusText();globalBarBrandEl.dataset.agentConnected = connected ? 'true' : 'false';- globalBarBrandEl.setAttribute('aria-label', connected- ? 'Impeccable live mode'- : 'Impeccable live mode - agent not polling');+ // The tooltip is mouse-only, so carry the same distinction in the label or+ // screen-reader users are left with the vaguer of the two readings.+ globalBarBrandEl.setAttribute('aria-label', agentStatusMessage+ ? 'Impeccable live mode - ' + (agentHasWorkInFlight() ? 'agent is working' : 'agent not polling')+ : 'Impeccable live mode');globalBarBrandEl.removeAttribute('title');- globalBarBrandEl.style.cursor = connected ? 'default' : 'help';+ globalBarBrandEl.style.cursor = agentStatusMessage ? 'help' : 'default';const mark = globalBarBrandEl.querySelector('[data-brand-mark]');if (mark) {mark.innerHTML = brandMarkSvg(connected ? P.accent : AGENT_DISCONNECTED_MARK, 18);mark.style.opacity = '1';}const dot = globalBarBrandEl.querySelector('[data-agent-dot]');- if (dot) dot.style.display = connected ? 'none' : 'block';- if (connected) hideAgentPollTooltip();+ if (dot) dot.style.display = agentStatusMessage ? 'block' : 'none';+ if (!agentStatusMessage) hideAgentPollTooltip();}function ensureAgentPollTooltip() {@@ -9339,14 +9698,17 @@ void main() {whiteSpace: 'normal',});agentPollTooltipEl.id = PREFIX + '-agent-poll-tooltip';- agentPollTooltipEl.textContent = AGENT_DISCONNECTED_TIP;+ agentPollTooltipEl.textContent = agentStatusText() || AGENT_DISCONNECTED_TIP;uiAppend(agentPollTooltipEl);return agentPollTooltipEl;}function showAgentPollTooltip(anchor) {- if (agentPollingConnected || !anchor) return;+ if (!agentStatusMessage || !anchor) return;const tip = ensureAgentPollTooltip();+ // Re-derive rather than reuse the cached copy: the live state may have moved+ // since the last status poll set it.+ tip.textContent = agentStatusText() || AGENT_DISCONNECTED_TIP;tip.style.transition = 'none';tip.style.display = 'block';tip.style.opacity = '1';@@ -9376,7 +9738,9 @@ void main() {fetch('http://localhost:' + PORT + '/status?token=' + TOKEN, { cache: 'no-store' }).then((res) => (res.ok ? res.json() : null)).then((data) => {- if (data && typeof data.agentPolling === 'boolean') syncAgentPollingUi(data.agentPolling);+ if (data && typeof data.agentPolling === 'boolean') {+ syncAgentPollingUi(data.agentPolling);+ }}).catch(() => { /* server loss handled elsewhere */ });}diff --git a/.gemini/skills/impeccable/scripts/live-inject.mjs b/.gemini/skills/impeccable/scripts/live-inject.mjsindex 7c8d91182..d99c37fd5 100644--- a/.gemini/skills/impeccable/scripts/live-inject.mjs+++ b/.gemini/skills/impeccable/scripts/live-inject.mjs@@ -27,6 +27,8 @@ const __dirname = path.dirname(fileURLToPath(import.meta.url));const CONFIG_PATH = resolveLiveConfigPath({ cwd: process.cwd(), scriptsDir: __dirname });const MARKER_OPEN_TEXT = 'impeccable-live-start';const MARKER_CLOSE_TEXT = 'impeccable-live-end';+const NUXT_PLUGIN_MARKER = 'impeccable-live-nuxt-plugin';+const NUXT_PLUGIN_NAME = 'impeccable-live.client.ts';const IGNORE_MARKER_OPEN = '# impeccable-live-ignore-start';const IGNORE_MARKER_CLOSE = '# impeccable-live-ignore-end';@@ -38,6 +40,9 @@ export const LIVE_IGNORE_PATTERNS = Object.freeze(['.impeccable/live/sessions/','.impeccable/live/previews/','.impeccable/live/annotations/',+ '.impeccable/live/artifacts/',+ '.impeccable/live/accept-receipts/',+ '.impeccable/live/locks/','.impeccable/live/cache/','.impeccable/live/manual-edit-apply-transaction.json','.impeccable/live/manual-edit-events.jsonl',@@ -46,10 +51,15 @@ export const LIVE_IGNORE_PATTERNS = Object.freeze(['.impeccable/live/deferred-svelte-component-accepts.json','.impeccable-live.json','.impeccable-live/',+ 'app/.impeccable-live/',+ 'src/.impeccable-live/','node_modules/.impeccable-live/','src/lib/impeccable/ImpeccableLiveRoot.svelte','src/lib/impeccable/__runtime.js','src/lib/impeccable/[0-9a-f]*/',+ 'plugins/impeccable-live.client.ts',+ 'app/plugins/impeccable-live.client.ts',+ 'src/plugins/impeccable-live.client.ts',]);/**@@ -113,6 +123,7 @@ Output (JSON):const resolvedFiles = resolveFiles(process.cwd(), config);const svelteKit = detectSvelteKitProject(process.cwd(), config);+ const nuxt = detectNuxtProject(process.cwd());if (args.includes('--remove')) {if (svelteKit) {@@ -120,6 +131,12 @@ Output (JSON):console.log(JSON.stringify({ ok: true, adapter: 'sveltekit', results: [adapterResult] }));return;}+ if (nuxt) {+ const adapterResult = removeNuxtLiveAdapter({ cwd: process.cwd(), project: nuxt });+ console.log(JSON.stringify({ ok: !adapterResult.error, adapter: 'nuxt', results: [adapterResult] }));+ if (adapterResult.error) process.exitCode = 1;+ return;+ }const results = resolvedFiles.map((relFile) => {const absFile = path.resolve(process.cwd(), relFile);if (!fs.existsSync(absFile)) return { file: relFile, error: 'file_not_found' };@@ -145,13 +162,28 @@ Output (JSON):console.error(JSON.stringify({ ok: false, error: 'missing_port' }));process.exit(1);}- const gitIgnore = ensureLiveGitIgnores(process.cwd());+ const gitIgnore = ensureLiveGitIgnores(+ process.cwd(),+ nuxt ? [nuxt.pluginFile] : [],+ );if (svelteKit) {const adapterResult = applySvelteKitLiveAdapter({ cwd: process.cwd(), port, config });console.log(JSON.stringify({ ok: true, port, adapter: 'sveltekit', gitIgnore, results: [adapterResult] }));return;}+ if (nuxt) {+ const adapterResult = applyNuxtLiveAdapter({ cwd: process.cwd(), port, project: nuxt });+ console.log(JSON.stringify({+ ok: !adapterResult.error,+ port,+ adapter: 'nuxt',+ gitIgnore,+ results: [adapterResult],+ }));+ if (adapterResult.error) process.exitCode = 1;+ return;+ }const results = resolvedFiles.map((relFile) => {const absFile = path.resolve(process.cwd(), relFile);@@ -175,12 +207,12 @@ Output (JSON):if (!anyInserted) process.exit(1);}-export function ensureLiveGitIgnores(cwd = process.cwd()) {+export function ensureLiveGitIgnores(cwd = process.cwd(), extraPatterns = []) {const target = resolveIgnoreTarget(cwd);const existing = fs.existsSync(target.path) ? fs.readFileSync(target.path, 'utf-8') : '';const block = [IGNORE_MARKER_OPEN,- ...LIVE_IGNORE_PATTERNS,+ ...new Set([...LIVE_IGNORE_PATTERNS, ...extraPatterns]),IGNORE_MARKER_CLOSE,].join('\n');const markerRe = new RegExp(`${escapeRegExp(IGNORE_MARKER_OPEN)}[\\s\\S]*?${escapeRegExp(IGNORE_MARKER_CLOSE)}`);@@ -202,10 +234,119 @@ export function ensureLiveGitIgnores(cwd = process.cwd()) {file: path.relative(cwd, target.path).split(path.sep).join('/'),mode: target.mode,changed: updated !== existing,- patterns: [...LIVE_IGNORE_PATTERNS],+ patterns: [...new Set([...LIVE_IGNORE_PATTERNS, ...extraPatterns])],};}+// ---------------------------------------------------------------------------+// Nuxt adapter+//+// A script element placed in app.vue is compiled as Vue-rendered DOM and is+// not executed. Nuxt instead auto-discovers client plugins. Keep the adapter+// generated, dev-only, and outside user-authored source: Live creates one+// marked .client.ts plugin on start and removes it on stop.+// ---------------------------------------------------------------------------++export function detectNuxtProject(cwd = process.cwd()) {+ const configFile = fs.readdirSync(cwd, { withFileTypes: true })+ .find((entry) => entry.isFile() && /^nuxt\.config\.(?:js|mjs|cjs|ts|mts|cts)$/.test(entry.name))+ ?.name;+ if (!configFile) return null;++ const config = fs.readFileSync(path.join(cwd, configFile), 'utf-8');+ const literalSrcDir = config.match(/\bsrcDir\s*:\s*(['"])([^'"]+)\1/);+ let appDir = '';+ if (literalSrcDir) {+ const candidate = literalSrcDir[2]+ .replace(/\\/g, '/')+ .replace(/^\.\//, '')+ .replace(/\/+$/, '');+ const normalized = path.posix.normalize(candidate);+ if (normalized !== '..' && !normalized.startsWith('../') && !path.isAbsolute(normalized)) {+ appDir = normalized === '.' ? '' : normalized;+ }+ } else if (+ fs.existsSync(path.join(cwd, 'app', 'app.vue'))+ || fs.existsSync(path.join(cwd, 'app', 'pages'))+ ) {+ appDir = 'app';+ }++ const pluginFile = [appDir, 'plugins', NUXT_PLUGIN_NAME].filter(Boolean).join('/');+ return { configFile, appDir, pluginFile };+}++export function buildNuxtPlugin(port) {+ return `/* ${NUXT_PLUGIN_MARKER} */+const liveSrc = 'http://localhost:${port}/live.js';+const liveSelector = 'script[data-impeccable-live-nuxt]';++export default defineNuxtPlugin(() => {+ if (!import.meta.dev || typeof document === 'undefined') return;++ const expectedSrc = new URL(liveSrc, window.location.href).href;+ let script = document.querySelector(liveSelector);+ if (script?.src === expectedSrc) return;+ script?.remove();++ script = document.createElement('script');+ script.src = liveSrc;+ script.async = true;+ script.dataset.impeccableLiveNuxt = '';+ document.head.appendChild(script);++ import.meta.hot?.dispose(() => {+ if (script?.isConnected) script.remove();+ });+});+/* /${NUXT_PLUGIN_MARKER} */+`;+}++export function applyNuxtLiveAdapter({ cwd = process.cwd(), port, project = detectNuxtProject(cwd) }) {+ if (!project) return { error: 'nuxt_not_detected' };+ const absFile = path.join(cwd, project.pluginFile);+ const existing = fs.existsSync(absFile) ? fs.readFileSync(absFile, 'utf-8') : null;+ if (existing !== null && !existing.includes(NUXT_PLUGIN_MARKER)) {+ return {+ file: project.pluginFile,+ error: 'nuxt_plugin_conflict',+ hint: `${project.pluginFile} already exists and is not managed by Impeccable Live`,+ };+ }++ const content = buildNuxtPlugin(port);+ fs.mkdirSync(path.dirname(absFile), { recursive: true });+ if (content !== existing) fs.writeFileSync(absFile, content, 'utf-8');+ return {+ file: project.pluginFile,+ inserted: true,+ changed: content !== existing,+ devOnly: true,+ };+}++export function removeNuxtLiveAdapter({ cwd = process.cwd(), project = detectNuxtProject(cwd) }) {+ if (!project) return { error: 'nuxt_not_detected' };+ const absFile = path.join(cwd, project.pluginFile);+ if (!fs.existsSync(absFile)) {+ return { file: project.pluginFile, removed: false, note: 'no adapter present' };+ }+ const content = fs.readFileSync(absFile, 'utf-8');+ if (!content.includes(NUXT_PLUGIN_MARKER)) {+ return {+ file: project.pluginFile,+ removed: false,+ error: 'nuxt_plugin_conflict',+ hint: `${project.pluginFile} is not managed by Impeccable Live`,+ };+ }+ fs.unlinkSync(absFile);+ const pluginDir = path.dirname(absFile);+ if (fs.readdirSync(pluginDir).length === 0) fs.rmdirSync(pluginDir);+ return { file: project.pluginFile, removed: true };+}+function resolveIgnoreTarget(cwd) {const gitExcludePath = resolveGitInfoExcludePath(cwd);if (gitExcludePath) {diff --git a/.gemini/skills/impeccable/scripts/live-poll.mjs b/.gemini/skills/impeccable/scripts/live-poll.mjsindex 740161e10..19a8b0f9b 100644--- a/.gemini/skills/impeccable/scripts/live-poll.mjs+++ b/.gemini/skills/impeccable/scripts/live-poll.mjs@@ -27,7 +27,7 @@ const scriptCmd = (name) => `node "${path.join(SELF_DIR, name)}"`;export const PER_REQUEST_TIMEOUT_MS = 270_000;export const DEFAULT_EVENT_LEASE_MS = 600_000;-const EVENT_TYPES_NEEDING_AGENT_REPLY = new Set(['generate', 'steer', 'manual_edit_apply']);+const EVENT_TYPES_NEEDING_AGENT_REPLY = new Set(['generate', 'steer', 'manual_edit_apply', 'carbonize_cleanup']);function readServerInfo() {const record = readLiveServerInfo(process.cwd());@@ -38,8 +38,8 @@ function readServerInfo() {return record.info;}-export function buildPollReplyPayload(token, { id, type, message, file, data }) {- return { token, id, type, message, file, data };+export function buildPollReplyPayload(token, { id, type, message, file, data, sourceEventType }) {+ return { token, id, type, message, file, data, sourceEventType };}export function manualApplyPollBanner(event = {}) {@@ -152,7 +152,14 @@ export async function waitForEventAck(base, token, eventId, {return false;}-export async function fetchNextEvent(base, token, { totalDeadline } = {}) {+export async function fetchNextEvent(base, token, {+ totalDeadline,+ types,+ resolveTypes,+ perRequestTimeoutMs = PER_REQUEST_TIMEOUT_MS,+ leaseMs = DEFAULT_EVENT_LEASE_MS,+ signal,+} = {}) {while (true) {if (totalDeadline && Date.now() >= totalDeadline) {return { type: 'timeout' };@@ -161,8 +168,15 @@ export async function fetchNextEvent(base, token, { totalDeadline } = {}) {const remaining = totalDeadline? totalDeadline - Date.now(): PER_REQUEST_TIMEOUT_MS;- const slice = Math.min(Math.max(remaining, 1000), PER_REQUEST_TIMEOUT_MS);- const res = await fetch(`${base}/poll?token=${token}&timeout=${slice}&leaseMs=${DEFAULT_EVENT_LEASE_MS}`);+ const slice = Math.min(Math.max(remaining, 1000), perRequestTimeoutMs);+ const query = new URLSearchParams({+ token,+ timeout: String(slice),+ leaseMs: String(leaseMs),+ });+ const normalizedTypes = normalizePollTypes(resolveTypes ? await resolveTypes() : types);+ if (normalizedTypes.length > 0) query.set('types', normalizedTypes.join(','));+ const res = await fetch(`${base}/poll?${query}`, { signal });if (res.status === 401) {const err = new Error('Authentication failed. The server token may have changed.');@@ -202,11 +216,17 @@ export async function augmentEventWithAcceptHandling(event, base, token) {event._acceptResult = { handled: false, mode: 'error', error: err.message };}+ await completeAcceptHandling(event, base, token);+ return event;+}++export async function completeAcceptHandling(event, base, token) {const completionType = completionTypeForAcceptResult(event.type, event._acceptResult);try {await postReply(base, token, {id: event.id,type: completionType,+ sourceEventType: event.type,message: event._acceptResult?.error,file: event._acceptResult?.file,data: event._acceptResult?.carbonize === true ? { carbonize: true } : undefined,@@ -217,7 +237,6 @@ export async function augmentEventWithAcceptHandling(event, base, token) {if (!event._completionAck) {event._completionAck = completionAckForAcceptResult(event.id, completionType, event._acceptResult);}-return event;}@@ -245,9 +264,9 @@ export function printPollEvent(event) {console.log(JSON.stringify(event));}-export async function runPollOnce(base, token, { totalTimeout = 600_000 } = {}) {+export async function runPollOnce(base, token, { totalTimeout = 600_000, types, resolveTypes, perRequestTimeoutMs } = {}) {const deadline = Date.now() + totalTimeout;- const event = await fetchNextEvent(base, token, { totalDeadline: deadline });+ const event = await fetchNextEvent(base, token, { totalDeadline: deadline, types, resolveTypes, perRequestTimeoutMs });await augmentEventWithAcceptHandling(event, base, token);writeCarbonizeBanner(event);printPollEvent(event);@@ -258,11 +277,14 @@ export async function runPollStream(base, token, {ackTimeoutMs = 600_000,ackPollIntervalMs = 400,shouldContinue = () => true,+ types,+ resolveTypes,+ perRequestTimeoutMs,} = {}) {process.stderr.write('[impeccable-poll] stream mode: one JSON object per line on stdout; use --reply while this process stays running\n');while (shouldContinue()) {- const event = await fetchNextEvent(base, token);+ const event = await fetchNextEvent(base, token, { types, resolveTypes, perRequestTimeoutMs });await augmentEventWithAcceptHandling(event, base, token);writeCarbonizeBanner(event);printPollEvent(event);@@ -322,14 +344,17 @@ Modes:Options:--timeout=MS One-shot poll timeout in ms (default: 600000). Ignored in --stream mode+ --types=A,B Lease only these event types--ack-timeout=MS Stream mode: max wait for --reply after generate/steer (default: 600000)--file PATH Attach a source file path to the reply (generate/steer flow)--data JSON Attach a JSON result object to the reply (manual_edit_apply flow). Must be valid JSON--help Show this help messageHarness note:- Default one-shot mode is the portable contract for Claude Code, Codex, and Cursor.- --stream is experimental for harnesses with fast incremental stdout; do not use on Cursor.`);+ Default one-shot mode is the primary contract, including Codex foreground polling.+ Claude Code may run it as a background task; Cursor uses a background terminal with exit notification.+ --stream is retained for harnesses with measured, reliable incremental stdout.+ Do not use --stream on Cursor.`);process.exit(0);}@@ -360,23 +385,30 @@ Harness note:}const streamMode = args.includes('--stream');+ const typesArg = args.find((a) => a.startsWith('--types='));+ const types = normalizePollTypes(typesArg ? typesArg.slice('--types='.length) : null);const ackTimeoutArg = args.find((a) => a.startsWith('--ack-timeout='));const ackTimeoutMs = ackTimeoutArg ? parseInt(ackTimeoutArg.split('=')[1], 10) : 600_000;try {if (streamMode) {- await runPollStream(base, info.token, { ackTimeoutMs });+ await runPollStream(base, info.token, { ackTimeoutMs, types });return;}const timeoutArg = args.find((a) => a.startsWith('--timeout='));const totalTimeout = timeoutArg ? parseInt(timeoutArg.split('=')[1], 10) : 600_000;- await runPollOnce(base, info.token, { totalTimeout });+ await runPollOnce(base, info.token, { totalTimeout, types });} catch (err) {handlePollError(err);}}+export function normalizePollTypes(value) {+ const values = Array.isArray(value) ? value : String(value || '').split(',');+ return [...new Set(values.map((type) => String(type).trim()).filter(Boolean))];+}+// Auto-execute when run directlyconst _running = process.argv[1];if (_running?.endsWith('live-poll.mjs') || _running?.endsWith('live-poll.mjs/')) {diff --git a/.gemini/skills/impeccable/scripts/live-server.mjs b/.gemini/skills/impeccable/scripts/live-server.mjsindex 5735f2aec..c6e951086 100644--- a/.gemini/skills/impeccable/scripts/live-server.mjs+++ b/.gemini/skills/impeccable/scripts/live-server.mjs@@ -28,8 +28,10 @@ import {readLiveBrowserScriptParts,resolveLiveBrowserScriptParts,} from './live/browser-script-parts.mjs';-import { createLiveSessionStore } from './live/session-store.mjs';+import { createLiveSessionStore, GENERATION_FENCED_PHASES } from './live/session-store.mjs';+import { runGenerationPreflight } from './live/generation-preflight.mjs';import { validateEvent } from './live/event-validation.mjs';+import { selectAvailablePendingEvent } from './live/poll-lanes.mjs';import { createManualEditRoutes } from './live/manual-edit-routes.mjs';import { LIVE_COMMANDS } from './live/vocabulary.mjs';import {@@ -63,6 +65,10 @@ const DESIGN_MD_PATH = PROJECT_CONTEXT.designPath: null;const DEFAULT_POLL_TIMEOUT = 600_000; // 10 min — agent re-polls on timeout anywayconst SSE_HEARTBEAT_INTERVAL = 30_000; // keepalive ping every 30s+// The browser checkpoints for several unrelated reasons (see checkpointPayload+// in live-browser.js). Only these two report that variant availability changed,+// and only they may drive variant_progress / the *_reviewable phases.+const VARIANT_PROGRESS_CHECKPOINT_REASONS = new Set(['variants_progress', 'variants_ready']);// ---------------------------------------------------------------------------// Port detection@@ -156,29 +162,206 @@ function restorePendingEventsFromStore() {}}-function findAvailablePendingEvent(now = Date.now()) {- for (const entry of state.pendingEvents) {- if (entry.leaseUntil && entry.leaseUntil > now) continue;- return entry;- }- return null;+function findAvailablePendingEvent(now = Date.now(), types = null) {+ return selectAvailablePendingEvent(state.pendingEvents, { now, types });}-function leaseEvent(entry, leaseMs) {+async function leaseEvent(entry, leaseMs) {+ // Claim the entry before awaiting anything. prepareGenerateEventForLease+ // yields to the event loop, and selectAvailablePendingEvent only skips+ // entries whose lease is in the future — an unclaimed entry would be handed+ // to a second poll in that window and generated twice.+ entry.leaseUntil = Date.now() + leaseMs;+ await prepareGenerateEventForLease(entry);if (!entry.event?.id) {const idx = state.pendingEvents.indexOf(entry);if (idx !== -1) state.pendingEvents.splice(idx, 1);return entry.event;}+ // Re-stamp so the lease window starts when the agent actually receives the+ // work, not when scaffolding began.entry.leaseUntil = Date.now() + leaseMs;+ recordGenerateDelivery(entry);scheduleLeaseFlush();broadcastAgentPollingIfChanged();return entry.event;}-function acknowledgePendingEvent(id) {+function recordGenerateDelivery(entry) {+ const event = entry?.event;+ if (!event || event.type !== 'generate' || event.generationReadyAt) return;+ const at = Date.now();+ entry.event = { ...event, generationReadyAt: at };+ state.sessionStore?.appendEvent(entry.event);+ recordAgentPhase(event.id, 'generation_ready', { at });+}++async function prepareGenerateEventForLease(entry) {+ const event = entry?.event;+ if (!event || event.type !== 'generate' || event.scaffoldAttempted) return;++ recordAgentPhase(event.id, 'picked_up');+ recordAgentPhase(event.id, 'scaffolding');+ const result = await runGenerationPreflight(event, {+ cwd: process.cwd(),+ scriptsDir: __dirname,+ });+ entry.event = {+ ...event,+ scaffoldAttempted: true,+ scaffoldDurationMs: result.durationMs ?? null,+ ...(result.ok ? { scaffold: result.scaffold } : { scaffoldError: result.error || result.reason }),+ };+ state.sessionStore?.appendEvent(entry.event);+ recordAgentPhase(event.id, result.ok ? 'source_ready' : 'scaffold_fallback', {+ durationMs: result.durationMs ?? null,+ previewMode: result.scaffold?.previewMode || 'source',+ });+}++function recordAgentPhase(id, phase, details = {}) {+ if (!id) return;+ const event = {+ type: 'agent_phase',+ id,+ phase,+ at: Date.now(),+ ...details,+ };+ state.sessionStore?.appendEvent(event);+ broadcast(event);+}++/**+ * Detect a browser that missed the generation `done` broadcast.+ *+ * The preflight scaffold write triggers a framework full-reload (Astro reloads+ * the page for any .astro edit). If the agent's variant write + `done` land+ * while the browser is mid-reload, the new page misses both the second HMR+ * reload and the SSE `done` — it resumes from the scaffold-only source and+ * sits in GENERATING at 0/N forever. That resumed page always checkpoints+ * (`browser_resumed`), so a checkpoint claiming "still generating, variants+ * missing" for a session whose generation already completed is direct+ * evidence of the miss. Rebuild the `done` payload from the snapshot so the+ * caller can re-broadcast it; the browser's done handler is idempotent and+ * falls back to injecting variants from source.+ *+ * Keys on the store's monotone `generationCompletedAt`, not `phase` — the+ * behind checkpoint itself regresses `phase` to `generating`, and a browser+ * that misses the redelivered `done` too (another reload) must still trigger+ * redelivery from its next checkpoint.+ */+function detectMissedGenerationCompletion(event) {+ if (!event?.id || event.type !== 'checkpoint') return null;+ if (event.phase !== 'generating') return null;+ if (!variantCountLooksBehind(event.arrivedVariants, event.expectedVariants)) return null;+ if (!state.sessionStore) return null;+ let snapshot = null;+ try {+ snapshot = state.sessionStore.getSnapshot(event.id);+ } catch {+ return null;+ }+ return missedCompletionFromSnapshot(snapshot);+}++function variantCountLooksBehind(arrivedValue, expectedValue) {+ const arrived = Number(arrivedValue) || 0;+ const expected = Number(expectedValue) || 0;+ return arrived <= 0 || (expected > 0 && arrived < expected);+}++function missedCompletionFromSnapshot(snapshot) {+ if (!snapshot?.id || !snapshot.generationCompletedAt) return null;+ if (snapshot.generationCanceled) return null;+ // Accept/discard already underway: the browser is no longer waiting on+ // generation, and a late `done` there would collide with teardown.+ if (GENERATION_FENCED_PHASES.has(snapshot.phase)) return null;+ const file = snapshot.sourceFile || snapshot.previewFile;+ if (!file) return null;+ return {+ type: 'done',+ id: snapshot.id,+ file,+ sourceFile: snapshot.sourceFile || undefined,+ previewFile: snapshot.previewFile || undefined,+ previewMode: snapshot.previewMode || undefined,+ redelivered: true,+ };+}++function recordGenerationCheckpoint(event) {+ if (!event?.id || event.type !== 'checkpoint') return;+ if (generationIsFenced(event.id)) return;+ // Only checkpoints that report a change in variant availability are+ // generation progress. The browser also checkpoints for durability on Tune+ // slider drags, resumes, and anchor recovery; treating those as progress+ // echoed `variant_progress` straight back to the browser that sent it, which+ // remounts the component preview mid-drag (reverting the user's live param+ // edit and detaching the popover's element), and permanently latched the+ // *_reviewable phases from the wrong trigger, corrupting generation timings.+ if (!VARIANT_PROGRESS_CHECKPOINT_REASONS.has(event.reason)) return;+ const arrived = Number(event.arrivedVariants) || 0;+ const expected = Number(event.expectedVariants) || 0;+ if (arrived <= 0 || expected <= 0) return;+ const previewMode = event.previewMode || 'source';+ const previewFile = event.previewFile || event.file;+ if (previewFile) {+ broadcast({+ type: 'variant_progress',+ id: event.id,+ file: previewFile,+ sourceFile: event.sourceFile || (previewMode === 'source' ? previewFile : undefined),+ previewFile,+ previewMode,+ arrivedVariants: arrived,+ expectedVariants: expected,+ publicationKind: event.publicationKind || 'variants',+ });+ }+ const details = {+ arrivedVariants: arrived,+ expectedVariants: expected,+ checkpointReason: event.reason || null,+ };+ const at = Date.now();+ if (!generationPhaseAlreadyRecorded(event.id, 'first_reviewable')) {+ recordAgentPhase(event.id, 'first_reviewable', { ...details, at });+ }+ if (arrived >= 2 && expected >= 3 && !generationPhaseAlreadyRecorded(event.id, 'second_reviewable')) {+ recordAgentPhase(event.id, 'second_reviewable', { ...details, at });+ }+ if (arrived >= expected && !generationPhaseAlreadyRecorded(event.id, 'all_variants_ready')) {+ recordAgentPhase(event.id, 'all_variants_ready', { ...details, at });+ }+}++function generationIsFenced(id) {+ if (!state.sessionStore || !id) return false;+ try {+ const snapshot = state.sessionStore.getSnapshot(id, { includeCompleted: true });+ return snapshot?.generationCanceled === true;+ } catch {+ return false;+ }+}++function generationPhaseAlreadyRecorded(id, phase) {+ if (!state.sessionStore) return false;+ try {+ const snapshot = state.sessionStore.getSnapshot(id, { includeCompleted: true });+ return !!snapshot?.generationTimings?.[phase];+ } catch {+ return false;+ }+}++function acknowledgePendingEvent(id, sourceEventType) {if (!id) return false;- const idx = state.pendingEvents.findIndex((entry) => entry.event?.id === id);+ const idx = state.pendingEvents.findIndex((entry) => (+ entry.event?.id === id+ && (!sourceEventType || entry.event?.type === sourceEventType)+ ));if (idx === -1) return false;const acknowledged = state.pendingEvents[idx].event;state.pendingEvents.splice(idx, 1);@@ -187,9 +370,39 @@ function acknowledgePendingEvent(id) {return acknowledged;}-function findPendingEventById(id) {+function releasePendingEvent(id, sourceEventType) {+ const entry = state.pendingEvents.find((item) => (+ item.event?.id === id+ && (!sourceEventType || item.event?.type === sourceEventType)+ ));+ if (!entry) return null;+ entry.leaseUntil = 0;+ scheduleLeaseFlush();+ return entry.event;+}++function retirePendingGeneration(id) {+ if (!id) return 0;+ let retired = 0;+ for (let index = state.pendingEvents.length - 1; index >= 0; index -= 1) {+ const event = state.pendingEvents[index]?.event;+ if (event?.id !== id || event.type !== 'generate') continue;+ state.pendingEvents.splice(index, 1);+ retired += 1;+ }+ if (retired > 0) {+ scheduleLeaseFlush();+ broadcastAgentPollingIfChanged();+ }+ return retired;+}++function findPendingEventById(id, sourceEventType) {if (!id) return null;- const entry = state.pendingEvents.find((item) => item.event?.id === id);+ const entry = state.pendingEvents.find((item) => (+ item.event?.id === id+ && (!sourceEventType || item.event?.type === sourceEventType)+ ));return entry?.event || null;}@@ -198,7 +411,7 @@ function summarizePendingEventForStatus(entry) {const summary = {id: event.id,type: event.type,- leased: !!(entry.leaseUntil && entry.leaseUntil > Date.now()),+ leased: isLeased(entry),leaseUntil: entry.leaseUntil || null,};if (event.type === 'manual_edit_apply') {@@ -224,7 +437,13 @@ function summarizeActiveSessionForClient(snapshot = {}) {arrivedVariants: snapshot.arrivedVariants ?? 0,visibleVariant: snapshot.visibleVariant ?? null,checkpointRevision: snapshot.checkpointRevision ?? 0,+ browserCheckpointRevision: snapshot.browserCheckpointRevision ?? snapshot.checkpointRevision ?? 0,+ publicationCheckpointRevision: snapshot.publicationCheckpointRevision ?? 0,paramValues: snapshot.paramValues || {},+ generationPhase: snapshot.generationPhase ?? null,+ generationCompletedAt: snapshot.generationCompletedAt ?? null,+ generationCanceled: snapshot.generationCanceled === true,+ cancelReason: snapshot.cancelReason ?? null,};}@@ -269,24 +488,46 @@ function scheduleLeaseFlush() {function flushPendingPolls() {let changed = false;while (state.pendingPolls.length > 0) {- const entry = findAvailablePendingEvent();+ let pollIndex = -1;+ let entry = null;+ for (let index = 0; index < state.pendingPolls.length; index += 1) {+ const candidate = findAvailablePendingEvent(Date.now(), state.pendingPolls[index].types);+ if (!candidate) continue;+ pollIndex = index;+ entry = candidate;+ break;+ }if (!entry) {scheduleLeaseFlush();broadcastAgentPollingIfChanged();return;}- const poll = state.pendingPolls.shift();- poll.resolve(leaseEvent(entry, poll.leaseMs));+ const [poll] = state.pendingPolls.splice(pollIndex, 1);+ // leaseEvent is async (it may scaffold source), but it claims the entry+ // synchronously, so the next loop iteration will not re-select it. Resolve+ // the poll when the lease settles rather than awaiting here, so one slow+ // scaffold never delays the other parked polls. On the exceptional failure+ // path, answer `timeout` so the agent re-polls; the claim stays until the+ // lease expires, which keeps a deterministic failure from hot-looping.+ leaseEvent(entry, poll.leaseMs).then(poll.resolve, (error) => {+ console.error('[live] lease failed for ' + (entry.event?.id || 'unknown') + ': ' + (error?.message || error));+ poll.resolve({ type: 'timeout' });+ });changed = true;}scheduleLeaseFlush();if (changed) broadcastAgentPollingIfChanged();}+function isLeased(entry) {+ return !!(entry?.leaseUntil && entry.leaseUntil > Date.now());+}+function agentPollingConnected() {- const now = Date.now();- return state.pendingPolls.length > 0- || state.pendingEvents.some((entry) => entry.leaseUntil && entry.leaseUntil > now);+ // A leased event only proves that a poll returned once. The foreground task+ // may have ended immediately afterward, so only an actively waiting poll is+ // evidence that steering can wake the task right now.+ return state.pendingPolls.length > 0;}function broadcastAgentPollingIfChanged() {@@ -689,6 +930,16 @@ function createRequestHandler({ detectScript, liveScriptParts }) {res.end(JSON.stringify({ error }));return;}+ if (msg.type === 'agent_phase') {+ recordAgentPhase(msg.id, msg.phase, {+ ...(Number.isFinite(msg.durationMs) ? { durationMs: msg.durationMs } : {}),+ owner: typeof msg.owner === 'string' ? msg.owner : undefined,+ });+ res.writeHead(200, { 'Content-Type': 'application/json' });+ res.end(JSON.stringify({ ok: true }));+ return;+ }+ const missedCompletion = detectMissedGenerationCompletion(msg);if (state.sessionStore && msg.id) {try {state.sessionStore.appendEvent(msg);@@ -698,6 +949,11 @@ function createRequestHandler({ detectScript, liveScriptParts }) {return;}}+ if (msg.type === 'accept' || msg.type === 'discard') {+ retirePendingGeneration(msg.id);+ }+ recordGenerationCheckpoint(msg);+ if (missedCompletion) broadcast(missedCompletion);if (msg.type === 'exit') {cleanupSvelteComponentSessionsBeforeExit();}@@ -738,6 +994,12 @@ function createRequestHandler({ detectScript, liveScriptParts }) {// Agent poll endpoints (unchanged from WS version)// ---------------------------------------------------------------------------+function parsePollTypes(value) {+ if (!value) return null;+ const types = String(value).split(',').map((type) => type.trim()).filter(Boolean);+ return types.length > 0 ? new Set(types) : null;+}+function handlePollGet(req, res, url) {const token = url.searchParams.get('token');if (token !== state.token) {@@ -748,13 +1010,25 @@ function handlePollGet(req, res, url) {state.lastPollAt = Date.now();const timeout = parseInt(url.searchParams.get('timeout') || DEFAULT_POLL_TIMEOUT, 10);const leaseMs = parseInt(url.searchParams.get('leaseMs') || '30000', 10);- const available = findAvailablePendingEvent();+ const types = parsePollTypes(url.searchParams.get('types'));+ const available = findAvailablePendingEvent(Date.now(), types);if (available) {- res.writeHead(200, { 'Content-Type': 'application/json' });- res.end(JSON.stringify(leaseEvent(available, leaseMs)));+ // Do not await inline: leaseEvent may scaffold source, and this handler runs+ // on the server's only thread. The client can disconnect during that window,+ // so check the socket before replying.+ leaseEvent(available, leaseMs).then((event) => {+ if (res.writableEnded || res.destroyed) return;+ res.writeHead(200, { 'Content-Type': 'application/json' });+ res.end(JSON.stringify(event));+ }, (error) => {+ console.error('[live] lease failed for ' + (available.event?.id || 'unknown') + ': ' + (error?.message || error));+ if (res.writableEnded || res.destroyed) return;+ res.writeHead(200, { 'Content-Type': 'application/json' });+ res.end(JSON.stringify({ type: 'timeout' }));+ });return;}- const poll = { resolve, leaseMs };+ const poll = { resolve, leaseMs, types };const timer = setTimeout(() => {const idx = state.pendingPolls.indexOf(poll);if (idx !== -1) state.pendingPolls.splice(idx, 1);@@ -783,12 +1057,15 @@ function sessionFileMetadataFromPollReply(file) {if (!file || typeof file !== 'string') return { file };const normalized = file.split(path.sep).join('/');const base = { file: normalized };- if (!normalized.endsWith('/manifest.json') && normalized !== 'manifest.json') return base;- if (!normalized.includes('node_modules/.impeccable-live/') && !normalized.includes('src/lib/impeccable/')) return base;+ const metadataFile = normalized;+ if (!metadataFile.endsWith('/manifest.json') && metadataFile !== 'manifest.json') return base;+ if (!metadataFile.includes('node_modules/.impeccable-live/')+ && !metadataFile.includes('src/lib/impeccable/')+ && !metadataFile.includes('/.impeccable-live/')) return base;let full;try {- full = path.resolve(process.cwd(), normalized);+ full = path.resolve(process.cwd(), metadataFile);const rel = path.relative(process.cwd(), full);if (!rel || rel.startsWith('..') || path.isAbsolute(rel)) return base;} catch {@@ -797,18 +1074,47 @@ function sessionFileMetadataFromPollReply(file) {try {const manifest = JSON.parse(fs.readFileSync(full, 'utf-8'));- if (manifest?.previewMode !== 'svelte-component' || !manifest.sourceFile) return base;+ if (manifest?.previewMode !== 'svelte-component'+ || !manifest.sourceFile) return base;return {file: String(manifest.sourceFile).split(path.sep).join('/'),sourceFile: String(manifest.sourceFile).split(path.sep).join('/'),previewFile: normalized,- previewMode: 'svelte-component',+ previewMode: manifest.previewMode,};} catch {return base;}}+function inferSourceEventType(msg = {}, pendingEvents = state.pendingEvents) {+ const entriesForId = pendingEvents.filter((entry) => entry.event?.id === msg.id);+ const pendingTypes = new Set(entriesForId.map((entry) => entry.event?.type));+ if (msg.type === 'discarded' || msg.type === 'discard') return 'discard';+ if (msg.type === 'complete') {+ if (pendingTypes.has('carbonize_cleanup')) return 'carbonize_cleanup';+ return pendingTypes.has('accept') ? 'accept' : (pendingTypes.has('generate') ? 'generate' : undefined);+ }+ if (msg.type === 'steer_done') return 'steer';+ // `agent_done` can be the automatic acknowledgement for a carbonize Accept.+ // New pollers send sourceEventType explicitly; default to generate only for+ // older callers so a late worker cannot acknowledge a queued Accept.+ if (msg.type === 'agent_done' || msg.type === 'done') return 'generate';+ // `error` is reference/live.md's documented failure reply, and parseReplyArgs+ // never sets sourceEventType on it (the poller is a fresh process that cannot+ // know what it leased). Returning undefined here makes acknowledgePendingEvent+ // match *any* event for this id: a stale generate worker's failure silently+ // consumed the user's queued Accept, which was then never delivered to any+ // agent and left the browser in SAVING forever. Attribute the failure to the+ // event this agent actually holds a lease on, and otherwise to `generate` —+ // never to a wildcard. If that generate was already retired by an Accept, the+ // ack simply finds no match, which is the correct outcome for a stale reply.+ if (msg.type === 'error') {+ return entriesForId.find(isLeased)?.event?.type || 'generate';+ }+ return undefined;+}+function handlePollPost(req, res) {let body = '';req.on('data', (c) => { body += c; });@@ -869,7 +1175,23 @@ function handlePollPost(req, res) {res.end(JSON.stringify({ error: 'stale_manual_edit_apply_reply', ...rollback }));return;}- const pendingEventBeforeAck = findPendingEventById(msg.id);+ const sourceEventType = msg.sourceEventType || inferSourceEventType(msg);+ if (msg.type === 'retry') {+ const releasedEvent = releasePendingEvent(msg.id, sourceEventType);+ if (!releasedEvent) {+ res.writeHead(msg.id ? 404 : 400, { 'Content-Type': 'application/json' });+ res.end(JSON.stringify({+ error: msg.id ? 'unknown_poll_retry_id' : 'missing_poll_retry_id',+ id: msg.id,+ }));+ return;+ }+ flushPendingPolls();+ res.writeHead(200, { 'Content-Type': 'application/json' });+ res.end(JSON.stringify({ ok: true, released: true }));+ return;+ }+ const pendingEventBeforeAck = findPendingEventById(msg.id, sourceEventType);if (pendingEventBeforeAck?.type === 'steer' && msg.type === 'steer_done'&& !msg.file && !(typeof msg.message === 'string' && msg.message.trim())) {res.writeHead(400, { 'Content-Type': 'application/json' });@@ -879,7 +1201,7 @@ function handlePollPost(req, res) {}));return;}- const acknowledgedEvent = acknowledgePendingEvent(msg.id);+ const acknowledgedEvent = acknowledgePendingEvent(msg.id, sourceEventType);let skipJournalReply = false;let existingSession = null;if (!acknowledgedEvent && state.sessionStore && msg.id) {@@ -1083,7 +1405,10 @@ if (args.includes('--background')) {process.exit(0);}} catch { /* not ready yet */ }- await new Promise(r => setTimeout(r, 200));+ // The detached child is typically listening in 35-45ms. A 200ms polling+ // floor dominated configured cold Live startup; poll cheaply and return+ // as soon as the child has written its ready record.+ await new Promise(r => setTimeout(r, 5));}console.error('Timed out waiting for live server to start.');process.exit(1);diff --git a/.gemini/skills/impeccable/scripts/live-status.mjs b/.gemini/skills/impeccable/scripts/live-status.mjsindex f7e464999..dc98b7386 100644--- a/.gemini/skills/impeccable/scripts/live-status.mjs+++ b/.gemini/skills/impeccable/scripts/live-status.mjs@@ -37,15 +37,19 @@ export async function statusCli() {pendingEvents: server.pendingEvents,} : null,activeSessions: server?.activeSessions || activeSessions,- recoveryHint: manualApply- ? manualApplyResumeHint(manualApply)- : server- ? 'Run live-poll.mjs to continue pending work, or live-complete.mjs --id <session> after manual cleanup.'- : 'Start live-server.mjs to requeue pending durable events, then run live-poll.mjs.',+ recoveryHint: recoveryHint({ server, manualApply }),};console.log(JSON.stringify(payload, null, 2));}+function recoveryHint({ server, manualApply }) {+ if (manualApply) return manualApplyResumeHint(manualApply);+ if (server) {+ return 'Run live-poll.mjs to continue pending work, or live-complete.mjs --id <session> after manual cleanup.';+ }+ return 'Start live-server.mjs to requeue pending durable events, then run live-poll.mjs.';+}+function findPendingManualApply(server, activeSessions) {const fromServer = server?.pendingEvents?.find((event) => event?.type === 'manual_edit_apply');if (fromServer) return fromServer;diff --git a/.gemini/skills/impeccable/scripts/live-wrap.mjs b/.gemini/skills/impeccable/scripts/live-wrap.mjsindex 438c01b68..48d7f7683 100644--- a/.gemini/skills/impeccable/scripts/live-wrap.mjs+++ b/.gemini/skills/impeccable/scripts/live-wrap.mjs@@ -160,11 +160,29 @@ The agent should insert variant HTML at insertLine.`);if (filtered.length === 1) {match = filtered[0];} else if (filtered.length === 0) {- // Source uses dynamic content (`<h1>{title}</h1>` etc.) so the- // browser-side textContent doesn't appear literally in source. Fall- // back to first-match rather than refusing — this is the same- // behavior unmodified callers see, just preserved.- match = candidates[0];+ const normalizedText = String(text).replace(/\s+/g, ' ').trim();+ if (normalizedText.length < 8) {+ // Very short labels cannot disambiguate siblings reliably. Preserve+ // the legacy behavior for these low-information picker events.+ match = candidates[0];+ } else {+ // Rendered text that is absent from every candidate usually means+ // the source uses expressions or component props. Picking the first+ // same-class sibling silently edits the wrong instance (observed on+ // Astro result cards), so stop and surface every candidate instead.+ console.error(JSON.stringify({+ error: 'element_ambiguous',+ fallback: 'agent-driven',+ reason: 'rendered_text_not_in_source',+ file: path.relative(process.cwd(), targetFile),+ candidates: candidates.map((c) => ({+ startLine: c.startLine + 1,+ endLine: c.endLine + 1,+ })),+ hint: 'Rendered text does not occur in any matching source branch. The element may use dynamic props or expressions; inspect the candidates and wrap the intended instance manually.',+ }));+ process.exit(1);+ }} else {// Multiple candidates ALSO match the text. Truly ambiguous — refuse// rather than pick wrong, and hand the agent the candidate locations@@ -269,6 +287,7 @@ The agent should insert variant HTML at insertLine.`);const originalIndented = reindentOriginal(' ');const relTargetFile = path.relative(process.cwd(), targetFile).split(path.sep).join('/');const useSvelteComponent = shouldUseSvelteComponentInjection(targetFile);+ const useFrameworkComponent = useSvelteComponent;// Wrapper attributes differ by syntax. HTML allows plain string attrs;// JSX requires object-literal style and parses string attrs as HTML (which@@ -288,7 +307,7 @@ The agent should insert variant HTML at insertLine.`);// replacement range to include the wrapper's `<div>` open / close lines// so the entire scaffold gets removed cleanly.const wrapperLines = isJsx ? [- indent + '<div data-impeccable-variants="' + id + '" data-impeccable-variant-count="' + count + '" ' + styleContents + '>',+ indent + '<div data-impeccable-variants="' + id + '" data-impeccable-variant-count="' + count + '"' + ' ' + styleContents + '>',indent + ' ' + commentSyntax.open + ' impeccable-variants-start ' + id + ' ' + commentSyntax.close,indent + ' ' + commentSyntax.open + ' Original ' + commentSyntax.close,indent + ' <div data-impeccable-variant="original">',@@ -299,7 +318,7 @@ The agent should insert variant HTML at insertLine.`);indent + '</div>',] : [indent + commentSyntax.open + ' impeccable-variants-start ' + id + ' ' + commentSyntax.close,- indent + '<div data-impeccable-variants="' + id + '" data-impeccable-variant-count="' + count + '" ' + styleContents + '>',+ indent + '<div data-impeccable-variants="' + id + '" data-impeccable-variant-count="' + count + '"' + ' ' + styleContents + '>',indent + ' ' + commentSyntax.open + ' Original ' + commentSyntax.close,indent + ' <div data-impeccable-variant="original">',originalIndented,@@ -356,15 +375,18 @@ The agent should insert variant HTML at insertLine.`);const outputRelFile = path.relative(process.cwd(), outputFile).split(path.sep).join('/');const svelteComponentAuthoring = useSvelteComponent ? buildSvelteComponentCssAuthoring(count) : null;+ const componentSession = svelteSession;+ const componentPreviewMode = useSvelteComponent ? 'svelte-component' : undefined;+ const previewMode = componentPreviewMode;console.log(JSON.stringify({file: outputRelFile,- sourceFile: useSvelteComponent ? relTargetFile : undefined,- previewMode: useSvelteComponent ? 'svelte-component' : undefined,- componentDir: svelteSession?.componentDir,- propContract: svelteSession?.propContract,- sourceStartLine: useSvelteComponent ? startLine + 1 : undefined,- sourceEndLine: useSvelteComponent ? endLine + 1 : undefined,+ sourceFile: useFrameworkComponent ? relTargetFile : undefined,+ previewMode,+ componentDir: componentSession?.componentDir,+ propContract: componentSession?.propContract,+ sourceStartLine: useFrameworkComponent ? startLine + 1 : undefined,+ sourceEndLine: useFrameworkComponent ? endLine + 1 : undefined,startLine: outputStartLine, // 1-indexed for the agent// wrapperLines is an array but one element (the original-content slot)// is a `\n`-joined multi-line string, so the actual file-row count is@@ -374,10 +396,10 @@ The agent should insert variant HTML at insertLine.`);endLine: outputEndLine, // 1-indexedinsertLine, // 1-indexed: where variants gocommentSyntax: commentSyntax,- styleMode: useSvelteComponent ? 'svelte-component' : styleMode.mode,- styleTag: useSvelteComponent ? null : styleMode.styleTag,- cssSelectorPrefixExamples: useSvelteComponent ? [] : buildCssSelectorPrefixExamples(styleMode.mode, count),- cssAuthoring: useSvelteComponent ? svelteComponentAuthoring : buildCssAuthoring(styleMode, count),+ styleMode: componentPreviewMode || styleMode.mode,+ styleTag: useFrameworkComponent ? null : styleMode.styleTag,+ cssSelectorPrefixExamples: useFrameworkComponent ? [] : buildCssSelectorPrefixExamples(styleMode.mode, count),+ cssAuthoring: svelteComponentAuthoring || buildCssAuthoring(styleMode, count),originalLineCount: originalLines.length,}));}diff --git a/.gemini/skills/impeccable/scripts/live.mjs b/.gemini/skills/impeccable/scripts/live.mjsindex e0bd1ad24..b21a71cc4 100644--- a/.gemini/skills/impeccable/scripts/live.mjs+++ b/.gemini/skills/impeccable/scripts/live.mjs@@ -10,7 +10,7 @@** After this, the agent's only remaining steps are:* - Open the project's live dev/preview URL in the browser (optional, if browser automation exists)—not `serverPort`; that port is the Impeccable helper for /live.js and /poll- * - Enter the poll loop: `node live-poll.mjs`+ * - Enter the harness-native poll loop: `node live-poll.mjs`** Usage:* node live.mjs # Prepare everything, print JSON, exit@@ -40,6 +40,7 @@ Prepare everything for live variant mode in a single command:- Starts (or reuses) the live server in the background- Injects the browser script tag- Reads PRODUCT.md / DESIGN.md for project context+ - Prepares the harness-native foreground/background poll loop- In monorepos, choose a child app first; --target <path> is the fallback/manual pathOn success, prints a JSON blob with:diff --git a/.gemini/skills/impeccable/scripts/live/completion.mjs b/.gemini/skills/impeccable/scripts/live/completion.mjsindex 986773066..6f539336d 100644--- a/.gemini/skills/impeccable/scripts/live/completion.mjs+++ b/.gemini/skills/impeccable/scripts/live/completion.mjs@@ -1,9 +1,18 @@+// A preview whose variants live in component modules rather than in the user's+// source. These leave no markers in the real file, so a failed accept gives the+// agent nothing to hand-edit and must be reported as a failure rather than+// reference/live.md's manual-cleanup handoff. Kept as a set: any future+// component-module preview mode belongs here the day it lands.+const PREVIEW_MODES_WITHOUT_SOURCE_MARKERS = new Set([+ 'svelte-component',+]);+export function completionTypeForAcceptResult(eventType, acceptResult) {if (eventType === 'discard') return acceptResult?.handled === true ? 'discarded' : 'error';if (acceptResult?.handled === true && acceptResult?.carbonize === true) return 'agent_done';if (acceptResult?.handled === true) return 'complete';if (acceptResult?.mode === 'error') return 'error';- if (eventType === 'accept' && acceptResult?.previewMode === 'svelte-component') return 'error';+ if (eventType === 'accept' && PREVIEW_MODES_WITHOUT_SOURCE_MARKERS.has(acceptResult?.previewMode)) return 'error';return 'agent_done';}diff --git a/.gemini/skills/impeccable/scripts/live/event-validation.mjs b/.gemini/skills/impeccable/scripts/live/event-validation.mjsindex 0897b1317..122c29836 100644--- a/.gemini/skills/impeccable/scripts/live/event-validation.mjs+++ b/.gemini/skills/impeccable/scripts/live/event-validation.mjs@@ -118,6 +118,15 @@ export function validateEvent(msg) {return 'checkpoint: paramValues must be an object';}return null;+ case 'agent_phase':+ if (!isValidId(msg.id)) return 'agent_phase: missing or malformed id';+ if (typeof msg.phase !== 'string' || !/^[a-z][a-z0-9_]{1,63}$/.test(msg.phase)) {+ return 'agent_phase: missing or malformed phase';+ }+ if (msg.durationMs !== undefined && (!Number.isFinite(msg.durationMs) || msg.durationMs < 0)) {+ return 'agent_phase: durationMs must be a non-negative number';+ }+ return null;case 'exit':return null;case 'prefetch':@@ -131,6 +140,12 @@ export function validateEvent(msg) {if (msg.message.length > 4000) return 'steer: message too long';if (msg.pageUrl !== undefined && typeof msg.pageUrl !== 'string') return 'steer: pageUrl must be string';return null;+ case 'carbonize_cleanup':+ if (!isValidId(msg.id)) return 'carbonize_cleanup: missing or malformed id';+ if (!isValidId(msg.sessionId)) return 'carbonize_cleanup: missing or malformed sessionId';+ if (!msg.file || typeof msg.file !== 'string') return 'carbonize_cleanup: missing file';+ if (!isValidVariantId(String(msg.variantId))) return 'carbonize_cleanup: missing or malformed variantId';+ return null;default:return 'Unknown event type: ' + msg.type;}diff --git a/.gemini/skills/impeccable/scripts/live/generation-preflight.mjs b/.gemini/skills/impeccable/scripts/live/generation-preflight.mjsnew file mode 100644index 000000000..07a5e957e--- /dev/null+++ b/.gemini/skills/impeccable/scripts/live/generation-preflight.mjs@@ -0,0 +1,102 @@+import { execFile } from 'node:child_process';+import path from 'node:path';+import { promisify } from 'node:util';++const execFileAsync = promisify(execFile);+const PREFLIGHT_TIMEOUT_MS = 15_000;++export function buildGenerationPreflight(event, scriptsDir) {+ if (!event || event.type !== 'generate' || !event.id) return null;++ const isInsert = event.mode === 'insert';+ const target = isInsert ? insertTarget(event) : replaceTarget(event);+ if (!target.elementId && !target.classes) return null;++ const script = path.join(scriptsDir, isInsert ? 'live-insert.mjs' : 'live-wrap.mjs');+ const args = [script, '--id', event.id, '--count', String(event.count || 3)];+ if (isInsert) args.push('--position', target.position);+ if (target.elementId) args.push('--element-id', target.elementId);+ if (target.classes) args.push('--classes', target.classes);+ if (target.tag) args.push('--tag', target.tag);+ if (target.text) args.push('--text', target.text);+ if (!isInsert && event.pageUrl) args.push('--page-url', event.pageUrl);+ return { script, args, mode: isInsert ? 'insert' : 'replace' };+}++/**+ * Scaffold the source for a generate event before handing it to an agent.+ *+ * Async on purpose. This spawns `live-wrap.mjs`, which walks the project's+ * source tree and can take seconds (measured at ~7.6s on a large repo when the+ * element is not found, with a 15s ceiling). The live server is single-threaded+ * and calls this while leasing a poll, so a synchronous spawn froze the whole+ * server for that entire window: Accept and Discard POSTs, SSE progress+ * broadcasts, and every other poll stalled behind it.+ */+export async function runGenerationPreflight(event, {+ cwd = process.cwd(),+ scriptsDir,+ execFileImpl = execFileAsync,+ timeoutMs = PREFLIGHT_TIMEOUT_MS,+} = {}) {+ const command = buildGenerationPreflight(event, scriptsDir);+ if (!command) {+ return { ok: false, skipped: true, reason: 'insufficient_locator' };+ }++ const startedAt = performance.now();+ try {+ const { stdout } = await execFileImpl(process.execPath, command.args, {+ cwd,+ encoding: 'utf-8',+ timeout: timeoutMs,+ });+ const line = String(stdout).trim().split('\n').filter(Boolean).pop();+ if (!line) throw new Error('preflight returned no scaffold metadata');+ return {+ ok: true,+ mode: command.mode,+ durationMs: performance.now() - startedAt,+ scaffold: JSON.parse(line),+ };+ } catch (error) {+ return {+ ok: false,+ mode: command.mode,+ durationMs: performance.now() - startedAt,+ error: compactError(error),+ };+ }+}++function replaceTarget(event) {+ return normalizeTarget(event.element || {});+}++function insertTarget(event) {+ return {+ ...normalizeTarget(event.insert?.anchor || {}),+ position: event.insert?.position === 'before' ? 'before' : 'after',+ };+}++function normalizeTarget(target) {+ const classes = Array.isArray(target.classes)+ ? target.classes.join(' ')+ : String(target.classes || '').trim();+ const text = typeof target.textContent === 'string'+ ? target.textContent.trim().slice(0, 80)+ : '';+ return {+ elementId: target.id || target.elementId || undefined,+ classes: classes || undefined,+ tag: target.tagName || target.tag || undefined,+ text: text || undefined,+ };+}++function compactError(error) {+ const stderr = error?.stderr ? String(error.stderr).trim() : '';+ const message = stderr.split('\n').filter(Boolean).pop() || error?.message || 'preflight failed';+ return String(message).slice(0, 500);+}diff --git a/.gemini/skills/impeccable/scripts/live/poll-lanes.mjs b/.gemini/skills/impeccable/scripts/live/poll-lanes.mjsnew file mode 100644index 000000000..65f20a87a--- /dev/null+++ b/.gemini/skills/impeccable/scripts/live/poll-lanes.mjs@@ -0,0 +1,14 @@+export function eventPriority(event = {}) {+ if (event.type === 'accept' || event.type === 'discard' || event.type === 'exit') return 0;+ if (event.type === 'manual_edit_apply' || event.type === 'steer' || event.type === 'carbonize_cleanup') return 1;+ if (event.type === 'generate') return 2;+ return 3;+}++export function selectAvailablePendingEvent(entries, { now = Date.now(), types = null } = {}) {+ const allowed = types instanceof Set ? types : (Array.isArray(types) ? new Set(types) : null);+ return entries+ .filter((entry) => !(entry.leaseUntil && entry.leaseUntil > now))+ .filter((entry) => !allowed || allowed.has(entry.event?.type))+ .sort((a, b) => eventPriority(a.event) - eventPriority(b.event) || a.seq - b.seq)[0] || null;+}diff --git a/.gemini/skills/impeccable/scripts/live/session-store.mjs b/.gemini/skills/impeccable/scripts/live/session-store.mjsindex affba67c9..9d20341dd 100644--- a/.gemini/skills/impeccable/scripts/live/session-store.mjs+++ b/.gemini/skills/impeccable/scripts/live/session-store.mjs@@ -1,24 +1,26 @@import fs from 'node:fs';import path from 'node:path';-import { getLegacyLiveSessionsDir, getLiveSessionsDir } from '../lib/impeccable-paths.mjs';+import { getLegacyLiveSessionsDir, getLiveSessionsDir, safeSessionId } from '../lib/impeccable-paths.mjs';const COMPLETED_PHASES = new Set(['completed', 'discarded']);+export const GENERATION_FENCED_PHASES = new Set([+ 'accept_requested',+ 'discard_requested',+ 'carbonize_required',+ 'completed',+ 'discarded',+]);export function createLiveSessionStore({ cwd = process.cwd(), sessionId } = {}) {const rootDir = getLiveSessionsDir(cwd);const legacyRootDir = getLegacyLiveSessionsDir(cwd);fs.mkdirSync(rootDir, { recursive: true });- const snapshotCache = new Map();-- function loadCachedOrRebuild(id) {- const cached = snapshotCache.get(id);- if (cached) return cached;- const journalPath = getReadableJournalPath(id);- const rebuilt = rebuildSnapshotFromJournal(journalPath, id);- snapshotCache.set(id, rebuilt);- return rebuilt;- }+ // No snapshot cache on purpose: appendEvent and getSnapshot both rebuild from+ // the journal so sequence numbers and phase fences never come from a stale+ // in-memory copy when the publisher/complete helpers append from another+ // process. A cache written but never read would grow per session for the+ // lifetime of the server without ever saving a rebuild.function getReadableJournalPath(id) {const primary = getJournalPath(rootDir, id);if (fs.existsSync(primary)) return primary;@@ -38,7 +40,10 @@ export function createLiveSessionStore({ cwd = process.cwd(), sessionId } = {})if (!fs.existsSync(journalPath) && fs.existsSync(legacyJournalPath)) {fs.copyFileSync(legacyJournalPath, journalPath);}- const prior = loadCachedOrRebuild(normalized.id);+ // Publisher/complete helpers can append from a separate process while+ // the server is alive. Rebuild here so sequence numbers and phase+ // fences never come from a stale in-memory cache.+ const prior = rebuildSnapshotFromJournal(getReadableJournalPath(normalized.id), normalized.id);const seq = prior.nextSeq;const entry = {seq,@@ -49,7 +54,6 @@ export function createLiveSessionStore({ cwd = process.cwd(), sessionId } = {})};fs.appendFileSync(journalPath, JSON.stringify(entry) + '\n');const next = applyEvent(prior.snapshot, entry, prior.diagnostics);- snapshotCache.set(normalized.id, { snapshot: next, diagnostics: next.diagnostics || [], nextSeq: seq + 1 });writeSnapshot(snapshotPath, next);return next;},@@ -58,7 +62,6 @@ export function createLiveSessionStore({ cwd = process.cwd(), sessionId } = {})const journalPath = getReadableJournalPath(id);const snapshotPath = getSnapshotPath(rootDir, id);const rebuilt = rebuildSnapshotFromJournal(journalPath, id);- snapshotCache.set(id, rebuilt);writeSnapshot(snapshotPath, rebuilt.snapshot);if (!opts.includeCompleted && COMPLETED_PHASES.has(rebuilt.snapshot.phase)) return null;return rebuilt.snapshot;@@ -95,11 +98,6 @@ function getSnapshotPath(rootDir, id) {return path.join(rootDir, safeSessionId(id) + '.snapshot.json');}-function safeSessionId(id) {- if (!/^[A-Za-z0-9_-]{1,128}$/.test(id)) throw new Error('invalid session id: ' + id);- return id;-}-function baseSnapshot(id) {return {id,@@ -116,9 +114,18 @@ function baseSnapshot(id) {pendingEvent: null,deliveryLease: null,checkpointRevision: 0,+ browserCheckpointRevision: 0,+ publicationCheckpointRevision: 0,activeOwner: null,sourceMarkers: {},fallbackMode: null,+ generationPhase: null,+ generationCompletedAt: null,+ generationTimings: {},+ variantPlan: null,+ generationCanceled: false,+ generationCanceledAt: null,+ cancelReason: null,annotationArtifacts: [],diagnostics: [],updatedAt: null,@@ -158,6 +165,8 @@ function applyEvent(snapshot, entry, inheritedDiagnostics = []) {...snapshot,paramValues: { ...(snapshot.paramValues || {}) },sourceMarkers: { ...(snapshot.sourceMarkers || {}) },+ generationTimings: { ...(snapshot.generationTimings || {}) },+ variantPlan: snapshot.variantPlan || null,annotationArtifacts: [...(snapshot.annotationArtifacts || [])],diagnostics: [...(snapshot.diagnostics || [])],updatedAt: entry.ts || new Date().toISOString(),@@ -174,11 +183,48 @@ function applyEvent(snapshot, entry, inheritedDiagnostics = []) {next.expectedVariants = event.count ?? next.expectedVariants;next.pendingEventSeq = entry.seq ?? next.pendingEventSeq;next.pendingEvent = toPendingEvent(event);+ next.variantPlan = null;if (event.screenshotPath) upsertArtifact(next.annotationArtifacts, { type: 'screenshot', path: event.screenshotPath });break;+ case 'variant_plan':+ if (!next.generationCanceled && !GENERATION_FENCED_PHASES.has(next.phase)) {+ next.variantPlan = event.plan ?? next.variantPlan;+ }+ break;+ case 'detector_waivers':+ if (!next.generationCanceled && !GENERATION_FENCED_PHASES.has(next.phase)) {+ next.detectorWaivers = [+ ...(next.detectorWaivers || []),+ ...(Array.isArray(event.waivers) ? event.waivers : []),+ ];+ }+ break;+ case 'agent_phase':+ next.generationPhase = event.phase ?? next.generationPhase;+ if (event.phase) {+ next.generationTimings[event.phase] = {+ at: event.at ?? (Date.parse(entry.ts || '') || null),+ durationMs: event.durationMs ?? null,+ };+ }+ break;case 'variants_ready':case 'agent_done':+ if ((next.generationCanceled || GENERATION_FENCED_PHASES.has(next.phase))+ && !(event.type === 'agent_done' && event.carbonize === true && next.phase === 'accept_requested')) {+ next.diagnostics.push({+ error: 'late_generation_event_ignored',+ type: event.type,+ phase: next.phase,+ });+ break;+ }next.phase = event.carbonize === true ? 'carbonize_required' : 'variants_ready';+ // Durable completion marker: later browser checkpoints (a resumed page+ // reporting phase "generating") regress `phase`, but generation staying+ // finished is monotone — the live server keys missed-`done` redelivery+ // on this field.+ next.generationCompletedAt = event.at ?? (Date.parse(entry.ts || '') || Date.now());next.sourceFile = event.sourceFile ?? event.file ?? next.sourceFile;next.previewFile = event.previewFile ?? next.previewFile;next.previewMode = event.previewMode ?? next.previewMode;@@ -194,27 +240,45 @@ function applyEvent(snapshot, entry, inheritedDiagnostics = []) {}break;case 'checkpoint':- if (COMPLETED_PHASES.has(next.phase)) {+ if (next.generationCanceled || GENERATION_FENCED_PHASES.has(next.phase)) {next.diagnostics.push({ error: 'checkpoint_after_terminal_ignored', phase: event.phase ?? null, revision: event.revision ?? null });break;}- if ((event.revision ?? 0) >= (next.checkpointRevision ?? 0)) {- next.phase = event.phase ?? next.phase;- next.checkpointRevision = event.revision ?? next.checkpointRevision;- next.activeOwner = event.owner ?? next.activeOwner;- next.arrivedVariants = event.arrivedVariants ?? next.arrivedVariants;- next.visibleVariant = event.visibleVariant ?? next.visibleVariant;- next.sourceFile = event.sourceFile ?? next.sourceFile;- next.previewFile = event.previewFile ?? next.previewFile;- next.previewMode = event.previewMode ?? next.previewMode;- if (event.paramValues) next.paramValues = { ...event.paramValues };- } else {- next.diagnostics.push({ error: 'stale_checkpoint_ignored', revision: event.revision });+ {+ const revisionDomain = event.revisionDomain === 'publication'+ || (event.reason === 'variants_progress' && !event.owner)+ ? 'publication'+ : 'browser';+ const revisionField = revisionDomain === 'publication'+ ? 'publicationCheckpointRevision'+ : 'browserCheckpointRevision';+ const currentRevision = next[revisionField]+ ?? (revisionDomain === 'browser' ? next.checkpointRevision : 0)+ ?? 0;+ if ((event.revision ?? 0) >= currentRevision) {+ next.phase = event.phase ?? next.phase;+ next[revisionField] = event.revision ?? currentRevision;+ if (revisionDomain === 'browser') {+ next.checkpointRevision = event.revision ?? next.checkpointRevision;+ next.activeOwner = event.owner ?? next.activeOwner;+ }+ next.arrivedVariants = event.arrivedVariants ?? next.arrivedVariants;+ if (revisionDomain === 'browser') next.visibleVariant = event.visibleVariant ?? next.visibleVariant;+ next.sourceFile = event.sourceFile ?? next.sourceFile;+ next.previewFile = event.previewFile ?? next.previewFile;+ next.previewMode = event.previewMode ?? next.previewMode;+ if (revisionDomain === 'browser' && event.paramValues) next.paramValues = { ...event.paramValues };+ } else {+ next.diagnostics.push({ error: 'stale_checkpoint_ignored', revision: event.revision, revisionDomain });+ }}break;case 'accept':case 'accept_intent':next.phase = 'accept_requested';+ next.generationCanceled = true;+ next.generationCanceledAt = event.at ?? (Date.parse(entry.ts || '') || Date.now());+ next.cancelReason = 'accept';next.visibleVariant = Number(event.variantId ?? next.visibleVariant);if (event.paramValues) next.paramValues = { ...event.paramValues };next.pendingEventSeq = entry.seq ?? next.pendingEventSeq;@@ -232,6 +296,12 @@ function applyEvent(snapshot, entry, inheritedDiagnostics = []) {next.pendingEventSeq = entry.seq ?? next.pendingEventSeq;next.pendingEvent = toPendingEvent(event);break;+ case 'carbonize_cleanup':+ next.phase = 'carbonize_cleanup_requested';+ next.sourceFile = event.file ?? next.sourceFile;+ next.pendingEventSeq = entry.seq ?? next.pendingEventSeq;+ next.pendingEvent = toPendingEvent(event);+ break;case 'steer_done':next.phase = 'steer_done';next.sourceFile = event.sourceFile ?? event.file ?? next.sourceFile;@@ -243,6 +313,9 @@ function applyEvent(snapshot, entry, inheritedDiagnostics = []) {break;case 'discard':next.phase = 'discard_requested';+ next.generationCanceled = true;+ next.generationCanceledAt = event.at ?? (Date.parse(entry.ts || '') || Date.now());+ next.cancelReason = 'discard';next.pendingEventSeq = entry.seq ?? next.pendingEventSeq;next.pendingEvent = toPendingEvent(event);break;@@ -260,6 +333,10 @@ function applyEvent(snapshot, entry, inheritedDiagnostics = []) {next.pendingEvent = null;break;case 'agent_error':+ if (next.generationCanceled && event.sourceEventType === 'generate') {+ next.diagnostics.push({ error: 'late_generation_event_ignored', type: event.type, phase: next.phase });+ break;+ }next.phase = 'agent_error';next.pendingEventSeq = null;next.pendingEvent = null;diff --git a/.gemini/skills/impeccable/scripts/live/source-lock.mjs b/.gemini/skills/impeccable/scripts/live/source-lock.mjsnew file mode 100644index 000000000..9ccc557be--- /dev/null+++ b/.gemini/skills/impeccable/scripts/live/source-lock.mjs@@ -0,0 +1,105 @@+import fs from 'node:fs';+import path from 'node:path';+import { createHash, randomUUID } from 'node:crypto';+import { getLiveDir, isLiveServerPidReachable } from '../lib/impeccable-paths.mjs';++// Only used to retire a lock whose contents we cannot read (empty or truncated+// by a crash mid-write). A readable lock's fate is decided by its owner's+// liveness instead, so a slow critical section is never swept.+const UNREADABLE_LOCK_STALE_MS = 60_000;++export function sourceLockPath(file, cwd = process.cwd()) {+ const digest = createHash('sha256').update(path.resolve(cwd, file)).digest('hex').slice(0, 24);+ return path.join(getLiveDir(cwd), 'locks', digest + '.lock');+}++export function withSourceLockSync(file, owner, fn, {+ cwd = process.cwd(),+ waitMs = 0,+ retryMs = 5,+} = {}) {+ const lockPath = sourceLockPath(file, cwd);+ fs.mkdirSync(path.dirname(lockPath), { recursive: true });+ const deadline = Date.now() + Math.max(0, Number(waitMs) || 0);+ // Identifies this acquisition specifically, so release can tell our own lock+ // from a replacement that some other writer created.+ const token = randomUUID();+ let acquired = false;++ while (!acquired) {+ clearStaleLock(lockPath);+ let fd;+ try {+ fd = fs.openSync(lockPath, 'wx');+ fs.writeFileSync(fd, JSON.stringify({+ owner,+ token,+ pid: process.pid,+ at: Date.now(),+ file: path.resolve(cwd, file),+ }) + '\n');+ acquired = true;+ } catch (error) {+ if (error?.code !== 'EEXIST') throw error;+ if (Date.now() >= deadline) {+ const locked = new Error('source_locked');+ locked.code = 'SOURCE_LOCKED';+ locked.lockPath = lockPath;+ throw locked;+ }+ sleepSync(Math.max(1, Math.min(Number(retryMs) || 5, deadline - Date.now())));+ } finally {+ try { if (fd !== undefined) fs.closeSync(fd); } catch {}+ }+ }++ try {+ return fn();+ } finally {+ releaseOwnLock(lockPath, token);+ }+}++function sleepSync(ms) {+ Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, ms);+}++function readLock(lockPath) {+ try { return JSON.parse(fs.readFileSync(lockPath, 'utf-8')); } catch { return null; }+}++/**+ * Remove the lock only if it is still the one this call created. If a sweeper+ * judged our lock stale and another writer replaced it, unlinking here would+ * end *their* critical section and admit a third writer to the same file.+ */+function releaseOwnLock(lockPath, token) {+ const held = readLock(lockPath);+ if (held && held.token !== token) return;+ try { fs.unlinkSync(lockPath); } catch {}+}++/**+ * A lock is stale when its owner is gone, not when it is old.+ *+ * Age alone cuts both ways: it sweeps a live holder whose critical section+ * outran the timeout (a suspended laptop, a stopped process), letting two+ * writers into the same source file, while still making every accept on a+ * crashed holder's file wait out the full timeout. Asking the OS whether the+ * recorded pid is alive answers both correctly: a dead owner releases at once,+ * and a live owner keeps its lock however long it needs.+ */+function clearStaleLock(lockPath) {+ const held = readLock(lockPath);+ if (!held) {+ // Unreadable: either a crash truncated it, or we caught the brief window+ // between create and write in a live acquisition. mtime distinguishes them.+ try {+ const stat = fs.statSync(lockPath);+ if (Date.now() - stat.mtimeMs > UNREADABLE_LOCK_STALE_MS) fs.unlinkSync(lockPath);+ } catch { /* gone already */ }+ return;+ }+ if (typeof held.pid === 'number' && isLiveServerPidReachable(held.pid)) return;+ try { fs.unlinkSync(lockPath); } catch {}+}diff --git a/.github/skills/impeccable/reference/live.md b/.github/skills/impeccable/reference/live.mdindex 854ff85da..522dc3839 100644--- a/.github/skills/impeccable/reference/live.md+++ b/.github/skills/impeccable/reference/live.md@@ -10,21 +10,24 @@ Execute in order. No step skipped, no step reordered.1. `live.mjs`: boot. If the request names or implies a file, route, or app inside a monorepo, infer the concrete path and run `node .github/skills/impeccable/scripts/live.mjs --target <path>` instead; then run the rest of this live session from the returned `projectRoot`.2. Open the app URL that serves `pageFile` (infer from `package.json`, docs, terminal output, or an open tab). Never use `serverPort`; it's the helper, not the app. **Cursor:** `browser_navigate` to that URL before polling; do not skip. **Other harnesses:** use the available browser tool; if the URL is uncertain, ask the user once.-3. Poll loop with the default long timeout (600000 ms). After every event or `--reply`, run `live-poll.mjs` again immediately. Never pass a short `--timeout=`.+3. Poll loop with the default long timeout (600000 ms). Run `live-poll.mjs` again immediately after every event or `--reply`; Codex runs this one-shot poll in the foreground. Never pass a short `--timeout=`.The global bar **Impeccable mark** dims and shows a pulsing amber dot when no agent is long-polling `/poll`. Hover the mark for the hint; restart `live-poll.mjs` to reconnect.-4. On `generate`: read screenshot if present; load the action's reference; plan three distinct directions; write all variants in one edit; `--reply done`; poll again.+4. On `generate`: reuse `event.scaffold` when present; read the screenshot if present; load the action's reference; deliver variants using the delivery policy below; `--reply done`; poll again. Generate in this thread. You already hold the project's tokens, conventions, and file layout; that context is the job, not overhead.5. On `steer`: read the message and `pageUrl`; do the work (page edits, navigation help, or a short reply in the `--reply` message); `--reply steer_done`; poll again. No pickup ack. The Steer bar unlocks when `steer_done` arrives over SSE.-6. On `accept` / `discard`: the poll script runs `live-accept.mjs`, acknowledges the delivered event, and prints `_completionAck`. Plain accepts/discards are terminal immediately; carbonize accepts remain recoverable until you finish cleanup, run `live-complete.mjs --id EVENT_ID`, and only then poll again.+6. On `accept` / `discard`: the poll script runs `live-accept.mjs`, acknowledges the delivered event, and prints `_completionAck`. Plain accepts/discards are terminal immediately. Carbonize accepts remain recoverable until the foreground task runs `live-complete.mjs --id EVENT_ID`; finish that cleanup before polling again.7. If interrupted, run `live-status.mjs` or `live-resume.mjs` before guessing. The durable journal replays unacknowledged work after helper restart.8. On `exit`: run the cleanup at the bottom.Harness policy:-- **Claude Code**: run the poll as a **background task** (no short timeout). The harness notifies you when it completes, so the main conversation stays free. Do not block the shell.+- **Claude Code**: run the poll as a **background task** (no short timeout). The harness notifies you when it completes, so the main conversation stays free while you generate and publish in it. Do not block the shell.- **Cursor**: run **one-shot** poll in a **background terminal** with notify on `"type":"(steer|generate|accept|discard|exit)"`. After each event the poll exits; handle it, `--reply`, then start `live-poll.mjs` again. Do **not** use `--stream` on Cursor: incremental stdout notify is slower in practice than exit-based notify (~5s vs sub-second in testing).-- **Codex**: run the poll in the **foreground** (blocking shell; not a background task, not a subagent). Codex background exec sessions do not reliably surface poll stdout back into the conversation at the moment events arrive, so a "fire-and-forget" background poll will stall live mode.+- **Codex**: run the default one-shot poll in a **yielded foreground exec session**. Do not suffix it with `&`, use `--stream`, or leave Live without an active foreground poll. Handle every event in the main task; after each handler/reply, restart the foreground poll.- **Other harnesses**: one-shot foreground unless you know stdout reliably returns to this session when a shell exits.+Generation delivery policy:+- **Default (Cursor and other harnesses):** keep the established atomic single-edit delivery. Do not switch a harness to progressive until its poll loop is known not to block on the extra publish calls. This avoids trading model latency for extra tool-call latency on harnesses with different streaming behavior.+Chat is overhead. No recap, no tutorial output, no pasting PRODUCT / DESIGN bodies. Spend tokens on tools and edits; on failure, one or two short sentences.## Start@@ -92,14 +95,14 @@ Server restart rule: start `live-server.mjs` again, then poll. Startup requeues**Insert mode** (`event.mode === "insert"`): `{id, mode: "insert", count, pageUrl, insert: { position, anchor }, placeholder: { width, height }, freeformPrompt?, screenshotPath?, comments?, strokes?}`. No `action`. Requires a non-empty `freeformPrompt` **or** annotations. Screenshot is sent only when annotations exist (same rule as replace). Use `placeholder` dimensions as a soft size hint for net-new content.-Speed matters; the user is watching a spinner. Minimize tool calls by using the wrap/insert helper and writing all variants in a single edit.+Speed matters; the user is watching the selected element. Reuse server preflight metadata when available, minimize discovery calls, and follow the harness-specific delivery policy above.### Insert mode branchWhen `event.mode === "insert"`:1. Read the screenshot if `event.screenshotPath` is present (annotations only).-2. Run the insert helper instead of wrap:+2. If `event.scaffold` is present, use it as the insert-helper result and do **not** run the helper again. Otherwise run the insert helper instead of wrap:```bashnode .github/skills/impeccable/scripts/live-insert.mjs --id EVENT_ID --count EVENT_COUNT --position after \@@ -109,7 +112,7 @@ node .github/skills/impeccable/scripts/live-insert.mjs --id EVENT_ID --count EVE- `--position` ← `event.insert.position` (`before` | `after`)- Anchor flags ← `event.insert.anchor` (same mapping as wrap: id, classes, tag, text)-The scaffold has **no** `data-impeccable-variant="original"`. Variants are net-new HTML+CSS inserted at `insertLine`. Load `brand.md` or `product.md` (freeform only, no action sub-command). Write all variants in one edit, then `--reply done`.+The scaffold has **no** `data-impeccable-variant="original"`. Variants are net-new HTML+CSS inserted at `insertLine`. Load `brand.md` or `product.md` (freeform only, no action sub-command). Deliver using the harness policy, then `--reply done`.For Svelte/SvelteKit targets, `live-insert.mjs` returns `previewMode: "svelte-component"` with `mode: "insert"`, `file` pointing at a temporary `node_modules/.impeccable-live/<id>/manifest.json`, `componentDir` pointing at the variant component files, and `sourceFile` pointing at the real `.svelte` route. Write each inserted variant as a real Svelte component (`v1.svelte`, `v2.svelte`, …) under `componentDir`. Insert variants must be non-empty net-new content with a single top-level root, no `data-impeccable-*` attributes, and CSS in each component's `<style>` block. Do **not** edit the route source during generation; the browser mounts the temporary component before/after the live anchor while the user cycles variants. On Accept, `live-accept.mjs` inserts the selected component markup into `sourceFile` immediately and deletes the temp session after the source write succeeds.@@ -134,6 +137,8 @@ Reading annotations precisely:### 2. Wrap the element+When `event.scaffold` is present, the local helper already found and wrapped the source before the poll returned. Treat `event.scaffold` as the successful helper output and skip this command entirely. `event.scaffoldAttempted` with `scaffoldError` means local preflight could not finish; use the command/fallback path below. This optimization removes a deterministic tool round trip without changing the generated design.+```bashnode .github/skills/impeccable/scripts/live-wrap.mjs --id EVENT_ID --count EVENT_COUNT --element-id "ELEMENT_ID" --classes "class1,class2" --tag "div" --text "TEXT_SNIPPET"```@@ -153,7 +158,7 @@ Output on success: `{ file, insertLine, commentSyntax, styleMode, styleTag, cssSFor Svelte/SvelteKit targets, `live-wrap.mjs` returns `previewMode: "svelte-component"` with `file` pointing at a temporary `node_modules/.impeccable-live/<id>/manifest.json`, `componentDir` pointing at the variant component files, and `sourceFile` pointing at the real `.svelte` route. Write each variant as a real Svelte component (`v1.svelte`, `v2.svelte`, …) under `componentDir`; use the `propContract` prop names for dynamic text (`{propName}`), not literal snapshot strings. Put variant CSS in each component's `<style>` block with semantic class selectors (no `@scope`, no `data-impeccable-*`). Reply with `--file` set to the manifest path; the browser dynamically imports and mounts the compiled components so Svelte HMR does not reset page state while the user cycles variants. On Accept, `live-accept.mjs` inlines the accepted component back into `sourceFile` immediately after source promotion succeeds.-**Params on the Svelte component path go in a sidecar, never as an attribute.** Svelte parses `{` inside an attribute value as the start of an expression, so a `data-impeccable-params='[{…}]'` attribute on a component element fails to compile (`Expected token }`). Declare params for this path in `componentDir/params.json`, keyed by variant number, using the exact param schema from section 7:+**Params on component-preview paths go in a sidecar, never as an attribute.** Svelte parses `{` inside an attribute value as the start of an expression, and both Svelte/Vue previews mount without an HTML variant wrapper. Declare params in `componentDir/params.json`, keyed by variant number, using the exact param schema from section 7:```json{@@ -291,11 +296,13 @@ In **departure mode**, the prompt narrows the lanes you draw from, not the familWhen the prompt and PRODUCT.md anti-references conflict (the prompt asks for X, the anti-references ban X), the anti-references win; they describe the brand's standing position, the prompt is one moment.-### 6. Write all variants in a single edit+### 6. Deliver variantsComplete HTML replacement of the original element for each variant, not a CSS-only patch. Consider the element's context (computed styles, parent structure, CSS variables from `event.element`).-Write CSS + all variants in ONE edit at the `insertLine` reported by `wrap`. Colocate CSS as a `<style>` tag inside the variant wrapper; `<style>` works anywhere in modern browsers and this ensures CSS and HTML arrive atomically (no FOUC).+Colocate preview CSS as a `<style>` tag inside the variant wrapper; `<style>` works anywhere in modern browsers and keeps each delivered state internally complete (no FOUC).++**Atomic default:** write CSS + all variants + parameter manifests in one edit at `insertLine`, preserving the established behavior.Use the `cssAuthoring` object returned by `live-wrap.mjs` to author the temporary preview CSS. The style opening tag shown below is the common case; replace it with `cssAuthoring.styleTag` when the tool returns a different one. The variant markup shape is otherwise stable:@@ -319,7 +326,7 @@ Use the `cssAuthoring` object returned by `live-wrap.mjs` to author the temporarThe first variant has no `display: none` (visible by default). All others do. If variants use only inline styles and no preview CSS, omit the `<style>` tag entirely.-One edit, all variants; the browser's MutationObserver picks everything up in one pass.+The browser's MutationObserver accepts either delivery shape. On the transactional progressive path it shows arrived variants and pending dots immediately; Accept and Discard are available as soon as one variant exists. Accepting an arrived variant fences the worker before the browser releases the picker, so later publications are rejected.For `styleMode: "scoped"`, author every `:scope` rule with a descendant combinator. The `@scope` boundary is the **variant wrapper `<div data-impeccable-variant="N">`**, not the element you're designing. A bare `:scope { background: cream; }` styles the wrapper, not the inner replacement, so the cream lands on a `display: contents` shell while the actual element keeps page defaults. Always step in: `:scope > .card`, `:scope > section`, `:scope .hero-title`, etc. The fake test agent's CSS in `tests/live-e2e/agent.mjs` is a faithful template; every scoped rule starts `:scope > ...`.@@ -361,7 +368,7 @@ Each variant can expose **coarse** knobs alongside the full HTML/CSS replacement**Hard cap per variant**: at most **four** parameters so the panel stays legible; rare fifth only if the reference explicitly allows it.-**How to declare.** Put a JSON manifest on the variant wrapper (HTML/JSX path). **On the Svelte `svelte-component` path, do not use this attribute** (Svelte can't compile `{` inside an attribute value). Declare params in `componentDir/params.json` keyed by variant number instead (see the Svelte component paragraph in the wrap section). The param schema below is identical for both paths.+**How to declare.** Put a JSON manifest on the variant wrapper (HTML/JSX path). **On the `svelte-component` path, do not use this attribute.** Declare params in `componentDir/params.json` keyed by variant number instead (see the component-preview paragraphs in the wrap section). The param schema below is identical for every path.```html<div data-impeccable-variant="1" data-impeccable-params='[@@ -462,15 +469,19 @@ Event: `{id, variantId, _acceptResult, _completionAck}`. The poll script already- The accept event includes `pageUrl`; the poll script must forward it to `live-accept.mjs --page-url PAGE_URL` so accept-time cleanup only scrubs staged copy edits for the current page.- `_completionAck.ok !== true`: do not poll yet. Run `live-status.mjs` / `live-resume.mjs`, complete the cleanup manually if needed, then run `live-complete.mjs --id EVENT_ID`.- `_acceptResult.handled: true` and `carbonize: false`: nothing to do. Poll again.-- `_acceptResult.handled: true` and `carbonize: true`: **post-accept cleanup is required before the next poll.** See the "Required after accept (carbonize)" section below. The `event._acceptResult.todo` field, `_completionAck.requiresComplete`, and a stderr banner all point at this required follow-up; none are decorative. After cleanup, run `live-complete.mjs --id EVENT_ID`, then poll again.+- `_acceptResult.handled: true` and `carbonize: true`: post-accept cleanup is required, but it must not stall Codex's control lane. See "Required after accept (carbonize)" below. The `event._acceptResult.todo` field, `_completionAck.requiresComplete`, and stderr banner all point at this required follow-up; none are decorative.- `_acceptResult.handled: false, mode: "fallback"`: the session lived in a generated file and the script refused to persist there. You've already written the accepted variant into true source during Handle fallback Step 3; just clean up the temporary wrapper in the served file if any, and poll again.+- `_acceptResult.handled: false, mode: "error"`: the operation genuinely failed. **Do not hand-edit the file**; the source was not touched and editing it yourself would either double-apply or race whoever holds it.+ - `error: "source_locked"`: a generation publish holds the file. Run the same `live-accept.mjs` command again; it is idempotent and will succeed once the publisher releases. Do not poll past it.+ - `error: "accept_receipt_conflict"`: this session already resolved as `priorOperation` (on `priorVariantId` for an accept), so the request contradicts durable truth. Do not edit. Run `live-status.mjs` and tell the user what the session actually resolved to.+ - anything else: report the error briefly and run `live-status.mjs` before continuing.- `_acceptResult.handled: false` without `mode`: manual cleanup: read file, find markers, edit.### Required after accept (carbonize)When `_acceptResult.carbonize === true`, the accepted variant was stitched into source with helper markers and inline CSS so the browser can render it immediately with no visual gap. That stitch-in is **temporary**. The agent must rewrite it into permanent form before doing anything else. Skipping this leaves dead `@scope` rules for unaccepted variants, a pointless `data-impeccable-variant` wrapper, and `impeccable-carbonize-start/end` comment noise in the source file; all of which accumulate across sessions.-Do these five steps in the current thread, synchronously, before the next poll. Do not poll again until the file is clean.+Do these five steps synchronously before the next poll. The source lock, generation epoch, and expected-source hash remain the final safety gates against a generator finishing concurrently with Accept.1. **Locate the carbonize block** in the source file (`_acceptResult.file`). It's bracketed by `<!-- impeccable-carbonize-start SESSION_ID -->` and `<!-- impeccable-carbonize-end SESSION_ID -->` and contains a `<style data-impeccable-css="SESSION_ID">` element. If the variant declared parameters, an `<!-- impeccable-param-values SESSION_ID: {...} -->` comment sits alongside the style tag with the user's chosen values; read it first; it drives steps 3 and 4 below.2. **Move the CSS rules** into the project's real stylesheet. Which stylesheet depends on the project (e.g. `site/styles/workflow.css` for an Astro project, or the component's co-located CSS file for a Vite/Next project; pick whichever already owns styling for the surrounding element).@@ -478,9 +489,7 @@ Do these five steps in the current thread, synchronously, before the next poll.4. **Unwrap the accepted content.** Delete the inner `<div data-impeccable-variant="N" style="display: contents">` that wraps it. On JSX/TSX, also delete the outer `<div data-impeccable-carbonize="SESSION_ID" style={{ display: 'contents' }}>` wrapper if present (accept adds it so ternary/`return` slots keep a single root). Drop `data-impeccable-params` and any `data-p-*` attributes; those are live-mode plumbing, not source.5. **Delete the inline `<style>` block, the `<!-- impeccable-param-values -->` comment if present, and both `<!-- impeccable-carbonize-start/end -->` markers.** Also drop any `@scope` rules for variants other than the accepted one; those are dead code now.-After the file is clean, run `live-complete.mjs --id SESSION_ID`, verify it reports `phase: "completed"`, then poll again.--A background agent may be used for the rewrite, but the current thread is responsible for verifying the five steps are complete before issuing the next poll. In practice, inline is usually faster and less error-prone.+After the file is clean, the cleanup owner runs `live-complete.mjs --id SESSION_ID` and verifies `phase: "completed"`. Poll again only after that verification.## Handle `discard`diff --git a/.github/skills/impeccable/scripts/lib/impeccable-paths.mjs b/.github/skills/impeccable/scripts/lib/impeccable-paths.mjsindex 2ccbe7b74..99956c0f3 100644--- a/.github/skills/impeccable/scripts/lib/impeccable-paths.mjs+++ b/.github/skills/impeccable/scripts/lib/impeccable-paths.mjs@@ -104,6 +104,20 @@ export function removeLiveServerInfo(cwd = process.cwd(), options = {}) {}}+/**+ * Session IDs become path segments (journals, snapshots, accept receipts,+ * preview manifests, generated component dirs). They arrive from CLI `--id`+ * arguments and HTTP payloads, so anything containing a separator or `..` must+ * be rejected before it reaches path.join, which would happily escape+ * `.impeccable/live/`. Real IDs are 8 hex chars; the tests use short slugs.+ */+export function safeSessionId(id) {+ if (typeof id !== 'string' || !/^[A-Za-z0-9_-]{1,128}$/.test(id)) {+ throw new Error('invalid session id: ' + id);+ }+ return id;+}+export function getLiveSessionsDir(cwd = process.cwd(), options = {}) {return path.join(getLiveDir(cwd, options), 'sessions');}diff --git a/.github/skills/impeccable/scripts/live-accept.mjs b/.github/skills/impeccable/scripts/live-accept.mjsindex 278dfbb2e..453ddea35 100644--- a/.github/skills/impeccable/scripts/live-accept.mjs+++ b/.github/skills/impeccable/scripts/live-accept.mjs@@ -16,7 +16,9 @@import fs from 'node:fs';import path from 'node:path';import { isGeneratedFile } from './lib/is-generated.mjs';+import { IMPECCABLE_DIR, getLiveDir, safeSessionId } from './lib/impeccable-paths.mjs';import { readBuffer as readManualEditsBuffer, writeBuffer as writeManualEditsBuffer } from './live/manual-edits-buffer.mjs';+import { withSourceLockSync } from './live/source-lock.mjs';import {applyDeferredSvelteComponentAccepts,findSvelteComponentManifest,@@ -25,6 +27,46 @@ import {} from './live/svelte-component.mjs';const EXTENSIONS = ['.html', '.jsx', '.tsx', '.vue', '.svelte', '.astro'];+const ACCEPT_LOCK_WAIT_MS = 1_000;+// Mirrors VARIANT_ID_PATTERN in live/event-validation.mjs, which gates the same+// value arriving over HTTP.+const VARIANT_NUM_PATTERN = /^[0-9]{1,3}$/;++/**+ * A thrown accept/discard is a real failure, not a manual handoff.+ *+ * live/completion.mjs only classifies a result as `error` when it carries+ * `mode: 'error'`; anything else unhandled falls through to `agent_done` with a+ * successful ack, and reference/live.md then tells the agent to finish the edit+ * by hand. That is right for the documented fallback paths and wrong here: a+ * `source_locked` contention needs a retry (hand-editing races the publisher+ * holding the lock), and a crash needs surfacing, not a hand-applied guess.+ */+function operationFailure(err, extra = {}) {+ return { handled: false, mode: 'error', error: err.message, ...extra };+}++/**+ * Mark an unhandled preview-path result as a real failure.+ *+ * operationFailure only covers results built from a *thrown* error. The accept+ * implementations also return `{handled: false, error}` for their own checks+ * (variant missing, template empty, original text ambiguous), and those arrived+ * without `mode`, so completion.mjs classified them as agent_done and+ * reference/live.md routed the agent to "read file, find markers, edit".+ *+ * That handoff only makes sense for a plain wrapper session, which is the one+ * shape with markers in the user's source to edit. Component and isolated+ * artifact previews keep the source clean until Accept, so there is nothing to+ * hand-edit and an unhandled result is always a failure. `previewMode` is+ * exactly that discriminator: only the preview branches set it.+ */+function markPreviewFailure(result) {+ if (result?.handled === false && !result.mode && result.previewMode) {+ return { ...result, mode: 'error' };+ }+ return result;+}// ---------------------------------------------------------------------------// CLI@@ -63,7 +105,52 @@ Output (JSON):const isDiscard = args.includes('--discard');if (!id) { console.error('Missing --id'); process.exit(1); }+ // `id` becomes a path segment (accept receipts, preview manifests, generated+ // component dirs). Reject separators and traversal here so one check covers+ // every downstream sink.+ try { safeSessionId(id); } catch { console.error('Invalid --id'); process.exit(1); }if (!isDiscard && !variantNum) { console.error('Need --discard or --variant N'); process.exit(1); }+ // `variantNum` is interpolated into a RegExp and into the markup written back+ // to source. The browser and the /events schema both constrain it to digits;+ // enforce the same here, or `--variant '.*'` matches the `original` block+ // first and silently accepts the original while reporting success.+ if (!isDiscard && !VARIANT_NUM_PATTERN.test(variantNum)) {+ console.error('Invalid --variant');+ process.exit(1);+ }++ const requestedOperation = isDiscard ? 'discard' : 'accept';+ const priorReceipt = readAcceptReceipt(process.cwd(), id);+ if (priorReceipt) {+ const sameOperation = priorReceipt.operation === requestedOperation+ && (isDiscard || String(priorReceipt.variantId) === String(variantNum));+ console.log(JSON.stringify(sameOperation+ ? { ...priorReceipt.result, handled: true, alreadyApplied: true }+ : {+ // mode: 'error' is what marks this a real failure rather than a manual+ // handoff. Without it, live/completion.mjs classifies the reply as+ // agent_done and reference/live.md tells the agent to "read file, find+ // markers, edit" by hand — which would apply a second, conflicting+ // accept on top of the one the receipt already recorded.+ handled: false,+ mode: 'error',+ error: 'accept_receipt_conflict',+ priorOperation: priorReceipt.operation,+ priorVariantId: priorReceipt.variantId ?? null,+ }));+ return;+ }+ const emitResult = (rawResult) => {+ const result = markPreviewFailure(rawResult);+ if (result?.handled !== false) {+ writeAcceptReceipt(process.cwd(), id, {+ operation: requestedOperation,+ variantId: isDiscard ? null : String(variantNum),+ result,+ });+ }+ console.log(JSON.stringify(result));+ };let paramValues = null;if (paramValuesRaw) {@@ -82,39 +169,55 @@ Output (JSON):if (svelteComponentManifest) {if (isDiscard) {- removeSvelteComponentSession(id, process.cwd());- console.log(JSON.stringify({- handled: true,+ let result;+ try {+ result = withSourceLockSync(+ path.resolve(process.cwd(), svelteComponentManifest.sourceFile),+ 'discard:' + id,+ () => {+ removeSvelteComponentSession(id, process.cwd());+ return { handled: true };+ },+ { waitMs: ACCEPT_LOCK_WAIT_MS },+ );+ } catch (err) {+ result = operationFailure(err);+ }+ emitResult({+ ...result,file: svelteComponentManifest.sourceFile,carbonize: false,previewMode: 'svelte-component',componentDir: svelteComponentManifest.componentDir,- }));+ });return;}let result;try {- result = inlineSvelteComponentAccept(- svelteComponentManifest,- variantNum,- paramValues,- process.cwd(),+ result = withSourceLockSync(+ path.resolve(process.cwd(), svelteComponentManifest.sourceFile),+ 'accept:' + id,+ () => inlineSvelteComponentAccept(+ svelteComponentManifest,+ variantNum,+ paramValues,+ process.cwd(),+ ),+ { waitMs: ACCEPT_LOCK_WAIT_MS },);} catch (err) {- result = {- handled: false,- error: err.message,+ result = operationFailure(err, {file: svelteComponentManifest.sourceFile,sourceFile: svelteComponentManifest.sourceFile,previewMode: 'svelte-component',componentDir: svelteComponentManifest.componentDir,- };+ });}if (result.carbonize) {result.todo = 'REQUIRED before next poll: carbonize cleanup in ' + result.file + '. See reference/live.md "Required after accept".';}- console.log(JSON.stringify({ handled: result.handled !== false, ...result }));+ emitResult({ handled: result.handled !== false, ...result });return;}@@ -145,10 +248,25 @@ Output (JSON):}if (isDiscard) {- const result = handleDiscard(id, lines, targetFile);- console.log(JSON.stringify({ handled: true, file: relFile, carbonize: false, ...result }));+ let result;+ // handleDiscard takes the source lock, which throws SOURCE_LOCKED under+ // contention. Without this catch the CLI exits non-zero with empty stdout+ // and the agent gets no JSON to act on.+ try {+ result = handleDiscard(id, lines, targetFile);+ } catch (err) {+ emitResult(operationFailure(err, { file: relFile }));+ return;+ }+ emitResult({ handled: true, file: relFile, carbonize: false, ...result });} else {- const result = handleAccept(id, variantNum, lines, targetFile, paramValues);+ let result;+ try {+ result = handleAccept(id, variantNum, lines, targetFile, paramValues);+ } catch (err) {+ emitResult(operationFailure(err, { file: relFile }));+ return;+ }const acceptedOriginalText = result.acceptedOriginalText || '';delete result.acceptedOriginalText;// Single-line attention-grabber when cleanup is required. The full@@ -167,7 +285,7 @@ Output (JSON):// Non-fatal; the buffer stays as-is and the user can discard later.}}- console.log(JSON.stringify({ handled: true, file: relFile, ...result }));+ emitResult({ handled: true, file: relFile, ...result });}}@@ -235,7 +353,14 @@ function scrubManualEditsAgainstFile(_targetFile, cwd = process.cwd(), originalB// Discard// ----------------------------------------------------------------------------function handleDiscard(id, lines, targetFile) {+function handleDiscard(id, _lines, targetFile) {+ return withSourceLockSync(targetFile, 'discard:' + id, () => {+ const lines = fs.readFileSync(targetFile, 'utf-8').split('\n');+ return handleDiscardUnlocked(id, lines, targetFile);+ }, { waitMs: ACCEPT_LOCK_WAIT_MS });+}++function handleDiscardUnlocked(id, lines, targetFile) {const block = findMarkerBlock(id, lines);if (!block) return { handled: false, error: 'Markers not found' };@@ -330,7 +455,24 @@ function reindentContent(contentLines, fromIndent, toIndent) {});}-function handleAccept(id, variantNum, lines, targetFile, paramValues) {+function handleAccept(id, variantNum, _lines, targetFile, paramValues) {+ return withSourceLockSync(targetFile, 'accept:' + id, () => {+ const lines = fs.readFileSync(targetFile, 'utf-8').split('\n');+ return handleAcceptUnlocked(id, variantNum, lines, targetFile, paramValues);+ }, { waitMs: ACCEPT_LOCK_WAIT_MS });+}++function handleAcceptUnlocked(id, variantNum, lines, targetFile, paramValues) {+ const built = buildAcceptedWrappedSource(id, variantNum, lines, targetFile, paramValues);+ if (built.handled === false) return built;+ fs.writeFileSync(targetFile, built.content, 'utf-8');+ return {+ carbonize: built.carbonize,+ acceptedOriginalText: built.acceptedOriginalText,+ };+}++function buildAcceptedWrappedSource(id, variantNum, lines, targetFile, paramValues) {const block = findMarkerBlock(id, lines);if (!block) return { handled: false, error: 'Markers not found' };@@ -375,11 +517,14 @@ function handleAccept(id, variantNum, lines, targetFile, paramValues) {...replacement,...lines.slice(replaceRange.end + 1),];- fs.writeFileSync(targetFile, newLines.join('\n'), 'utf-8');-- return { carbonize: needsCarbonize, acceptedOriginalText: originalContent.join('\n') };+ return {+ content: newLines.join('\n'),+ carbonize: needsCarbonize,+ acceptedOriginalText: originalContent.join('\n'),+ };}+function readSourceShadowPreviewMeta(content, id) {const escaped = escapeRegExp(id);const wrapperRe = new RegExp('<[^>]+data-impeccable-variants=(["\'])' + escaped + '\\1[^>]*>');@@ -746,6 +891,21 @@ function detectCommentSyntax(filePath) {// File search (find the file containing session markers)// ---------------------------------------------------------------------------+/**+ * `.impeccable` is the critical entry, and it is not cosmetic.+ *+ * Progressive publication stages each revision as `.impeccable/live/artifacts/+ * <id>-r<n>.<source-ext>`, and those artifacts carry the very marker this search+ * looks for. The walk reaches `.` for any project whose source is not under one+ * of the privileged dirs above (this repo's own site lives in `site/pages/`), and+ * dot-directories sort before letters, so the artifact was found *before* the+ * real file. isGeneratedFile then declined the accept, and the agent fell back to+ * carbonizing several hundred lines of stylesheet by hand.+ *+ * Impeccable's own state directory is never project source. Never search it.+ */+const SEARCH_SKIP_DIRS = new Set(['node_modules', '.git', 'dist', 'build', IMPECCABLE_DIR]);+function findSessionFile(id, cwd) {const marker = 'impeccable-variants-start ' + id;const searchDirs = ['src', 'app', 'pages', 'components', 'public', 'views', 'templates', '.'];@@ -786,7 +946,7 @@ function searchDir(dir, query, seen, depth) {for (const entry of entries) {if (!entry.isDirectory()) continue;- if (['node_modules', '.git', 'dist', 'build'].includes(entry.name)) continue;+ if (SEARCH_SKIP_DIRS.has(entry.name)) continue;const result = searchDir(path.join(dir, entry.name), query, seen, depth + 1);if (result) return result;}@@ -798,6 +958,28 @@ function searchDir(dir, query, seen, depth) {// Utilities// ---------------------------------------------------------------------------+function acceptReceiptPath(cwd, id) {+ return path.join(getLiveDir(cwd), 'accept-receipts', `${safeSessionId(id)}.json`);+}++function readAcceptReceipt(cwd, id) {+ try { return JSON.parse(fs.readFileSync(acceptReceiptPath(cwd, id), 'utf-8')); } catch { return null; }+}++function writeAcceptReceipt(cwd, id, receipt) {+ const file = acceptReceiptPath(cwd, id);+ fs.mkdirSync(path.dirname(file), { recursive: true });+ const value = {+ id,+ ...receipt,+ completedAt: new Date().toISOString(),+ };+ const temporary = `${file}.${process.pid}.${Date.now()}.tmp`;+ fs.writeFileSync(temporary, JSON.stringify(value, null, 2) + '\n', 'utf-8');+ fs.renameSync(temporary, file);+ return value;+}+function argVal(args, flag) {const idx = args.indexOf(flag);return idx !== -1 && idx + 1 < args.length ? args[idx + 1] : null;diff --git a/.github/skills/impeccable/scripts/live-browser.js b/.github/skills/impeccable/scripts/live-browser.jsindex 616f1290a..20d875b93 100644--- a/.github/skills/impeccable/scripts/live-browser.js+++ b/.github/skills/impeccable/scripts/live-browser.js@@ -126,6 +126,9 @@let expectedVariants = 0;let arrivedVariants = 0;let visibleVariant = 0;+ let generationPhase = null;+ let parameterGenerationState = 'idle';+ let parameterReadyAnnouncedSession = null;let svelteComponentSession = null;let svelteRuntimePromise = null;let pendingSvelteComponentRetryObserver = null;@@ -134,6 +137,7 @@let currentPreviewMode = null;let recoveryWaitingForAnchor = false;let pickedAnchorSnapshot = null;+ let pickedAnchorViewportTop = null;let pendingVariantAnchorRetryObserver = null;let pendingAcceptedSession = null;let variantObserver = null;@@ -151,10 +155,12 @@// startScrollLock / stopScrollLock below.let scrollLockObserver = null;let scrollLockTargetY = null;+ let scrollLockAnchorTop = null;let scrollLockRaf = null;let scrollLockAbort = null;const SCROLL_ANCHOR_LOCK_ID = 'impeccable-scroll-anchor-lock';const VARIANT_STATE_STYLE_ID = 'impeccable-variant-state';+ const DISCARD_STATE_STYLE_ID = 'impeccable-discard-state';// Dedicated key for scroll position - SEPARATE from LS_KEY so that// saveSession's state updates don't clobber a carefully-captured scrollY.@@ -252,6 +258,13 @@barConnected: !!barEl?.isConnected,hasSvelteComponentSession: !!svelteComponentSession,mountedSvelteVariant: svelteComponentSession?.mountedVariant || 0,+ pickActive,+ pendingApplyInFlight,+ hoveredElement: hoveredElement ? {+ tag: hoveredElement.tagName,+ classes: hoveredElement.className,+ pickable: pickable(hoveredElement),+ } : null,pendingSvelteComponentRetry: !!pendingSvelteComponentRetryObserver,recoveryWaitingForAnchor,evtSourceReadyState: evtSource ? evtSource.readyState : null,@@ -1114,14 +1127,15 @@});}- function hideBar() {+ function hideBar(instant) {if (!barEl) return;const hideSeq = ++barHideSeq;stopVoice({ suppressSubmit: true });if (configureKind === 'insert') clearInsertPicking();barEl.style.opacity = '0';- barEl.style.transform = 'translateY(6px)';- setTimeout(() => { if (barEl && hideSeq === barHideSeq) barEl.style.display = 'none'; }, 250);+ barEl.style.transform = instant ? 'translateY(0)' : 'translateY(6px)';+ if (instant) barEl.style.display = 'none';+ else setTimeout(() => { if (barEl && hideSeq === barHideSeq) barEl.style.display = 'none'; }, 250);hideActionPicker();closeTunePopover();hideConfigureBarTooltip();@@ -1966,6 +1980,7 @@*/function setLiveState(next) {state = next;+ window.__IMPECCABLE_LIVE_STATE__ = next;syncPageInteractionCursor();}@@ -2516,18 +2531,27 @@fontSize: '11px', color: BP.textDim, whiteSpace: 'nowrap',marginLeft: 'auto',});- // Variants currently arrive atomically in a single file edit, so a- // per-variant counter would lie. Say what's true.status.textContent = recoveryWaitingForAnchor? 'Variants ready. Reveal the selected element to resume.'- : (arrivedVariants < expectedVariants- ? 'Generating ' + expectedVariants + ' variants...'- : 'Done');+ : generationStatusText();row.appendChild(status);return row;}+ function generationStatusText() {+ if (arrivedVariants >= expectedVariants && expectedVariants > 0) return 'Done';+ if (generationPhase === 'picked_up') return 'Agent picked up the request...';+ if (generationPhase === 'scaffolding') return 'Finding the source...';+ if (generationPhase === 'source_ready') return 'Source ready. Generating...';+ if (generationPhase === 'scaffold_fallback') return 'Agent is locating the source...';+ if (generationPhase === 'first_variant_generating') return 'Designing the first variant...';+ if (generationPhase === 'first_variant_validating') return 'Checking the first variant...';+ if (generationPhase === 'remaining_variants_generating') return 'Exploring two more directions...';+ if (generationPhase === 'remaining_variants_validating') return 'Checking the remaining variants...';+ return 'Generating ' + expectedVariants + ' variants...';+ }+// Cycling rowconst TUNE_ICON_SVG = '<svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" style="flex-shrink:0"><line x1="4" y1="8" x2="20" y2="8"/><circle cx="14" cy="8" r="2.4" fill="currentColor" stroke="none"/><line x1="4" y1="16" x2="20" y2="16"/><circle cx="10" cy="16" r="2.4" fill="currentColor" stroke="none"/></svg>';@@ -2557,7 +2581,7 @@color: BP.textDim, minWidth: '24px', textAlign: 'center',});counter.id = PREFIX + '-variant-counter';- counter.textContent = visibleVariant + '/' + arrivedVariants;+ counter.textContent = visibleVariant + '/' + expectedVariants;row.appendChild(counter);// Next@@ -2567,10 +2591,12 @@if (visibleVariant >= arrivedVariants) next.style.opacity = '0.3';row.appendChild(next);- // Tune chip - only when the visible variant exposes params+ // Tune chip stays visible while the deferred parameter phase is running,+ // then becomes interactive as soon as this variant exposes controls.const visParams = parseVariantParams(getVisibleVariantEl());const hasParams = visParams.length > 0;- if (hasParams) {+ const paramsPending = !hasParams && (parameterGenerationState === 'pending' || parameterGenerationState === 'loading');+ if (hasParams || paramsPending) {const tune = el('button', {display: 'inline-flex', alignItems: 'center', gap: '6px',padding: '4px 10px', borderRadius: '5px',@@ -2578,35 +2604,54 @@background: tuneOpen ? BP.accentSoft : 'transparent',color: tuneOpen ? BP.accent : BP.text,fontFamily: FONT, fontSize: '11px', fontWeight: '500',- cursor: 'pointer',+ cursor: paramsPending ? 'wait' : 'pointer',transition: 'color 0.12s ease, background 0.12s ease',whiteSpace: 'nowrap',});- tune.innerHTML = TUNE_ICON_SVG;+ if (paramsPending) {+ const spinner = el('span', {+ width: '11px', height: '11px', borderRadius: '50%',+ border: '1.5px solid ' + BP.hairline,+ borderTopColor: BP.accent,+ animation: 'impeccable-spin 0.6s linear infinite',+ boxSizing: 'border-box', flexShrink: '0',+ });+ spinner.setAttribute('aria-hidden', 'true');+ tune.appendChild(spinner);+ } else {+ tune.innerHTML = TUNE_ICON_SVG;+ }const tuneLabel = document.createElement('span');tuneLabel.textContent = 'Tune';tune.appendChild(tuneLabel);- const tuneBadge = document.createElement('span');- Object.assign(tuneBadge.style, {- display: 'inline-flex', alignItems: 'center', justifyContent: 'center',- minWidth: '16px', height: '16px', padding: '0 4px',- borderRadius: '999px',- background: tuneOpen ? C.brand : BP.hairline,- color: tuneOpen ? 'oklch(98% 0 0)' : 'inherit',- fontFamily: MONO, fontSize: '9.5px', fontWeight: '600',- lineHeight: '1',- boxSizing: 'border-box',- });- tuneBadge.textContent = String(visParams.length);- tune.appendChild(tuneBadge);- tune.title = 'Tune this variant (' + visParams.length + ' knob' + (visParams.length === 1 ? '' : 's') + ')';- tune.addEventListener('mouseenter', () => {- if (!tuneOpen) tune.style.background = BP.accentSoft;- });- tune.addEventListener('mouseleave', () => {- if (!tuneOpen) tune.style.background = 'transparent';- });- tune.addEventListener('click', (e) => { e.stopPropagation(); toggleTunePopover(); });+ if (hasParams) {+ const tuneBadge = document.createElement('span');+ Object.assign(tuneBadge.style, {+ display: 'inline-flex', alignItems: 'center', justifyContent: 'center',+ minWidth: '16px', height: '16px', padding: '0 4px',+ borderRadius: '999px',+ background: tuneOpen ? C.brand : BP.hairline,+ color: tuneOpen ? 'oklch(98% 0 0)' : 'inherit',+ fontFamily: MONO, fontSize: '9.5px', fontWeight: '600',+ lineHeight: '1',+ boxSizing: 'border-box',+ });+ tuneBadge.textContent = String(visParams.length);+ tune.appendChild(tuneBadge);+ tune.title = 'Tune this variant (' + visParams.length + ' knob' + (visParams.length === 1 ? '' : 's') + ')';+ tune.addEventListener('mouseenter', () => {+ if (!tuneOpen) tune.style.background = BP.accentSoft;+ });+ tune.addEventListener('mouseleave', () => {+ if (!tuneOpen) tune.style.background = 'transparent';+ });+ tune.addEventListener('click', (e) => { e.stopPropagation(); toggleTunePopover(); });+ } else {+ tune.disabled = true;+ tune.setAttribute('aria-label', 'Tune controls are still being prepared');+ tune.title = 'Tune controls are still being prepared';+ tune.style.opacity = '0.72';+ }tune.dataset.iceqTune = '1';row.appendChild(tune);}@@ -2614,6 +2659,15 @@// Spacerrow.appendChild(el('div', { flex: '1' }));+ if (arrivedVariants < expectedVariants) {+ const remaining = expectedVariants - arrivedVariants;+ const progress = el('span', {+ fontSize: '11px', color: BP.textDim, whiteSpace: 'nowrap',+ });+ progress.textContent = remaining + ' more arriving...';+ row.appendChild(progress);+ }+// Accept - primary action, kinpaku gold + lacquer-deep (matches demo .live-demo-ctx-accept)const accept = el('button', {padding: '5px 14px', borderRadius: '5px',@@ -2628,7 +2682,11 @@accept.addEventListener('mousedown', () => accept.style.transform = 'scale(0.97)');accept.addEventListener('mouseup', () => accept.style.transform = 'scale(1)');accept.addEventListener('click', (e) => { e.stopPropagation(); handleAccept(); });- if (arrivedVariants === 0) { accept.style.opacity = '0.3'; accept.style.pointerEvents = 'none'; }+ if (arrivedVariants === 0) {+ accept.style.opacity = '0.3';+ accept.style.pointerEvents = 'none';+ accept.title = 'Accept becomes available when the first variant arrives';+ }row.appendChild(accept);// Discard@@ -4743,6 +4801,32 @@}}+ function mountedParameterCount() {+ if (svelteComponentSession?.sessionId === currentSessionId) {+ return Object.values(svelteComponentSession.paramsByVariant || {})+ .reduce((total, params) => total + (Array.isArray(params) ? params.length : 0), 0);+ }+ const wrapper = document.querySelector('[data-impeccable-variants="' + currentSessionId + '"]');+ if (!wrapper) return 0;+ return [...wrapper.querySelectorAll('[data-impeccable-variant]:not([data-impeccable-variant="original"])')]+ .reduce((total, variant) => total + parseVariantParams(variant).length, 0);+ }++ function completeParameterPublication() {+ if (!currentSessionId) return;+ const ready = mountedParameterCount() > 0;+ parameterGenerationState = ready ? 'ready' : 'none';+ if (ready && parameterReadyAnnouncedSession !== currentSessionId) {+ parameterReadyAnnouncedSession = currentSessionId;+ showToast('Tune controls are ready.', 3000);+ }+ if (state === 'CYCLING') {+ refreshParamsPanel();+ showOrUpdateCyclingBar();+ }+ saveSession();+ }+function toggleTunePopover() {if (pendingApplyInFlight) { showManualApplyBusyToast(); return; }if (tuneOpen) { closeTunePopover(); return; }@@ -4835,6 +4919,10 @@return String(filePath || '').endsWith('manifest.json');}+ function isFrameworkComponentPreviewMode(mode) {+ return mode === 'svelte-component';+ }+function parseOriginalMarkupElement(originalMarkup) {const parser = new DOMParser();const doc = parser.parseFromString('<div id="impeccable-anchor">' + originalMarkup + '</div>', 'text/html');@@ -5029,9 +5117,13 @@}}- function loadSvelteRuntime(runtimeModule) {+ function resolveComponentModuleUrl(manifest, modulePath) {+ return new URL(String(modulePath || ''), location.origin).href;+ }++ function loadSvelteRuntime(runtimeModule, manifest) {const modulePath = runtimeModule || '/src/lib/impeccable/__runtime.js';- const url = new URL(modulePath, location.origin).href;+ const url = resolveComponentModuleUrl(manifest, modulePath);if (!svelteRuntimePromise) {svelteRuntimePromise = import(/* @vite-ignore */ url);}@@ -5065,7 +5157,8 @@async function loadSvelteComponentVariantSource(manifest, variantNum) {const dir = String(manifest?.componentDir || '').replace(/^\/+/, '');if (!dir || !variantNum) return '';- const sourcePath = dir + '/v' + variantNum + '.svelte';+ const extension = manifest.componentExtension || 'svelte';+ const sourcePath = dir + '/v' + variantNum + '.' + extension;const url = 'http://localhost:' + PORT + '/source?token=' + TOKEN + '&path=' + encodeURIComponent(sourcePath);try {const res = await fetch(url);@@ -5221,7 +5314,7 @@if (!sourceOriginal) return values;const map = buildSvelteExpressionTextMap(sourceOriginal, liveEl);for (const entry of contract) {- const token = '{' + entry.expr + '}';+ const token = entry.previewToken || ('{' + entry.expr + '}');values[entry.prop] = map.get(token) || '';}return values;@@ -5233,9 +5326,12 @@try {const previousAnchor = getMountedSvelteComponentAnchor(svelteComponentSession) || selectedElement;svelteComponentSession.swapAnchor = makeFrozenAnchor(previousAnchor) || svelteComponentSession.swapAnchor || null;- const runtime = await loadSvelteRuntime(manifest.runtimeModule);- const modulePath = '/' + String(manifest.componentDir || '').replace(/^\/+/, '') + '/v' + variantNum + '.svelte';- const moduleUrl = new URL(modulePath, location.origin).href + '?t=' + Date.now();+ const runtime = await loadSvelteRuntime(manifest.runtimeModule, manifest);+ const extension = manifest.componentExtension || 'svelte';+ const moduleBase = manifest.componentModuleBase+ || ('/' + String(manifest.componentDir || '').replace(/^\/+/, ''));+ const modulePath = String(moduleBase).replace(/\/+$/, '') + '/v' + variantNum + '.' + extension;+ const moduleUrl = resolveComponentModuleUrl(manifest, modulePath) + '?t=' + Date.now();const mod = await import(/* @vite-ignore */ moduleUrl);const Component = mod.default;if (svelteComponentSession.mountedInstance && runtime.unmount) {@@ -5275,7 +5371,7 @@if (svelteComponentSession?.sessionId === sessionId) {svelteComponentSession.swapAnchor = null;}- console.error('[impeccable] Failed to mount Svelte variant ' + variantNum + ' for ' + sessionId + ':', err);+ console.error('[impeccable] Failed to mount component variant ' + variantNum + ' for ' + sessionId + ':', err);return false;}}@@ -5340,40 +5436,46 @@if (manifest.id !== sessionId) return;const paramsByVariant = await loadSvelteComponentParams(manifest);+ const availableVariants = Number(manifest.arrivedVariants) || Number(manifest.count) || 1;+ const componentPreviewMode = isFrameworkComponentPreviewMode(manifest.previewMode)+ ? manifest.previewMode+ : 'svelte-component';currentSessionId = sessionId;expectedVariants = Number(manifest.count) || expectedVariants || 1;rememberSessionFileMeta({sourceFile: manifest.sourceFile,previewFile: manifestPath,- previewMode: 'svelte-component',+ previewMode: componentPreviewMode,});if (state !== 'CYCLING') setLiveState('GENERATING');const existingWrapper = document.querySelector('[data-impeccable-variants="' + sessionId + '"]');if (existingWrapper && svelteComponentSession?.sessionId === sessionId) {recoveryWaitingForAnchor = false;+ svelteComponentSession.manifest = manifest;svelteComponentSession.paramsByVariant = paramsByVariant;- arrivedVariants = Number(manifest.count) || expectedVariants || 1;- expectedVariants = arrivedVariants;+ arrivedVariants = availableVariants;+ expectedVariants = Number(manifest.count) || expectedVariants || arrivedVariants;visibleVariant = visibleVariant > 0 && visibleVariant <= arrivedVariants ? visibleVariant : 1;await mountSvelteComponentVariant(visibleVariant || 1);setLiveState('CYCLING');showOrUpdateCyclingBar();saveSession();+ if (parameterGenerationState === 'loading') completeParameterPublication();return;}const liveEl = findLiveElementForSvelteManifest(manifest);if (!liveEl?.parentElement) {console.warn('[impeccable] Could not find original element in live DOM.');- arrivedVariants = Number(manifest.count) || expectedVariants || 1;- expectedVariants = arrivedVariants;+ arrivedVariants = availableVariants;+ expectedVariants = Number(manifest.count) || expectedVariants || arrivedVariants;const saved = loadSession();const savedVisibleVariant = saved && saved.id === sessionId ? saved.visible : 0;visibleVariant = visibleVariant > 0 && visibleVariant <= arrivedVariants? visibleVariant: (savedVisibleVariant > 0 && savedVisibleVariant <= arrivedVariants ? savedVisibleVariant : 1);- enterRecoveryWaitingForAnchor({ checkpointReason: 'svelte_component_anchor_missing', trackScroll: true });+ enterRecoveryWaitingForAnchor({ checkpointReason: 'component_preview_anchor_missing', trackScroll: true });waitForSvelteComponentTargetAndRetry({ manifestPath, sessionId, manifest });return;}@@ -5381,7 +5483,7 @@const wrapper = document.createElement('div');wrapper.dataset.impeccableVariants = sessionId;wrapper.dataset.impeccableVariantCount = String(manifest.count || expectedVariants || 1);- wrapper.dataset.impeccablePreview = 'svelte-component';+ wrapper.dataset.impeccablePreview = componentPreviewMode;wrapper.style.display = 'contents';const mountTarget = document.createElement('div');@@ -5419,8 +5521,8 @@recoveryWaitingForAnchor = false;const previousVisibleVariant = currentSessionId === sessionId ? visibleVariant : 0;- arrivedVariants = Number(manifest.count) || expectedVariants || 1;- expectedVariants = arrivedVariants;+ arrivedVariants = availableVariants;+ expectedVariants = Number(manifest.count) || expectedVariants || arrivedVariants;const saved = loadSession();const savedVisibleVariant = saved && saved.id === sessionId ? saved.visible : 0;visibleVariant = previousVisibleVariant > 0 && previousVisibleVariant <= arrivedVariants@@ -5445,9 +5547,10 @@refreshParamsPanel();positionBar();saveSession();- console.log('[impeccable] Mounted ' + arrivedVariants + ' Svelte component variants.');+ if (parameterGenerationState === 'loading') completeParameterPublication();+ console.log('[impeccable] Mounted ' + arrivedVariants + ' ' + manifest.framework + ' component variants.');} catch (err) {- console.error('[impeccable] Failed to mount Svelte component variants:', err);+ console.error('[impeccable] Failed to mount component-preview variants:', err);abortSvelteComponentInjection(sessionId, 'Could not load variants. Fix the error and re-run.');}}@@ -5493,6 +5596,8 @@clearHandled();resetSessionFileMeta();currentSessionId = null;+ parameterGenerationState = 'idle';+ parameterReadyAnnouncedSession = null;expectedVariants = 0;arrivedVariants = 0;visibleVariant = 0;@@ -5502,12 +5607,24 @@if (message) showToast(message, 5000);}+ // How many delayed re-reads a completion-driven source fallback gets when+ // the fetched source still shows only the preflight scaffold, before the+ // failure is surfaced via recoverEmptyCycling.+ const COMPLETED_SOURCE_FALLBACK_RETRIES = 3;+ const COMPLETED_SOURCE_FALLBACK_RETRY_MS = 1200;+/*** No-HMR fallback: fetch the raw source file from the live server,* parse it, extract the variant wrapper, and inject it into the live DOM.* This works even when the dev server caches HTML (Bun, static servers).+ *+ * opts.generationCompleted marks callers that KNOW the agent finished (a+ * `done` arrived or the server reported a completed generation). For them an+ * empty read is a stale source view and no further event is coming, so the+ * read retries a few times and then surfaces recovery. Callers without the+ * flag may be mid-generation and wait indefinitely for the real completion.*/- function injectVariantsFromSource(filePath, sessionId) {+ function injectVariantsFromSource(filePath, sessionId, opts = {}) {if (isSvelteComponentManifestPath(filePath)) {injectSvelteComponentsFromManifest(filePath, sessionId);return;@@ -5573,6 +5690,32 @@arrivedVariants = variants.length;expectedVariants = parseInt(wrapper.dataset.impeccableVariantCount || arrivedVariants);if (arrivedVariants <= 0) {+ if (state === 'GENERATING') {+ // Mid-generation the source legitimately holds a scaffold wrapper+ // with no variants yet (the server-side preflight wraps before the+ // agent writes). Tearing the session down here would destroy an+ // in-flight generation; stay in GENERATING — the variant observer+ // is armed and the server re-delivers a missed `done`.+ if (!opts.generationCompleted) {+ console.log('[impeccable] Source has scaffold but no variants yet; still generating.');+ return;+ }+ // Generation finished, yet the read shows only the scaffold: the+ // source view is stale and no further event will fire. Re-read a+ // few times before surfacing recovery — a single silent return+ // here would strand the tab in GENERATING forever.+ const attempt = opts.attempt || 0;+ if (attempt < COMPLETED_SOURCE_FALLBACK_RETRIES) {+ console.log('[impeccable] Generation is done but source shows no variants yet; retrying read ('+ + (attempt + 1) + '/' + COMPLETED_SOURCE_FALLBACK_RETRIES + ').');+ setTimeout(() => {+ if (state !== 'GENERATING' || currentSessionId !== sessionId) return;+ if (arrivedVariants > 0) return;+ injectVariantsFromSource(filePath, sessionId, { ...opts, attempt: attempt + 1 });+ }, COMPLETED_SOURCE_FALLBACK_RETRY_MS);+ return;+ }+ }recoverEmptyCycling('source-fallback-empty');return;}@@ -5594,6 +5737,7 @@refreshParamsPanel();positionBar();saveSession();+ if (parameterGenerationState === 'loading') completeParameterPublication();console.log('[impeccable] Injected ' + arrivedVariants + ' variants from source file.');}).catch(err => {@@ -5865,13 +6009,36 @@document.getElementById(VARIANT_STATE_STYLE_ID)?.remove();}+ function showOriginalDuringDiscard(sessionId) {+ if (!sessionId) return;+ let styleEl = document.getElementById(DISCARD_STATE_STYLE_ID);+ if (!styleEl) {+ styleEl = document.createElement('style');+ styleEl.id = DISCARD_STATE_STYLE_ID;+ (document.head || document.documentElement).appendChild(styleEl);+ }+ const wrapper = '[data-impeccable-variants="' + sessionId + '"]';+ styleEl.textContent = wrapper + ' > [data-impeccable-variant]:not([data-impeccable-variant="original"]) { display:none !important; }\n'+ + wrapper + ' > [data-impeccable-variant="original"] { display:block !important; }';+ }++ function resolveScrollLockAnchorTop() {+ const anchor = resolveBarAnchor();+ if (!anchor?.isConnected) return null;+ const top = anchor.getBoundingClientRect().top;+ return Number.isFinite(top) ? top : null;+ }+// Hold window.scrollY at a fixed value across DOM mutations inside the// session's wrapper (HMR patches, variant inserts, cycle swaps).- function startScrollLock(sessionId, initialTargetY) {+ function startScrollLock(sessionId, initialTargetY, initialAnchorTop) {stopScrollLock();scrollLockTargetY = typeof initialTargetY === 'number' && isFinite(initialTargetY)? initialTargetY: window.scrollY;+ scrollLockAnchorTop = typeof initialAnchorTop === 'number' && isFinite(initialAnchorTop)+ ? initialAnchorTop+ : resolveScrollLockAnchorTop();try { history.scrollRestoration = 'manual'; } catch {}@@ -5895,6 +6062,17 @@const correct = (why) => {scrollLockRaf = null;if (scrollLockTargetY == null) return;+ const anchor = resolveBarAnchor();+ if (anchor?.isConnected && typeof scrollLockAnchorTop === 'number' && isFinite(scrollLockAnchorTop)) {+ const anchorTop = anchor.getBoundingClientRect().top;+ const anchorDelta = anchorTop - scrollLockAnchorTop;+ if (Math.abs(anchorDelta) >= 0.5) {+ window.scrollTo({ top: window.scrollY + anchorDelta, left: window.scrollX, behavior: 'instant' });+ scrollLockTargetY = window.scrollY;+ writeScrollY(scrollLockTargetY);+ return;+ }+ }const before = window.scrollY;const delta = before - scrollLockTargetY;if (Math.abs(delta) < 0.5) {@@ -5939,6 +6117,7 @@if (scrollLockRaf != null) { cancelAnimationFrame(scrollLockRaf); scrollLockRaf = null; }const prevTarget = scrollLockTargetY;scrollLockTargetY = window.scrollY;+ scrollLockAnchorTop = resolveScrollLockAnchorTop();writeScrollY(scrollLockTargetY);};const markGesture = (why) => {@@ -5976,6 +6155,7 @@if (scrollLockRaf != null) { cancelAnimationFrame(scrollLockRaf); scrollLockRaf = null; }if (scrollLockAbort) { scrollLockAbort.abort(); scrollLockAbort = null; }scrollLockTargetY = null;+ scrollLockAnchorTop = null;// NOTE: do NOT clear the persistent scroll key here. startScrollLock// calls us as a reset, and clearing the key would nuke the Go-time// scrollY that the next resume needs to read.@@ -6049,6 +6229,7 @@updating = true;arrivedVariants = count;+ generationPhase = arrivedVariants >= expectedVariants ? 'variants_ready' : 'variants_progress';if (visibleVariant === 0 && arrivedVariants > 0) {const saved = loadSession();const savedVisibleVariant = saved && saved.id === sessionId ? saved.visible : 0;@@ -6064,7 +6245,7 @@const expected = parseInt(wrapper.dataset.impeccableVariantCount || '0');if (expected > 0) expectedVariants = expected;- if (arrivedVariants >= expectedVariants && expectedVariants > 0) {+ if (arrivedVariants > 0) {setLiveState('CYCLING');recoveryWaitingForAnchor = false;hideShaderOverlay();@@ -6072,13 +6253,18 @@updateSelectedElement();showOrUpdateCyclingBar();disableInlineEdit();- refreshParamsPanel();+ if (arrivedVariants >= expectedVariants && expectedVariants > 0) refreshParamsPanel();+ else hideParamsPanel();positionBar();} else if (state === 'GENERATING') {updateBarContent('generating');}saveSession();- queueCheckpoint(state === 'CYCLING' ? 'variants_ready' : 'variants_progress');+ sendCheckpoint(+ arrivedVariants >= expectedVariants && expectedVariants > 0+ ? 'variants_ready'+ : 'variants_progress',+ );updating = false;});@@ -6151,6 +6337,7 @@syncAgentPollingUi(!!msg.agentPolling);startAgentStatusPoll();restoreFromActiveSessions(msg.activeSessions, 'sse_connected');+ recoverMissedGenerationCompletion(msg.activeSessions);if (state === 'IDLE' && (pickActive || insertActive)) setLiveState('PICKING');syncPageInteractionCursor();syncPageChatFocus('sse-connected');@@ -6158,6 +6345,42 @@case 'agent_polling':syncAgentPollingUi(!!msg.connected);break;+ case 'agent_phase':+ if (msg.id === currentSessionId && (state === 'GENERATING' || state === 'CYCLING')) {+ generationPhase = msg.phase || generationPhase;+ if (msg.phase === 'variant_parameters_generating' || msg.phase === 'variant_parameters_validating') {+ parameterGenerationState = 'loading';+ }+ if (msg.phase === 'parameters_ready' && parameterGenerationState !== 'ready') {+ parameterGenerationState = 'loading';+ }+ updateBarContent(state === 'CYCLING' ? 'cycling' : 'generating');+ saveSession();+ }+ break;+ case 'variant_progress':+ if (msg.id === currentSessionId) {+ if (msg.publicationKind === 'params') parameterGenerationState = 'loading';+ rememberSessionFileMeta(msg);+ if (isFrameworkComponentPreviewMode(msg.previewMode) && msg.previewFile) {+ injectSvelteComponentsFromManifest(msg.previewFile, msg.id);+ } else if ((msg.previewMode === 'source' || !msg.previewMode) && (msg.previewFile || msg.file)) {+ // Give normal framework HMR the first chance to reconcile its+ // own managed tree. Nuxt route-module HMR can skip intermediate+ // revisions, so fall back to source injection only when the+ // advertised progress still has not appeared after a short+ // settle. Immediate injection races React/Vue ownership and can+ // trigger removeChild errors on the next HMR commit.+ const targetArrived = Number(msg.arrivedVariants) || 1;+ setTimeout(() => {+ if (msg.id !== currentSessionId) return;+ if (state !== 'GENERATING' && state !== 'CYCLING') return;+ if (msg.publicationKind !== 'params' && arrivedVariants >= targetArrived) return;+ injectVariantsFromSource(msg.previewFile || msg.file, msg.id);+ }, 150);+ }+ }+ break;case 'steer_done':maybeCompleteSteer(msg);break;@@ -6175,6 +6398,10 @@case 'done':if (maybeCompleteSteer(msg)) break;rememberSessionFileMeta(msg);+ if (msg.id === currentSessionId && isFrameworkComponentPreviewMode(currentPreviewMode) && currentPreviewFile) {+ injectSvelteComponentsFromManifest(currentPreviewFile, msg.id);+ break;+ }// Variants already arrived via HMR → normal transition.if (arrivedVariants >= expectedVariants && expectedVariants > 0) {if (state === 'GENERATING') {@@ -6190,7 +6417,7 @@setTimeout(() => {if (arrivedVariants >= expectedVariants && expectedVariants > 0) return;if (state !== 'GENERATING' || msg.id !== currentSessionId) return;- injectVariantsFromSource(msg.file, msg.id);+ injectVariantsFromSource(msg.file, msg.id, { generationCompleted: true });}, 750);break;}@@ -6215,9 +6442,10 @@if (maybeCompleteAcceptedSession(msg)) break;break;case 'agent_done':- // Carbonize accepts are not terminal until live-complete.mjs sends- // the final complete event. Keep the browser in its recoverable- // saving state while the source cleanup is still in flight.+ // The deterministic accept has already committed the reviewed DOM+ // and fenced generation. Carbonize may continue in the background;+ // it must not hold the foreground picker hostage.+ if (msg.data?.carbonize === true && maybeCompleteAcceptedSession(msg)) break;break;case 'discarded':if (msg.id && msg.id === currentSessionId) {@@ -6306,6 +6534,7 @@type: 'checkpoint',id: currentSessionId,revision: sessionState.nextCheckpointRevision(),+ revisionDomain: 'browser',owner: browserOwner,phase: String(state || '').toLowerCase(),reason,@@ -6331,6 +6560,7 @@type: 'checkpoint',id,revision: sessionState.nextCheckpointRevision(),+ revisionDomain: 'browser',owner: browserOwner,phase: 'steer',reason,@@ -6684,6 +6914,9 @@expectedVariants = selectedCount;arrivedVariants = 0;visibleVariant = 0;+ generationPhase = 'queued';+ parameterGenerationState = 'pending';+ parameterReadyAnnouncedSession = null;resetSessionFileMeta();// Flip to GENERATING immediately so the bar morphs without waiting on@@ -6693,6 +6926,7 @@const elForCapture = selectedElement;pickedAnchorSnapshot = buildPickedAnchorSnapshot(elForCapture);const captureRect = elForCapture.getBoundingClientRect();+ pickedAnchorViewportTop = captureRect.top;const snapshot = {comments: annotState.comments.map(c => ({ x: c.x, y: c.y, text: c.text })),strokes: annotState.strokes.map(s => ({ points: s.points.map(p => [p[0], p[1]]) })),@@ -6724,7 +6958,7 @@writeScrollY(window.scrollY);if (variantObserver) variantObserver.disconnect();variantObserver = startVariantObserver(currentSessionId);- startScrollLock(currentSessionId);+ startScrollLock(currentSessionId, window.scrollY, pickedAnchorViewportTop);captureAndEmit(elForCapture, basePayload, snapshot, captureRect);}@@ -6759,12 +6993,16 @@expectedVariants = selectedCount;arrivedVariants = 0;visibleVariant = 0;+ generationPhase = 'queued';+ parameterGenerationState = 'pending';+ parameterReadyAnnouncedSession = null;resetSessionFileMeta();selectedElement = placeholderElement;insertPlaceholderSnapshot = buildInsertPlaceholderSnapshotFromDom(insertAnchorElement, placeholderElement);const elForCapture = placeholderElement;const captureRect = elForCapture.getBoundingClientRect();+ pickedAnchorViewportTop = captureRect.top;const basePayload = {type: 'generate',mode: 'insert',@@ -6795,7 +7033,7 @@writeScrollY(window.scrollY);if (variantObserver) variantObserver.disconnect();variantObserver = startVariantObserver(currentSessionId);- startScrollLock(currentSessionId);+ startScrollLock(currentSessionId, window.scrollY, pickedAnchorViewportTop);captureAndEmit(elForCapture, basePayload, snapshot, captureRect);}@@ -6975,9 +7213,9 @@// preview mounts are covered by the same shader regression checks.const adapter = String(window.__IMPECCABLE_LIVE_ADAPTER__ || '').toLowerCase();if (adapter === 'svelte' || adapter === 'sveltekit') return true;- if (currentPreviewMode === 'svelte-component' || svelteComponentSession) return true;+ if (isFrameworkComponentPreviewMode(currentPreviewMode) || svelteComponentSession) return true;const wrapper = el?.closest?.('[data-impeccable-variants]');- return wrapper?.dataset?.impeccablePreview === 'svelte-component';+ return isFrameworkComponentPreviewMode(wrapper?.dataset?.impeccablePreview);}function paintsShaderProxySurface(node) {@@ -7105,6 +7343,17 @@}async function captureAndEmit(el, basePayload, snapshot, rect) {+ const hasAnnotations = snapshot && (snapshot.comments.length > 0 || snapshot.strokes.length > 0);++ // Plain requests do not send a screenshot to the agent, so capture is+ // presentation-only. Wait only for the helper to accept the event before+ // starting CPU-heavy capture; this yields the browser task and prevents+ // rasterization from delaying the fetch itself.+ if (!hasAnnotations) {+ basePayload.clientSentAt = Date.now();+ await sendEvent(basePayload);+ }+let screenshotPath;let blob;let paper;@@ -7122,7 +7371,6 @@// are present. Without annotations the image is pure visual anchoring -// it biases the model toward the current rendering and works against the// three-distinct-directions brief.- const hasAnnotations = snapshot && (snapshot.comments.length > 0 || snapshot.strokes.length > 0);if (blob && hasAnnotations) {try {const uploadRes = await fetch(@@ -7140,7 +7388,12 @@console.warn('[impeccable] annotation upload failed:', err);}}- sendEvent(screenshotPath ? { ...basePayload, screenshotPath } : basePayload);+ // Annotated requests must wait for capture + upload because the screenshot+ // is semantic input. Plain requests were already dispatched above.+ if (hasAnnotations) {+ basePayload.clientSentAt = Date.now();+ sendEvent(screenshotPath ? { ...basePayload, screenshotPath } : basePayload);+ }}//@@ -7520,7 +7773,6 @@ void main() {if (variantSelectionPromise) {try { await variantSelectionPromise; } catch { /* failed selection falls back below */ }}- if (!currentSessionId || arrivedVariants === 0) return;const domVisibleVariant = readVisibleVariantFromDOM(currentSessionId);if (domVisibleVariant > 0) visibleVariant = domVisibleVariant;const acceptPayload = {@@ -7528,7 +7780,9 @@ void main() {id: currentSessionId,variantId: String(visibleVariant),pageUrl: location.pathname,+ clientSentAt: Date.now(),};+ if (!currentSessionId || arrivedVariants === 0) return;const acceptWrapper = document.querySelector('[data-impeccable-variants="' + currentSessionId + '"]');if (Object.keys(paramsCurrentValues).length > 0) {acceptPayload.paramValues = { ...paramsCurrentValues };@@ -7542,7 +7796,7 @@ void main() {const acceptedSessionId = currentSessionId;const acceptedVariant = visibleVariant;const acceptedIsSvelteComponent = svelteComponentSession?.sessionId === acceptedSessionId- || acceptWrapper?.dataset?.impeccablePreview === 'svelte-component';+ || isFrameworkComponentPreviewMode(acceptWrapper?.dataset?.impeccablePreview);const acceptedSnapshot = snapshotAcceptedVariantDom(acceptedSessionId, acceptedVariant);setLiveState('SAVING');@@ -7557,7 +7811,17 @@ void main() {saveSession();sendEvent(acceptPayload, { throwOnError: true })- .then(() => {})+ .then(() => {+ const pending = pendingAcceptedSession;+ if (!pending || pending.id !== acceptedSessionId) return;+ // POST /events returns only after the accept intent is durable and the+ // generation epoch is fenced. Source promotion/carbonize can finish in+ // the background; the foreground picker is free immediately.+ markSessionHandled();+ setLiveState('CONFIRMED');+ document.documentElement.dataset.impeccableAcceptToPickingMs = String(Date.now() - acceptPayload.clientSentAt);+ scheduleAcceptCleanup(pending);+ }).catch(() => {if (pendingAcceptedSession?.id === acceptedSessionId) pendingAcceptedSession = null;setLiveState('CYCLING');@@ -7586,17 +7850,26 @@ void main() {}function scheduleAcceptCleanup(accepted) {- setTimeout(function() {- if (!accepted?.isSvelteComponent && !acceptedDomAlreadyClean(accepted)) {- setTimeout(function() {- if (pendingAcceptedSession?.id !== accepted?.id) return;- if (!accepted?.isSvelteComponent) ensureAcceptedDomClean(accepted);- cleanupAcceptedSession();- }, 1800);- return;+ queueMicrotask(function() {+ if (pendingAcceptedSession?.id !== accepted?.id) return;+ // Svelte previews live in an adapter-owned mount rather than in source+ // wrapper markup. Promote the mounted variant before releasing the+ // session so the old adapter instance cannot linger behind the next+ // Pick → Go loop while carbonize finishes in the background.+ if (accepted?.isSvelteComponent) {+ commitAcceptedSvelteComponentToDom(accepted.id);}cleanupAcceptedSession();- }, 1200);+ });+ // Let React/Vue/Svelte own the HMR reconciliation. Mutating their DOM in+ // the same turn as the source update causes removeChild/NotFoundError+ // races. Static servers still need a fallback, but it must not keep Live+ // in SAVING or block the user's next pick.+ if (!accepted?.isSvelteComponent) {+ setTimeout(function() {+ if (!acceptedDomAlreadyClean(accepted)) ensureAcceptedDomClean(accepted);+ }, 1200);+ }}function snapshotAcceptedVariantDom(sessionId, variantId) {@@ -7700,7 +7973,11 @@ void main() {clearSession();resetSessionFileMeta();selectedElement = null;+ hoveredElement = null;+ pagePickSkipClick = false;currentSessionId = null;+ parameterGenerationState = 'idle';+ parameterReadyAnnouncedSession = null;selectedAction = 'impeccable';pendingAcceptedSession = null;renderEditBadge('hidden');@@ -7735,7 +8012,7 @@ void main() {sendEvent({ type: 'discard', id: currentSessionId }, { throwOnError: true }).then(() => {markSessionHandled();- cleanup();+ cleanup({ restoreOriginal: true, instantChrome: true });}).catch(() => showToast('Could not confirm discard with the live server. Session kept for recovery.', 5000));}@@ -7757,6 +8034,7 @@ void main() {currentPreviewMode = null;recoveryWaitingForAnchor = false;pickedAnchorSnapshot = null;+ pickedAnchorViewportTop = null;}function rememberSessionFileMeta(meta = {}) {@@ -7765,8 +8043,8 @@ void main() {const previewFile = normalizeSessionPath(meta.previewFile);const previewMode = meta.previewMode || (isSvelteComponentManifestPath(previewFile || file) ? 'svelte-component' : null);- if (previewMode === 'svelte-component' || isSvelteComponentManifestPath(file)) {- currentPreviewMode = 'svelte-component';+ if (isFrameworkComponentPreviewMode(previewMode) || isSvelteComponentManifestPath(file)) {+ currentPreviewMode = isFrameworkComponentPreviewMode(previewMode) ? previewMode : 'svelte-component';currentPreviewFile = previewFile || (isSvelteComponentManifestPath(file) ? file : currentPreviewFile);currentSourceFile = sourceFile || currentSourceFile;return;@@ -7782,12 +8060,15 @@ void main() {rememberSessionFileMeta(saved);if (saved.insertPlaceholder) insertPlaceholderSnapshot = saved.insertPlaceholder;if (saved.pickedAnchor) pickedAnchorSnapshot = saved.pickedAnchor;+ if (Number.isFinite(saved.pickedAnchorViewportTop)) pickedAnchorViewportTop = saved.pickedAnchorViewportTop;if (saved.action) selectedAction = saved.action;if (saved.count) selectedCount = saved.count;if (saved.previewMode) currentPreviewMode = saved.previewMode;if (saved.paramValues && typeof saved.paramValues === 'object') {paramsCurrentValues = { ...saved.paramValues };}+ if (saved.parameterState) parameterGenerationState = saved.parameterState;+ if (saved.generationPhase) generationPhase = saved.generationPhase;}function normalizePagePath(value) {@@ -7859,7 +8140,7 @@ void main() {saveSession();queueCheckpoint(reason || 'browser_restore_without_wrapper');- const restoreFile = currentPreviewMode === 'svelte-component'+ const restoreFile = isFrameworkComponentPreviewMode(currentPreviewMode)? currentPreviewFile: (currentSourceFile || currentPreviewFile);if (restoreFile) {@@ -7872,11 +8153,41 @@ void main() {function restoreFromActiveSessions(activeSessions, reason) {const wrapper = document.querySelector('[data-impeccable-variants]');- if (wrapper && wrapper.dataset.impeccablePreview !== 'svelte-component') return false;+ if (wrapper && !isFrameworkComponentPreviewMode(wrapper.dataset.impeccablePreview)) return false;if (svelteComponentSession?.sessionId === currentSessionId) return false;return restoreSessionWithoutWrapper(reason || 'sse_connected', activeSessions);}+ // Self-heal on SSE (re)connect. The preflight scaffold write triggers a+ // framework full-reload (Astro reloads pages for any .astro edit); if the+ // agent's variant write + `done` broadcast land while this page is+ // mid-reload, both the done SSE and the second HMR reload are missed and+ // the resumed page would wait in GENERATING at 0/N forever. The server's+ // session summary carries the durable generationCompletedAt marker, so on+ // every connect compare it against our own progress and pull the finished+ // variants from source when behind. Mirrors the `done` handler's source+ // fallback, including its give-HMR-the-first-chance settle delay.+ function recoverMissedGenerationCompletion(activeSessions) {+ if (!currentSessionId || state !== 'GENERATING') return;+ if (!Array.isArray(activeSessions)) return;+ const summary = activeSessions.find((session) => session?.id === currentSessionId);+ if (!summary?.generationCompletedAt || summary.generationCanceled) return;+ if (isTerminalSessionSummary(summary)) return;+ if (arrivedVariants > 0 && arrivedVariants >= expectedVariants) return;+ rememberSessionFileMeta(summary);+ const sessionId = currentSessionId;+ const file = isFrameworkComponentPreviewMode(currentPreviewMode)+ ? currentPreviewFile+ : (summary.sourceFile || summary.previewFile || currentSourceFile || currentPreviewFile);+ if (!file) return;+ console.log('[impeccable] Reconnected after generation completed; recovering variants from source.');+ setTimeout(() => {+ if (sessionId !== currentSessionId || state !== 'GENERATING') return;+ if (arrivedVariants > 0 && arrivedVariants >= expectedVariants) return;+ injectVariantsFromSource(file, sessionId, { generationCompleted: true });+ }, 750);+ }+function saveSession() {if (!currentSessionId) return;// NOTE: scrollY is stored under a separate key (writeScrollY). Storing@@ -7894,8 +8205,12 @@ void main() {previewMode: currentPreviewMode || undefined,pageUrl: location.pathname,paramValues: { ...paramsCurrentValues },+ parameterState: parameterGenerationState,insertPlaceholder: insertPlaceholderSnapshot || undefined,pickedAnchor: pickedAnchorSnapshot || undefined,+ pickedAnchorViewportTop: Number.isFinite(pickedAnchorViewportTop) ? pickedAnchorViewportTop : undefined,+ pageHash: location.hash || undefined,+ pageSearch: location.search || undefined,});}@@ -7923,20 +8238,26 @@ void main() {sessionState.clearHandled();}- function cleanup() {+ function cleanup(options) {+ const restoreOriginal = options?.restoreOriginal === true;+ const instantChrome = options?.instantChrome === true;const cleanupSessionId = currentSessionId;if (svelteComponentSession?.sessionId === cleanupSessionId) {teardownSvelteComponentSession(true);} else if (cleanupSessionId) {- // Hide the wrapper immediately so variants disappear. DON'T structurally- // mutate the DOM yet - HMR from the agent's source rewrite is on its way,+ // Switch visibility immediately without structurally mutating the DOM.+ // HMR from the agent's source rewrite may still be on its way,// and a manual replaceChild under React causes NotFoundError when the// reconciler later tries to remove a wrapper we already removed.// Schedule a 2s fallback that does the manual swap only if HMR hasn't// replaced the wrapper by then (keeps static-server / no-HMR flows alive).const wrapper = document.querySelector('[data-impeccable-variants="' + cleanupSessionId + '"]');- if (wrapper) wrapper.style.display = 'none';+ if (wrapper) {+ if (restoreOriginal) showOriginalDuringDiscard(cleanupSessionId);+ else wrapper.style.display = 'none';+ }setTimeout(function() {+ document.getElementById(DISCARD_STATE_STYLE_ID)?.remove();if (!cleanupSessionId) return;const lateWrapper = document.querySelector('[data-impeccable-variants="' + cleanupSessionId + '"]');if (!lateWrapper) return;@@ -7951,7 +8272,7 @@ void main() {lateWrapper.remove();}, 2000);}- hideBar();+ hideBar(instantChrome);hideHighlight();stopScrollTracking();if (variantObserver) { variantObserver.disconnect(); variantObserver = null; }@@ -7963,7 +8284,11 @@ void main() {clearSession();resetSessionFileMeta();selectedElement = null;+ hoveredElement = null;+ pagePickSkipClick = false;currentSessionId = null;+ parameterGenerationState = 'idle';+ parameterReadyAnnouncedSession = null;selectedAction = 'impeccable';renderEditBadge('hidden');setLiveState('PICKING');@@ -8047,7 +8372,7 @@ void main() {// would strand the bar in CYCLING at 0/0. If there's no live in-memory mount// for this wrapper, it's an orphan (reload / failed mount): drop it and let// the live-server's SSE re-inject the manifest if the session is still live.- if (wrapper.dataset.impeccablePreview === 'svelte-component'+ if (isFrameworkComponentPreviewMode(wrapper.dataset.impeccablePreview)&& svelteComponentSession?.sessionId !== sessionId) {wrapper.remove();if (restoreSessionWithoutWrapper('browser_resumed_svelte_orphan_wrapper')) return true;@@ -8056,7 +8381,7 @@ void main() {return false;}- if (wrapper.dataset.impeccablePreview === 'svelte-component') {+ if (isFrameworkComponentPreviewMode(wrapper.dataset.impeccablePreview)) {if (!svelteComponentSession?.mountedVariant) {return true;}@@ -8104,7 +8429,7 @@ void main() {insertPlaceholderSnapshot = saved.insertPlaceholder;}- const resumedState = arrivedVariants >= expectedVariants ? 'CYCLING' : 'GENERATING';+ const resumedState = arrivedVariants > 0 ? 'CYCLING' : 'GENERATING';// Find the visible variant's content element for highlight positioning.const isInsert = wrapper.dataset.impeccableMode === 'insert';@@ -8128,7 +8453,11 @@ void main() {// hid. Now that state is CYCLING, re-fire.if (state === 'CYCLING') refreshParamsPanel();saveSession();- queueCheckpoint('browser_resumed');+ if (arrivedVariants > 0 && arrivedVariants < expectedVariants) {+ sendCheckpoint('variants_progress');+ } else {+ queueCheckpoint('browser_resumed');+ }// Start observing for more variants AFTER initial setupif (variantObserver) variantObserver.disconnect();@@ -8136,7 +8465,7 @@ void main() {// Hold the target at its saved viewport top through any subsequent// HMR patches, variant inserts, or cycle swaps.- startScrollLock(currentSessionId, readScrollY());+ startScrollLock(currentSessionId, readScrollY(), pickedAnchorViewportTop);// If we reloaded mid-generation (Bun's HTML HMR destroys the shader// canvas), re-capture the original's content and restart the shader so@@ -8171,6 +8500,7 @@ void main() {let globalBarBrandEl = null;let agentPollTooltipEl = null;let agentPollingConnected = false;+ let agentStatusMessage = null;let agentStatusPollTimer = null;let steerFocusSuspended = false;let steerFocusPauseUntil = 0;@@ -8275,6 +8605,13 @@ void main() {const AGENT_STATUS_POLL_MS = 5000;const AGENT_DISCONNECTED_MARK = 'oklch(62% 0 0 / 0.78)';const AGENT_DISCONNECTED_TIP = 'Agent disconnected - run live-poll.mjs to connect';+ // The indicator tracks whether a poll is parked, which is what decides if+ // steering can reach the agent right now. That goes quiet two ways, and they+ // need different copy: nobody is polling at all, or the agent took the work+ // and is busy with it. Under one-shot foreground polling the second case is+ // every normal generation, and telling the user to start a poll loop then is+ // wrong advice about a healthy session.+ const AGENT_BUSY_TIP = 'Agent is working - steering resumes when it finishes';const GLOBAL_BAR_SECTION_GAP = 8;const GLOBAL_BAR_INNER_GAP = 2;const GLOBAL_BAR_INNER_PAD_LEFT = 2;@@ -9295,24 +9632,46 @@ void main() {</svg>`;}+ /**+ * True while the browser is waiting on work it already handed to the agent.+ * In these states a quiet poll indicator means "busy", not "absent".+ */+ function agentHasWorkInFlight() {+ return state === 'GENERATING' || state === 'SAVING';+ }++ /**+ * Derived at read time, not cached: which of the two reasons applies depends on+ * the live state, which moves between the 5s status polls. The truthiness is+ * the same either way, so the indicator's visuals can stay driven by the+ * cached value while the wording stays current.+ */+ function agentStatusText() {+ if (agentPollingConnected) return null;+ return agentHasWorkInFlight() ? AGENT_BUSY_TIP : AGENT_DISCONNECTED_TIP;+ }+function syncAgentPollingUi(connected) {agentPollingConnected = !!connected;if (!globalBarBrandEl) return;const P = barPaletteForTheme(globalBarEl?.dataset.theme || detectPageTheme());+ agentStatusMessage = agentStatusText();globalBarBrandEl.dataset.agentConnected = connected ? 'true' : 'false';- globalBarBrandEl.setAttribute('aria-label', connected- ? 'Impeccable live mode'- : 'Impeccable live mode - agent not polling');+ // The tooltip is mouse-only, so carry the same distinction in the label or+ // screen-reader users are left with the vaguer of the two readings.+ globalBarBrandEl.setAttribute('aria-label', agentStatusMessage+ ? 'Impeccable live mode - ' + (agentHasWorkInFlight() ? 'agent is working' : 'agent not polling')+ : 'Impeccable live mode');globalBarBrandEl.removeAttribute('title');- globalBarBrandEl.style.cursor = connected ? 'default' : 'help';+ globalBarBrandEl.style.cursor = agentStatusMessage ? 'help' : 'default';const mark = globalBarBrandEl.querySelector('[data-brand-mark]');if (mark) {mark.innerHTML = brandMarkSvg(connected ? P.accent : AGENT_DISCONNECTED_MARK, 18);mark.style.opacity = '1';}const dot = globalBarBrandEl.querySelector('[data-agent-dot]');- if (dot) dot.style.display = connected ? 'none' : 'block';- if (connected) hideAgentPollTooltip();+ if (dot) dot.style.display = agentStatusMessage ? 'block' : 'none';+ if (!agentStatusMessage) hideAgentPollTooltip();}function ensureAgentPollTooltip() {@@ -9339,14 +9698,17 @@ void main() {whiteSpace: 'normal',});agentPollTooltipEl.id = PREFIX + '-agent-poll-tooltip';- agentPollTooltipEl.textContent = AGENT_DISCONNECTED_TIP;+ agentPollTooltipEl.textContent = agentStatusText() || AGENT_DISCONNECTED_TIP;uiAppend(agentPollTooltipEl);return agentPollTooltipEl;}function showAgentPollTooltip(anchor) {- if (agentPollingConnected || !anchor) return;+ if (!agentStatusMessage || !anchor) return;const tip = ensureAgentPollTooltip();+ // Re-derive rather than reuse the cached copy: the live state may have moved+ // since the last status poll set it.+ tip.textContent = agentStatusText() || AGENT_DISCONNECTED_TIP;tip.style.transition = 'none';tip.style.display = 'block';tip.style.opacity = '1';@@ -9376,7 +9738,9 @@ void main() {fetch('http://localhost:' + PORT + '/status?token=' + TOKEN, { cache: 'no-store' }).then((res) => (res.ok ? res.json() : null)).then((data) => {- if (data && typeof data.agentPolling === 'boolean') syncAgentPollingUi(data.agentPolling);+ if (data && typeof data.agentPolling === 'boolean') {+ syncAgentPollingUi(data.agentPolling);+ }}).catch(() => { /* server loss handled elsewhere */ });}diff --git a/.github/skills/impeccable/scripts/live-inject.mjs b/.github/skills/impeccable/scripts/live-inject.mjsindex 7c8d91182..d99c37fd5 100644--- a/.github/skills/impeccable/scripts/live-inject.mjs+++ b/.github/skills/impeccable/scripts/live-inject.mjs@@ -27,6 +27,8 @@ const __dirname = path.dirname(fileURLToPath(import.meta.url));const CONFIG_PATH = resolveLiveConfigPath({ cwd: process.cwd(), scriptsDir: __dirname });const MARKER_OPEN_TEXT = 'impeccable-live-start';const MARKER_CLOSE_TEXT = 'impeccable-live-end';+const NUXT_PLUGIN_MARKER = 'impeccable-live-nuxt-plugin';+const NUXT_PLUGIN_NAME = 'impeccable-live.client.ts';const IGNORE_MARKER_OPEN = '# impeccable-live-ignore-start';const IGNORE_MARKER_CLOSE = '# impeccable-live-ignore-end';@@ -38,6 +40,9 @@ export const LIVE_IGNORE_PATTERNS = Object.freeze(['.impeccable/live/sessions/','.impeccable/live/previews/','.impeccable/live/annotations/',+ '.impeccable/live/artifacts/',+ '.impeccable/live/accept-receipts/',+ '.impeccable/live/locks/','.impeccable/live/cache/','.impeccable/live/manual-edit-apply-transaction.json','.impeccable/live/manual-edit-events.jsonl',@@ -46,10 +51,15 @@ export const LIVE_IGNORE_PATTERNS = Object.freeze(['.impeccable/live/deferred-svelte-component-accepts.json','.impeccable-live.json','.impeccable-live/',+ 'app/.impeccable-live/',+ 'src/.impeccable-live/','node_modules/.impeccable-live/','src/lib/impeccable/ImpeccableLiveRoot.svelte','src/lib/impeccable/__runtime.js','src/lib/impeccable/[0-9a-f]*/',+ 'plugins/impeccable-live.client.ts',+ 'app/plugins/impeccable-live.client.ts',+ 'src/plugins/impeccable-live.client.ts',]);/**@@ -113,6 +123,7 @@ Output (JSON):const resolvedFiles = resolveFiles(process.cwd(), config);const svelteKit = detectSvelteKitProject(process.cwd(), config);+ const nuxt = detectNuxtProject(process.cwd());if (args.includes('--remove')) {if (svelteKit) {@@ -120,6 +131,12 @@ Output (JSON):console.log(JSON.stringify({ ok: true, adapter: 'sveltekit', results: [adapterResult] }));return;}+ if (nuxt) {+ const adapterResult = removeNuxtLiveAdapter({ cwd: process.cwd(), project: nuxt });+ console.log(JSON.stringify({ ok: !adapterResult.error, adapter: 'nuxt', results: [adapterResult] }));+ if (adapterResult.error) process.exitCode = 1;+ return;+ }const results = resolvedFiles.map((relFile) => {const absFile = path.resolve(process.cwd(), relFile);if (!fs.existsSync(absFile)) return { file: relFile, error: 'file_not_found' };@@ -145,13 +162,28 @@ Output (JSON):console.error(JSON.stringify({ ok: false, error: 'missing_port' }));process.exit(1);}- const gitIgnore = ensureLiveGitIgnores(process.cwd());+ const gitIgnore = ensureLiveGitIgnores(+ process.cwd(),+ nuxt ? [nuxt.pluginFile] : [],+ );if (svelteKit) {const adapterResult = applySvelteKitLiveAdapter({ cwd: process.cwd(), port, config });console.log(JSON.stringify({ ok: true, port, adapter: 'sveltekit', gitIgnore, results: [adapterResult] }));return;}+ if (nuxt) {+ const adapterResult = applyNuxtLiveAdapter({ cwd: process.cwd(), port, project: nuxt });+ console.log(JSON.stringify({+ ok: !adapterResult.error,+ port,+ adapter: 'nuxt',+ gitIgnore,+ results: [adapterResult],+ }));+ if (adapterResult.error) process.exitCode = 1;+ return;+ }const results = resolvedFiles.map((relFile) => {const absFile = path.resolve(process.cwd(), relFile);@@ -175,12 +207,12 @@ Output (JSON):if (!anyInserted) process.exit(1);}-export function ensureLiveGitIgnores(cwd = process.cwd()) {+export function ensureLiveGitIgnores(cwd = process.cwd(), extraPatterns = []) {const target = resolveIgnoreTarget(cwd);const existing = fs.existsSync(target.path) ? fs.readFileSync(target.path, 'utf-8') : '';const block = [IGNORE_MARKER_OPEN,- ...LIVE_IGNORE_PATTERNS,+ ...new Set([...LIVE_IGNORE_PATTERNS, ...extraPatterns]),IGNORE_MARKER_CLOSE,].join('\n');const markerRe = new RegExp(`${escapeRegExp(IGNORE_MARKER_OPEN)}[\\s\\S]*?${escapeRegExp(IGNORE_MARKER_CLOSE)}`);@@ -202,10 +234,119 @@ export function ensureLiveGitIgnores(cwd = process.cwd()) {file: path.relative(cwd, target.path).split(path.sep).join('/'),mode: target.mode,changed: updated !== existing,- patterns: [...LIVE_IGNORE_PATTERNS],+ patterns: [...new Set([...LIVE_IGNORE_PATTERNS, ...extraPatterns])],};}+// ---------------------------------------------------------------------------+// Nuxt adapter+//+// A script element placed in app.vue is compiled as Vue-rendered DOM and is+// not executed. Nuxt instead auto-discovers client plugins. Keep the adapter+// generated, dev-only, and outside user-authored source: Live creates one+// marked .client.ts plugin on start and removes it on stop.+// ---------------------------------------------------------------------------++export function detectNuxtProject(cwd = process.cwd()) {+ const configFile = fs.readdirSync(cwd, { withFileTypes: true })+ .find((entry) => entry.isFile() && /^nuxt\.config\.(?:js|mjs|cjs|ts|mts|cts)$/.test(entry.name))+ ?.name;+ if (!configFile) return null;++ const config = fs.readFileSync(path.join(cwd, configFile), 'utf-8');+ const literalSrcDir = config.match(/\bsrcDir\s*:\s*(['"])([^'"]+)\1/);+ let appDir = '';+ if (literalSrcDir) {+ const candidate = literalSrcDir[2]+ .replace(/\\/g, '/')+ .replace(/^\.\//, '')+ .replace(/\/+$/, '');+ const normalized = path.posix.normalize(candidate);+ if (normalized !== '..' && !normalized.startsWith('../') && !path.isAbsolute(normalized)) {+ appDir = normalized === '.' ? '' : normalized;+ }+ } else if (+ fs.existsSync(path.join(cwd, 'app', 'app.vue'))+ || fs.existsSync(path.join(cwd, 'app', 'pages'))+ ) {+ appDir = 'app';+ }++ const pluginFile = [appDir, 'plugins', NUXT_PLUGIN_NAME].filter(Boolean).join('/');+ return { configFile, appDir, pluginFile };+}++export function buildNuxtPlugin(port) {+ return `/* ${NUXT_PLUGIN_MARKER} */+const liveSrc = 'http://localhost:${port}/live.js';+const liveSelector = 'script[data-impeccable-live-nuxt]';++export default defineNuxtPlugin(() => {+ if (!import.meta.dev || typeof document === 'undefined') return;++ const expectedSrc = new URL(liveSrc, window.location.href).href;+ let script = document.querySelector(liveSelector);+ if (script?.src === expectedSrc) return;+ script?.remove();++ script = document.createElement('script');+ script.src = liveSrc;+ script.async = true;+ script.dataset.impeccableLiveNuxt = '';+ document.head.appendChild(script);++ import.meta.hot?.dispose(() => {+ if (script?.isConnected) script.remove();+ });+});+/* /${NUXT_PLUGIN_MARKER} */+`;+}++export function applyNuxtLiveAdapter({ cwd = process.cwd(), port, project = detectNuxtProject(cwd) }) {+ if (!project) return { error: 'nuxt_not_detected' };+ const absFile = path.join(cwd, project.pluginFile);+ const existing = fs.existsSync(absFile) ? fs.readFileSync(absFile, 'utf-8') : null;+ if (existing !== null && !existing.includes(NUXT_PLUGIN_MARKER)) {+ return {+ file: project.pluginFile,+ error: 'nuxt_plugin_conflict',+ hint: `${project.pluginFile} already exists and is not managed by Impeccable Live`,+ };+ }++ const content = buildNuxtPlugin(port);+ fs.mkdirSync(path.dirname(absFile), { recursive: true });+ if (content !== existing) fs.writeFileSync(absFile, content, 'utf-8');+ return {+ file: project.pluginFile,+ inserted: true,+ changed: content !== existing,+ devOnly: true,+ };+}++export function removeNuxtLiveAdapter({ cwd = process.cwd(), project = detectNuxtProject(cwd) }) {+ if (!project) return { error: 'nuxt_not_detected' };+ const absFile = path.join(cwd, project.pluginFile);+ if (!fs.existsSync(absFile)) {+ return { file: project.pluginFile, removed: false, note: 'no adapter present' };+ }+ const content = fs.readFileSync(absFile, 'utf-8');+ if (!content.includes(NUXT_PLUGIN_MARKER)) {+ return {+ file: project.pluginFile,+ removed: false,+ error: 'nuxt_plugin_conflict',+ hint: `${project.pluginFile} is not managed by Impeccable Live`,+ };+ }+ fs.unlinkSync(absFile);+ const pluginDir = path.dirname(absFile);+ if (fs.readdirSync(pluginDir).length === 0) fs.rmdirSync(pluginDir);+ return { file: project.pluginFile, removed: true };+}+function resolveIgnoreTarget(cwd) {const gitExcludePath = resolveGitInfoExcludePath(cwd);if (gitExcludePath) {diff --git a/.github/skills/impeccable/scripts/live-poll.mjs b/.github/skills/impeccable/scripts/live-poll.mjsindex 740161e10..19a8b0f9b 100644--- a/.github/skills/impeccable/scripts/live-poll.mjs+++ b/.github/skills/impeccable/scripts/live-poll.mjs@@ -27,7 +27,7 @@ const scriptCmd = (name) => `node "${path.join(SELF_DIR, name)}"`;export const PER_REQUEST_TIMEOUT_MS = 270_000;export const DEFAULT_EVENT_LEASE_MS = 600_000;-const EVENT_TYPES_NEEDING_AGENT_REPLY = new Set(['generate', 'steer', 'manual_edit_apply']);+const EVENT_TYPES_NEEDING_AGENT_REPLY = new Set(['generate', 'steer', 'manual_edit_apply', 'carbonize_cleanup']);function readServerInfo() {const record = readLiveServerInfo(process.cwd());@@ -38,8 +38,8 @@ function readServerInfo() {return record.info;}-export function buildPollReplyPayload(token, { id, type, message, file, data }) {- return { token, id, type, message, file, data };+export function buildPollReplyPayload(token, { id, type, message, file, data, sourceEventType }) {+ return { token, id, type, message, file, data, sourceEventType };}export function manualApplyPollBanner(event = {}) {@@ -152,7 +152,14 @@ export async function waitForEventAck(base, token, eventId, {return false;}-export async function fetchNextEvent(base, token, { totalDeadline } = {}) {+export async function fetchNextEvent(base, token, {+ totalDeadline,+ types,+ resolveTypes,+ perRequestTimeoutMs = PER_REQUEST_TIMEOUT_MS,+ leaseMs = DEFAULT_EVENT_LEASE_MS,+ signal,+} = {}) {while (true) {if (totalDeadline && Date.now() >= totalDeadline) {return { type: 'timeout' };@@ -161,8 +168,15 @@ export async function fetchNextEvent(base, token, { totalDeadline } = {}) {const remaining = totalDeadline? totalDeadline - Date.now(): PER_REQUEST_TIMEOUT_MS;- const slice = Math.min(Math.max(remaining, 1000), PER_REQUEST_TIMEOUT_MS);- const res = await fetch(`${base}/poll?token=${token}&timeout=${slice}&leaseMs=${DEFAULT_EVENT_LEASE_MS}`);+ const slice = Math.min(Math.max(remaining, 1000), perRequestTimeoutMs);+ const query = new URLSearchParams({+ token,+ timeout: String(slice),+ leaseMs: String(leaseMs),+ });+ const normalizedTypes = normalizePollTypes(resolveTypes ? await resolveTypes() : types);+ if (normalizedTypes.length > 0) query.set('types', normalizedTypes.join(','));+ const res = await fetch(`${base}/poll?${query}`, { signal });if (res.status === 401) {const err = new Error('Authentication failed. The server token may have changed.');@@ -202,11 +216,17 @@ export async function augmentEventWithAcceptHandling(event, base, token) {event._acceptResult = { handled: false, mode: 'error', error: err.message };}+ await completeAcceptHandling(event, base, token);+ return event;+}++export async function completeAcceptHandling(event, base, token) {const completionType = completionTypeForAcceptResult(event.type, event._acceptResult);try {await postReply(base, token, {id: event.id,type: completionType,+ sourceEventType: event.type,message: event._acceptResult?.error,file: event._acceptResult?.file,data: event._acceptResult?.carbonize === true ? { carbonize: true } : undefined,@@ -217,7 +237,6 @@ export async function augmentEventWithAcceptHandling(event, base, token) {if (!event._completionAck) {event._completionAck = completionAckForAcceptResult(event.id, completionType, event._acceptResult);}-return event;}@@ -245,9 +264,9 @@ export function printPollEvent(event) {console.log(JSON.stringify(event));}-export async function runPollOnce(base, token, { totalTimeout = 600_000 } = {}) {+export async function runPollOnce(base, token, { totalTimeout = 600_000, types, resolveTypes, perRequestTimeoutMs } = {}) {const deadline = Date.now() + totalTimeout;- const event = await fetchNextEvent(base, token, { totalDeadline: deadline });+ const event = await fetchNextEvent(base, token, { totalDeadline: deadline, types, resolveTypes, perRequestTimeoutMs });await augmentEventWithAcceptHandling(event, base, token);writeCarbonizeBanner(event);printPollEvent(event);@@ -258,11 +277,14 @@ export async function runPollStream(base, token, {ackTimeoutMs = 600_000,ackPollIntervalMs = 400,shouldContinue = () => true,+ types,+ resolveTypes,+ perRequestTimeoutMs,} = {}) {process.stderr.write('[impeccable-poll] stream mode: one JSON object per line on stdout; use --reply while this process stays running\n');while (shouldContinue()) {- const event = await fetchNextEvent(base, token);+ const event = await fetchNextEvent(base, token, { types, resolveTypes, perRequestTimeoutMs });await augmentEventWithAcceptHandling(event, base, token);writeCarbonizeBanner(event);printPollEvent(event);@@ -322,14 +344,17 @@ Modes:Options:--timeout=MS One-shot poll timeout in ms (default: 600000). Ignored in --stream mode+ --types=A,B Lease only these event types--ack-timeout=MS Stream mode: max wait for --reply after generate/steer (default: 600000)--file PATH Attach a source file path to the reply (generate/steer flow)--data JSON Attach a JSON result object to the reply (manual_edit_apply flow). Must be valid JSON--help Show this help messageHarness note:- Default one-shot mode is the portable contract for Claude Code, Codex, and Cursor.- --stream is experimental for harnesses with fast incremental stdout; do not use on Cursor.`);+ Default one-shot mode is the primary contract, including Codex foreground polling.+ Claude Code may run it as a background task; Cursor uses a background terminal with exit notification.+ --stream is retained for harnesses with measured, reliable incremental stdout.+ Do not use --stream on Cursor.`);process.exit(0);}@@ -360,23 +385,30 @@ Harness note:}const streamMode = args.includes('--stream');+ const typesArg = args.find((a) => a.startsWith('--types='));+ const types = normalizePollTypes(typesArg ? typesArg.slice('--types='.length) : null);const ackTimeoutArg = args.find((a) => a.startsWith('--ack-timeout='));const ackTimeoutMs = ackTimeoutArg ? parseInt(ackTimeoutArg.split('=')[1], 10) : 600_000;try {if (streamMode) {- await runPollStream(base, info.token, { ackTimeoutMs });+ await runPollStream(base, info.token, { ackTimeoutMs, types });return;}const timeoutArg = args.find((a) => a.startsWith('--timeout='));const totalTimeout = timeoutArg ? parseInt(timeoutArg.split('=')[1], 10) : 600_000;- await runPollOnce(base, info.token, { totalTimeout });+ await runPollOnce(base, info.token, { totalTimeout, types });} catch (err) {handlePollError(err);}}+export function normalizePollTypes(value) {+ const values = Array.isArray(value) ? value : String(value || '').split(',');+ return [...new Set(values.map((type) => String(type).trim()).filter(Boolean))];+}+// Auto-execute when run directlyconst _running = process.argv[1];if (_running?.endsWith('live-poll.mjs') || _running?.endsWith('live-poll.mjs/')) {diff --git a/.github/skills/impeccable/scripts/live-server.mjs b/.github/skills/impeccable/scripts/live-server.mjsindex 5735f2aec..c6e951086 100644--- a/.github/skills/impeccable/scripts/live-server.mjs+++ b/.github/skills/impeccable/scripts/live-server.mjs@@ -28,8 +28,10 @@ import {readLiveBrowserScriptParts,resolveLiveBrowserScriptParts,} from './live/browser-script-parts.mjs';-import { createLiveSessionStore } from './live/session-store.mjs';+import { createLiveSessionStore, GENERATION_FENCED_PHASES } from './live/session-store.mjs';+import { runGenerationPreflight } from './live/generation-preflight.mjs';import { validateEvent } from './live/event-validation.mjs';+import { selectAvailablePendingEvent } from './live/poll-lanes.mjs';import { createManualEditRoutes } from './live/manual-edit-routes.mjs';import { LIVE_COMMANDS } from './live/vocabulary.mjs';import {@@ -63,6 +65,10 @@ const DESIGN_MD_PATH = PROJECT_CONTEXT.designPath: null;const DEFAULT_POLL_TIMEOUT = 600_000; // 10 min — agent re-polls on timeout anywayconst SSE_HEARTBEAT_INTERVAL = 30_000; // keepalive ping every 30s+// The browser checkpoints for several unrelated reasons (see checkpointPayload+// in live-browser.js). Only these two report that variant availability changed,+// and only they may drive variant_progress / the *_reviewable phases.+const VARIANT_PROGRESS_CHECKPOINT_REASONS = new Set(['variants_progress', 'variants_ready']);// ---------------------------------------------------------------------------// Port detection@@ -156,29 +162,206 @@ function restorePendingEventsFromStore() {}}-function findAvailablePendingEvent(now = Date.now()) {- for (const entry of state.pendingEvents) {- if (entry.leaseUntil && entry.leaseUntil > now) continue;- return entry;- }- return null;+function findAvailablePendingEvent(now = Date.now(), types = null) {+ return selectAvailablePendingEvent(state.pendingEvents, { now, types });}-function leaseEvent(entry, leaseMs) {+async function leaseEvent(entry, leaseMs) {+ // Claim the entry before awaiting anything. prepareGenerateEventForLease+ // yields to the event loop, and selectAvailablePendingEvent only skips+ // entries whose lease is in the future — an unclaimed entry would be handed+ // to a second poll in that window and generated twice.+ entry.leaseUntil = Date.now() + leaseMs;+ await prepareGenerateEventForLease(entry);if (!entry.event?.id) {const idx = state.pendingEvents.indexOf(entry);if (idx !== -1) state.pendingEvents.splice(idx, 1);return entry.event;}+ // Re-stamp so the lease window starts when the agent actually receives the+ // work, not when scaffolding began.entry.leaseUntil = Date.now() + leaseMs;+ recordGenerateDelivery(entry);scheduleLeaseFlush();broadcastAgentPollingIfChanged();return entry.event;}-function acknowledgePendingEvent(id) {+function recordGenerateDelivery(entry) {+ const event = entry?.event;+ if (!event || event.type !== 'generate' || event.generationReadyAt) return;+ const at = Date.now();+ entry.event = { ...event, generationReadyAt: at };+ state.sessionStore?.appendEvent(entry.event);+ recordAgentPhase(event.id, 'generation_ready', { at });+}++async function prepareGenerateEventForLease(entry) {+ const event = entry?.event;+ if (!event || event.type !== 'generate' || event.scaffoldAttempted) return;++ recordAgentPhase(event.id, 'picked_up');+ recordAgentPhase(event.id, 'scaffolding');+ const result = await runGenerationPreflight(event, {+ cwd: process.cwd(),+ scriptsDir: __dirname,+ });+ entry.event = {+ ...event,+ scaffoldAttempted: true,+ scaffoldDurationMs: result.durationMs ?? null,+ ...(result.ok ? { scaffold: result.scaffold } : { scaffoldError: result.error || result.reason }),+ };+ state.sessionStore?.appendEvent(entry.event);+ recordAgentPhase(event.id, result.ok ? 'source_ready' : 'scaffold_fallback', {+ durationMs: result.durationMs ?? null,+ previewMode: result.scaffold?.previewMode || 'source',+ });+}++function recordAgentPhase(id, phase, details = {}) {+ if (!id) return;+ const event = {+ type: 'agent_phase',+ id,+ phase,+ at: Date.now(),+ ...details,+ };+ state.sessionStore?.appendEvent(event);+ broadcast(event);+}++/**+ * Detect a browser that missed the generation `done` broadcast.+ *+ * The preflight scaffold write triggers a framework full-reload (Astro reloads+ * the page for any .astro edit). If the agent's variant write + `done` land+ * while the browser is mid-reload, the new page misses both the second HMR+ * reload and the SSE `done` — it resumes from the scaffold-only source and+ * sits in GENERATING at 0/N forever. That resumed page always checkpoints+ * (`browser_resumed`), so a checkpoint claiming "still generating, variants+ * missing" for a session whose generation already completed is direct+ * evidence of the miss. Rebuild the `done` payload from the snapshot so the+ * caller can re-broadcast it; the browser's done handler is idempotent and+ * falls back to injecting variants from source.+ *+ * Keys on the store's monotone `generationCompletedAt`, not `phase` — the+ * behind checkpoint itself regresses `phase` to `generating`, and a browser+ * that misses the redelivered `done` too (another reload) must still trigger+ * redelivery from its next checkpoint.+ */+function detectMissedGenerationCompletion(event) {+ if (!event?.id || event.type !== 'checkpoint') return null;+ if (event.phase !== 'generating') return null;+ if (!variantCountLooksBehind(event.arrivedVariants, event.expectedVariants)) return null;+ if (!state.sessionStore) return null;+ let snapshot = null;+ try {+ snapshot = state.sessionStore.getSnapshot(event.id);+ } catch {+ return null;+ }+ return missedCompletionFromSnapshot(snapshot);+}++function variantCountLooksBehind(arrivedValue, expectedValue) {+ const arrived = Number(arrivedValue) || 0;+ const expected = Number(expectedValue) || 0;+ return arrived <= 0 || (expected > 0 && arrived < expected);+}++function missedCompletionFromSnapshot(snapshot) {+ if (!snapshot?.id || !snapshot.generationCompletedAt) return null;+ if (snapshot.generationCanceled) return null;+ // Accept/discard already underway: the browser is no longer waiting on+ // generation, and a late `done` there would collide with teardown.+ if (GENERATION_FENCED_PHASES.has(snapshot.phase)) return null;+ const file = snapshot.sourceFile || snapshot.previewFile;+ if (!file) return null;+ return {+ type: 'done',+ id: snapshot.id,+ file,+ sourceFile: snapshot.sourceFile || undefined,+ previewFile: snapshot.previewFile || undefined,+ previewMode: snapshot.previewMode || undefined,+ redelivered: true,+ };+}++function recordGenerationCheckpoint(event) {+ if (!event?.id || event.type !== 'checkpoint') return;+ if (generationIsFenced(event.id)) return;+ // Only checkpoints that report a change in variant availability are+ // generation progress. The browser also checkpoints for durability on Tune+ // slider drags, resumes, and anchor recovery; treating those as progress+ // echoed `variant_progress` straight back to the browser that sent it, which+ // remounts the component preview mid-drag (reverting the user's live param+ // edit and detaching the popover's element), and permanently latched the+ // *_reviewable phases from the wrong trigger, corrupting generation timings.+ if (!VARIANT_PROGRESS_CHECKPOINT_REASONS.has(event.reason)) return;+ const arrived = Number(event.arrivedVariants) || 0;+ const expected = Number(event.expectedVariants) || 0;+ if (arrived <= 0 || expected <= 0) return;+ const previewMode = event.previewMode || 'source';+ const previewFile = event.previewFile || event.file;+ if (previewFile) {+ broadcast({+ type: 'variant_progress',+ id: event.id,+ file: previewFile,+ sourceFile: event.sourceFile || (previewMode === 'source' ? previewFile : undefined),+ previewFile,+ previewMode,+ arrivedVariants: arrived,+ expectedVariants: expected,+ publicationKind: event.publicationKind || 'variants',+ });+ }+ const details = {+ arrivedVariants: arrived,+ expectedVariants: expected,+ checkpointReason: event.reason || null,+ };+ const at = Date.now();+ if (!generationPhaseAlreadyRecorded(event.id, 'first_reviewable')) {+ recordAgentPhase(event.id, 'first_reviewable', { ...details, at });+ }+ if (arrived >= 2 && expected >= 3 && !generationPhaseAlreadyRecorded(event.id, 'second_reviewable')) {+ recordAgentPhase(event.id, 'second_reviewable', { ...details, at });+ }+ if (arrived >= expected && !generationPhaseAlreadyRecorded(event.id, 'all_variants_ready')) {+ recordAgentPhase(event.id, 'all_variants_ready', { ...details, at });+ }+}++function generationIsFenced(id) {+ if (!state.sessionStore || !id) return false;+ try {+ const snapshot = state.sessionStore.getSnapshot(id, { includeCompleted: true });+ return snapshot?.generationCanceled === true;+ } catch {+ return false;+ }+}++function generationPhaseAlreadyRecorded(id, phase) {+ if (!state.sessionStore) return false;+ try {+ const snapshot = state.sessionStore.getSnapshot(id, { includeCompleted: true });+ return !!snapshot?.generationTimings?.[phase];+ } catch {+ return false;+ }+}++function acknowledgePendingEvent(id, sourceEventType) {if (!id) return false;- const idx = state.pendingEvents.findIndex((entry) => entry.event?.id === id);+ const idx = state.pendingEvents.findIndex((entry) => (+ entry.event?.id === id+ && (!sourceEventType || entry.event?.type === sourceEventType)+ ));if (idx === -1) return false;const acknowledged = state.pendingEvents[idx].event;state.pendingEvents.splice(idx, 1);@@ -187,9 +370,39 @@ function acknowledgePendingEvent(id) {return acknowledged;}-function findPendingEventById(id) {+function releasePendingEvent(id, sourceEventType) {+ const entry = state.pendingEvents.find((item) => (+ item.event?.id === id+ && (!sourceEventType || item.event?.type === sourceEventType)+ ));+ if (!entry) return null;+ entry.leaseUntil = 0;+ scheduleLeaseFlush();+ return entry.event;+}++function retirePendingGeneration(id) {+ if (!id) return 0;+ let retired = 0;+ for (let index = state.pendingEvents.length - 1; index >= 0; index -= 1) {+ const event = state.pendingEvents[index]?.event;+ if (event?.id !== id || event.type !== 'generate') continue;+ state.pendingEvents.splice(index, 1);+ retired += 1;+ }+ if (retired > 0) {+ scheduleLeaseFlush();+ broadcastAgentPollingIfChanged();+ }+ return retired;+}++function findPendingEventById(id, sourceEventType) {if (!id) return null;- const entry = state.pendingEvents.find((item) => item.event?.id === id);+ const entry = state.pendingEvents.find((item) => (+ item.event?.id === id+ && (!sourceEventType || item.event?.type === sourceEventType)+ ));return entry?.event || null;}@@ -198,7 +411,7 @@ function summarizePendingEventForStatus(entry) {const summary = {id: event.id,type: event.type,- leased: !!(entry.leaseUntil && entry.leaseUntil > Date.now()),+ leased: isLeased(entry),leaseUntil: entry.leaseUntil || null,};if (event.type === 'manual_edit_apply') {@@ -224,7 +437,13 @@ function summarizeActiveSessionForClient(snapshot = {}) {arrivedVariants: snapshot.arrivedVariants ?? 0,visibleVariant: snapshot.visibleVariant ?? null,checkpointRevision: snapshot.checkpointRevision ?? 0,+ browserCheckpointRevision: snapshot.browserCheckpointRevision ?? snapshot.checkpointRevision ?? 0,+ publicationCheckpointRevision: snapshot.publicationCheckpointRevision ?? 0,paramValues: snapshot.paramValues || {},+ generationPhase: snapshot.generationPhase ?? null,+ generationCompletedAt: snapshot.generationCompletedAt ?? null,+ generationCanceled: snapshot.generationCanceled === true,+ cancelReason: snapshot.cancelReason ?? null,};}@@ -269,24 +488,46 @@ function scheduleLeaseFlush() {function flushPendingPolls() {let changed = false;while (state.pendingPolls.length > 0) {- const entry = findAvailablePendingEvent();+ let pollIndex = -1;+ let entry = null;+ for (let index = 0; index < state.pendingPolls.length; index += 1) {+ const candidate = findAvailablePendingEvent(Date.now(), state.pendingPolls[index].types);+ if (!candidate) continue;+ pollIndex = index;+ entry = candidate;+ break;+ }if (!entry) {scheduleLeaseFlush();broadcastAgentPollingIfChanged();return;}- const poll = state.pendingPolls.shift();- poll.resolve(leaseEvent(entry, poll.leaseMs));+ const [poll] = state.pendingPolls.splice(pollIndex, 1);+ // leaseEvent is async (it may scaffold source), but it claims the entry+ // synchronously, so the next loop iteration will not re-select it. Resolve+ // the poll when the lease settles rather than awaiting here, so one slow+ // scaffold never delays the other parked polls. On the exceptional failure+ // path, answer `timeout` so the agent re-polls; the claim stays until the+ // lease expires, which keeps a deterministic failure from hot-looping.+ leaseEvent(entry, poll.leaseMs).then(poll.resolve, (error) => {+ console.error('[live] lease failed for ' + (entry.event?.id || 'unknown') + ': ' + (error?.message || error));+ poll.resolve({ type: 'timeout' });+ });changed = true;}scheduleLeaseFlush();if (changed) broadcastAgentPollingIfChanged();}+function isLeased(entry) {+ return !!(entry?.leaseUntil && entry.leaseUntil > Date.now());+}+function agentPollingConnected() {- const now = Date.now();- return state.pendingPolls.length > 0- || state.pendingEvents.some((entry) => entry.leaseUntil && entry.leaseUntil > now);+ // A leased event only proves that a poll returned once. The foreground task+ // may have ended immediately afterward, so only an actively waiting poll is+ // evidence that steering can wake the task right now.+ return state.pendingPolls.length > 0;}function broadcastAgentPollingIfChanged() {@@ -689,6 +930,16 @@ function createRequestHandler({ detectScript, liveScriptParts }) {res.end(JSON.stringify({ error }));return;}+ if (msg.type === 'agent_phase') {+ recordAgentPhase(msg.id, msg.phase, {+ ...(Number.isFinite(msg.durationMs) ? { durationMs: msg.durationMs } : {}),+ owner: typeof msg.owner === 'string' ? msg.owner : undefined,+ });+ res.writeHead(200, { 'Content-Type': 'application/json' });+ res.end(JSON.stringify({ ok: true }));+ return;+ }+ const missedCompletion = detectMissedGenerationCompletion(msg);if (state.sessionStore && msg.id) {try {state.sessionStore.appendEvent(msg);@@ -698,6 +949,11 @@ function createRequestHandler({ detectScript, liveScriptParts }) {return;}}+ if (msg.type === 'accept' || msg.type === 'discard') {+ retirePendingGeneration(msg.id);+ }+ recordGenerationCheckpoint(msg);+ if (missedCompletion) broadcast(missedCompletion);if (msg.type === 'exit') {cleanupSvelteComponentSessionsBeforeExit();}@@ -738,6 +994,12 @@ function createRequestHandler({ detectScript, liveScriptParts }) {// Agent poll endpoints (unchanged from WS version)// ---------------------------------------------------------------------------+function parsePollTypes(value) {+ if (!value) return null;+ const types = String(value).split(',').map((type) => type.trim()).filter(Boolean);+ return types.length > 0 ? new Set(types) : null;+}+function handlePollGet(req, res, url) {const token = url.searchParams.get('token');if (token !== state.token) {@@ -748,13 +1010,25 @@ function handlePollGet(req, res, url) {state.lastPollAt = Date.now();const timeout = parseInt(url.searchParams.get('timeout') || DEFAULT_POLL_TIMEOUT, 10);const leaseMs = parseInt(url.searchParams.get('leaseMs') || '30000', 10);- const available = findAvailablePendingEvent();+ const types = parsePollTypes(url.searchParams.get('types'));+ const available = findAvailablePendingEvent(Date.now(), types);if (available) {- res.writeHead(200, { 'Content-Type': 'application/json' });- res.end(JSON.stringify(leaseEvent(available, leaseMs)));+ // Do not await inline: leaseEvent may scaffold source, and this handler runs+ // on the server's only thread. The client can disconnect during that window,+ // so check the socket before replying.+ leaseEvent(available, leaseMs).then((event) => {+ if (res.writableEnded || res.destroyed) return;+ res.writeHead(200, { 'Content-Type': 'application/json' });+ res.end(JSON.stringify(event));+ }, (error) => {+ console.error('[live] lease failed for ' + (available.event?.id || 'unknown') + ': ' + (error?.message || error));+ if (res.writableEnded || res.destroyed) return;+ res.writeHead(200, { 'Content-Type': 'application/json' });+ res.end(JSON.stringify({ type: 'timeout' }));+ });return;}- const poll = { resolve, leaseMs };+ const poll = { resolve, leaseMs, types };const timer = setTimeout(() => {const idx = state.pendingPolls.indexOf(poll);if (idx !== -1) state.pendingPolls.splice(idx, 1);@@ -783,12 +1057,15 @@ function sessionFileMetadataFromPollReply(file) {if (!file || typeof file !== 'string') return { file };const normalized = file.split(path.sep).join('/');const base = { file: normalized };- if (!normalized.endsWith('/manifest.json') && normalized !== 'manifest.json') return base;- if (!normalized.includes('node_modules/.impeccable-live/') && !normalized.includes('src/lib/impeccable/')) return base;+ const metadataFile = normalized;+ if (!metadataFile.endsWith('/manifest.json') && metadataFile !== 'manifest.json') return base;+ if (!metadataFile.includes('node_modules/.impeccable-live/')+ && !metadataFile.includes('src/lib/impeccable/')+ && !metadataFile.includes('/.impeccable-live/')) return base;let full;try {- full = path.resolve(process.cwd(), normalized);+ full = path.resolve(process.cwd(), metadataFile);const rel = path.relative(process.cwd(), full);if (!rel || rel.startsWith('..') || path.isAbsolute(rel)) return base;} catch {@@ -797,18 +1074,47 @@ function sessionFileMetadataFromPollReply(file) {try {const manifest = JSON.parse(fs.readFileSync(full, 'utf-8'));- if (manifest?.previewMode !== 'svelte-component' || !manifest.sourceFile) return base;+ if (manifest?.previewMode !== 'svelte-component'+ || !manifest.sourceFile) return base;return {file: String(manifest.sourceFile).split(path.sep).join('/'),sourceFile: String(manifest.sourceFile).split(path.sep).join('/'),previewFile: normalized,- previewMode: 'svelte-component',+ previewMode: manifest.previewMode,};} catch {return base;}}+function inferSourceEventType(msg = {}, pendingEvents = state.pendingEvents) {+ const entriesForId = pendingEvents.filter((entry) => entry.event?.id === msg.id);+ const pendingTypes = new Set(entriesForId.map((entry) => entry.event?.type));+ if (msg.type === 'discarded' || msg.type === 'discard') return 'discard';+ if (msg.type === 'complete') {+ if (pendingTypes.has('carbonize_cleanup')) return 'carbonize_cleanup';+ return pendingTypes.has('accept') ? 'accept' : (pendingTypes.has('generate') ? 'generate' : undefined);+ }+ if (msg.type === 'steer_done') return 'steer';+ // `agent_done` can be the automatic acknowledgement for a carbonize Accept.+ // New pollers send sourceEventType explicitly; default to generate only for+ // older callers so a late worker cannot acknowledge a queued Accept.+ if (msg.type === 'agent_done' || msg.type === 'done') return 'generate';+ // `error` is reference/live.md's documented failure reply, and parseReplyArgs+ // never sets sourceEventType on it (the poller is a fresh process that cannot+ // know what it leased). Returning undefined here makes acknowledgePendingEvent+ // match *any* event for this id: a stale generate worker's failure silently+ // consumed the user's queued Accept, which was then never delivered to any+ // agent and left the browser in SAVING forever. Attribute the failure to the+ // event this agent actually holds a lease on, and otherwise to `generate` —+ // never to a wildcard. If that generate was already retired by an Accept, the+ // ack simply finds no match, which is the correct outcome for a stale reply.+ if (msg.type === 'error') {+ return entriesForId.find(isLeased)?.event?.type || 'generate';+ }+ return undefined;+}+function handlePollPost(req, res) {let body = '';req.on('data', (c) => { body += c; });@@ -869,7 +1175,23 @@ function handlePollPost(req, res) {res.end(JSON.stringify({ error: 'stale_manual_edit_apply_reply', ...rollback }));return;}- const pendingEventBeforeAck = findPendingEventById(msg.id);+ const sourceEventType = msg.sourceEventType || inferSourceEventType(msg);+ if (msg.type === 'retry') {+ const releasedEvent = releasePendingEvent(msg.id, sourceEventType);+ if (!releasedEvent) {+ res.writeHead(msg.id ? 404 : 400, { 'Content-Type': 'application/json' });+ res.end(JSON.stringify({+ error: msg.id ? 'unknown_poll_retry_id' : 'missing_poll_retry_id',+ id: msg.id,+ }));+ return;+ }+ flushPendingPolls();+ res.writeHead(200, { 'Content-Type': 'application/json' });+ res.end(JSON.stringify({ ok: true, released: true }));+ return;+ }+ const pendingEventBeforeAck = findPendingEventById(msg.id, sourceEventType);if (pendingEventBeforeAck?.type === 'steer' && msg.type === 'steer_done'&& !msg.file && !(typeof msg.message === 'string' && msg.message.trim())) {res.writeHead(400, { 'Content-Type': 'application/json' });@@ -879,7 +1201,7 @@ function handlePollPost(req, res) {}));return;}- const acknowledgedEvent = acknowledgePendingEvent(msg.id);+ const acknowledgedEvent = acknowledgePendingEvent(msg.id, sourceEventType);let skipJournalReply = false;let existingSession = null;if (!acknowledgedEvent && state.sessionStore && msg.id) {@@ -1083,7 +1405,10 @@ if (args.includes('--background')) {process.exit(0);}} catch { /* not ready yet */ }- await new Promise(r => setTimeout(r, 200));+ // The detached child is typically listening in 35-45ms. A 200ms polling+ // floor dominated configured cold Live startup; poll cheaply and return+ // as soon as the child has written its ready record.+ await new Promise(r => setTimeout(r, 5));}console.error('Timed out waiting for live server to start.');process.exit(1);diff --git a/.github/skills/impeccable/scripts/live-status.mjs b/.github/skills/impeccable/scripts/live-status.mjsindex f7e464999..dc98b7386 100644--- a/.github/skills/impeccable/scripts/live-status.mjs+++ b/.github/skills/impeccable/scripts/live-status.mjs@@ -37,15 +37,19 @@ export async function statusCli() {pendingEvents: server.pendingEvents,} : null,activeSessions: server?.activeSessions || activeSessions,- recoveryHint: manualApply- ? manualApplyResumeHint(manualApply)- : server- ? 'Run live-poll.mjs to continue pending work, or live-complete.mjs --id <session> after manual cleanup.'- : 'Start live-server.mjs to requeue pending durable events, then run live-poll.mjs.',+ recoveryHint: recoveryHint({ server, manualApply }),};console.log(JSON.stringify(payload, null, 2));}+function recoveryHint({ server, manualApply }) {+ if (manualApply) return manualApplyResumeHint(manualApply);+ if (server) {+ return 'Run live-poll.mjs to continue pending work, or live-complete.mjs --id <session> after manual cleanup.';+ }+ return 'Start live-server.mjs to requeue pending durable events, then run live-poll.mjs.';+}+function findPendingManualApply(server, activeSessions) {const fromServer = server?.pendingEvents?.find((event) => event?.type === 'manual_edit_apply');if (fromServer) return fromServer;diff --git a/.github/skills/impeccable/scripts/live-wrap.mjs b/.github/skills/impeccable/scripts/live-wrap.mjsindex 438c01b68..48d7f7683 100644--- a/.github/skills/impeccable/scripts/live-wrap.mjs+++ b/.github/skills/impeccable/scripts/live-wrap.mjs@@ -160,11 +160,29 @@ The agent should insert variant HTML at insertLine.`);if (filtered.length === 1) {match = filtered[0];} else if (filtered.length === 0) {- // Source uses dynamic content (`<h1>{title}</h1>` etc.) so the- // browser-side textContent doesn't appear literally in source. Fall- // back to first-match rather than refusing — this is the same- // behavior unmodified callers see, just preserved.- match = candidates[0];+ const normalizedText = String(text).replace(/\s+/g, ' ').trim();+ if (normalizedText.length < 8) {+ // Very short labels cannot disambiguate siblings reliably. Preserve+ // the legacy behavior for these low-information picker events.+ match = candidates[0];+ } else {+ // Rendered text that is absent from every candidate usually means+ // the source uses expressions or component props. Picking the first+ // same-class sibling silently edits the wrong instance (observed on+ // Astro result cards), so stop and surface every candidate instead.+ console.error(JSON.stringify({+ error: 'element_ambiguous',+ fallback: 'agent-driven',+ reason: 'rendered_text_not_in_source',+ file: path.relative(process.cwd(), targetFile),+ candidates: candidates.map((c) => ({+ startLine: c.startLine + 1,+ endLine: c.endLine + 1,+ })),+ hint: 'Rendered text does not occur in any matching source branch. The element may use dynamic props or expressions; inspect the candidates and wrap the intended instance manually.',+ }));+ process.exit(1);+ }} else {// Multiple candidates ALSO match the text. Truly ambiguous — refuse// rather than pick wrong, and hand the agent the candidate locations@@ -269,6 +287,7 @@ The agent should insert variant HTML at insertLine.`);const originalIndented = reindentOriginal(' ');const relTargetFile = path.relative(process.cwd(), targetFile).split(path.sep).join('/');const useSvelteComponent = shouldUseSvelteComponentInjection(targetFile);+ const useFrameworkComponent = useSvelteComponent;// Wrapper attributes differ by syntax. HTML allows plain string attrs;// JSX requires object-literal style and parses string attrs as HTML (which@@ -288,7 +307,7 @@ The agent should insert variant HTML at insertLine.`);// replacement range to include the wrapper's `<div>` open / close lines// so the entire scaffold gets removed cleanly.const wrapperLines = isJsx ? [- indent + '<div data-impeccable-variants="' + id + '" data-impeccable-variant-count="' + count + '" ' + styleContents + '>',+ indent + '<div data-impeccable-variants="' + id + '" data-impeccable-variant-count="' + count + '"' + ' ' + styleContents + '>',indent + ' ' + commentSyntax.open + ' impeccable-variants-start ' + id + ' ' + commentSyntax.close,indent + ' ' + commentSyntax.open + ' Original ' + commentSyntax.close,indent + ' <div data-impeccable-variant="original">',@@ -299,7 +318,7 @@ The agent should insert variant HTML at insertLine.`);indent + '</div>',] : [indent + commentSyntax.open + ' impeccable-variants-start ' + id + ' ' + commentSyntax.close,- indent + '<div data-impeccable-variants="' + id + '" data-impeccable-variant-count="' + count + '" ' + styleContents + '>',+ indent + '<div data-impeccable-variants="' + id + '" data-impeccable-variant-count="' + count + '"' + ' ' + styleContents + '>',indent + ' ' + commentSyntax.open + ' Original ' + commentSyntax.close,indent + ' <div data-impeccable-variant="original">',originalIndented,@@ -356,15 +375,18 @@ The agent should insert variant HTML at insertLine.`);const outputRelFile = path.relative(process.cwd(), outputFile).split(path.sep).join('/');const svelteComponentAuthoring = useSvelteComponent ? buildSvelteComponentCssAuthoring(count) : null;+ const componentSession = svelteSession;+ const componentPreviewMode = useSvelteComponent ? 'svelte-component' : undefined;+ const previewMode = componentPreviewMode;console.log(JSON.stringify({file: outputRelFile,- sourceFile: useSvelteComponent ? relTargetFile : undefined,- previewMode: useSvelteComponent ? 'svelte-component' : undefined,- componentDir: svelteSession?.componentDir,- propContract: svelteSession?.propContract,- sourceStartLine: useSvelteComponent ? startLine + 1 : undefined,- sourceEndLine: useSvelteComponent ? endLine + 1 : undefined,+ sourceFile: useFrameworkComponent ? relTargetFile : undefined,+ previewMode,+ componentDir: componentSession?.componentDir,+ propContract: componentSession?.propContract,+ sourceStartLine: useFrameworkComponent ? startLine + 1 : undefined,+ sourceEndLine: useFrameworkComponent ? endLine + 1 : undefined,startLine: outputStartLine, // 1-indexed for the agent// wrapperLines is an array but one element (the original-content slot)// is a `\n`-joined multi-line string, so the actual file-row count is@@ -374,10 +396,10 @@ The agent should insert variant HTML at insertLine.`);endLine: outputEndLine, // 1-indexedinsertLine, // 1-indexed: where variants gocommentSyntax: commentSyntax,- styleMode: useSvelteComponent ? 'svelte-component' : styleMode.mode,- styleTag: useSvelteComponent ? null : styleMode.styleTag,- cssSelectorPrefixExamples: useSvelteComponent ? [] : buildCssSelectorPrefixExamples(styleMode.mode, count),- cssAuthoring: useSvelteComponent ? svelteComponentAuthoring : buildCssAuthoring(styleMode, count),+ styleMode: componentPreviewMode || styleMode.mode,+ styleTag: useFrameworkComponent ? null : styleMode.styleTag,+ cssSelectorPrefixExamples: useFrameworkComponent ? [] : buildCssSelectorPrefixExamples(styleMode.mode, count),+ cssAuthoring: svelteComponentAuthoring || buildCssAuthoring(styleMode, count),originalLineCount: originalLines.length,}));}diff --git a/.github/skills/impeccable/scripts/live.mjs b/.github/skills/impeccable/scripts/live.mjsindex e0bd1ad24..b21a71cc4 100644--- a/.github/skills/impeccable/scripts/live.mjs+++ b/.github/skills/impeccable/scripts/live.mjs@@ -10,7 +10,7 @@** After this, the agent's only remaining steps are:* - Open the project's live dev/preview URL in the browser (optional, if browser automation exists)—not `serverPort`; that port is the Impeccable helper for /live.js and /poll- * - Enter the poll loop: `node live-poll.mjs`+ * - Enter the harness-native poll loop: `node live-poll.mjs`** Usage:* node live.mjs # Prepare everything, print JSON, exit@@ -40,6 +40,7 @@ Prepare everything for live variant mode in a single command:- Starts (or reuses) the live server in the background- Injects the browser script tag- Reads PRODUCT.md / DESIGN.md for project context+ - Prepares the harness-native foreground/background poll loop- In monorepos, choose a child app first; --target <path> is the fallback/manual pathOn success, prints a JSON blob with:diff --git a/.github/skills/impeccable/scripts/live/completion.mjs b/.github/skills/impeccable/scripts/live/completion.mjsindex 986773066..6f539336d 100644--- a/.github/skills/impeccable/scripts/live/completion.mjs+++ b/.github/skills/impeccable/scripts/live/completion.mjs@@ -1,9 +1,18 @@+// A preview whose variants live in component modules rather than in the user's+// source. These leave no markers in the real file, so a failed accept gives the+// agent nothing to hand-edit and must be reported as a failure rather than+// reference/live.md's manual-cleanup handoff. Kept as a set: any future+// component-module preview mode belongs here the day it lands.+const PREVIEW_MODES_WITHOUT_SOURCE_MARKERS = new Set([+ 'svelte-component',+]);+export function completionTypeForAcceptResult(eventType, acceptResult) {if (eventType === 'discard') return acceptResult?.handled === true ? 'discarded' : 'error';if (acceptResult?.handled === true && acceptResult?.carbonize === true) return 'agent_done';if (acceptResult?.handled === true) return 'complete';if (acceptResult?.mode === 'error') return 'error';- if (eventType === 'accept' && acceptResult?.previewMode === 'svelte-component') return 'error';+ if (eventType === 'accept' && PREVIEW_MODES_WITHOUT_SOURCE_MARKERS.has(acceptResult?.previewMode)) return 'error';return 'agent_done';}diff --git a/.github/skills/impeccable/scripts/live/event-validation.mjs b/.github/skills/impeccable/scripts/live/event-validation.mjsindex 0897b1317..122c29836 100644--- a/.github/skills/impeccable/scripts/live/event-validation.mjs+++ b/.github/skills/impeccable/scripts/live/event-validation.mjs@@ -118,6 +118,15 @@ export function validateEvent(msg) {return 'checkpoint: paramValues must be an object';}return null;+ case 'agent_phase':+ if (!isValidId(msg.id)) return 'agent_phase: missing or malformed id';+ if (typeof msg.phase !== 'string' || !/^[a-z][a-z0-9_]{1,63}$/.test(msg.phase)) {+ return 'agent_phase: missing or malformed phase';+ }+ if (msg.durationMs !== undefined && (!Number.isFinite(msg.durationMs) || msg.durationMs < 0)) {+ return 'agent_phase: durationMs must be a non-negative number';+ }+ return null;case 'exit':return null;case 'prefetch':@@ -131,6 +140,12 @@ export function validateEvent(msg) {if (msg.message.length > 4000) return 'steer: message too long';if (msg.pageUrl !== undefined && typeof msg.pageUrl !== 'string') return 'steer: pageUrl must be string';return null;+ case 'carbonize_cleanup':+ if (!isValidId(msg.id)) return 'carbonize_cleanup: missing or malformed id';+ if (!isValidId(msg.sessionId)) return 'carbonize_cleanup: missing or malformed sessionId';+ if (!msg.file || typeof msg.file !== 'string') return 'carbonize_cleanup: missing file';+ if (!isValidVariantId(String(msg.variantId))) return 'carbonize_cleanup: missing or malformed variantId';+ return null;default:return 'Unknown event type: ' + msg.type;}diff --git a/.github/skills/impeccable/scripts/live/generation-preflight.mjs b/.github/skills/impeccable/scripts/live/generation-preflight.mjsnew file mode 100644index 000000000..07a5e957e--- /dev/null+++ b/.github/skills/impeccable/scripts/live/generation-preflight.mjs@@ -0,0 +1,102 @@+import { execFile } from 'node:child_process';+import path from 'node:path';+import { promisify } from 'node:util';++const execFileAsync = promisify(execFile);+const PREFLIGHT_TIMEOUT_MS = 15_000;++export function buildGenerationPreflight(event, scriptsDir) {+ if (!event || event.type !== 'generate' || !event.id) return null;++ const isInsert = event.mode === 'insert';+ const target = isInsert ? insertTarget(event) : replaceTarget(event);+ if (!target.elementId && !target.classes) return null;++ const script = path.join(scriptsDir, isInsert ? 'live-insert.mjs' : 'live-wrap.mjs');+ const args = [script, '--id', event.id, '--count', String(event.count || 3)];+ if (isInsert) args.push('--position', target.position);+ if (target.elementId) args.push('--element-id', target.elementId);+ if (target.classes) args.push('--classes', target.classes);+ if (target.tag) args.push('--tag', target.tag);+ if (target.text) args.push('--text', target.text);+ if (!isInsert && event.pageUrl) args.push('--page-url', event.pageUrl);+ return { script, args, mode: isInsert ? 'insert' : 'replace' };+}++/**+ * Scaffold the source for a generate event before handing it to an agent.+ *+ * Async on purpose. This spawns `live-wrap.mjs`, which walks the project's+ * source tree and can take seconds (measured at ~7.6s on a large repo when the+ * element is not found, with a 15s ceiling). The live server is single-threaded+ * and calls this while leasing a poll, so a synchronous spawn froze the whole+ * server for that entire window: Accept and Discard POSTs, SSE progress+ * broadcasts, and every other poll stalled behind it.+ */+export async function runGenerationPreflight(event, {+ cwd = process.cwd(),+ scriptsDir,+ execFileImpl = execFileAsync,+ timeoutMs = PREFLIGHT_TIMEOUT_MS,+} = {}) {+ const command = buildGenerationPreflight(event, scriptsDir);+ if (!command) {+ return { ok: false, skipped: true, reason: 'insufficient_locator' };+ }++ const startedAt = performance.now();+ try {+ const { stdout } = await execFileImpl(process.execPath, command.args, {+ cwd,+ encoding: 'utf-8',+ timeout: timeoutMs,+ });+ const line = String(stdout).trim().split('\n').filter(Boolean).pop();+ if (!line) throw new Error('preflight returned no scaffold metadata');+ return {+ ok: true,+ mode: command.mode,+ durationMs: performance.now() - startedAt,+ scaffold: JSON.parse(line),+ };+ } catch (error) {+ return {+ ok: false,+ mode: command.mode,+ durationMs: performance.now() - startedAt,+ error: compactError(error),+ };+ }+}++function replaceTarget(event) {+ return normalizeTarget(event.element || {});+}++function insertTarget(event) {+ return {+ ...normalizeTarget(event.insert?.anchor || {}),+ position: event.insert?.position === 'before' ? 'before' : 'after',+ };+}++function normalizeTarget(target) {+ const classes = Array.isArray(target.classes)+ ? target.classes.join(' ')+ : String(target.classes || '').trim();+ const text = typeof target.textContent === 'string'+ ? target.textContent.trim().slice(0, 80)+ : '';+ return {+ elementId: target.id || target.elementId || undefined,+ classes: classes || undefined,+ tag: target.tagName || target.tag || undefined,+ text: text || undefined,+ };+}++function compactError(error) {+ const stderr = error?.stderr ? String(error.stderr).trim() : '';+ const message = stderr.split('\n').filter(Boolean).pop() || error?.message || 'preflight failed';+ return String(message).slice(0, 500);+}diff --git a/.github/skills/impeccable/scripts/live/poll-lanes.mjs b/.github/skills/impeccable/scripts/live/poll-lanes.mjsnew file mode 100644index 000000000..65f20a87a--- /dev/null+++ b/.github/skills/impeccable/scripts/live/poll-lanes.mjs@@ -0,0 +1,14 @@+export function eventPriority(event = {}) {+ if (event.type === 'accept' || event.type === 'discard' || event.type === 'exit') return 0;+ if (event.type === 'manual_edit_apply' || event.type === 'steer' || event.type === 'carbonize_cleanup') return 1;+ if (event.type === 'generate') return 2;+ return 3;+}++export function selectAvailablePendingEvent(entries, { now = Date.now(), types = null } = {}) {+ const allowed = types instanceof Set ? types : (Array.isArray(types) ? new Set(types) : null);+ return entries+ .filter((entry) => !(entry.leaseUntil && entry.leaseUntil > now))+ .filter((entry) => !allowed || allowed.has(entry.event?.type))+ .sort((a, b) => eventPriority(a.event) - eventPriority(b.event) || a.seq - b.seq)[0] || null;+}diff --git a/.github/skills/impeccable/scripts/live/session-store.mjs b/.github/skills/impeccable/scripts/live/session-store.mjsindex affba67c9..9d20341dd 100644--- a/.github/skills/impeccable/scripts/live/session-store.mjs+++ b/.github/skills/impeccable/scripts/live/session-store.mjs@@ -1,24 +1,26 @@import fs from 'node:fs';import path from 'node:path';-import { getLegacyLiveSessionsDir, getLiveSessionsDir } from '../lib/impeccable-paths.mjs';+import { getLegacyLiveSessionsDir, getLiveSessionsDir, safeSessionId } from '../lib/impeccable-paths.mjs';const COMPLETED_PHASES = new Set(['completed', 'discarded']);+export const GENERATION_FENCED_PHASES = new Set([+ 'accept_requested',+ 'discard_requested',+ 'carbonize_required',+ 'completed',+ 'discarded',+]);export function createLiveSessionStore({ cwd = process.cwd(), sessionId } = {}) {const rootDir = getLiveSessionsDir(cwd);const legacyRootDir = getLegacyLiveSessionsDir(cwd);fs.mkdirSync(rootDir, { recursive: true });- const snapshotCache = new Map();-- function loadCachedOrRebuild(id) {- const cached = snapshotCache.get(id);- if (cached) return cached;- const journalPath = getReadableJournalPath(id);- const rebuilt = rebuildSnapshotFromJournal(journalPath, id);- snapshotCache.set(id, rebuilt);- return rebuilt;- }+ // No snapshot cache on purpose: appendEvent and getSnapshot both rebuild from+ // the journal so sequence numbers and phase fences never come from a stale+ // in-memory copy when the publisher/complete helpers append from another+ // process. A cache written but never read would grow per session for the+ // lifetime of the server without ever saving a rebuild.function getReadableJournalPath(id) {const primary = getJournalPath(rootDir, id);if (fs.existsSync(primary)) return primary;@@ -38,7 +40,10 @@ export function createLiveSessionStore({ cwd = process.cwd(), sessionId } = {})if (!fs.existsSync(journalPath) && fs.existsSync(legacyJournalPath)) {fs.copyFileSync(legacyJournalPath, journalPath);}- const prior = loadCachedOrRebuild(normalized.id);+ // Publisher/complete helpers can append from a separate process while+ // the server is alive. Rebuild here so sequence numbers and phase+ // fences never come from a stale in-memory cache.+ const prior = rebuildSnapshotFromJournal(getReadableJournalPath(normalized.id), normalized.id);const seq = prior.nextSeq;const entry = {seq,@@ -49,7 +54,6 @@ export function createLiveSessionStore({ cwd = process.cwd(), sessionId } = {})};fs.appendFileSync(journalPath, JSON.stringify(entry) + '\n');const next = applyEvent(prior.snapshot, entry, prior.diagnostics);- snapshotCache.set(normalized.id, { snapshot: next, diagnostics: next.diagnostics || [], nextSeq: seq + 1 });writeSnapshot(snapshotPath, next);return next;},@@ -58,7 +62,6 @@ export function createLiveSessionStore({ cwd = process.cwd(), sessionId } = {})const journalPath = getReadableJournalPath(id);const snapshotPath = getSnapshotPath(rootDir, id);const rebuilt = rebuildSnapshotFromJournal(journalPath, id);- snapshotCache.set(id, rebuilt);writeSnapshot(snapshotPath, rebuilt.snapshot);if (!opts.includeCompleted && COMPLETED_PHASES.has(rebuilt.snapshot.phase)) return null;return rebuilt.snapshot;@@ -95,11 +98,6 @@ function getSnapshotPath(rootDir, id) {return path.join(rootDir, safeSessionId(id) + '.snapshot.json');}-function safeSessionId(id) {- if (!/^[A-Za-z0-9_-]{1,128}$/.test(id)) throw new Error('invalid session id: ' + id);- return id;-}-function baseSnapshot(id) {return {id,@@ -116,9 +114,18 @@ function baseSnapshot(id) {pendingEvent: null,deliveryLease: null,checkpointRevision: 0,+ browserCheckpointRevision: 0,+ publicationCheckpointRevision: 0,activeOwner: null,sourceMarkers: {},fallbackMode: null,+ generationPhase: null,+ generationCompletedAt: null,+ generationTimings: {},+ variantPlan: null,+ generationCanceled: false,+ generationCanceledAt: null,+ cancelReason: null,annotationArtifacts: [],diagnostics: [],updatedAt: null,@@ -158,6 +165,8 @@ function applyEvent(snapshot, entry, inheritedDiagnostics = []) {...snapshot,paramValues: { ...(snapshot.paramValues || {}) },sourceMarkers: { ...(snapshot.sourceMarkers || {}) },+ generationTimings: { ...(snapshot.generationTimings || {}) },+ variantPlan: snapshot.variantPlan || null,annotationArtifacts: [...(snapshot.annotationArtifacts || [])],diagnostics: [...(snapshot.diagnostics || [])],updatedAt: entry.ts || new Date().toISOString(),@@ -174,11 +183,48 @@ function applyEvent(snapshot, entry, inheritedDiagnostics = []) {next.expectedVariants = event.count ?? next.expectedVariants;next.pendingEventSeq = entry.seq ?? next.pendingEventSeq;next.pendingEvent = toPendingEvent(event);+ next.variantPlan = null;if (event.screenshotPath) upsertArtifact(next.annotationArtifacts, { type: 'screenshot', path: event.screenshotPath });break;+ case 'variant_plan':+ if (!next.generationCanceled && !GENERATION_FENCED_PHASES.has(next.phase)) {+ next.variantPlan = event.plan ?? next.variantPlan;+ }+ break;+ case 'detector_waivers':+ if (!next.generationCanceled && !GENERATION_FENCED_PHASES.has(next.phase)) {+ next.detectorWaivers = [+ ...(next.detectorWaivers || []),+ ...(Array.isArray(event.waivers) ? event.waivers : []),+ ];+ }+ break;+ case 'agent_phase':+ next.generationPhase = event.phase ?? next.generationPhase;+ if (event.phase) {+ next.generationTimings[event.phase] = {+ at: event.at ?? (Date.parse(entry.ts || '') || null),+ durationMs: event.durationMs ?? null,+ };+ }+ break;case 'variants_ready':case 'agent_done':+ if ((next.generationCanceled || GENERATION_FENCED_PHASES.has(next.phase))+ && !(event.type === 'agent_done' && event.carbonize === true && next.phase === 'accept_requested')) {+ next.diagnostics.push({+ error: 'late_generation_event_ignored',+ type: event.type,+ phase: next.phase,+ });+ break;+ }next.phase = event.carbonize === true ? 'carbonize_required' : 'variants_ready';+ // Durable completion marker: later browser checkpoints (a resumed page+ // reporting phase "generating") regress `phase`, but generation staying+ // finished is monotone — the live server keys missed-`done` redelivery+ // on this field.+ next.generationCompletedAt = event.at ?? (Date.parse(entry.ts || '') || Date.now());next.sourceFile = event.sourceFile ?? event.file ?? next.sourceFile;next.previewFile = event.previewFile ?? next.previewFile;next.previewMode = event.previewMode ?? next.previewMode;@@ -194,27 +240,45 @@ function applyEvent(snapshot, entry, inheritedDiagnostics = []) {}break;case 'checkpoint':- if (COMPLETED_PHASES.has(next.phase)) {+ if (next.generationCanceled || GENERATION_FENCED_PHASES.has(next.phase)) {next.diagnostics.push({ error: 'checkpoint_after_terminal_ignored', phase: event.phase ?? null, revision: event.revision ?? null });break;}- if ((event.revision ?? 0) >= (next.checkpointRevision ?? 0)) {- next.phase = event.phase ?? next.phase;- next.checkpointRevision = event.revision ?? next.checkpointRevision;- next.activeOwner = event.owner ?? next.activeOwner;- next.arrivedVariants = event.arrivedVariants ?? next.arrivedVariants;- next.visibleVariant = event.visibleVariant ?? next.visibleVariant;- next.sourceFile = event.sourceFile ?? next.sourceFile;- next.previewFile = event.previewFile ?? next.previewFile;- next.previewMode = event.previewMode ?? next.previewMode;- if (event.paramValues) next.paramValues = { ...event.paramValues };- } else {- next.diagnostics.push({ error: 'stale_checkpoint_ignored', revision: event.revision });+ {+ const revisionDomain = event.revisionDomain === 'publication'+ || (event.reason === 'variants_progress' && !event.owner)+ ? 'publication'+ : 'browser';+ const revisionField = revisionDomain === 'publication'+ ? 'publicationCheckpointRevision'+ : 'browserCheckpointRevision';+ const currentRevision = next[revisionField]+ ?? (revisionDomain === 'browser' ? next.checkpointRevision : 0)+ ?? 0;+ if ((event.revision ?? 0) >= currentRevision) {+ next.phase = event.phase ?? next.phase;+ next[revisionField] = event.revision ?? currentRevision;+ if (revisionDomain === 'browser') {+ next.checkpointRevision = event.revision ?? next.checkpointRevision;+ next.activeOwner = event.owner ?? next.activeOwner;+ }+ next.arrivedVariants = event.arrivedVariants ?? next.arrivedVariants;+ if (revisionDomain === 'browser') next.visibleVariant = event.visibleVariant ?? next.visibleVariant;+ next.sourceFile = event.sourceFile ?? next.sourceFile;+ next.previewFile = event.previewFile ?? next.previewFile;+ next.previewMode = event.previewMode ?? next.previewMode;+ if (revisionDomain === 'browser' && event.paramValues) next.paramValues = { ...event.paramValues };+ } else {+ next.diagnostics.push({ error: 'stale_checkpoint_ignored', revision: event.revision, revisionDomain });+ }}break;case 'accept':case 'accept_intent':next.phase = 'accept_requested';+ next.generationCanceled = true;+ next.generationCanceledAt = event.at ?? (Date.parse(entry.ts || '') || Date.now());+ next.cancelReason = 'accept';next.visibleVariant = Number(event.variantId ?? next.visibleVariant);if (event.paramValues) next.paramValues = { ...event.paramValues };next.pendingEventSeq = entry.seq ?? next.pendingEventSeq;@@ -232,6 +296,12 @@ function applyEvent(snapshot, entry, inheritedDiagnostics = []) {next.pendingEventSeq = entry.seq ?? next.pendingEventSeq;next.pendingEvent = toPendingEvent(event);break;+ case 'carbonize_cleanup':+ next.phase = 'carbonize_cleanup_requested';+ next.sourceFile = event.file ?? next.sourceFile;+ next.pendingEventSeq = entry.seq ?? next.pendingEventSeq;+ next.pendingEvent = toPendingEvent(event);+ break;case 'steer_done':next.phase = 'steer_done';next.sourceFile = event.sourceFile ?? event.file ?? next.sourceFile;@@ -243,6 +313,9 @@ function applyEvent(snapshot, entry, inheritedDiagnostics = []) {break;case 'discard':next.phase = 'discard_requested';+ next.generationCanceled = true;+ next.generationCanceledAt = event.at ?? (Date.parse(entry.ts || '') || Date.now());+ next.cancelReason = 'discard';next.pendingEventSeq = entry.seq ?? next.pendingEventSeq;next.pendingEvent = toPendingEvent(event);break;@@ -260,6 +333,10 @@ function applyEvent(snapshot, entry, inheritedDiagnostics = []) {next.pendingEvent = null;break;case 'agent_error':+ if (next.generationCanceled && event.sourceEventType === 'generate') {+ next.diagnostics.push({ error: 'late_generation_event_ignored', type: event.type, phase: next.phase });+ break;+ }next.phase = 'agent_error';next.pendingEventSeq = null;next.pendingEvent = null;diff --git a/.github/skills/impeccable/scripts/live/source-lock.mjs b/.github/skills/impeccable/scripts/live/source-lock.mjsnew file mode 100644index 000000000..9ccc557be--- /dev/null+++ b/.github/skills/impeccable/scripts/live/source-lock.mjs@@ -0,0 +1,105 @@+import fs from 'node:fs';+import path from 'node:path';+import { createHash, randomUUID } from 'node:crypto';+import { getLiveDir, isLiveServerPidReachable } from '../lib/impeccable-paths.mjs';++// Only used to retire a lock whose contents we cannot read (empty or truncated+// by a crash mid-write). A readable lock's fate is decided by its owner's+// liveness instead, so a slow critical section is never swept.+const UNREADABLE_LOCK_STALE_MS = 60_000;++export function sourceLockPath(file, cwd = process.cwd()) {+ const digest = createHash('sha256').update(path.resolve(cwd, file)).digest('hex').slice(0, 24);+ return path.join(getLiveDir(cwd), 'locks', digest + '.lock');+}++export function withSourceLockSync(file, owner, fn, {+ cwd = process.cwd(),+ waitMs = 0,+ retryMs = 5,+} = {}) {+ const lockPath = sourceLockPath(file, cwd);+ fs.mkdirSync(path.dirname(lockPath), { recursive: true });+ const deadline = Date.now() + Math.max(0, Number(waitMs) || 0);+ // Identifies this acquisition specifically, so release can tell our own lock+ // from a replacement that some other writer created.+ const token = randomUUID();+ let acquired = false;++ while (!acquired) {+ clearStaleLock(lockPath);+ let fd;+ try {+ fd = fs.openSync(lockPath, 'wx');+ fs.writeFileSync(fd, JSON.stringify({+ owner,+ token,+ pid: process.pid,+ at: Date.now(),+ file: path.resolve(cwd, file),+ }) + '\n');+ acquired = true;+ } catch (error) {+ if (error?.code !== 'EEXIST') throw error;+ if (Date.now() >= deadline) {+ const locked = new Error('source_locked');+ locked.code = 'SOURCE_LOCKED';+ locked.lockPath = lockPath;+ throw locked;+ }+ sleepSync(Math.max(1, Math.min(Number(retryMs) || 5, deadline - Date.now())));+ } finally {+ try { if (fd !== undefined) fs.closeSync(fd); } catch {}+ }+ }++ try {+ return fn();+ } finally {+ releaseOwnLock(lockPath, token);+ }+}++function sleepSync(ms) {+ Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, ms);+}++function readLock(lockPath) {+ try { return JSON.parse(fs.readFileSync(lockPath, 'utf-8')); } catch { return null; }+}++/**+ * Remove the lock only if it is still the one this call created. If a sweeper+ * judged our lock stale and another writer replaced it, unlinking here would+ * end *their* critical section and admit a third writer to the same file.+ */+function releaseOwnLock(lockPath, token) {+ const held = readLock(lockPath);+ if (held && held.token !== token) return;+ try { fs.unlinkSync(lockPath); } catch {}+}++/**+ * A lock is stale when its owner is gone, not when it is old.+ *+ * Age alone cuts both ways: it sweeps a live holder whose critical section+ * outran the timeout (a suspended laptop, a stopped process), letting two+ * writers into the same source file, while still making every accept on a+ * crashed holder's file wait out the full timeout. Asking the OS whether the+ * recorded pid is alive answers both correctly: a dead owner releases at once,+ * and a live owner keeps its lock however long it needs.+ */+function clearStaleLock(lockPath) {+ const held = readLock(lockPath);+ if (!held) {+ // Unreadable: either a crash truncated it, or we caught the brief window+ // between create and write in a live acquisition. mtime distinguishes them.+ try {+ const stat = fs.statSync(lockPath);+ if (Date.now() - stat.mtimeMs > UNREADABLE_LOCK_STALE_MS) fs.unlinkSync(lockPath);+ } catch { /* gone already */ }+ return;+ }+ if (typeof held.pid === 'number' && isLiveServerPidReachable(held.pid)) return;+ try { fs.unlinkSync(lockPath); } catch {}+}diff --git a/.kiro/skills/impeccable/reference/live.md b/.kiro/skills/impeccable/reference/live.mdindex 00d1812c4..a01223336 100644--- a/.kiro/skills/impeccable/reference/live.md+++ b/.kiro/skills/impeccable/reference/live.md@@ -10,21 +10,24 @@ Execute in order. No step skipped, no step reordered.1. `live.mjs`: boot. If the request names or implies a file, route, or app inside a monorepo, infer the concrete path and run `node .kiro/skills/impeccable/scripts/live.mjs --target <path>` instead; then run the rest of this live session from the returned `projectRoot`.2. Open the app URL that serves `pageFile` (infer from `package.json`, docs, terminal output, or an open tab). Never use `serverPort`; it's the helper, not the app. **Cursor:** `browser_navigate` to that URL before polling; do not skip. **Other harnesses:** use the available browser tool; if the URL is uncertain, ask the user once.-3. Poll loop with the default long timeout (600000 ms). After every event or `--reply`, run `live-poll.mjs` again immediately. Never pass a short `--timeout=`.+3. Poll loop with the default long timeout (600000 ms). Run `live-poll.mjs` again immediately after every event or `--reply`; Codex runs this one-shot poll in the foreground. Never pass a short `--timeout=`.The global bar **Impeccable mark** dims and shows a pulsing amber dot when no agent is long-polling `/poll`. Hover the mark for the hint; restart `live-poll.mjs` to reconnect.-4. On `generate`: read screenshot if present; load the action's reference; plan three distinct directions; write all variants in one edit; `--reply done`; poll again.+4. On `generate`: reuse `event.scaffold` when present; read the screenshot if present; load the action's reference; deliver variants using the delivery policy below; `--reply done`; poll again. Generate in this thread. You already hold the project's tokens, conventions, and file layout; that context is the job, not overhead.5. On `steer`: read the message and `pageUrl`; do the work (page edits, navigation help, or a short reply in the `--reply` message); `--reply steer_done`; poll again. No pickup ack. The Steer bar unlocks when `steer_done` arrives over SSE.-6. On `accept` / `discard`: the poll script runs `live-accept.mjs`, acknowledges the delivered event, and prints `_completionAck`. Plain accepts/discards are terminal immediately; carbonize accepts remain recoverable until you finish cleanup, run `live-complete.mjs --id EVENT_ID`, and only then poll again.+6. On `accept` / `discard`: the poll script runs `live-accept.mjs`, acknowledges the delivered event, and prints `_completionAck`. Plain accepts/discards are terminal immediately. Carbonize accepts remain recoverable until the foreground task runs `live-complete.mjs --id EVENT_ID`; finish that cleanup before polling again.7. If interrupted, run `live-status.mjs` or `live-resume.mjs` before guessing. The durable journal replays unacknowledged work after helper restart.8. On `exit`: run the cleanup at the bottom.Harness policy:-- **Claude Code**: run the poll as a **background task** (no short timeout). The harness notifies you when it completes, so the main conversation stays free. Do not block the shell.+- **Claude Code**: run the poll as a **background task** (no short timeout). The harness notifies you when it completes, so the main conversation stays free while you generate and publish in it. Do not block the shell.- **Cursor**: run **one-shot** poll in a **background terminal** with notify on `"type":"(steer|generate|accept|discard|exit)"`. After each event the poll exits; handle it, `--reply`, then start `live-poll.mjs` again. Do **not** use `--stream` on Cursor: incremental stdout notify is slower in practice than exit-based notify (~5s vs sub-second in testing).-- **Codex**: run the poll in the **foreground** (blocking shell; not a background task, not a subagent). Codex background exec sessions do not reliably surface poll stdout back into the conversation at the moment events arrive, so a "fire-and-forget" background poll will stall live mode.+- **Codex**: run the default one-shot poll in a **yielded foreground exec session**. Do not suffix it with `&`, use `--stream`, or leave Live without an active foreground poll. Handle every event in the main task; after each handler/reply, restart the foreground poll.- **Other harnesses**: one-shot foreground unless you know stdout reliably returns to this session when a shell exits.+Generation delivery policy:+- **Default (Cursor and other harnesses):** keep the established atomic single-edit delivery. Do not switch a harness to progressive until its poll loop is known not to block on the extra publish calls. This avoids trading model latency for extra tool-call latency on harnesses with different streaming behavior.+Chat is overhead. No recap, no tutorial output, no pasting PRODUCT / DESIGN bodies. Spend tokens on tools and edits; on failure, one or two short sentences.## Start@@ -92,14 +95,14 @@ Server restart rule: start `live-server.mjs` again, then poll. Startup requeues**Insert mode** (`event.mode === "insert"`): `{id, mode: "insert", count, pageUrl, insert: { position, anchor }, placeholder: { width, height }, freeformPrompt?, screenshotPath?, comments?, strokes?}`. No `action`. Requires a non-empty `freeformPrompt` **or** annotations. Screenshot is sent only when annotations exist (same rule as replace). Use `placeholder` dimensions as a soft size hint for net-new content.-Speed matters; the user is watching a spinner. Minimize tool calls by using the wrap/insert helper and writing all variants in a single edit.+Speed matters; the user is watching the selected element. Reuse server preflight metadata when available, minimize discovery calls, and follow the harness-specific delivery policy above.### Insert mode branchWhen `event.mode === "insert"`:1. Read the screenshot if `event.screenshotPath` is present (annotations only).-2. Run the insert helper instead of wrap:+2. If `event.scaffold` is present, use it as the insert-helper result and do **not** run the helper again. Otherwise run the insert helper instead of wrap:```bashnode .kiro/skills/impeccable/scripts/live-insert.mjs --id EVENT_ID --count EVENT_COUNT --position after \@@ -109,7 +112,7 @@ node .kiro/skills/impeccable/scripts/live-insert.mjs --id EVENT_ID --count EVENT- `--position` ← `event.insert.position` (`before` | `after`)- Anchor flags ← `event.insert.anchor` (same mapping as wrap: id, classes, tag, text)-The scaffold has **no** `data-impeccable-variant="original"`. Variants are net-new HTML+CSS inserted at `insertLine`. Load `brand.md` or `product.md` (freeform only, no action sub-command). Write all variants in one edit, then `--reply done`.+The scaffold has **no** `data-impeccable-variant="original"`. Variants are net-new HTML+CSS inserted at `insertLine`. Load `brand.md` or `product.md` (freeform only, no action sub-command). Deliver using the harness policy, then `--reply done`.For Svelte/SvelteKit targets, `live-insert.mjs` returns `previewMode: "svelte-component"` with `mode: "insert"`, `file` pointing at a temporary `node_modules/.impeccable-live/<id>/manifest.json`, `componentDir` pointing at the variant component files, and `sourceFile` pointing at the real `.svelte` route. Write each inserted variant as a real Svelte component (`v1.svelte`, `v2.svelte`, …) under `componentDir`. Insert variants must be non-empty net-new content with a single top-level root, no `data-impeccable-*` attributes, and CSS in each component's `<style>` block. Do **not** edit the route source during generation; the browser mounts the temporary component before/after the live anchor while the user cycles variants. On Accept, `live-accept.mjs` inserts the selected component markup into `sourceFile` immediately and deletes the temp session after the source write succeeds.@@ -134,6 +137,8 @@ Reading annotations precisely:### 2. Wrap the element+When `event.scaffold` is present, the local helper already found and wrapped the source before the poll returned. Treat `event.scaffold` as the successful helper output and skip this command entirely. `event.scaffoldAttempted` with `scaffoldError` means local preflight could not finish; use the command/fallback path below. This optimization removes a deterministic tool round trip without changing the generated design.+```bashnode .kiro/skills/impeccable/scripts/live-wrap.mjs --id EVENT_ID --count EVENT_COUNT --element-id "ELEMENT_ID" --classes "class1,class2" --tag "div" --text "TEXT_SNIPPET"```@@ -153,7 +158,7 @@ Output on success: `{ file, insertLine, commentSyntax, styleMode, styleTag, cssSFor Svelte/SvelteKit targets, `live-wrap.mjs` returns `previewMode: "svelte-component"` with `file` pointing at a temporary `node_modules/.impeccable-live/<id>/manifest.json`, `componentDir` pointing at the variant component files, and `sourceFile` pointing at the real `.svelte` route. Write each variant as a real Svelte component (`v1.svelte`, `v2.svelte`, …) under `componentDir`; use the `propContract` prop names for dynamic text (`{propName}`), not literal snapshot strings. Put variant CSS in each component's `<style>` block with semantic class selectors (no `@scope`, no `data-impeccable-*`). Reply with `--file` set to the manifest path; the browser dynamically imports and mounts the compiled components so Svelte HMR does not reset page state while the user cycles variants. On Accept, `live-accept.mjs` inlines the accepted component back into `sourceFile` immediately after source promotion succeeds.-**Params on the Svelte component path go in a sidecar, never as an attribute.** Svelte parses `{` inside an attribute value as the start of an expression, so a `data-impeccable-params='[{…}]'` attribute on a component element fails to compile (`Expected token }`). Declare params for this path in `componentDir/params.json`, keyed by variant number, using the exact param schema from section 7:+**Params on component-preview paths go in a sidecar, never as an attribute.** Svelte parses `{` inside an attribute value as the start of an expression, and both Svelte/Vue previews mount without an HTML variant wrapper. Declare params in `componentDir/params.json`, keyed by variant number, using the exact param schema from section 7:```json{@@ -291,11 +296,13 @@ In **departure mode**, the prompt narrows the lanes you draw from, not the familWhen the prompt and PRODUCT.md anti-references conflict (the prompt asks for X, the anti-references ban X), the anti-references win; they describe the brand's standing position, the prompt is one moment.-### 6. Write all variants in a single edit+### 6. Deliver variantsComplete HTML replacement of the original element for each variant, not a CSS-only patch. Consider the element's context (computed styles, parent structure, CSS variables from `event.element`).-Write CSS + all variants in ONE edit at the `insertLine` reported by `wrap`. Colocate CSS as a `<style>` tag inside the variant wrapper; `<style>` works anywhere in modern browsers and this ensures CSS and HTML arrive atomically (no FOUC).+Colocate preview CSS as a `<style>` tag inside the variant wrapper; `<style>` works anywhere in modern browsers and keeps each delivered state internally complete (no FOUC).++**Atomic default:** write CSS + all variants + parameter manifests in one edit at `insertLine`, preserving the established behavior.Use the `cssAuthoring` object returned by `live-wrap.mjs` to author the temporary preview CSS. The style opening tag shown below is the common case; replace it with `cssAuthoring.styleTag` when the tool returns a different one. The variant markup shape is otherwise stable:@@ -319,7 +326,7 @@ Use the `cssAuthoring` object returned by `live-wrap.mjs` to author the temporarThe first variant has no `display: none` (visible by default). All others do. If variants use only inline styles and no preview CSS, omit the `<style>` tag entirely.-One edit, all variants; the browser's MutationObserver picks everything up in one pass.+The browser's MutationObserver accepts either delivery shape. On the transactional progressive path it shows arrived variants and pending dots immediately; Accept and Discard are available as soon as one variant exists. Accepting an arrived variant fences the worker before the browser releases the picker, so later publications are rejected.For `styleMode: "scoped"`, author every `:scope` rule with a descendant combinator. The `@scope` boundary is the **variant wrapper `<div data-impeccable-variant="N">`**, not the element you're designing. A bare `:scope { background: cream; }` styles the wrapper, not the inner replacement, so the cream lands on a `display: contents` shell while the actual element keeps page defaults. Always step in: `:scope > .card`, `:scope > section`, `:scope .hero-title`, etc. The fake test agent's CSS in `tests/live-e2e/agent.mjs` is a faithful template; every scoped rule starts `:scope > ...`.@@ -361,7 +368,7 @@ Each variant can expose **coarse** knobs alongside the full HTML/CSS replacement**Hard cap per variant**: at most **four** parameters so the panel stays legible; rare fifth only if the reference explicitly allows it.-**How to declare.** Put a JSON manifest on the variant wrapper (HTML/JSX path). **On the Svelte `svelte-component` path, do not use this attribute** (Svelte can't compile `{` inside an attribute value). Declare params in `componentDir/params.json` keyed by variant number instead (see the Svelte component paragraph in the wrap section). The param schema below is identical for both paths.+**How to declare.** Put a JSON manifest on the variant wrapper (HTML/JSX path). **On the `svelte-component` path, do not use this attribute.** Declare params in `componentDir/params.json` keyed by variant number instead (see the component-preview paragraphs in the wrap section). The param schema below is identical for every path.```html<div data-impeccable-variant="1" data-impeccable-params='[@@ -462,15 +469,19 @@ Event: `{id, variantId, _acceptResult, _completionAck}`. The poll script already- The accept event includes `pageUrl`; the poll script must forward it to `live-accept.mjs --page-url PAGE_URL` so accept-time cleanup only scrubs staged copy edits for the current page.- `_completionAck.ok !== true`: do not poll yet. Run `live-status.mjs` / `live-resume.mjs`, complete the cleanup manually if needed, then run `live-complete.mjs --id EVENT_ID`.- `_acceptResult.handled: true` and `carbonize: false`: nothing to do. Poll again.-- `_acceptResult.handled: true` and `carbonize: true`: **post-accept cleanup is required before the next poll.** See the "Required after accept (carbonize)" section below. The `event._acceptResult.todo` field, `_completionAck.requiresComplete`, and a stderr banner all point at this required follow-up; none are decorative. After cleanup, run `live-complete.mjs --id EVENT_ID`, then poll again.+- `_acceptResult.handled: true` and `carbonize: true`: post-accept cleanup is required, but it must not stall Codex's control lane. See "Required after accept (carbonize)" below. The `event._acceptResult.todo` field, `_completionAck.requiresComplete`, and stderr banner all point at this required follow-up; none are decorative.- `_acceptResult.handled: false, mode: "fallback"`: the session lived in a generated file and the script refused to persist there. You've already written the accepted variant into true source during Handle fallback Step 3; just clean up the temporary wrapper in the served file if any, and poll again.+- `_acceptResult.handled: false, mode: "error"`: the operation genuinely failed. **Do not hand-edit the file**; the source was not touched and editing it yourself would either double-apply or race whoever holds it.+ - `error: "source_locked"`: a generation publish holds the file. Run the same `live-accept.mjs` command again; it is idempotent and will succeed once the publisher releases. Do not poll past it.+ - `error: "accept_receipt_conflict"`: this session already resolved as `priorOperation` (on `priorVariantId` for an accept), so the request contradicts durable truth. Do not edit. Run `live-status.mjs` and tell the user what the session actually resolved to.+ - anything else: report the error briefly and run `live-status.mjs` before continuing.- `_acceptResult.handled: false` without `mode`: manual cleanup: read file, find markers, edit.### Required after accept (carbonize)When `_acceptResult.carbonize === true`, the accepted variant was stitched into source with helper markers and inline CSS so the browser can render it immediately with no visual gap. That stitch-in is **temporary**. The agent must rewrite it into permanent form before doing anything else. Skipping this leaves dead `@scope` rules for unaccepted variants, a pointless `data-impeccable-variant` wrapper, and `impeccable-carbonize-start/end` comment noise in the source file; all of which accumulate across sessions.-Do these five steps in the current thread, synchronously, before the next poll. Do not poll again until the file is clean.+Do these five steps synchronously before the next poll. The source lock, generation epoch, and expected-source hash remain the final safety gates against a generator finishing concurrently with Accept.1. **Locate the carbonize block** in the source file (`_acceptResult.file`). It's bracketed by `<!-- impeccable-carbonize-start SESSION_ID -->` and `<!-- impeccable-carbonize-end SESSION_ID -->` and contains a `<style data-impeccable-css="SESSION_ID">` element. If the variant declared parameters, an `<!-- impeccable-param-values SESSION_ID: {...} -->` comment sits alongside the style tag with the user's chosen values; read it first; it drives steps 3 and 4 below.2. **Move the CSS rules** into the project's real stylesheet. Which stylesheet depends on the project (e.g. `site/styles/workflow.css` for an Astro project, or the component's co-located CSS file for a Vite/Next project; pick whichever already owns styling for the surrounding element).@@ -478,9 +489,7 @@ Do these five steps in the current thread, synchronously, before the next poll.4. **Unwrap the accepted content.** Delete the inner `<div data-impeccable-variant="N" style="display: contents">` that wraps it. On JSX/TSX, also delete the outer `<div data-impeccable-carbonize="SESSION_ID" style={{ display: 'contents' }}>` wrapper if present (accept adds it so ternary/`return` slots keep a single root). Drop `data-impeccable-params` and any `data-p-*` attributes; those are live-mode plumbing, not source.5. **Delete the inline `<style>` block, the `<!-- impeccable-param-values -->` comment if present, and both `<!-- impeccable-carbonize-start/end -->` markers.** Also drop any `@scope` rules for variants other than the accepted one; those are dead code now.-After the file is clean, run `live-complete.mjs --id SESSION_ID`, verify it reports `phase: "completed"`, then poll again.--A background agent may be used for the rewrite, but the current thread is responsible for verifying the five steps are complete before issuing the next poll. In practice, inline is usually faster and less error-prone.+After the file is clean, the cleanup owner runs `live-complete.mjs --id SESSION_ID` and verifies `phase: "completed"`. Poll again only after that verification.## Handle `discard`diff --git a/.kiro/skills/impeccable/scripts/lib/impeccable-paths.mjs b/.kiro/skills/impeccable/scripts/lib/impeccable-paths.mjsindex 2ccbe7b74..99956c0f3 100644--- a/.kiro/skills/impeccable/scripts/lib/impeccable-paths.mjs+++ b/.kiro/skills/impeccable/scripts/lib/impeccable-paths.mjs@@ -104,6 +104,20 @@ export function removeLiveServerInfo(cwd = process.cwd(), options = {}) {}}+/**+ * Session IDs become path segments (journals, snapshots, accept receipts,+ * preview manifests, generated component dirs). They arrive from CLI `--id`+ * arguments and HTTP payloads, so anything containing a separator or `..` must+ * be rejected before it reaches path.join, which would happily escape+ * `.impeccable/live/`. Real IDs are 8 hex chars; the tests use short slugs.+ */+export function safeSessionId(id) {+ if (typeof id !== 'string' || !/^[A-Za-z0-9_-]{1,128}$/.test(id)) {+ throw new Error('invalid session id: ' + id);+ }+ return id;+}+export function getLiveSessionsDir(cwd = process.cwd(), options = {}) {return path.join(getLiveDir(cwd, options), 'sessions');}diff --git a/.kiro/skills/impeccable/scripts/live-accept.mjs b/.kiro/skills/impeccable/scripts/live-accept.mjsindex 278dfbb2e..453ddea35 100644--- a/.kiro/skills/impeccable/scripts/live-accept.mjs+++ b/.kiro/skills/impeccable/scripts/live-accept.mjs@@ -16,7 +16,9 @@import fs from 'node:fs';import path from 'node:path';import { isGeneratedFile } from './lib/is-generated.mjs';+import { IMPECCABLE_DIR, getLiveDir, safeSessionId } from './lib/impeccable-paths.mjs';import { readBuffer as readManualEditsBuffer, writeBuffer as writeManualEditsBuffer } from './live/manual-edits-buffer.mjs';+import { withSourceLockSync } from './live/source-lock.mjs';import {applyDeferredSvelteComponentAccepts,findSvelteComponentManifest,@@ -25,6 +27,46 @@ import {} from './live/svelte-component.mjs';const EXTENSIONS = ['.html', '.jsx', '.tsx', '.vue', '.svelte', '.astro'];+const ACCEPT_LOCK_WAIT_MS = 1_000;+// Mirrors VARIANT_ID_PATTERN in live/event-validation.mjs, which gates the same+// value arriving over HTTP.+const VARIANT_NUM_PATTERN = /^[0-9]{1,3}$/;++/**+ * A thrown accept/discard is a real failure, not a manual handoff.+ *+ * live/completion.mjs only classifies a result as `error` when it carries+ * `mode: 'error'`; anything else unhandled falls through to `agent_done` with a+ * successful ack, and reference/live.md then tells the agent to finish the edit+ * by hand. That is right for the documented fallback paths and wrong here: a+ * `source_locked` contention needs a retry (hand-editing races the publisher+ * holding the lock), and a crash needs surfacing, not a hand-applied guess.+ */+function operationFailure(err, extra = {}) {+ return { handled: false, mode: 'error', error: err.message, ...extra };+}++/**+ * Mark an unhandled preview-path result as a real failure.+ *+ * operationFailure only covers results built from a *thrown* error. The accept+ * implementations also return `{handled: false, error}` for their own checks+ * (variant missing, template empty, original text ambiguous), and those arrived+ * without `mode`, so completion.mjs classified them as agent_done and+ * reference/live.md routed the agent to "read file, find markers, edit".+ *+ * That handoff only makes sense for a plain wrapper session, which is the one+ * shape with markers in the user's source to edit. Component and isolated+ * artifact previews keep the source clean until Accept, so there is nothing to+ * hand-edit and an unhandled result is always a failure. `previewMode` is+ * exactly that discriminator: only the preview branches set it.+ */+function markPreviewFailure(result) {+ if (result?.handled === false && !result.mode && result.previewMode) {+ return { ...result, mode: 'error' };+ }+ return result;+}// ---------------------------------------------------------------------------// CLI@@ -63,7 +105,52 @@ Output (JSON):const isDiscard = args.includes('--discard');if (!id) { console.error('Missing --id'); process.exit(1); }+ // `id` becomes a path segment (accept receipts, preview manifests, generated+ // component dirs). Reject separators and traversal here so one check covers+ // every downstream sink.+ try { safeSessionId(id); } catch { console.error('Invalid --id'); process.exit(1); }if (!isDiscard && !variantNum) { console.error('Need --discard or --variant N'); process.exit(1); }+ // `variantNum` is interpolated into a RegExp and into the markup written back+ // to source. The browser and the /events schema both constrain it to digits;+ // enforce the same here, or `--variant '.*'` matches the `original` block+ // first and silently accepts the original while reporting success.+ if (!isDiscard && !VARIANT_NUM_PATTERN.test(variantNum)) {+ console.error('Invalid --variant');+ process.exit(1);+ }++ const requestedOperation = isDiscard ? 'discard' : 'accept';+ const priorReceipt = readAcceptReceipt(process.cwd(), id);+ if (priorReceipt) {+ const sameOperation = priorReceipt.operation === requestedOperation+ && (isDiscard || String(priorReceipt.variantId) === String(variantNum));+ console.log(JSON.stringify(sameOperation+ ? { ...priorReceipt.result, handled: true, alreadyApplied: true }+ : {+ // mode: 'error' is what marks this a real failure rather than a manual+ // handoff. Without it, live/completion.mjs classifies the reply as+ // agent_done and reference/live.md tells the agent to "read file, find+ // markers, edit" by hand — which would apply a second, conflicting+ // accept on top of the one the receipt already recorded.+ handled: false,+ mode: 'error',+ error: 'accept_receipt_conflict',+ priorOperation: priorReceipt.operation,+ priorVariantId: priorReceipt.variantId ?? null,+ }));+ return;+ }+ const emitResult = (rawResult) => {+ const result = markPreviewFailure(rawResult);+ if (result?.handled !== false) {+ writeAcceptReceipt(process.cwd(), id, {+ operation: requestedOperation,+ variantId: isDiscard ? null : String(variantNum),+ result,+ });+ }+ console.log(JSON.stringify(result));+ };let paramValues = null;if (paramValuesRaw) {@@ -82,39 +169,55 @@ Output (JSON):if (svelteComponentManifest) {if (isDiscard) {- removeSvelteComponentSession(id, process.cwd());- console.log(JSON.stringify({- handled: true,+ let result;+ try {+ result = withSourceLockSync(+ path.resolve(process.cwd(), svelteComponentManifest.sourceFile),+ 'discard:' + id,+ () => {+ removeSvelteComponentSession(id, process.cwd());+ return { handled: true };+ },+ { waitMs: ACCEPT_LOCK_WAIT_MS },+ );+ } catch (err) {+ result = operationFailure(err);+ }+ emitResult({+ ...result,file: svelteComponentManifest.sourceFile,carbonize: false,previewMode: 'svelte-component',componentDir: svelteComponentManifest.componentDir,- }));+ });return;}let result;try {- result = inlineSvelteComponentAccept(- svelteComponentManifest,- variantNum,- paramValues,- process.cwd(),+ result = withSourceLockSync(+ path.resolve(process.cwd(), svelteComponentManifest.sourceFile),+ 'accept:' + id,+ () => inlineSvelteComponentAccept(+ svelteComponentManifest,+ variantNum,+ paramValues,+ process.cwd(),+ ),+ { waitMs: ACCEPT_LOCK_WAIT_MS },);} catch (err) {- result = {- handled: false,- error: err.message,+ result = operationFailure(err, {file: svelteComponentManifest.sourceFile,sourceFile: svelteComponentManifest.sourceFile,previewMode: 'svelte-component',componentDir: svelteComponentManifest.componentDir,- };+ });}if (result.carbonize) {result.todo = 'REQUIRED before next poll: carbonize cleanup in ' + result.file + '. See reference/live.md "Required after accept".';}- console.log(JSON.stringify({ handled: result.handled !== false, ...result }));+ emitResult({ handled: result.handled !== false, ...result });return;}@@ -145,10 +248,25 @@ Output (JSON):}if (isDiscard) {- const result = handleDiscard(id, lines, targetFile);- console.log(JSON.stringify({ handled: true, file: relFile, carbonize: false, ...result }));+ let result;+ // handleDiscard takes the source lock, which throws SOURCE_LOCKED under+ // contention. Without this catch the CLI exits non-zero with empty stdout+ // and the agent gets no JSON to act on.+ try {+ result = handleDiscard(id, lines, targetFile);+ } catch (err) {+ emitResult(operationFailure(err, { file: relFile }));+ return;+ }+ emitResult({ handled: true, file: relFile, carbonize: false, ...result });} else {- const result = handleAccept(id, variantNum, lines, targetFile, paramValues);+ let result;+ try {+ result = handleAccept(id, variantNum, lines, targetFile, paramValues);+ } catch (err) {+ emitResult(operationFailure(err, { file: relFile }));+ return;+ }const acceptedOriginalText = result.acceptedOriginalText || '';delete result.acceptedOriginalText;// Single-line attention-grabber when cleanup is required. The full@@ -167,7 +285,7 @@ Output (JSON):// Non-fatal; the buffer stays as-is and the user can discard later.}}- console.log(JSON.stringify({ handled: true, file: relFile, ...result }));+ emitResult({ handled: true, file: relFile, ...result });}}@@ -235,7 +353,14 @@ function scrubManualEditsAgainstFile(_targetFile, cwd = process.cwd(), originalB// Discard// ----------------------------------------------------------------------------function handleDiscard(id, lines, targetFile) {+function handleDiscard(id, _lines, targetFile) {+ return withSourceLockSync(targetFile, 'discard:' + id, () => {+ const lines = fs.readFileSync(targetFile, 'utf-8').split('\n');+ return handleDiscardUnlocked(id, lines, targetFile);+ }, { waitMs: ACCEPT_LOCK_WAIT_MS });+}++function handleDiscardUnlocked(id, lines, targetFile) {const block = findMarkerBlock(id, lines);if (!block) return { handled: false, error: 'Markers not found' };@@ -330,7 +455,24 @@ function reindentContent(contentLines, fromIndent, toIndent) {});}-function handleAccept(id, variantNum, lines, targetFile, paramValues) {+function handleAccept(id, variantNum, _lines, targetFile, paramValues) {+ return withSourceLockSync(targetFile, 'accept:' + id, () => {+ const lines = fs.readFileSync(targetFile, 'utf-8').split('\n');+ return handleAcceptUnlocked(id, variantNum, lines, targetFile, paramValues);+ }, { waitMs: ACCEPT_LOCK_WAIT_MS });+}++function handleAcceptUnlocked(id, variantNum, lines, targetFile, paramValues) {+ const built = buildAcceptedWrappedSource(id, variantNum, lines, targetFile, paramValues);+ if (built.handled === false) return built;+ fs.writeFileSync(targetFile, built.content, 'utf-8');+ return {+ carbonize: built.carbonize,+ acceptedOriginalText: built.acceptedOriginalText,+ };+}++function buildAcceptedWrappedSource(id, variantNum, lines, targetFile, paramValues) {const block = findMarkerBlock(id, lines);if (!block) return { handled: false, error: 'Markers not found' };@@ -375,11 +517,14 @@ function handleAccept(id, variantNum, lines, targetFile, paramValues) {...replacement,...lines.slice(replaceRange.end + 1),];- fs.writeFileSync(targetFile, newLines.join('\n'), 'utf-8');-- return { carbonize: needsCarbonize, acceptedOriginalText: originalContent.join('\n') };+ return {+ content: newLines.join('\n'),+ carbonize: needsCarbonize,+ acceptedOriginalText: originalContent.join('\n'),+ };}+function readSourceShadowPreviewMeta(content, id) {const escaped = escapeRegExp(id);const wrapperRe = new RegExp('<[^>]+data-impeccable-variants=(["\'])' + escaped + '\\1[^>]*>');@@ -746,6 +891,21 @@ function detectCommentSyntax(filePath) {// File search (find the file containing session markers)// ---------------------------------------------------------------------------+/**+ * `.impeccable` is the critical entry, and it is not cosmetic.+ *+ * Progressive publication stages each revision as `.impeccable/live/artifacts/+ * <id>-r<n>.<source-ext>`, and those artifacts carry the very marker this search+ * looks for. The walk reaches `.` for any project whose source is not under one+ * of the privileged dirs above (this repo's own site lives in `site/pages/`), and+ * dot-directories sort before letters, so the artifact was found *before* the+ * real file. isGeneratedFile then declined the accept, and the agent fell back to+ * carbonizing several hundred lines of stylesheet by hand.+ *+ * Impeccable's own state directory is never project source. Never search it.+ */+const SEARCH_SKIP_DIRS = new Set(['node_modules', '.git', 'dist', 'build', IMPECCABLE_DIR]);+function findSessionFile(id, cwd) {const marker = 'impeccable-variants-start ' + id;const searchDirs = ['src', 'app', 'pages', 'components', 'public', 'views', 'templates', '.'];@@ -786,7 +946,7 @@ function searchDir(dir, query, seen, depth) {for (const entry of entries) {if (!entry.isDirectory()) continue;- if (['node_modules', '.git', 'dist', 'build'].includes(entry.name)) continue;+ if (SEARCH_SKIP_DIRS.has(entry.name)) continue;const result = searchDir(path.join(dir, entry.name), query, seen, depth + 1);if (result) return result;}@@ -798,6 +958,28 @@ function searchDir(dir, query, seen, depth) {// Utilities// ---------------------------------------------------------------------------+function acceptReceiptPath(cwd, id) {+ return path.join(getLiveDir(cwd), 'accept-receipts', `${safeSessionId(id)}.json`);+}++function readAcceptReceipt(cwd, id) {+ try { return JSON.parse(fs.readFileSync(acceptReceiptPath(cwd, id), 'utf-8')); } catch { return null; }+}++function writeAcceptReceipt(cwd, id, receipt) {+ const file = acceptReceiptPath(cwd, id);+ fs.mkdirSync(path.dirname(file), { recursive: true });+ const value = {+ id,+ ...receipt,+ completedAt: new Date().toISOString(),+ };+ const temporary = `${file}.${process.pid}.${Date.now()}.tmp`;+ fs.writeFileSync(temporary, JSON.stringify(value, null, 2) + '\n', 'utf-8');+ fs.renameSync(temporary, file);+ return value;+}+function argVal(args, flag) {const idx = args.indexOf(flag);return idx !== -1 && idx + 1 < args.length ? args[idx + 1] : null;diff --git a/.kiro/skills/impeccable/scripts/live-browser.js b/.kiro/skills/impeccable/scripts/live-browser.jsindex 616f1290a..20d875b93 100644--- a/.kiro/skills/impeccable/scripts/live-browser.js+++ b/.kiro/skills/impeccable/scripts/live-browser.js@@ -126,6 +126,9 @@let expectedVariants = 0;let arrivedVariants = 0;let visibleVariant = 0;+ let generationPhase = null;+ let parameterGenerationState = 'idle';+ let parameterReadyAnnouncedSession = null;let svelteComponentSession = null;let svelteRuntimePromise = null;let pendingSvelteComponentRetryObserver = null;@@ -134,6 +137,7 @@let currentPreviewMode = null;let recoveryWaitingForAnchor = false;let pickedAnchorSnapshot = null;+ let pickedAnchorViewportTop = null;let pendingVariantAnchorRetryObserver = null;let pendingAcceptedSession = null;let variantObserver = null;@@ -151,10 +155,12 @@// startScrollLock / stopScrollLock below.let scrollLockObserver = null;let scrollLockTargetY = null;+ let scrollLockAnchorTop = null;let scrollLockRaf = null;let scrollLockAbort = null;const SCROLL_ANCHOR_LOCK_ID = 'impeccable-scroll-anchor-lock';const VARIANT_STATE_STYLE_ID = 'impeccable-variant-state';+ const DISCARD_STATE_STYLE_ID = 'impeccable-discard-state';// Dedicated key for scroll position - SEPARATE from LS_KEY so that// saveSession's state updates don't clobber a carefully-captured scrollY.@@ -252,6 +258,13 @@barConnected: !!barEl?.isConnected,hasSvelteComponentSession: !!svelteComponentSession,mountedSvelteVariant: svelteComponentSession?.mountedVariant || 0,+ pickActive,+ pendingApplyInFlight,+ hoveredElement: hoveredElement ? {+ tag: hoveredElement.tagName,+ classes: hoveredElement.className,+ pickable: pickable(hoveredElement),+ } : null,pendingSvelteComponentRetry: !!pendingSvelteComponentRetryObserver,recoveryWaitingForAnchor,evtSourceReadyState: evtSource ? evtSource.readyState : null,@@ -1114,14 +1127,15 @@});}- function hideBar() {+ function hideBar(instant) {if (!barEl) return;const hideSeq = ++barHideSeq;stopVoice({ suppressSubmit: true });if (configureKind === 'insert') clearInsertPicking();barEl.style.opacity = '0';- barEl.style.transform = 'translateY(6px)';- setTimeout(() => { if (barEl && hideSeq === barHideSeq) barEl.style.display = 'none'; }, 250);+ barEl.style.transform = instant ? 'translateY(0)' : 'translateY(6px)';+ if (instant) barEl.style.display = 'none';+ else setTimeout(() => { if (barEl && hideSeq === barHideSeq) barEl.style.display = 'none'; }, 250);hideActionPicker();closeTunePopover();hideConfigureBarTooltip();@@ -1966,6 +1980,7 @@*/function setLiveState(next) {state = next;+ window.__IMPECCABLE_LIVE_STATE__ = next;syncPageInteractionCursor();}@@ -2516,18 +2531,27 @@fontSize: '11px', color: BP.textDim, whiteSpace: 'nowrap',marginLeft: 'auto',});- // Variants currently arrive atomically in a single file edit, so a- // per-variant counter would lie. Say what's true.status.textContent = recoveryWaitingForAnchor? 'Variants ready. Reveal the selected element to resume.'- : (arrivedVariants < expectedVariants- ? 'Generating ' + expectedVariants + ' variants...'- : 'Done');+ : generationStatusText();row.appendChild(status);return row;}+ function generationStatusText() {+ if (arrivedVariants >= expectedVariants && expectedVariants > 0) return 'Done';+ if (generationPhase === 'picked_up') return 'Agent picked up the request...';+ if (generationPhase === 'scaffolding') return 'Finding the source...';+ if (generationPhase === 'source_ready') return 'Source ready. Generating...';+ if (generationPhase === 'scaffold_fallback') return 'Agent is locating the source...';+ if (generationPhase === 'first_variant_generating') return 'Designing the first variant...';+ if (generationPhase === 'first_variant_validating') return 'Checking the first variant...';+ if (generationPhase === 'remaining_variants_generating') return 'Exploring two more directions...';+ if (generationPhase === 'remaining_variants_validating') return 'Checking the remaining variants...';+ return 'Generating ' + expectedVariants + ' variants...';+ }+// Cycling rowconst TUNE_ICON_SVG = '<svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" style="flex-shrink:0"><line x1="4" y1="8" x2="20" y2="8"/><circle cx="14" cy="8" r="2.4" fill="currentColor" stroke="none"/><line x1="4" y1="16" x2="20" y2="16"/><circle cx="10" cy="16" r="2.4" fill="currentColor" stroke="none"/></svg>';@@ -2557,7 +2581,7 @@color: BP.textDim, minWidth: '24px', textAlign: 'center',});counter.id = PREFIX + '-variant-counter';- counter.textContent = visibleVariant + '/' + arrivedVariants;+ counter.textContent = visibleVariant + '/' + expectedVariants;row.appendChild(counter);// Next@@ -2567,10 +2591,12 @@if (visibleVariant >= arrivedVariants) next.style.opacity = '0.3';row.appendChild(next);- // Tune chip - only when the visible variant exposes params+ // Tune chip stays visible while the deferred parameter phase is running,+ // then becomes interactive as soon as this variant exposes controls.const visParams = parseVariantParams(getVisibleVariantEl());const hasParams = visParams.length > 0;- if (hasParams) {+ const paramsPending = !hasParams && (parameterGenerationState === 'pending' || parameterGenerationState === 'loading');+ if (hasParams || paramsPending) {const tune = el('button', {display: 'inline-flex', alignItems: 'center', gap: '6px',padding: '4px 10px', borderRadius: '5px',@@ -2578,35 +2604,54 @@background: tuneOpen ? BP.accentSoft : 'transparent',color: tuneOpen ? BP.accent : BP.text,fontFamily: FONT, fontSize: '11px', fontWeight: '500',- cursor: 'pointer',+ cursor: paramsPending ? 'wait' : 'pointer',transition: 'color 0.12s ease, background 0.12s ease',whiteSpace: 'nowrap',});- tune.innerHTML = TUNE_ICON_SVG;+ if (paramsPending) {+ const spinner = el('span', {+ width: '11px', height: '11px', borderRadius: '50%',+ border: '1.5px solid ' + BP.hairline,+ borderTopColor: BP.accent,+ animation: 'impeccable-spin 0.6s linear infinite',+ boxSizing: 'border-box', flexShrink: '0',+ });+ spinner.setAttribute('aria-hidden', 'true');+ tune.appendChild(spinner);+ } else {+ tune.innerHTML = TUNE_ICON_SVG;+ }const tuneLabel = document.createElement('span');tuneLabel.textContent = 'Tune';tune.appendChild(tuneLabel);- const tuneBadge = document.createElement('span');- Object.assign(tuneBadge.style, {- display: 'inline-flex', alignItems: 'center', justifyContent: 'center',- minWidth: '16px', height: '16px', padding: '0 4px',- borderRadius: '999px',- background: tuneOpen ? C.brand : BP.hairline,- color: tuneOpen ? 'oklch(98% 0 0)' : 'inherit',- fontFamily: MONO, fontSize: '9.5px', fontWeight: '600',- lineHeight: '1',- boxSizing: 'border-box',- });- tuneBadge.textContent = String(visParams.length);- tune.appendChild(tuneBadge);- tune.title = 'Tune this variant (' + visParams.length + ' knob' + (visParams.length === 1 ? '' : 's') + ')';- tune.addEventListener('mouseenter', () => {- if (!tuneOpen) tune.style.background = BP.accentSoft;- });- tune.addEventListener('mouseleave', () => {- if (!tuneOpen) tune.style.background = 'transparent';- });- tune.addEventListener('click', (e) => { e.stopPropagation(); toggleTunePopover(); });+ if (hasParams) {+ const tuneBadge = document.createElement('span');+ Object.assign(tuneBadge.style, {+ display: 'inline-flex', alignItems: 'center', justifyContent: 'center',+ minWidth: '16px', height: '16px', padding: '0 4px',+ borderRadius: '999px',+ background: tuneOpen ? C.brand : BP.hairline,+ color: tuneOpen ? 'oklch(98% 0 0)' : 'inherit',+ fontFamily: MONO, fontSize: '9.5px', fontWeight: '600',+ lineHeight: '1',+ boxSizing: 'border-box',+ });+ tuneBadge.textContent = String(visParams.length);+ tune.appendChild(tuneBadge);+ tune.title = 'Tune this variant (' + visParams.length + ' knob' + (visParams.length === 1 ? '' : 's') + ')';+ tune.addEventListener('mouseenter', () => {+ if (!tuneOpen) tune.style.background = BP.accentSoft;+ });+ tune.addEventListener('mouseleave', () => {+ if (!tuneOpen) tune.style.background = 'transparent';+ });+ tune.addEventListener('click', (e) => { e.stopPropagation(); toggleTunePopover(); });+ } else {+ tune.disabled = true;+ tune.setAttribute('aria-label', 'Tune controls are still being prepared');+ tune.title = 'Tune controls are still being prepared';+ tune.style.opacity = '0.72';+ }tune.dataset.iceqTune = '1';row.appendChild(tune);}@@ -2614,6 +2659,15 @@// Spacerrow.appendChild(el('div', { flex: '1' }));+ if (arrivedVariants < expectedVariants) {+ const remaining = expectedVariants - arrivedVariants;+ const progress = el('span', {+ fontSize: '11px', color: BP.textDim, whiteSpace: 'nowrap',+ });+ progress.textContent = remaining + ' more arriving...';+ row.appendChild(progress);+ }+// Accept - primary action, kinpaku gold + lacquer-deep (matches demo .live-demo-ctx-accept)const accept = el('button', {padding: '5px 14px', borderRadius: '5px',@@ -2628,7 +2682,11 @@accept.addEventListener('mousedown', () => accept.style.transform = 'scale(0.97)');accept.addEventListener('mouseup', () => accept.style.transform = 'scale(1)');accept.addEventListener('click', (e) => { e.stopPropagation(); handleAccept(); });- if (arrivedVariants === 0) { accept.style.opacity = '0.3'; accept.style.pointerEvents = 'none'; }+ if (arrivedVariants === 0) {+ accept.style.opacity = '0.3';+ accept.style.pointerEvents = 'none';+ accept.title = 'Accept becomes available when the first variant arrives';+ }row.appendChild(accept);// Discard@@ -4743,6 +4801,32 @@}}+ function mountedParameterCount() {+ if (svelteComponentSession?.sessionId === currentSessionId) {+ return Object.values(svelteComponentSession.paramsByVariant || {})+ .reduce((total, params) => total + (Array.isArray(params) ? params.length : 0), 0);+ }+ const wrapper = document.querySelector('[data-impeccable-variants="' + currentSessionId + '"]');+ if (!wrapper) return 0;+ return [...wrapper.querySelectorAll('[data-impeccable-variant]:not([data-impeccable-variant="original"])')]+ .reduce((total, variant) => total + parseVariantParams(variant).length, 0);+ }++ function completeParameterPublication() {+ if (!currentSessionId) return;+ const ready = mountedParameterCount() > 0;+ parameterGenerationState = ready ? 'ready' : 'none';+ if (ready && parameterReadyAnnouncedSession !== currentSessionId) {+ parameterReadyAnnouncedSession = currentSessionId;+ showToast('Tune controls are ready.', 3000);+ }+ if (state === 'CYCLING') {+ refreshParamsPanel();+ showOrUpdateCyclingBar();+ }+ saveSession();+ }+function toggleTunePopover() {if (pendingApplyInFlight) { showManualApplyBusyToast(); return; }if (tuneOpen) { closeTunePopover(); return; }@@ -4835,6 +4919,10 @@return String(filePath || '').endsWith('manifest.json');}+ function isFrameworkComponentPreviewMode(mode) {+ return mode === 'svelte-component';+ }+function parseOriginalMarkupElement(originalMarkup) {const parser = new DOMParser();const doc = parser.parseFromString('<div id="impeccable-anchor">' + originalMarkup + '</div>', 'text/html');@@ -5029,9 +5117,13 @@}}- function loadSvelteRuntime(runtimeModule) {+ function resolveComponentModuleUrl(manifest, modulePath) {+ return new URL(String(modulePath || ''), location.origin).href;+ }++ function loadSvelteRuntime(runtimeModule, manifest) {const modulePath = runtimeModule || '/src/lib/impeccable/__runtime.js';- const url = new URL(modulePath, location.origin).href;+ const url = resolveComponentModuleUrl(manifest, modulePath);if (!svelteRuntimePromise) {svelteRuntimePromise = import(/* @vite-ignore */ url);}@@ -5065,7 +5157,8 @@async function loadSvelteComponentVariantSource(manifest, variantNum) {const dir = String(manifest?.componentDir || '').replace(/^\/+/, '');if (!dir || !variantNum) return '';- const sourcePath = dir + '/v' + variantNum + '.svelte';+ const extension = manifest.componentExtension || 'svelte';+ const sourcePath = dir + '/v' + variantNum + '.' + extension;const url = 'http://localhost:' + PORT + '/source?token=' + TOKEN + '&path=' + encodeURIComponent(sourcePath);try {const res = await fetch(url);@@ -5221,7 +5314,7 @@if (!sourceOriginal) return values;const map = buildSvelteExpressionTextMap(sourceOriginal, liveEl);for (const entry of contract) {- const token = '{' + entry.expr + '}';+ const token = entry.previewToken || ('{' + entry.expr + '}');values[entry.prop] = map.get(token) || '';}return values;@@ -5233,9 +5326,12 @@try {const previousAnchor = getMountedSvelteComponentAnchor(svelteComponentSession) || selectedElement;svelteComponentSession.swapAnchor = makeFrozenAnchor(previousAnchor) || svelteComponentSession.swapAnchor || null;- const runtime = await loadSvelteRuntime(manifest.runtimeModule);- const modulePath = '/' + String(manifest.componentDir || '').replace(/^\/+/, '') + '/v' + variantNum + '.svelte';- const moduleUrl = new URL(modulePath, location.origin).href + '?t=' + Date.now();+ const runtime = await loadSvelteRuntime(manifest.runtimeModule, manifest);+ const extension = manifest.componentExtension || 'svelte';+ const moduleBase = manifest.componentModuleBase+ || ('/' + String(manifest.componentDir || '').replace(/^\/+/, ''));+ const modulePath = String(moduleBase).replace(/\/+$/, '') + '/v' + variantNum + '.' + extension;+ const moduleUrl = resolveComponentModuleUrl(manifest, modulePath) + '?t=' + Date.now();const mod = await import(/* @vite-ignore */ moduleUrl);const Component = mod.default;if (svelteComponentSession.mountedInstance && runtime.unmount) {@@ -5275,7 +5371,7 @@if (svelteComponentSession?.sessionId === sessionId) {svelteComponentSession.swapAnchor = null;}- console.error('[impeccable] Failed to mount Svelte variant ' + variantNum + ' for ' + sessionId + ':', err);+ console.error('[impeccable] Failed to mount component variant ' + variantNum + ' for ' + sessionId + ':', err);return false;}}@@ -5340,40 +5436,46 @@if (manifest.id !== sessionId) return;const paramsByVariant = await loadSvelteComponentParams(manifest);+ const availableVariants = Number(manifest.arrivedVariants) || Number(manifest.count) || 1;+ const componentPreviewMode = isFrameworkComponentPreviewMode(manifest.previewMode)+ ? manifest.previewMode+ : 'svelte-component';currentSessionId = sessionId;expectedVariants = Number(manifest.count) || expectedVariants || 1;rememberSessionFileMeta({sourceFile: manifest.sourceFile,previewFile: manifestPath,- previewMode: 'svelte-component',+ previewMode: componentPreviewMode,});if (state !== 'CYCLING') setLiveState('GENERATING');const existingWrapper = document.querySelector('[data-impeccable-variants="' + sessionId + '"]');if (existingWrapper && svelteComponentSession?.sessionId === sessionId) {recoveryWaitingForAnchor = false;+ svelteComponentSession.manifest = manifest;svelteComponentSession.paramsByVariant = paramsByVariant;- arrivedVariants = Number(manifest.count) || expectedVariants || 1;- expectedVariants = arrivedVariants;+ arrivedVariants = availableVariants;+ expectedVariants = Number(manifest.count) || expectedVariants || arrivedVariants;visibleVariant = visibleVariant > 0 && visibleVariant <= arrivedVariants ? visibleVariant : 1;await mountSvelteComponentVariant(visibleVariant || 1);setLiveState('CYCLING');showOrUpdateCyclingBar();saveSession();+ if (parameterGenerationState === 'loading') completeParameterPublication();return;}const liveEl = findLiveElementForSvelteManifest(manifest);if (!liveEl?.parentElement) {console.warn('[impeccable] Could not find original element in live DOM.');- arrivedVariants = Number(manifest.count) || expectedVariants || 1;- expectedVariants = arrivedVariants;+ arrivedVariants = availableVariants;+ expectedVariants = Number(manifest.count) || expectedVariants || arrivedVariants;const saved = loadSession();const savedVisibleVariant = saved && saved.id === sessionId ? saved.visible : 0;visibleVariant = visibleVariant > 0 && visibleVariant <= arrivedVariants? visibleVariant: (savedVisibleVariant > 0 && savedVisibleVariant <= arrivedVariants ? savedVisibleVariant : 1);- enterRecoveryWaitingForAnchor({ checkpointReason: 'svelte_component_anchor_missing', trackScroll: true });+ enterRecoveryWaitingForAnchor({ checkpointReason: 'component_preview_anchor_missing', trackScroll: true });waitForSvelteComponentTargetAndRetry({ manifestPath, sessionId, manifest });return;}@@ -5381,7 +5483,7 @@const wrapper = document.createElement('div');wrapper.dataset.impeccableVariants = sessionId;wrapper.dataset.impeccableVariantCount = String(manifest.count || expectedVariants || 1);- wrapper.dataset.impeccablePreview = 'svelte-component';+ wrapper.dataset.impeccablePreview = componentPreviewMode;wrapper.style.display = 'contents';const mountTarget = document.createElement('div');@@ -5419,8 +5521,8 @@recoveryWaitingForAnchor = false;const previousVisibleVariant = currentSessionId === sessionId ? visibleVariant : 0;- arrivedVariants = Number(manifest.count) || expectedVariants || 1;- expectedVariants = arrivedVariants;+ arrivedVariants = availableVariants;+ expectedVariants = Number(manifest.count) || expectedVariants || arrivedVariants;const saved = loadSession();const savedVisibleVariant = saved && saved.id === sessionId ? saved.visible : 0;visibleVariant = previousVisibleVariant > 0 && previousVisibleVariant <= arrivedVariants@@ -5445,9 +5547,10 @@refreshParamsPanel();positionBar();saveSession();- console.log('[impeccable] Mounted ' + arrivedVariants + ' Svelte component variants.');+ if (parameterGenerationState === 'loading') completeParameterPublication();+ console.log('[impeccable] Mounted ' + arrivedVariants + ' ' + manifest.framework + ' component variants.');} catch (err) {- console.error('[impeccable] Failed to mount Svelte component variants:', err);+ console.error('[impeccable] Failed to mount component-preview variants:', err);abortSvelteComponentInjection(sessionId, 'Could not load variants. Fix the error and re-run.');}}@@ -5493,6 +5596,8 @@clearHandled();resetSessionFileMeta();currentSessionId = null;+ parameterGenerationState = 'idle';+ parameterReadyAnnouncedSession = null;expectedVariants = 0;arrivedVariants = 0;visibleVariant = 0;@@ -5502,12 +5607,24 @@if (message) showToast(message, 5000);}+ // How many delayed re-reads a completion-driven source fallback gets when+ // the fetched source still shows only the preflight scaffold, before the+ // failure is surfaced via recoverEmptyCycling.+ const COMPLETED_SOURCE_FALLBACK_RETRIES = 3;+ const COMPLETED_SOURCE_FALLBACK_RETRY_MS = 1200;+/*** No-HMR fallback: fetch the raw source file from the live server,* parse it, extract the variant wrapper, and inject it into the live DOM.* This works even when the dev server caches HTML (Bun, static servers).+ *+ * opts.generationCompleted marks callers that KNOW the agent finished (a+ * `done` arrived or the server reported a completed generation). For them an+ * empty read is a stale source view and no further event is coming, so the+ * read retries a few times and then surfaces recovery. Callers without the+ * flag may be mid-generation and wait indefinitely for the real completion.*/- function injectVariantsFromSource(filePath, sessionId) {+ function injectVariantsFromSource(filePath, sessionId, opts = {}) {if (isSvelteComponentManifestPath(filePath)) {injectSvelteComponentsFromManifest(filePath, sessionId);return;@@ -5573,6 +5690,32 @@arrivedVariants = variants.length;expectedVariants = parseInt(wrapper.dataset.impeccableVariantCount || arrivedVariants);if (arrivedVariants <= 0) {+ if (state === 'GENERATING') {+ // Mid-generation the source legitimately holds a scaffold wrapper+ // with no variants yet (the server-side preflight wraps before the+ // agent writes). Tearing the session down here would destroy an+ // in-flight generation; stay in GENERATING — the variant observer+ // is armed and the server re-delivers a missed `done`.+ if (!opts.generationCompleted) {+ console.log('[impeccable] Source has scaffold but no variants yet; still generating.');+ return;+ }+ // Generation finished, yet the read shows only the scaffold: the+ // source view is stale and no further event will fire. Re-read a+ // few times before surfacing recovery — a single silent return+ // here would strand the tab in GENERATING forever.+ const attempt = opts.attempt || 0;+ if (attempt < COMPLETED_SOURCE_FALLBACK_RETRIES) {+ console.log('[impeccable] Generation is done but source shows no variants yet; retrying read ('+ + (attempt + 1) + '/' + COMPLETED_SOURCE_FALLBACK_RETRIES + ').');+ setTimeout(() => {+ if (state !== 'GENERATING' || currentSessionId !== sessionId) return;+ if (arrivedVariants > 0) return;+ injectVariantsFromSource(filePath, sessionId, { ...opts, attempt: attempt + 1 });+ }, COMPLETED_SOURCE_FALLBACK_RETRY_MS);+ return;+ }+ }recoverEmptyCycling('source-fallback-empty');return;}@@ -5594,6 +5737,7 @@refreshParamsPanel();positionBar();saveSession();+ if (parameterGenerationState === 'loading') completeParameterPublication();console.log('[impeccable] Injected ' + arrivedVariants + ' variants from source file.');}).catch(err => {@@ -5865,13 +6009,36 @@document.getElementById(VARIANT_STATE_STYLE_ID)?.remove();}+ function showOriginalDuringDiscard(sessionId) {+ if (!sessionId) return;+ let styleEl = document.getElementById(DISCARD_STATE_STYLE_ID);+ if (!styleEl) {+ styleEl = document.createElement('style');+ styleEl.id = DISCARD_STATE_STYLE_ID;+ (document.head || document.documentElement).appendChild(styleEl);+ }+ const wrapper = '[data-impeccable-variants="' + sessionId + '"]';+ styleEl.textContent = wrapper + ' > [data-impeccable-variant]:not([data-impeccable-variant="original"]) { display:none !important; }\n'+ + wrapper + ' > [data-impeccable-variant="original"] { display:block !important; }';+ }++ function resolveScrollLockAnchorTop() {+ const anchor = resolveBarAnchor();+ if (!anchor?.isConnected) return null;+ const top = anchor.getBoundingClientRect().top;+ return Number.isFinite(top) ? top : null;+ }+// Hold window.scrollY at a fixed value across DOM mutations inside the// session's wrapper (HMR patches, variant inserts, cycle swaps).- function startScrollLock(sessionId, initialTargetY) {+ function startScrollLock(sessionId, initialTargetY, initialAnchorTop) {stopScrollLock();scrollLockTargetY = typeof initialTargetY === 'number' && isFinite(initialTargetY)? initialTargetY: window.scrollY;+ scrollLockAnchorTop = typeof initialAnchorTop === 'number' && isFinite(initialAnchorTop)+ ? initialAnchorTop+ : resolveScrollLockAnchorTop();try { history.scrollRestoration = 'manual'; } catch {}@@ -5895,6 +6062,17 @@const correct = (why) => {scrollLockRaf = null;if (scrollLockTargetY == null) return;+ const anchor = resolveBarAnchor();+ if (anchor?.isConnected && typeof scrollLockAnchorTop === 'number' && isFinite(scrollLockAnchorTop)) {+ const anchorTop = anchor.getBoundingClientRect().top;+ const anchorDelta = anchorTop - scrollLockAnchorTop;+ if (Math.abs(anchorDelta) >= 0.5) {+ window.scrollTo({ top: window.scrollY + anchorDelta, left: window.scrollX, behavior: 'instant' });+ scrollLockTargetY = window.scrollY;+ writeScrollY(scrollLockTargetY);+ return;+ }+ }const before = window.scrollY;const delta = before - scrollLockTargetY;if (Math.abs(delta) < 0.5) {@@ -5939,6 +6117,7 @@if (scrollLockRaf != null) { cancelAnimationFrame(scrollLockRaf); scrollLockRaf = null; }const prevTarget = scrollLockTargetY;scrollLockTargetY = window.scrollY;+ scrollLockAnchorTop = resolveScrollLockAnchorTop();writeScrollY(scrollLockTargetY);};const markGesture = (why) => {@@ -5976,6 +6155,7 @@if (scrollLockRaf != null) { cancelAnimationFrame(scrollLockRaf); scrollLockRaf = null; }if (scrollLockAbort) { scrollLockAbort.abort(); scrollLockAbort = null; }scrollLockTargetY = null;+ scrollLockAnchorTop = null;// NOTE: do NOT clear the persistent scroll key here. startScrollLock// calls us as a reset, and clearing the key would nuke the Go-time// scrollY that the next resume needs to read.@@ -6049,6 +6229,7 @@updating = true;arrivedVariants = count;+ generationPhase = arrivedVariants >= expectedVariants ? 'variants_ready' : 'variants_progress';if (visibleVariant === 0 && arrivedVariants > 0) {const saved = loadSession();const savedVisibleVariant = saved && saved.id === sessionId ? saved.visible : 0;@@ -6064,7 +6245,7 @@const expected = parseInt(wrapper.dataset.impeccableVariantCount || '0');if (expected > 0) expectedVariants = expected;- if (arrivedVariants >= expectedVariants && expectedVariants > 0) {+ if (arrivedVariants > 0) {setLiveState('CYCLING');recoveryWaitingForAnchor = false;hideShaderOverlay();@@ -6072,13 +6253,18 @@updateSelectedElement();showOrUpdateCyclingBar();disableInlineEdit();- refreshParamsPanel();+ if (arrivedVariants >= expectedVariants && expectedVariants > 0) refreshParamsPanel();+ else hideParamsPanel();positionBar();} else if (state === 'GENERATING') {updateBarContent('generating');}saveSession();- queueCheckpoint(state === 'CYCLING' ? 'variants_ready' : 'variants_progress');+ sendCheckpoint(+ arrivedVariants >= expectedVariants && expectedVariants > 0+ ? 'variants_ready'+ : 'variants_progress',+ );updating = false;});@@ -6151,6 +6337,7 @@syncAgentPollingUi(!!msg.agentPolling);startAgentStatusPoll();restoreFromActiveSessions(msg.activeSessions, 'sse_connected');+ recoverMissedGenerationCompletion(msg.activeSessions);if (state === 'IDLE' && (pickActive || insertActive)) setLiveState('PICKING');syncPageInteractionCursor();syncPageChatFocus('sse-connected');@@ -6158,6 +6345,42 @@case 'agent_polling':syncAgentPollingUi(!!msg.connected);break;+ case 'agent_phase':+ if (msg.id === currentSessionId && (state === 'GENERATING' || state === 'CYCLING')) {+ generationPhase = msg.phase || generationPhase;+ if (msg.phase === 'variant_parameters_generating' || msg.phase === 'variant_parameters_validating') {+ parameterGenerationState = 'loading';+ }+ if (msg.phase === 'parameters_ready' && parameterGenerationState !== 'ready') {+ parameterGenerationState = 'loading';+ }+ updateBarContent(state === 'CYCLING' ? 'cycling' : 'generating');+ saveSession();+ }+ break;+ case 'variant_progress':+ if (msg.id === currentSessionId) {+ if (msg.publicationKind === 'params') parameterGenerationState = 'loading';+ rememberSessionFileMeta(msg);+ if (isFrameworkComponentPreviewMode(msg.previewMode) && msg.previewFile) {+ injectSvelteComponentsFromManifest(msg.previewFile, msg.id);+ } else if ((msg.previewMode === 'source' || !msg.previewMode) && (msg.previewFile || msg.file)) {+ // Give normal framework HMR the first chance to reconcile its+ // own managed tree. Nuxt route-module HMR can skip intermediate+ // revisions, so fall back to source injection only when the+ // advertised progress still has not appeared after a short+ // settle. Immediate injection races React/Vue ownership and can+ // trigger removeChild errors on the next HMR commit.+ const targetArrived = Number(msg.arrivedVariants) || 1;+ setTimeout(() => {+ if (msg.id !== currentSessionId) return;+ if (state !== 'GENERATING' && state !== 'CYCLING') return;+ if (msg.publicationKind !== 'params' && arrivedVariants >= targetArrived) return;+ injectVariantsFromSource(msg.previewFile || msg.file, msg.id);+ }, 150);+ }+ }+ break;case 'steer_done':maybeCompleteSteer(msg);break;@@ -6175,6 +6398,10 @@case 'done':if (maybeCompleteSteer(msg)) break;rememberSessionFileMeta(msg);+ if (msg.id === currentSessionId && isFrameworkComponentPreviewMode(currentPreviewMode) && currentPreviewFile) {+ injectSvelteComponentsFromManifest(currentPreviewFile, msg.id);+ break;+ }// Variants already arrived via HMR → normal transition.if (arrivedVariants >= expectedVariants && expectedVariants > 0) {if (state === 'GENERATING') {@@ -6190,7 +6417,7 @@setTimeout(() => {if (arrivedVariants >= expectedVariants && expectedVariants > 0) return;if (state !== 'GENERATING' || msg.id !== currentSessionId) return;- injectVariantsFromSource(msg.file, msg.id);+ injectVariantsFromSource(msg.file, msg.id, { generationCompleted: true });}, 750);break;}@@ -6215,9 +6442,10 @@if (maybeCompleteAcceptedSession(msg)) break;break;case 'agent_done':- // Carbonize accepts are not terminal until live-complete.mjs sends- // the final complete event. Keep the browser in its recoverable- // saving state while the source cleanup is still in flight.+ // The deterministic accept has already committed the reviewed DOM+ // and fenced generation. Carbonize may continue in the background;+ // it must not hold the foreground picker hostage.+ if (msg.data?.carbonize === true && maybeCompleteAcceptedSession(msg)) break;break;case 'discarded':if (msg.id && msg.id === currentSessionId) {@@ -6306,6 +6534,7 @@type: 'checkpoint',id: currentSessionId,revision: sessionState.nextCheckpointRevision(),+ revisionDomain: 'browser',owner: browserOwner,phase: String(state || '').toLowerCase(),reason,@@ -6331,6 +6560,7 @@type: 'checkpoint',id,revision: sessionState.nextCheckpointRevision(),+ revisionDomain: 'browser',owner: browserOwner,phase: 'steer',reason,@@ -6684,6 +6914,9 @@expectedVariants = selectedCount;arrivedVariants = 0;visibleVariant = 0;+ generationPhase = 'queued';+ parameterGenerationState = 'pending';+ parameterReadyAnnouncedSession = null;resetSessionFileMeta();// Flip to GENERATING immediately so the bar morphs without waiting on@@ -6693,6 +6926,7 @@const elForCapture = selectedElement;pickedAnchorSnapshot = buildPickedAnchorSnapshot(elForCapture);const captureRect = elForCapture.getBoundingClientRect();+ pickedAnchorViewportTop = captureRect.top;const snapshot = {comments: annotState.comments.map(c => ({ x: c.x, y: c.y, text: c.text })),strokes: annotState.strokes.map(s => ({ points: s.points.map(p => [p[0], p[1]]) })),@@ -6724,7 +6958,7 @@writeScrollY(window.scrollY);if (variantObserver) variantObserver.disconnect();variantObserver = startVariantObserver(currentSessionId);- startScrollLock(currentSessionId);+ startScrollLock(currentSessionId, window.scrollY, pickedAnchorViewportTop);captureAndEmit(elForCapture, basePayload, snapshot, captureRect);}@@ -6759,12 +6993,16 @@expectedVariants = selectedCount;arrivedVariants = 0;visibleVariant = 0;+ generationPhase = 'queued';+ parameterGenerationState = 'pending';+ parameterReadyAnnouncedSession = null;resetSessionFileMeta();selectedElement = placeholderElement;insertPlaceholderSnapshot = buildInsertPlaceholderSnapshotFromDom(insertAnchorElement, placeholderElement);const elForCapture = placeholderElement;const captureRect = elForCapture.getBoundingClientRect();+ pickedAnchorViewportTop = captureRect.top;const basePayload = {type: 'generate',mode: 'insert',@@ -6795,7 +7033,7 @@writeScrollY(window.scrollY);if (variantObserver) variantObserver.disconnect();variantObserver = startVariantObserver(currentSessionId);- startScrollLock(currentSessionId);+ startScrollLock(currentSessionId, window.scrollY, pickedAnchorViewportTop);captureAndEmit(elForCapture, basePayload, snapshot, captureRect);}@@ -6975,9 +7213,9 @@// preview mounts are covered by the same shader regression checks.const adapter = String(window.__IMPECCABLE_LIVE_ADAPTER__ || '').toLowerCase();if (adapter === 'svelte' || adapter === 'sveltekit') return true;- if (currentPreviewMode === 'svelte-component' || svelteComponentSession) return true;+ if (isFrameworkComponentPreviewMode(currentPreviewMode) || svelteComponentSession) return true;const wrapper = el?.closest?.('[data-impeccable-variants]');- return wrapper?.dataset?.impeccablePreview === 'svelte-component';+ return isFrameworkComponentPreviewMode(wrapper?.dataset?.impeccablePreview);}function paintsShaderProxySurface(node) {@@ -7105,6 +7343,17 @@}async function captureAndEmit(el, basePayload, snapshot, rect) {+ const hasAnnotations = snapshot && (snapshot.comments.length > 0 || snapshot.strokes.length > 0);++ // Plain requests do not send a screenshot to the agent, so capture is+ // presentation-only. Wait only for the helper to accept the event before+ // starting CPU-heavy capture; this yields the browser task and prevents+ // rasterization from delaying the fetch itself.+ if (!hasAnnotations) {+ basePayload.clientSentAt = Date.now();+ await sendEvent(basePayload);+ }+let screenshotPath;let blob;let paper;@@ -7122,7 +7371,6 @@// are present. Without annotations the image is pure visual anchoring -// it biases the model toward the current rendering and works against the// three-distinct-directions brief.- const hasAnnotations = snapshot && (snapshot.comments.length > 0 || snapshot.strokes.length > 0);if (blob && hasAnnotations) {try {const uploadRes = await fetch(@@ -7140,7 +7388,12 @@console.warn('[impeccable] annotation upload failed:', err);}}- sendEvent(screenshotPath ? { ...basePayload, screenshotPath } : basePayload);+ // Annotated requests must wait for capture + upload because the screenshot+ // is semantic input. Plain requests were already dispatched above.+ if (hasAnnotations) {+ basePayload.clientSentAt = Date.now();+ sendEvent(screenshotPath ? { ...basePayload, screenshotPath } : basePayload);+ }}//@@ -7520,7 +7773,6 @@ void main() {if (variantSelectionPromise) {try { await variantSelectionPromise; } catch { /* failed selection falls back below */ }}- if (!currentSessionId || arrivedVariants === 0) return;const domVisibleVariant = readVisibleVariantFromDOM(currentSessionId);if (domVisibleVariant > 0) visibleVariant = domVisibleVariant;const acceptPayload = {@@ -7528,7 +7780,9 @@ void main() {id: currentSessionId,variantId: String(visibleVariant),pageUrl: location.pathname,+ clientSentAt: Date.now(),};+ if (!currentSessionId || arrivedVariants === 0) return;const acceptWrapper = document.querySelector('[data-impeccable-variants="' + currentSessionId + '"]');if (Object.keys(paramsCurrentValues).length > 0) {acceptPayload.paramValues = { ...paramsCurrentValues };@@ -7542,7 +7796,7 @@ void main() {const acceptedSessionId = currentSessionId;const acceptedVariant = visibleVariant;const acceptedIsSvelteComponent = svelteComponentSession?.sessionId === acceptedSessionId- || acceptWrapper?.dataset?.impeccablePreview === 'svelte-component';+ || isFrameworkComponentPreviewMode(acceptWrapper?.dataset?.impeccablePreview);const acceptedSnapshot = snapshotAcceptedVariantDom(acceptedSessionId, acceptedVariant);setLiveState('SAVING');@@ -7557,7 +7811,17 @@ void main() {saveSession();sendEvent(acceptPayload, { throwOnError: true })- .then(() => {})+ .then(() => {+ const pending = pendingAcceptedSession;+ if (!pending || pending.id !== acceptedSessionId) return;+ // POST /events returns only after the accept intent is durable and the+ // generation epoch is fenced. Source promotion/carbonize can finish in+ // the background; the foreground picker is free immediately.+ markSessionHandled();+ setLiveState('CONFIRMED');+ document.documentElement.dataset.impeccableAcceptToPickingMs = String(Date.now() - acceptPayload.clientSentAt);+ scheduleAcceptCleanup(pending);+ }).catch(() => {if (pendingAcceptedSession?.id === acceptedSessionId) pendingAcceptedSession = null;setLiveState('CYCLING');@@ -7586,17 +7850,26 @@ void main() {}function scheduleAcceptCleanup(accepted) {- setTimeout(function() {- if (!accepted?.isSvelteComponent && !acceptedDomAlreadyClean(accepted)) {- setTimeout(function() {- if (pendingAcceptedSession?.id !== accepted?.id) return;- if (!accepted?.isSvelteComponent) ensureAcceptedDomClean(accepted);- cleanupAcceptedSession();- }, 1800);- return;+ queueMicrotask(function() {+ if (pendingAcceptedSession?.id !== accepted?.id) return;+ // Svelte previews live in an adapter-owned mount rather than in source+ // wrapper markup. Promote the mounted variant before releasing the+ // session so the old adapter instance cannot linger behind the next+ // Pick → Go loop while carbonize finishes in the background.+ if (accepted?.isSvelteComponent) {+ commitAcceptedSvelteComponentToDom(accepted.id);}cleanupAcceptedSession();- }, 1200);+ });+ // Let React/Vue/Svelte own the HMR reconciliation. Mutating their DOM in+ // the same turn as the source update causes removeChild/NotFoundError+ // races. Static servers still need a fallback, but it must not keep Live+ // in SAVING or block the user's next pick.+ if (!accepted?.isSvelteComponent) {+ setTimeout(function() {+ if (!acceptedDomAlreadyClean(accepted)) ensureAcceptedDomClean(accepted);+ }, 1200);+ }}function snapshotAcceptedVariantDom(sessionId, variantId) {@@ -7700,7 +7973,11 @@ void main() {clearSession();resetSessionFileMeta();selectedElement = null;+ hoveredElement = null;+ pagePickSkipClick = false;currentSessionId = null;+ parameterGenerationState = 'idle';+ parameterReadyAnnouncedSession = null;selectedAction = 'impeccable';pendingAcceptedSession = null;renderEditBadge('hidden');@@ -7735,7 +8012,7 @@ void main() {sendEvent({ type: 'discard', id: currentSessionId }, { throwOnError: true }).then(() => {markSessionHandled();- cleanup();+ cleanup({ restoreOriginal: true, instantChrome: true });}).catch(() => showToast('Could not confirm discard with the live server. Session kept for recovery.', 5000));}@@ -7757,6 +8034,7 @@ void main() {currentPreviewMode = null;recoveryWaitingForAnchor = false;pickedAnchorSnapshot = null;+ pickedAnchorViewportTop = null;}function rememberSessionFileMeta(meta = {}) {@@ -7765,8 +8043,8 @@ void main() {const previewFile = normalizeSessionPath(meta.previewFile);const previewMode = meta.previewMode || (isSvelteComponentManifestPath(previewFile || file) ? 'svelte-component' : null);- if (previewMode === 'svelte-component' || isSvelteComponentManifestPath(file)) {- currentPreviewMode = 'svelte-component';+ if (isFrameworkComponentPreviewMode(previewMode) || isSvelteComponentManifestPath(file)) {+ currentPreviewMode = isFrameworkComponentPreviewMode(previewMode) ? previewMode : 'svelte-component';currentPreviewFile = previewFile || (isSvelteComponentManifestPath(file) ? file : currentPreviewFile);currentSourceFile = sourceFile || currentSourceFile;return;@@ -7782,12 +8060,15 @@ void main() {rememberSessionFileMeta(saved);if (saved.insertPlaceholder) insertPlaceholderSnapshot = saved.insertPlaceholder;if (saved.pickedAnchor) pickedAnchorSnapshot = saved.pickedAnchor;+ if (Number.isFinite(saved.pickedAnchorViewportTop)) pickedAnchorViewportTop = saved.pickedAnchorViewportTop;if (saved.action) selectedAction = saved.action;if (saved.count) selectedCount = saved.count;if (saved.previewMode) currentPreviewMode = saved.previewMode;if (saved.paramValues && typeof saved.paramValues === 'object') {paramsCurrentValues = { ...saved.paramValues };}+ if (saved.parameterState) parameterGenerationState = saved.parameterState;+ if (saved.generationPhase) generationPhase = saved.generationPhase;}function normalizePagePath(value) {@@ -7859,7 +8140,7 @@ void main() {saveSession();queueCheckpoint(reason || 'browser_restore_without_wrapper');- const restoreFile = currentPreviewMode === 'svelte-component'+ const restoreFile = isFrameworkComponentPreviewMode(currentPreviewMode)? currentPreviewFile: (currentSourceFile || currentPreviewFile);if (restoreFile) {@@ -7872,11 +8153,41 @@ void main() {function restoreFromActiveSessions(activeSessions, reason) {const wrapper = document.querySelector('[data-impeccable-variants]');- if (wrapper && wrapper.dataset.impeccablePreview !== 'svelte-component') return false;+ if (wrapper && !isFrameworkComponentPreviewMode(wrapper.dataset.impeccablePreview)) return false;if (svelteComponentSession?.sessionId === currentSessionId) return false;return restoreSessionWithoutWrapper(reason || 'sse_connected', activeSessions);}+ // Self-heal on SSE (re)connect. The preflight scaffold write triggers a+ // framework full-reload (Astro reloads pages for any .astro edit); if the+ // agent's variant write + `done` broadcast land while this page is+ // mid-reload, both the done SSE and the second HMR reload are missed and+ // the resumed page would wait in GENERATING at 0/N forever. The server's+ // session summary carries the durable generationCompletedAt marker, so on+ // every connect compare it against our own progress and pull the finished+ // variants from source when behind. Mirrors the `done` handler's source+ // fallback, including its give-HMR-the-first-chance settle delay.+ function recoverMissedGenerationCompletion(activeSessions) {+ if (!currentSessionId || state !== 'GENERATING') return;+ if (!Array.isArray(activeSessions)) return;+ const summary = activeSessions.find((session) => session?.id === currentSessionId);+ if (!summary?.generationCompletedAt || summary.generationCanceled) return;+ if (isTerminalSessionSummary(summary)) return;+ if (arrivedVariants > 0 && arrivedVariants >= expectedVariants) return;+ rememberSessionFileMeta(summary);+ const sessionId = currentSessionId;+ const file = isFrameworkComponentPreviewMode(currentPreviewMode)+ ? currentPreviewFile+ : (summary.sourceFile || summary.previewFile || currentSourceFile || currentPreviewFile);+ if (!file) return;+ console.log('[impeccable] Reconnected after generation completed; recovering variants from source.');+ setTimeout(() => {+ if (sessionId !== currentSessionId || state !== 'GENERATING') return;+ if (arrivedVariants > 0 && arrivedVariants >= expectedVariants) return;+ injectVariantsFromSource(file, sessionId, { generationCompleted: true });+ }, 750);+ }+function saveSession() {if (!currentSessionId) return;// NOTE: scrollY is stored under a separate key (writeScrollY). Storing@@ -7894,8 +8205,12 @@ void main() {previewMode: currentPreviewMode || undefined,pageUrl: location.pathname,paramValues: { ...paramsCurrentValues },+ parameterState: parameterGenerationState,insertPlaceholder: insertPlaceholderSnapshot || undefined,pickedAnchor: pickedAnchorSnapshot || undefined,+ pickedAnchorViewportTop: Number.isFinite(pickedAnchorViewportTop) ? pickedAnchorViewportTop : undefined,+ pageHash: location.hash || undefined,+ pageSearch: location.search || undefined,});}@@ -7923,20 +8238,26 @@ void main() {sessionState.clearHandled();}- function cleanup() {+ function cleanup(options) {+ const restoreOriginal = options?.restoreOriginal === true;+ const instantChrome = options?.instantChrome === true;const cleanupSessionId = currentSessionId;if (svelteComponentSession?.sessionId === cleanupSessionId) {teardownSvelteComponentSession(true);} else if (cleanupSessionId) {- // Hide the wrapper immediately so variants disappear. DON'T structurally- // mutate the DOM yet - HMR from the agent's source rewrite is on its way,+ // Switch visibility immediately without structurally mutating the DOM.+ // HMR from the agent's source rewrite may still be on its way,// and a manual replaceChild under React causes NotFoundError when the// reconciler later tries to remove a wrapper we already removed.// Schedule a 2s fallback that does the manual swap only if HMR hasn't// replaced the wrapper by then (keeps static-server / no-HMR flows alive).const wrapper = document.querySelector('[data-impeccable-variants="' + cleanupSessionId + '"]');- if (wrapper) wrapper.style.display = 'none';+ if (wrapper) {+ if (restoreOriginal) showOriginalDuringDiscard(cleanupSessionId);+ else wrapper.style.display = 'none';+ }setTimeout(function() {+ document.getElementById(DISCARD_STATE_STYLE_ID)?.remove();if (!cleanupSessionId) return;const lateWrapper = document.querySelector('[data-impeccable-variants="' + cleanupSessionId + '"]');if (!lateWrapper) return;@@ -7951,7 +8272,7 @@ void main() {lateWrapper.remove();}, 2000);}- hideBar();+ hideBar(instantChrome);hideHighlight();stopScrollTracking();if (variantObserver) { variantObserver.disconnect(); variantObserver = null; }@@ -7963,7 +8284,11 @@ void main() {clearSession();resetSessionFileMeta();selectedElement = null;+ hoveredElement = null;+ pagePickSkipClick = false;currentSessionId = null;+ parameterGenerationState = 'idle';+ parameterReadyAnnouncedSession = null;selectedAction = 'impeccable';renderEditBadge('hidden');setLiveState('PICKING');@@ -8047,7 +8372,7 @@ void main() {// would strand the bar in CYCLING at 0/0. If there's no live in-memory mount// for this wrapper, it's an orphan (reload / failed mount): drop it and let// the live-server's SSE re-inject the manifest if the session is still live.- if (wrapper.dataset.impeccablePreview === 'svelte-component'+ if (isFrameworkComponentPreviewMode(wrapper.dataset.impeccablePreview)&& svelteComponentSession?.sessionId !== sessionId) {wrapper.remove();if (restoreSessionWithoutWrapper('browser_resumed_svelte_orphan_wrapper')) return true;@@ -8056,7 +8381,7 @@ void main() {return false;}- if (wrapper.dataset.impeccablePreview === 'svelte-component') {+ if (isFrameworkComponentPreviewMode(wrapper.dataset.impeccablePreview)) {if (!svelteComponentSession?.mountedVariant) {return true;}@@ -8104,7 +8429,7 @@ void main() {insertPlaceholderSnapshot = saved.insertPlaceholder;}- const resumedState = arrivedVariants >= expectedVariants ? 'CYCLING' : 'GENERATING';+ const resumedState = arrivedVariants > 0 ? 'CYCLING' : 'GENERATING';// Find the visible variant's content element for highlight positioning.const isInsert = wrapper.dataset.impeccableMode === 'insert';@@ -8128,7 +8453,11 @@ void main() {// hid. Now that state is CYCLING, re-fire.if (state === 'CYCLING') refreshParamsPanel();saveSession();- queueCheckpoint('browser_resumed');+ if (arrivedVariants > 0 && arrivedVariants < expectedVariants) {+ sendCheckpoint('variants_progress');+ } else {+ queueCheckpoint('browser_resumed');+ }// Start observing for more variants AFTER initial setupif (variantObserver) variantObserver.disconnect();@@ -8136,7 +8465,7 @@ void main() {// Hold the target at its saved viewport top through any subsequent// HMR patches, variant inserts, or cycle swaps.- startScrollLock(currentSessionId, readScrollY());+ startScrollLock(currentSessionId, readScrollY(), pickedAnchorViewportTop);// If we reloaded mid-generation (Bun's HTML HMR destroys the shader// canvas), re-capture the original's content and restart the shader so@@ -8171,6 +8500,7 @@ void main() {let globalBarBrandEl = null;let agentPollTooltipEl = null;let agentPollingConnected = false;+ let agentStatusMessage = null;let agentStatusPollTimer = null;let steerFocusSuspended = false;let steerFocusPauseUntil = 0;@@ -8275,6 +8605,13 @@ void main() {const AGENT_STATUS_POLL_MS = 5000;const AGENT_DISCONNECTED_MARK = 'oklch(62% 0 0 / 0.78)';const AGENT_DISCONNECTED_TIP = 'Agent disconnected - run live-poll.mjs to connect';+ // The indicator tracks whether a poll is parked, which is what decides if+ // steering can reach the agent right now. That goes quiet two ways, and they+ // need different copy: nobody is polling at all, or the agent took the work+ // and is busy with it. Under one-shot foreground polling the second case is+ // every normal generation, and telling the user to start a poll loop then is+ // wrong advice about a healthy session.+ const AGENT_BUSY_TIP = 'Agent is working - steering resumes when it finishes';const GLOBAL_BAR_SECTION_GAP = 8;const GLOBAL_BAR_INNER_GAP = 2;const GLOBAL_BAR_INNER_PAD_LEFT = 2;@@ -9295,24 +9632,46 @@ void main() {</svg>`;}+ /**+ * True while the browser is waiting on work it already handed to the agent.+ * In these states a quiet poll indicator means "busy", not "absent".+ */+ function agentHasWorkInFlight() {+ return state === 'GENERATING' || state === 'SAVING';+ }++ /**+ * Derived at read time, not cached: which of the two reasons applies depends on+ * the live state, which moves between the 5s status polls. The truthiness is+ * the same either way, so the indicator's visuals can stay driven by the+ * cached value while the wording stays current.+ */+ function agentStatusText() {+ if (agentPollingConnected) return null;+ return agentHasWorkInFlight() ? AGENT_BUSY_TIP : AGENT_DISCONNECTED_TIP;+ }+function syncAgentPollingUi(connected) {agentPollingConnected = !!connected;if (!globalBarBrandEl) return;const P = barPaletteForTheme(globalBarEl?.dataset.theme || detectPageTheme());+ agentStatusMessage = agentStatusText();globalBarBrandEl.dataset.agentConnected = connected ? 'true' : 'false';- globalBarBrandEl.setAttribute('aria-label', connected- ? 'Impeccable live mode'- : 'Impeccable live mode - agent not polling');+ // The tooltip is mouse-only, so carry the same distinction in the label or+ // screen-reader users are left with the vaguer of the two readings.+ globalBarBrandEl.setAttribute('aria-label', agentStatusMessage+ ? 'Impeccable live mode - ' + (agentHasWorkInFlight() ? 'agent is working' : 'agent not polling')+ : 'Impeccable live mode');globalBarBrandEl.removeAttribute('title');- globalBarBrandEl.style.cursor = connected ? 'default' : 'help';+ globalBarBrandEl.style.cursor = agentStatusMessage ? 'help' : 'default';const mark = globalBarBrandEl.querySelector('[data-brand-mark]');if (mark) {mark.innerHTML = brandMarkSvg(connected ? P.accent : AGENT_DISCONNECTED_MARK, 18);mark.style.opacity = '1';}const dot = globalBarBrandEl.querySelector('[data-agent-dot]');- if (dot) dot.style.display = connected ? 'none' : 'block';- if (connected) hideAgentPollTooltip();+ if (dot) dot.style.display = agentStatusMessage ? 'block' : 'none';+ if (!agentStatusMessage) hideAgentPollTooltip();}function ensureAgentPollTooltip() {@@ -9339,14 +9698,17 @@ void main() {whiteSpace: 'normal',});agentPollTooltipEl.id = PREFIX + '-agent-poll-tooltip';- agentPollTooltipEl.textContent = AGENT_DISCONNECTED_TIP;+ agentPollTooltipEl.textContent = agentStatusText() || AGENT_DISCONNECTED_TIP;uiAppend(agentPollTooltipEl);return agentPollTooltipEl;}function showAgentPollTooltip(anchor) {- if (agentPollingConnected || !anchor) return;+ if (!agentStatusMessage || !anchor) return;const tip = ensureAgentPollTooltip();+ // Re-derive rather than reuse the cached copy: the live state may have moved+ // since the last status poll set it.+ tip.textContent = agentStatusText() || AGENT_DISCONNECTED_TIP;tip.style.transition = 'none';tip.style.display = 'block';tip.style.opacity = '1';@@ -9376,7 +9738,9 @@ void main() {fetch('http://localhost:' + PORT + '/status?token=' + TOKEN, { cache: 'no-store' }).then((res) => (res.ok ? res.json() : null)).then((data) => {- if (data && typeof data.agentPolling === 'boolean') syncAgentPollingUi(data.agentPolling);+ if (data && typeof data.agentPolling === 'boolean') {+ syncAgentPollingUi(data.agentPolling);+ }}).catch(() => { /* server loss handled elsewhere */ });}diff --git a/.kiro/skills/impeccable/scripts/live-inject.mjs b/.kiro/skills/impeccable/scripts/live-inject.mjsindex 7c8d91182..d99c37fd5 100644--- a/.kiro/skills/impeccable/scripts/live-inject.mjs+++ b/.kiro/skills/impeccable/scripts/live-inject.mjs@@ -27,6 +27,8 @@ const __dirname = path.dirname(fileURLToPath(import.meta.url));const CONFIG_PATH = resolveLiveConfigPath({ cwd: process.cwd(), scriptsDir: __dirname });const MARKER_OPEN_TEXT = 'impeccable-live-start';const MARKER_CLOSE_TEXT = 'impeccable-live-end';+const NUXT_PLUGIN_MARKER = 'impeccable-live-nuxt-plugin';+const NUXT_PLUGIN_NAME = 'impeccable-live.client.ts';const IGNORE_MARKER_OPEN = '# impeccable-live-ignore-start';const IGNORE_MARKER_CLOSE = '# impeccable-live-ignore-end';@@ -38,6 +40,9 @@ export const LIVE_IGNORE_PATTERNS = Object.freeze(['.impeccable/live/sessions/','.impeccable/live/previews/','.impeccable/live/annotations/',+ '.impeccable/live/artifacts/',+ '.impeccable/live/accept-receipts/',+ '.impeccable/live/locks/','.impeccable/live/cache/','.impeccable/live/manual-edit-apply-transaction.json','.impeccable/live/manual-edit-events.jsonl',@@ -46,10 +51,15 @@ export const LIVE_IGNORE_PATTERNS = Object.freeze(['.impeccable/live/deferred-svelte-component-accepts.json','.impeccable-live.json','.impeccable-live/',+ 'app/.impeccable-live/',+ 'src/.impeccable-live/','node_modules/.impeccable-live/','src/lib/impeccable/ImpeccableLiveRoot.svelte','src/lib/impeccable/__runtime.js','src/lib/impeccable/[0-9a-f]*/',+ 'plugins/impeccable-live.client.ts',+ 'app/plugins/impeccable-live.client.ts',+ 'src/plugins/impeccable-live.client.ts',]);/**@@ -113,6 +123,7 @@ Output (JSON):const resolvedFiles = resolveFiles(process.cwd(), config);const svelteKit = detectSvelteKitProject(process.cwd(), config);+ const nuxt = detectNuxtProject(process.cwd());if (args.includes('--remove')) {if (svelteKit) {@@ -120,6 +131,12 @@ Output (JSON):console.log(JSON.stringify({ ok: true, adapter: 'sveltekit', results: [adapterResult] }));return;}+ if (nuxt) {+ const adapterResult = removeNuxtLiveAdapter({ cwd: process.cwd(), project: nuxt });+ console.log(JSON.stringify({ ok: !adapterResult.error, adapter: 'nuxt', results: [adapterResult] }));+ if (adapterResult.error) process.exitCode = 1;+ return;+ }const results = resolvedFiles.map((relFile) => {const absFile = path.resolve(process.cwd(), relFile);if (!fs.existsSync(absFile)) return { file: relFile, error: 'file_not_found' };@@ -145,13 +162,28 @@ Output (JSON):console.error(JSON.stringify({ ok: false, error: 'missing_port' }));process.exit(1);}- const gitIgnore = ensureLiveGitIgnores(process.cwd());+ const gitIgnore = ensureLiveGitIgnores(+ process.cwd(),+ nuxt ? [nuxt.pluginFile] : [],+ );if (svelteKit) {const adapterResult = applySvelteKitLiveAdapter({ cwd: process.cwd(), port, config });console.log(JSON.stringify({ ok: true, port, adapter: 'sveltekit', gitIgnore, results: [adapterResult] }));return;}+ if (nuxt) {+ const adapterResult = applyNuxtLiveAdapter({ cwd: process.cwd(), port, project: nuxt });+ console.log(JSON.stringify({+ ok: !adapterResult.error,+ port,+ adapter: 'nuxt',+ gitIgnore,+ results: [adapterResult],+ }));+ if (adapterResult.error) process.exitCode = 1;+ return;+ }const results = resolvedFiles.map((relFile) => {const absFile = path.resolve(process.cwd(), relFile);@@ -175,12 +207,12 @@ Output (JSON):if (!anyInserted) process.exit(1);}-export function ensureLiveGitIgnores(cwd = process.cwd()) {+export function ensureLiveGitIgnores(cwd = process.cwd(), extraPatterns = []) {const target = resolveIgnoreTarget(cwd);const existing = fs.existsSync(target.path) ? fs.readFileSync(target.path, 'utf-8') : '';const block = [IGNORE_MARKER_OPEN,- ...LIVE_IGNORE_PATTERNS,+ ...new Set([...LIVE_IGNORE_PATTERNS, ...extraPatterns]),IGNORE_MARKER_CLOSE,].join('\n');const markerRe = new RegExp(`${escapeRegExp(IGNORE_MARKER_OPEN)}[\\s\\S]*?${escapeRegExp(IGNORE_MARKER_CLOSE)}`);@@ -202,10 +234,119 @@ export function ensureLiveGitIgnores(cwd = process.cwd()) {file: path.relative(cwd, target.path).split(path.sep).join('/'),mode: target.mode,changed: updated !== existing,- patterns: [...LIVE_IGNORE_PATTERNS],+ patterns: [...new Set([...LIVE_IGNORE_PATTERNS, ...extraPatterns])],};}+// ---------------------------------------------------------------------------+// Nuxt adapter+//+// A script element placed in app.vue is compiled as Vue-rendered DOM and is+// not executed. Nuxt instead auto-discovers client plugins. Keep the adapter+// generated, dev-only, and outside user-authored source: Live creates one+// marked .client.ts plugin on start and removes it on stop.+// ---------------------------------------------------------------------------++export function detectNuxtProject(cwd = process.cwd()) {+ const configFile = fs.readdirSync(cwd, { withFileTypes: true })+ .find((entry) => entry.isFile() && /^nuxt\.config\.(?:js|mjs|cjs|ts|mts|cts)$/.test(entry.name))+ ?.name;+ if (!configFile) return null;++ const config = fs.readFileSync(path.join(cwd, configFile), 'utf-8');+ const literalSrcDir = config.match(/\bsrcDir\s*:\s*(['"])([^'"]+)\1/);+ let appDir = '';+ if (literalSrcDir) {+ const candidate = literalSrcDir[2]+ .replace(/\\/g, '/')+ .replace(/^\.\//, '')+ .replace(/\/+$/, '');+ const normalized = path.posix.normalize(candidate);+ if (normalized !== '..' && !normalized.startsWith('../') && !path.isAbsolute(normalized)) {+ appDir = normalized === '.' ? '' : normalized;+ }+ } else if (+ fs.existsSync(path.join(cwd, 'app', 'app.vue'))+ || fs.existsSync(path.join(cwd, 'app', 'pages'))+ ) {+ appDir = 'app';+ }++ const pluginFile = [appDir, 'plugins', NUXT_PLUGIN_NAME].filter(Boolean).join('/');+ return { configFile, appDir, pluginFile };+}++export function buildNuxtPlugin(port) {+ return `/* ${NUXT_PLUGIN_MARKER} */+const liveSrc = 'http://localhost:${port}/live.js';+const liveSelector = 'script[data-impeccable-live-nuxt]';++export default defineNuxtPlugin(() => {+ if (!import.meta.dev || typeof document === 'undefined') return;++ const expectedSrc = new URL(liveSrc, window.location.href).href;+ let script = document.querySelector(liveSelector);+ if (script?.src === expectedSrc) return;+ script?.remove();++ script = document.createElement('script');+ script.src = liveSrc;+ script.async = true;+ script.dataset.impeccableLiveNuxt = '';+ document.head.appendChild(script);++ import.meta.hot?.dispose(() => {+ if (script?.isConnected) script.remove();+ });+});+/* /${NUXT_PLUGIN_MARKER} */+`;+}++export function applyNuxtLiveAdapter({ cwd = process.cwd(), port, project = detectNuxtProject(cwd) }) {+ if (!project) return { error: 'nuxt_not_detected' };+ const absFile = path.join(cwd, project.pluginFile);+ const existing = fs.existsSync(absFile) ? fs.readFileSync(absFile, 'utf-8') : null;+ if (existing !== null && !existing.includes(NUXT_PLUGIN_MARKER)) {+ return {+ file: project.pluginFile,+ error: 'nuxt_plugin_conflict',+ hint: `${project.pluginFile} already exists and is not managed by Impeccable Live`,+ };+ }++ const content = buildNuxtPlugin(port);+ fs.mkdirSync(path.dirname(absFile), { recursive: true });+ if (content !== existing) fs.writeFileSync(absFile, content, 'utf-8');+ return {+ file: project.pluginFile,+ inserted: true,+ changed: content !== existing,+ devOnly: true,+ };+}++export function removeNuxtLiveAdapter({ cwd = process.cwd(), project = detectNuxtProject(cwd) }) {+ if (!project) return { error: 'nuxt_not_detected' };+ const absFile = path.join(cwd, project.pluginFile);+ if (!fs.existsSync(absFile)) {+ return { file: project.pluginFile, removed: false, note: 'no adapter present' };+ }+ const content = fs.readFileSync(absFile, 'utf-8');+ if (!content.includes(NUXT_PLUGIN_MARKER)) {+ return {+ file: project.pluginFile,+ removed: false,+ error: 'nuxt_plugin_conflict',+ hint: `${project.pluginFile} is not managed by Impeccable Live`,+ };+ }+ fs.unlinkSync(absFile);+ const pluginDir = path.dirname(absFile);+ if (fs.readdirSync(pluginDir).length === 0) fs.rmdirSync(pluginDir);+ return { file: project.pluginFile, removed: true };+}+function resolveIgnoreTarget(cwd) {const gitExcludePath = resolveGitInfoExcludePath(cwd);if (gitExcludePath) {diff --git a/.kiro/skills/impeccable/scripts/live-poll.mjs b/.kiro/skills/impeccable/scripts/live-poll.mjsindex 740161e10..19a8b0f9b 100644--- a/.kiro/skills/impeccable/scripts/live-poll.mjs+++ b/.kiro/skills/impeccable/scripts/live-poll.mjs@@ -27,7 +27,7 @@ const scriptCmd = (name) => `node "${path.join(SELF_DIR, name)}"`;export const PER_REQUEST_TIMEOUT_MS = 270_000;export const DEFAULT_EVENT_LEASE_MS = 600_000;-const EVENT_TYPES_NEEDING_AGENT_REPLY = new Set(['generate', 'steer', 'manual_edit_apply']);+const EVENT_TYPES_NEEDING_AGENT_REPLY = new Set(['generate', 'steer', 'manual_edit_apply', 'carbonize_cleanup']);function readServerInfo() {const record = readLiveServerInfo(process.cwd());@@ -38,8 +38,8 @@ function readServerInfo() {return record.info;}-export function buildPollReplyPayload(token, { id, type, message, file, data }) {- return { token, id, type, message, file, data };+export function buildPollReplyPayload(token, { id, type, message, file, data, sourceEventType }) {+ return { token, id, type, message, file, data, sourceEventType };}export function manualApplyPollBanner(event = {}) {@@ -152,7 +152,14 @@ export async function waitForEventAck(base, token, eventId, {return false;}-export async function fetchNextEvent(base, token, { totalDeadline } = {}) {+export async function fetchNextEvent(base, token, {+ totalDeadline,+ types,+ resolveTypes,+ perRequestTimeoutMs = PER_REQUEST_TIMEOUT_MS,+ leaseMs = DEFAULT_EVENT_LEASE_MS,+ signal,+} = {}) {while (true) {if (totalDeadline && Date.now() >= totalDeadline) {return { type: 'timeout' };@@ -161,8 +168,15 @@ export async function fetchNextEvent(base, token, { totalDeadline } = {}) {const remaining = totalDeadline? totalDeadline - Date.now(): PER_REQUEST_TIMEOUT_MS;- const slice = Math.min(Math.max(remaining, 1000), PER_REQUEST_TIMEOUT_MS);- const res = await fetch(`${base}/poll?token=${token}&timeout=${slice}&leaseMs=${DEFAULT_EVENT_LEASE_MS}`);+ const slice = Math.min(Math.max(remaining, 1000), perRequestTimeoutMs);+ const query = new URLSearchParams({+ token,+ timeout: String(slice),+ leaseMs: String(leaseMs),+ });+ const normalizedTypes = normalizePollTypes(resolveTypes ? await resolveTypes() : types);+ if (normalizedTypes.length > 0) query.set('types', normalizedTypes.join(','));+ const res = await fetch(`${base}/poll?${query}`, { signal });if (res.status === 401) {const err = new Error('Authentication failed. The server token may have changed.');@@ -202,11 +216,17 @@ export async function augmentEventWithAcceptHandling(event, base, token) {event._acceptResult = { handled: false, mode: 'error', error: err.message };}+ await completeAcceptHandling(event, base, token);+ return event;+}++export async function completeAcceptHandling(event, base, token) {const completionType = completionTypeForAcceptResult(event.type, event._acceptResult);try {await postReply(base, token, {id: event.id,type: completionType,+ sourceEventType: event.type,message: event._acceptResult?.error,file: event._acceptResult?.file,data: event._acceptResult?.carbonize === true ? { carbonize: true } : undefined,@@ -217,7 +237,6 @@ export async function augmentEventWithAcceptHandling(event, base, token) {if (!event._completionAck) {event._completionAck = completionAckForAcceptResult(event.id, completionType, event._acceptResult);}-return event;}@@ -245,9 +264,9 @@ export function printPollEvent(event) {console.log(JSON.stringify(event));}-export async function runPollOnce(base, token, { totalTimeout = 600_000 } = {}) {+export async function runPollOnce(base, token, { totalTimeout = 600_000, types, resolveTypes, perRequestTimeoutMs } = {}) {const deadline = Date.now() + totalTimeout;- const event = await fetchNextEvent(base, token, { totalDeadline: deadline });+ const event = await fetchNextEvent(base, token, { totalDeadline: deadline, types, resolveTypes, perRequestTimeoutMs });await augmentEventWithAcceptHandling(event, base, token);writeCarbonizeBanner(event);printPollEvent(event);@@ -258,11 +277,14 @@ export async function runPollStream(base, token, {ackTimeoutMs = 600_000,ackPollIntervalMs = 400,shouldContinue = () => true,+ types,+ resolveTypes,+ perRequestTimeoutMs,} = {}) {process.stderr.write('[impeccable-poll] stream mode: one JSON object per line on stdout; use --reply while this process stays running\n');while (shouldContinue()) {- const event = await fetchNextEvent(base, token);+ const event = await fetchNextEvent(base, token, { types, resolveTypes, perRequestTimeoutMs });await augmentEventWithAcceptHandling(event, base, token);writeCarbonizeBanner(event);printPollEvent(event);@@ -322,14 +344,17 @@ Modes:Options:--timeout=MS One-shot poll timeout in ms (default: 600000). Ignored in --stream mode+ --types=A,B Lease only these event types--ack-timeout=MS Stream mode: max wait for --reply after generate/steer (default: 600000)--file PATH Attach a source file path to the reply (generate/steer flow)--data JSON Attach a JSON result object to the reply (manual_edit_apply flow). Must be valid JSON--help Show this help messageHarness note:- Default one-shot mode is the portable contract for Claude Code, Codex, and Cursor.- --stream is experimental for harnesses with fast incremental stdout; do not use on Cursor.`);+ Default one-shot mode is the primary contract, including Codex foreground polling.+ Claude Code may run it as a background task; Cursor uses a background terminal with exit notification.+ --stream is retained for harnesses with measured, reliable incremental stdout.+ Do not use --stream on Cursor.`);process.exit(0);}@@ -360,23 +385,30 @@ Harness note:}const streamMode = args.includes('--stream');+ const typesArg = args.find((a) => a.startsWith('--types='));+ const types = normalizePollTypes(typesArg ? typesArg.slice('--types='.length) : null);const ackTimeoutArg = args.find((a) => a.startsWith('--ack-timeout='));const ackTimeoutMs = ackTimeoutArg ? parseInt(ackTimeoutArg.split('=')[1], 10) : 600_000;try {if (streamMode) {- await runPollStream(base, info.token, { ackTimeoutMs });+ await runPollStream(base, info.token, { ackTimeoutMs, types });return;}const timeoutArg = args.find((a) => a.startsWith('--timeout='));const totalTimeout = timeoutArg ? parseInt(timeoutArg.split('=')[1], 10) : 600_000;- await runPollOnce(base, info.token, { totalTimeout });+ await runPollOnce(base, info.token, { totalTimeout, types });} catch (err) {handlePollError(err);}}+export function normalizePollTypes(value) {+ const values = Array.isArray(value) ? value : String(value || '').split(',');+ return [...new Set(values.map((type) => String(type).trim()).filter(Boolean))];+}+// Auto-execute when run directlyconst _running = process.argv[1];if (_running?.endsWith('live-poll.mjs') || _running?.endsWith('live-poll.mjs/')) {diff --git a/.kiro/skills/impeccable/scripts/live-server.mjs b/.kiro/skills/impeccable/scripts/live-server.mjsindex 5735f2aec..c6e951086 100644--- a/.kiro/skills/impeccable/scripts/live-server.mjs+++ b/.kiro/skills/impeccable/scripts/live-server.mjs@@ -28,8 +28,10 @@ import {readLiveBrowserScriptParts,resolveLiveBrowserScriptParts,} from './live/browser-script-parts.mjs';-import { createLiveSessionStore } from './live/session-store.mjs';+import { createLiveSessionStore, GENERATION_FENCED_PHASES } from './live/session-store.mjs';+import { runGenerationPreflight } from './live/generation-preflight.mjs';import { validateEvent } from './live/event-validation.mjs';+import { selectAvailablePendingEvent } from './live/poll-lanes.mjs';import { createManualEditRoutes } from './live/manual-edit-routes.mjs';import { LIVE_COMMANDS } from './live/vocabulary.mjs';import {@@ -63,6 +65,10 @@ const DESIGN_MD_PATH = PROJECT_CONTEXT.designPath: null;const DEFAULT_POLL_TIMEOUT = 600_000; // 10 min — agent re-polls on timeout anywayconst SSE_HEARTBEAT_INTERVAL = 30_000; // keepalive ping every 30s+// The browser checkpoints for several unrelated reasons (see checkpointPayload+// in live-browser.js). Only these two report that variant availability changed,+// and only they may drive variant_progress / the *_reviewable phases.+const VARIANT_PROGRESS_CHECKPOINT_REASONS = new Set(['variants_progress', 'variants_ready']);// ---------------------------------------------------------------------------// Port detection@@ -156,29 +162,206 @@ function restorePendingEventsFromStore() {}}-function findAvailablePendingEvent(now = Date.now()) {- for (const entry of state.pendingEvents) {- if (entry.leaseUntil && entry.leaseUntil > now) continue;- return entry;- }- return null;+function findAvailablePendingEvent(now = Date.now(), types = null) {+ return selectAvailablePendingEvent(state.pendingEvents, { now, types });}-function leaseEvent(entry, leaseMs) {+async function leaseEvent(entry, leaseMs) {+ // Claim the entry before awaiting anything. prepareGenerateEventForLease+ // yields to the event loop, and selectAvailablePendingEvent only skips+ // entries whose lease is in the future — an unclaimed entry would be handed+ // to a second poll in that window and generated twice.+ entry.leaseUntil = Date.now() + leaseMs;+ await prepareGenerateEventForLease(entry);if (!entry.event?.id) {const idx = state.pendingEvents.indexOf(entry);if (idx !== -1) state.pendingEvents.splice(idx, 1);return entry.event;}+ // Re-stamp so the lease window starts when the agent actually receives the+ // work, not when scaffolding began.entry.leaseUntil = Date.now() + leaseMs;+ recordGenerateDelivery(entry);scheduleLeaseFlush();broadcastAgentPollingIfChanged();return entry.event;}-function acknowledgePendingEvent(id) {+function recordGenerateDelivery(entry) {+ const event = entry?.event;+ if (!event || event.type !== 'generate' || event.generationReadyAt) return;+ const at = Date.now();+ entry.event = { ...event, generationReadyAt: at };+ state.sessionStore?.appendEvent(entry.event);+ recordAgentPhase(event.id, 'generation_ready', { at });+}++async function prepareGenerateEventForLease(entry) {+ const event = entry?.event;+ if (!event || event.type !== 'generate' || event.scaffoldAttempted) return;++ recordAgentPhase(event.id, 'picked_up');+ recordAgentPhase(event.id, 'scaffolding');+ const result = await runGenerationPreflight(event, {+ cwd: process.cwd(),+ scriptsDir: __dirname,+ });+ entry.event = {+ ...event,+ scaffoldAttempted: true,+ scaffoldDurationMs: result.durationMs ?? null,+ ...(result.ok ? { scaffold: result.scaffold } : { scaffoldError: result.error || result.reason }),+ };+ state.sessionStore?.appendEvent(entry.event);+ recordAgentPhase(event.id, result.ok ? 'source_ready' : 'scaffold_fallback', {+ durationMs: result.durationMs ?? null,+ previewMode: result.scaffold?.previewMode || 'source',+ });+}++function recordAgentPhase(id, phase, details = {}) {+ if (!id) return;+ const event = {+ type: 'agent_phase',+ id,+ phase,+ at: Date.now(),+ ...details,+ };+ state.sessionStore?.appendEvent(event);+ broadcast(event);+}++/**+ * Detect a browser that missed the generation `done` broadcast.+ *+ * The preflight scaffold write triggers a framework full-reload (Astro reloads+ * the page for any .astro edit). If the agent's variant write + `done` land+ * while the browser is mid-reload, the new page misses both the second HMR+ * reload and the SSE `done` — it resumes from the scaffold-only source and+ * sits in GENERATING at 0/N forever. That resumed page always checkpoints+ * (`browser_resumed`), so a checkpoint claiming "still generating, variants+ * missing" for a session whose generation already completed is direct+ * evidence of the miss. Rebuild the `done` payload from the snapshot so the+ * caller can re-broadcast it; the browser's done handler is idempotent and+ * falls back to injecting variants from source.+ *+ * Keys on the store's monotone `generationCompletedAt`, not `phase` — the+ * behind checkpoint itself regresses `phase` to `generating`, and a browser+ * that misses the redelivered `done` too (another reload) must still trigger+ * redelivery from its next checkpoint.+ */+function detectMissedGenerationCompletion(event) {+ if (!event?.id || event.type !== 'checkpoint') return null;+ if (event.phase !== 'generating') return null;+ if (!variantCountLooksBehind(event.arrivedVariants, event.expectedVariants)) return null;+ if (!state.sessionStore) return null;+ let snapshot = null;+ try {+ snapshot = state.sessionStore.getSnapshot(event.id);+ } catch {+ return null;+ }+ return missedCompletionFromSnapshot(snapshot);+}++function variantCountLooksBehind(arrivedValue, expectedValue) {+ const arrived = Number(arrivedValue) || 0;+ const expected = Number(expectedValue) || 0;+ return arrived <= 0 || (expected > 0 && arrived < expected);+}++function missedCompletionFromSnapshot(snapshot) {+ if (!snapshot?.id || !snapshot.generationCompletedAt) return null;+ if (snapshot.generationCanceled) return null;+ // Accept/discard already underway: the browser is no longer waiting on+ // generation, and a late `done` there would collide with teardown.+ if (GENERATION_FENCED_PHASES.has(snapshot.phase)) return null;+ const file = snapshot.sourceFile || snapshot.previewFile;+ if (!file) return null;+ return {+ type: 'done',+ id: snapshot.id,+ file,+ sourceFile: snapshot.sourceFile || undefined,+ previewFile: snapshot.previewFile || undefined,+ previewMode: snapshot.previewMode || undefined,+ redelivered: true,+ };+}++function recordGenerationCheckpoint(event) {+ if (!event?.id || event.type !== 'checkpoint') return;+ if (generationIsFenced(event.id)) return;+ // Only checkpoints that report a change in variant availability are+ // generation progress. The browser also checkpoints for durability on Tune+ // slider drags, resumes, and anchor recovery; treating those as progress+ // echoed `variant_progress` straight back to the browser that sent it, which+ // remounts the component preview mid-drag (reverting the user's live param+ // edit and detaching the popover's element), and permanently latched the+ // *_reviewable phases from the wrong trigger, corrupting generation timings.+ if (!VARIANT_PROGRESS_CHECKPOINT_REASONS.has(event.reason)) return;+ const arrived = Number(event.arrivedVariants) || 0;+ const expected = Number(event.expectedVariants) || 0;+ if (arrived <= 0 || expected <= 0) return;+ const previewMode = event.previewMode || 'source';+ const previewFile = event.previewFile || event.file;+ if (previewFile) {+ broadcast({+ type: 'variant_progress',+ id: event.id,+ file: previewFile,+ sourceFile: event.sourceFile || (previewMode === 'source' ? previewFile : undefined),+ previewFile,+ previewMode,+ arrivedVariants: arrived,+ expectedVariants: expected,+ publicationKind: event.publicationKind || 'variants',+ });+ }+ const details = {+ arrivedVariants: arrived,+ expectedVariants: expected,+ checkpointReason: event.reason || null,+ };+ const at = Date.now();+ if (!generationPhaseAlreadyRecorded(event.id, 'first_reviewable')) {+ recordAgentPhase(event.id, 'first_reviewable', { ...details, at });+ }+ if (arrived >= 2 && expected >= 3 && !generationPhaseAlreadyRecorded(event.id, 'second_reviewable')) {+ recordAgentPhase(event.id, 'second_reviewable', { ...details, at });+ }+ if (arrived >= expected && !generationPhaseAlreadyRecorded(event.id, 'all_variants_ready')) {+ recordAgentPhase(event.id, 'all_variants_ready', { ...details, at });+ }+}++function generationIsFenced(id) {+ if (!state.sessionStore || !id) return false;+ try {+ const snapshot = state.sessionStore.getSnapshot(id, { includeCompleted: true });+ return snapshot?.generationCanceled === true;+ } catch {+ return false;+ }+}++function generationPhaseAlreadyRecorded(id, phase) {+ if (!state.sessionStore) return false;+ try {+ const snapshot = state.sessionStore.getSnapshot(id, { includeCompleted: true });+ return !!snapshot?.generationTimings?.[phase];+ } catch {+ return false;+ }+}++function acknowledgePendingEvent(id, sourceEventType) {if (!id) return false;- const idx = state.pendingEvents.findIndex((entry) => entry.event?.id === id);+ const idx = state.pendingEvents.findIndex((entry) => (+ entry.event?.id === id+ && (!sourceEventType || entry.event?.type === sourceEventType)+ ));if (idx === -1) return false;const acknowledged = state.pendingEvents[idx].event;state.pendingEvents.splice(idx, 1);@@ -187,9 +370,39 @@ function acknowledgePendingEvent(id) {return acknowledged;}-function findPendingEventById(id) {+function releasePendingEvent(id, sourceEventType) {+ const entry = state.pendingEvents.find((item) => (+ item.event?.id === id+ && (!sourceEventType || item.event?.type === sourceEventType)+ ));+ if (!entry) return null;+ entry.leaseUntil = 0;+ scheduleLeaseFlush();+ return entry.event;+}++function retirePendingGeneration(id) {+ if (!id) return 0;+ let retired = 0;+ for (let index = state.pendingEvents.length - 1; index >= 0; index -= 1) {+ const event = state.pendingEvents[index]?.event;+ if (event?.id !== id || event.type !== 'generate') continue;+ state.pendingEvents.splice(index, 1);+ retired += 1;+ }+ if (retired > 0) {+ scheduleLeaseFlush();+ broadcastAgentPollingIfChanged();+ }+ return retired;+}++function findPendingEventById(id, sourceEventType) {if (!id) return null;- const entry = state.pendingEvents.find((item) => item.event?.id === id);+ const entry = state.pendingEvents.find((item) => (+ item.event?.id === id+ && (!sourceEventType || item.event?.type === sourceEventType)+ ));return entry?.event || null;}@@ -198,7 +411,7 @@ function summarizePendingEventForStatus(entry) {const summary = {id: event.id,type: event.type,- leased: !!(entry.leaseUntil && entry.leaseUntil > Date.now()),+ leased: isLeased(entry),leaseUntil: entry.leaseUntil || null,};if (event.type === 'manual_edit_apply') {@@ -224,7 +437,13 @@ function summarizeActiveSessionForClient(snapshot = {}) {arrivedVariants: snapshot.arrivedVariants ?? 0,visibleVariant: snapshot.visibleVariant ?? null,checkpointRevision: snapshot.checkpointRevision ?? 0,+ browserCheckpointRevision: snapshot.browserCheckpointRevision ?? snapshot.checkpointRevision ?? 0,+ publicationCheckpointRevision: snapshot.publicationCheckpointRevision ?? 0,paramValues: snapshot.paramValues || {},+ generationPhase: snapshot.generationPhase ?? null,+ generationCompletedAt: snapshot.generationCompletedAt ?? null,+ generationCanceled: snapshot.generationCanceled === true,+ cancelReason: snapshot.cancelReason ?? null,};}@@ -269,24 +488,46 @@ function scheduleLeaseFlush() {function flushPendingPolls() {let changed = false;while (state.pendingPolls.length > 0) {- const entry = findAvailablePendingEvent();+ let pollIndex = -1;+ let entry = null;+ for (let index = 0; index < state.pendingPolls.length; index += 1) {+ const candidate = findAvailablePendingEvent(Date.now(), state.pendingPolls[index].types);+ if (!candidate) continue;+ pollIndex = index;+ entry = candidate;+ break;+ }if (!entry) {scheduleLeaseFlush();broadcastAgentPollingIfChanged();return;}- const poll = state.pendingPolls.shift();- poll.resolve(leaseEvent(entry, poll.leaseMs));+ const [poll] = state.pendingPolls.splice(pollIndex, 1);+ // leaseEvent is async (it may scaffold source), but it claims the entry+ // synchronously, so the next loop iteration will not re-select it. Resolve+ // the poll when the lease settles rather than awaiting here, so one slow+ // scaffold never delays the other parked polls. On the exceptional failure+ // path, answer `timeout` so the agent re-polls; the claim stays until the+ // lease expires, which keeps a deterministic failure from hot-looping.+ leaseEvent(entry, poll.leaseMs).then(poll.resolve, (error) => {+ console.error('[live] lease failed for ' + (entry.event?.id || 'unknown') + ': ' + (error?.message || error));+ poll.resolve({ type: 'timeout' });+ });changed = true;}scheduleLeaseFlush();if (changed) broadcastAgentPollingIfChanged();}+function isLeased(entry) {+ return !!(entry?.leaseUntil && entry.leaseUntil > Date.now());+}+function agentPollingConnected() {- const now = Date.now();- return state.pendingPolls.length > 0- || state.pendingEvents.some((entry) => entry.leaseUntil && entry.leaseUntil > now);+ // A leased event only proves that a poll returned once. The foreground task+ // may have ended immediately afterward, so only an actively waiting poll is+ // evidence that steering can wake the task right now.+ return state.pendingPolls.length > 0;}function broadcastAgentPollingIfChanged() {@@ -689,6 +930,16 @@ function createRequestHandler({ detectScript, liveScriptParts }) {res.end(JSON.stringify({ error }));return;}+ if (msg.type === 'agent_phase') {+ recordAgentPhase(msg.id, msg.phase, {+ ...(Number.isFinite(msg.durationMs) ? { durationMs: msg.durationMs } : {}),+ owner: typeof msg.owner === 'string' ? msg.owner : undefined,+ });+ res.writeHead(200, { 'Content-Type': 'application/json' });+ res.end(JSON.stringify({ ok: true }));+ return;+ }+ const missedCompletion = detectMissedGenerationCompletion(msg);if (state.sessionStore && msg.id) {try {state.sessionStore.appendEvent(msg);@@ -698,6 +949,11 @@ function createRequestHandler({ detectScript, liveScriptParts }) {return;}}+ if (msg.type === 'accept' || msg.type === 'discard') {+ retirePendingGeneration(msg.id);+ }+ recordGenerationCheckpoint(msg);+ if (missedCompletion) broadcast(missedCompletion);if (msg.type === 'exit') {cleanupSvelteComponentSessionsBeforeExit();}@@ -738,6 +994,12 @@ function createRequestHandler({ detectScript, liveScriptParts }) {// Agent poll endpoints (unchanged from WS version)// ---------------------------------------------------------------------------+function parsePollTypes(value) {+ if (!value) return null;+ const types = String(value).split(',').map((type) => type.trim()).filter(Boolean);+ return types.length > 0 ? new Set(types) : null;+}+function handlePollGet(req, res, url) {const token = url.searchParams.get('token');if (token !== state.token) {@@ -748,13 +1010,25 @@ function handlePollGet(req, res, url) {state.lastPollAt = Date.now();const timeout = parseInt(url.searchParams.get('timeout') || DEFAULT_POLL_TIMEOUT, 10);const leaseMs = parseInt(url.searchParams.get('leaseMs') || '30000', 10);- const available = findAvailablePendingEvent();+ const types = parsePollTypes(url.searchParams.get('types'));+ const available = findAvailablePendingEvent(Date.now(), types);if (available) {- res.writeHead(200, { 'Content-Type': 'application/json' });- res.end(JSON.stringify(leaseEvent(available, leaseMs)));+ // Do not await inline: leaseEvent may scaffold source, and this handler runs+ // on the server's only thread. The client can disconnect during that window,+ // so check the socket before replying.+ leaseEvent(available, leaseMs).then((event) => {+ if (res.writableEnded || res.destroyed) return;+ res.writeHead(200, { 'Content-Type': 'application/json' });+ res.end(JSON.stringify(event));+ }, (error) => {+ console.error('[live] lease failed for ' + (available.event?.id || 'unknown') + ': ' + (error?.message || error));+ if (res.writableEnded || res.destroyed) return;+ res.writeHead(200, { 'Content-Type': 'application/json' });+ res.end(JSON.stringify({ type: 'timeout' }));+ });return;}- const poll = { resolve, leaseMs };+ const poll = { resolve, leaseMs, types };const timer = setTimeout(() => {const idx = state.pendingPolls.indexOf(poll);if (idx !== -1) state.pendingPolls.splice(idx, 1);@@ -783,12 +1057,15 @@ function sessionFileMetadataFromPollReply(file) {if (!file || typeof file !== 'string') return { file };const normalized = file.split(path.sep).join('/');const base = { file: normalized };- if (!normalized.endsWith('/manifest.json') && normalized !== 'manifest.json') return base;- if (!normalized.includes('node_modules/.impeccable-live/') && !normalized.includes('src/lib/impeccable/')) return base;+ const metadataFile = normalized;+ if (!metadataFile.endsWith('/manifest.json') && metadataFile !== 'manifest.json') return base;+ if (!metadataFile.includes('node_modules/.impeccable-live/')+ && !metadataFile.includes('src/lib/impeccable/')+ && !metadataFile.includes('/.impeccable-live/')) return base;let full;try {- full = path.resolve(process.cwd(), normalized);+ full = path.resolve(process.cwd(), metadataFile);const rel = path.relative(process.cwd(), full);if (!rel || rel.startsWith('..') || path.isAbsolute(rel)) return base;} catch {@@ -797,18 +1074,47 @@ function sessionFileMetadataFromPollReply(file) {try {const manifest = JSON.parse(fs.readFileSync(full, 'utf-8'));- if (manifest?.previewMode !== 'svelte-component' || !manifest.sourceFile) return base;+ if (manifest?.previewMode !== 'svelte-component'+ || !manifest.sourceFile) return base;return {file: String(manifest.sourceFile).split(path.sep).join('/'),sourceFile: String(manifest.sourceFile).split(path.sep).join('/'),previewFile: normalized,- previewMode: 'svelte-component',+ previewMode: manifest.previewMode,};} catch {return base;}}+function inferSourceEventType(msg = {}, pendingEvents = state.pendingEvents) {+ const entriesForId = pendingEvents.filter((entry) => entry.event?.id === msg.id);+ const pendingTypes = new Set(entriesForId.map((entry) => entry.event?.type));+ if (msg.type === 'discarded' || msg.type === 'discard') return 'discard';+ if (msg.type === 'complete') {+ if (pendingTypes.has('carbonize_cleanup')) return 'carbonize_cleanup';+ return pendingTypes.has('accept') ? 'accept' : (pendingTypes.has('generate') ? 'generate' : undefined);+ }+ if (msg.type === 'steer_done') return 'steer';+ // `agent_done` can be the automatic acknowledgement for a carbonize Accept.+ // New pollers send sourceEventType explicitly; default to generate only for+ // older callers so a late worker cannot acknowledge a queued Accept.+ if (msg.type === 'agent_done' || msg.type === 'done') return 'generate';+ // `error` is reference/live.md's documented failure reply, and parseReplyArgs+ // never sets sourceEventType on it (the poller is a fresh process that cannot+ // know what it leased). Returning undefined here makes acknowledgePendingEvent+ // match *any* event for this id: a stale generate worker's failure silently+ // consumed the user's queued Accept, which was then never delivered to any+ // agent and left the browser in SAVING forever. Attribute the failure to the+ // event this agent actually holds a lease on, and otherwise to `generate` —+ // never to a wildcard. If that generate was already retired by an Accept, the+ // ack simply finds no match, which is the correct outcome for a stale reply.+ if (msg.type === 'error') {+ return entriesForId.find(isLeased)?.event?.type || 'generate';+ }+ return undefined;+}+function handlePollPost(req, res) {let body = '';req.on('data', (c) => { body += c; });@@ -869,7 +1175,23 @@ function handlePollPost(req, res) {res.end(JSON.stringify({ error: 'stale_manual_edit_apply_reply', ...rollback }));return;}- const pendingEventBeforeAck = findPendingEventById(msg.id);+ const sourceEventType = msg.sourceEventType || inferSourceEventType(msg);+ if (msg.type === 'retry') {+ const releasedEvent = releasePendingEvent(msg.id, sourceEventType);+ if (!releasedEvent) {+ res.writeHead(msg.id ? 404 : 400, { 'Content-Type': 'application/json' });+ res.end(JSON.stringify({+ error: msg.id ? 'unknown_poll_retry_id' : 'missing_poll_retry_id',+ id: msg.id,+ }));+ return;+ }+ flushPendingPolls();+ res.writeHead(200, { 'Content-Type': 'application/json' });+ res.end(JSON.stringify({ ok: true, released: true }));+ return;+ }+ const pendingEventBeforeAck = findPendingEventById(msg.id, sourceEventType);if (pendingEventBeforeAck?.type === 'steer' && msg.type === 'steer_done'&& !msg.file && !(typeof msg.message === 'string' && msg.message.trim())) {res.writeHead(400, { 'Content-Type': 'application/json' });@@ -879,7 +1201,7 @@ function handlePollPost(req, res) {}));return;}- const acknowledgedEvent = acknowledgePendingEvent(msg.id);+ const acknowledgedEvent = acknowledgePendingEvent(msg.id, sourceEventType);let skipJournalReply = false;let existingSession = null;if (!acknowledgedEvent && state.sessionStore && msg.id) {@@ -1083,7 +1405,10 @@ if (args.includes('--background')) {process.exit(0);}} catch { /* not ready yet */ }- await new Promise(r => setTimeout(r, 200));+ // The detached child is typically listening in 35-45ms. A 200ms polling+ // floor dominated configured cold Live startup; poll cheaply and return+ // as soon as the child has written its ready record.+ await new Promise(r => setTimeout(r, 5));}console.error('Timed out waiting for live server to start.');process.exit(1);diff --git a/.kiro/skills/impeccable/scripts/live-status.mjs b/.kiro/skills/impeccable/scripts/live-status.mjsindex f7e464999..dc98b7386 100644--- a/.kiro/skills/impeccable/scripts/live-status.mjs+++ b/.kiro/skills/impeccable/scripts/live-status.mjs@@ -37,15 +37,19 @@ export async function statusCli() {pendingEvents: server.pendingEvents,} : null,activeSessions: server?.activeSessions || activeSessions,- recoveryHint: manualApply- ? manualApplyResumeHint(manualApply)- : server- ? 'Run live-poll.mjs to continue pending work, or live-complete.mjs --id <session> after manual cleanup.'- : 'Start live-server.mjs to requeue pending durable events, then run live-poll.mjs.',+ recoveryHint: recoveryHint({ server, manualApply }),};console.log(JSON.stringify(payload, null, 2));}+function recoveryHint({ server, manualApply }) {+ if (manualApply) return manualApplyResumeHint(manualApply);+ if (server) {+ return 'Run live-poll.mjs to continue pending work, or live-complete.mjs --id <session> after manual cleanup.';+ }+ return 'Start live-server.mjs to requeue pending durable events, then run live-poll.mjs.';+}+function findPendingManualApply(server, activeSessions) {const fromServer = server?.pendingEvents?.find((event) => event?.type === 'manual_edit_apply');if (fromServer) return fromServer;diff --git a/.kiro/skills/impeccable/scripts/live-wrap.mjs b/.kiro/skills/impeccable/scripts/live-wrap.mjsindex 438c01b68..48d7f7683 100644--- a/.kiro/skills/impeccable/scripts/live-wrap.mjs+++ b/.kiro/skills/impeccable/scripts/live-wrap.mjs@@ -160,11 +160,29 @@ The agent should insert variant HTML at insertLine.`);if (filtered.length === 1) {match = filtered[0];} else if (filtered.length === 0) {- // Source uses dynamic content (`<h1>{title}</h1>` etc.) so the- // browser-side textContent doesn't appear literally in source. Fall- // back to first-match rather than refusing — this is the same- // behavior unmodified callers see, just preserved.- match = candidates[0];+ const normalizedText = String(text).replace(/\s+/g, ' ').trim();+ if (normalizedText.length < 8) {+ // Very short labels cannot disambiguate siblings reliably. Preserve+ // the legacy behavior for these low-information picker events.+ match = candidates[0];+ } else {+ // Rendered text that is absent from every candidate usually means+ // the source uses expressions or component props. Picking the first+ // same-class sibling silently edits the wrong instance (observed on+ // Astro result cards), so stop and surface every candidate instead.+ console.error(JSON.stringify({+ error: 'element_ambiguous',+ fallback: 'agent-driven',+ reason: 'rendered_text_not_in_source',+ file: path.relative(process.cwd(), targetFile),+ candidates: candidates.map((c) => ({+ startLine: c.startLine + 1,+ endLine: c.endLine + 1,+ })),+ hint: 'Rendered text does not occur in any matching source branch. The element may use dynamic props or expressions; inspect the candidates and wrap the intended instance manually.',+ }));+ process.exit(1);+ }} else {// Multiple candidates ALSO match the text. Truly ambiguous — refuse// rather than pick wrong, and hand the agent the candidate locations@@ -269,6 +287,7 @@ The agent should insert variant HTML at insertLine.`);const originalIndented = reindentOriginal(' ');const relTargetFile = path.relative(process.cwd(), targetFile).split(path.sep).join('/');const useSvelteComponent = shouldUseSvelteComponentInjection(targetFile);+ const useFrameworkComponent = useSvelteComponent;// Wrapper attributes differ by syntax. HTML allows plain string attrs;// JSX requires object-literal style and parses string attrs as HTML (which@@ -288,7 +307,7 @@ The agent should insert variant HTML at insertLine.`);// replacement range to include the wrapper's `<div>` open / close lines// so the entire scaffold gets removed cleanly.const wrapperLines = isJsx ? [- indent + '<div data-impeccable-variants="' + id + '" data-impeccable-variant-count="' + count + '" ' + styleContents + '>',+ indent + '<div data-impeccable-variants="' + id + '" data-impeccable-variant-count="' + count + '"' + ' ' + styleContents + '>',indent + ' ' + commentSyntax.open + ' impeccable-variants-start ' + id + ' ' + commentSyntax.close,indent + ' ' + commentSyntax.open + ' Original ' + commentSyntax.close,indent + ' <div data-impeccable-variant="original">',@@ -299,7 +318,7 @@ The agent should insert variant HTML at insertLine.`);indent + '</div>',] : [indent + commentSyntax.open + ' impeccable-variants-start ' + id + ' ' + commentSyntax.close,- indent + '<div data-impeccable-variants="' + id + '" data-impeccable-variant-count="' + count + '" ' + styleContents + '>',+ indent + '<div data-impeccable-variants="' + id + '" data-impeccable-variant-count="' + count + '"' + ' ' + styleContents + '>',indent + ' ' + commentSyntax.open + ' Original ' + commentSyntax.close,indent + ' <div data-impeccable-variant="original">',originalIndented,@@ -356,15 +375,18 @@ The agent should insert variant HTML at insertLine.`);const outputRelFile = path.relative(process.cwd(), outputFile).split(path.sep).join('/');const svelteComponentAuthoring = useSvelteComponent ? buildSvelteComponentCssAuthoring(count) : null;+ const componentSession = svelteSession;+ const componentPreviewMode = useSvelteComponent ? 'svelte-component' : undefined;+ const previewMode = componentPreviewMode;console.log(JSON.stringify({file: outputRelFile,- sourceFile: useSvelteComponent ? relTargetFile : undefined,- previewMode: useSvelteComponent ? 'svelte-component' : undefined,- componentDir: svelteSession?.componentDir,- propContract: svelteSession?.propContract,- sourceStartLine: useSvelteComponent ? startLine + 1 : undefined,- sourceEndLine: useSvelteComponent ? endLine + 1 : undefined,+ sourceFile: useFrameworkComponent ? relTargetFile : undefined,+ previewMode,+ componentDir: componentSession?.componentDir,+ propContract: componentSession?.propContract,+ sourceStartLine: useFrameworkComponent ? startLine + 1 : undefined,+ sourceEndLine: useFrameworkComponent ? endLine + 1 : undefined,startLine: outputStartLine, // 1-indexed for the agent// wrapperLines is an array but one element (the original-content slot)// is a `\n`-joined multi-line string, so the actual file-row count is@@ -374,10 +396,10 @@ The agent should insert variant HTML at insertLine.`);endLine: outputEndLine, // 1-indexedinsertLine, // 1-indexed: where variants gocommentSyntax: commentSyntax,- styleMode: useSvelteComponent ? 'svelte-component' : styleMode.mode,- styleTag: useSvelteComponent ? null : styleMode.styleTag,- cssSelectorPrefixExamples: useSvelteComponent ? [] : buildCssSelectorPrefixExamples(styleMode.mode, count),- cssAuthoring: useSvelteComponent ? svelteComponentAuthoring : buildCssAuthoring(styleMode, count),+ styleMode: componentPreviewMode || styleMode.mode,+ styleTag: useFrameworkComponent ? null : styleMode.styleTag,+ cssSelectorPrefixExamples: useFrameworkComponent ? [] : buildCssSelectorPrefixExamples(styleMode.mode, count),+ cssAuthoring: svelteComponentAuthoring || buildCssAuthoring(styleMode, count),originalLineCount: originalLines.length,}));}diff --git a/.kiro/skills/impeccable/scripts/live.mjs b/.kiro/skills/impeccable/scripts/live.mjsindex e0bd1ad24..b21a71cc4 100644--- a/.kiro/skills/impeccable/scripts/live.mjs+++ b/.kiro/skills/impeccable/scripts/live.mjs@@ -10,7 +10,7 @@** After this, the agent's only remaining steps are:* - Open the project's live dev/preview URL in the browser (optional, if browser automation exists)—not `serverPort`; that port is the Impeccable helper for /live.js and /poll- * - Enter the poll loop: `node live-poll.mjs`+ * - Enter the harness-native poll loop: `node live-poll.mjs`** Usage:* node live.mjs # Prepare everything, print JSON, exit@@ -40,6 +40,7 @@ Prepare everything for live variant mode in a single command:- Starts (or reuses) the live server in the background- Injects the browser script tag- Reads PRODUCT.md / DESIGN.md for project context+ - Prepares the harness-native foreground/background poll loop- In monorepos, choose a child app first; --target <path> is the fallback/manual pathOn success, prints a JSON blob with:diff --git a/.kiro/skills/impeccable/scripts/live/completion.mjs b/.kiro/skills/impeccable/scripts/live/completion.mjsindex 986773066..6f539336d 100644--- a/.kiro/skills/impeccable/scripts/live/completion.mjs+++ b/.kiro/skills/impeccable/scripts/live/completion.mjs@@ -1,9 +1,18 @@+// A preview whose variants live in component modules rather than in the user's+// source. These leave no markers in the real file, so a failed accept gives the+// agent nothing to hand-edit and must be reported as a failure rather than+// reference/live.md's manual-cleanup handoff. Kept as a set: any future+// component-module preview mode belongs here the day it lands.+const PREVIEW_MODES_WITHOUT_SOURCE_MARKERS = new Set([+ 'svelte-component',+]);+export function completionTypeForAcceptResult(eventType, acceptResult) {if (eventType === 'discard') return acceptResult?.handled === true ? 'discarded' : 'error';if (acceptResult?.handled === true && acceptResult?.carbonize === true) return 'agent_done';if (acceptResult?.handled === true) return 'complete';if (acceptResult?.mode === 'error') return 'error';- if (eventType === 'accept' && acceptResult?.previewMode === 'svelte-component') return 'error';+ if (eventType === 'accept' && PREVIEW_MODES_WITHOUT_SOURCE_MARKERS.has(acceptResult?.previewMode)) return 'error';return 'agent_done';}diff --git a/.kiro/skills/impeccable/scripts/live/event-validation.mjs b/.kiro/skills/impeccable/scripts/live/event-validation.mjsindex 0897b1317..122c29836 100644--- a/.kiro/skills/impeccable/scripts/live/event-validation.mjs+++ b/.kiro/skills/impeccable/scripts/live/event-validation.mjs@@ -118,6 +118,15 @@ export function validateEvent(msg) {return 'checkpoint: paramValues must be an object';}return null;+ case 'agent_phase':+ if (!isValidId(msg.id)) return 'agent_phase: missing or malformed id';+ if (typeof msg.phase !== 'string' || !/^[a-z][a-z0-9_]{1,63}$/.test(msg.phase)) {+ return 'agent_phase: missing or malformed phase';+ }+ if (msg.durationMs !== undefined && (!Number.isFinite(msg.durationMs) || msg.durationMs < 0)) {+ return 'agent_phase: durationMs must be a non-negative number';+ }+ return null;case 'exit':return null;case 'prefetch':@@ -131,6 +140,12 @@ export function validateEvent(msg) {if (msg.message.length > 4000) return 'steer: message too long';if (msg.pageUrl !== undefined && typeof msg.pageUrl !== 'string') return 'steer: pageUrl must be string';return null;+ case 'carbonize_cleanup':+ if (!isValidId(msg.id)) return 'carbonize_cleanup: missing or malformed id';+ if (!isValidId(msg.sessionId)) return 'carbonize_cleanup: missing or malformed sessionId';+ if (!msg.file || typeof msg.file !== 'string') return 'carbonize_cleanup: missing file';+ if (!isValidVariantId(String(msg.variantId))) return 'carbonize_cleanup: missing or malformed variantId';+ return null;default:return 'Unknown event type: ' + msg.type;}diff --git a/.kiro/skills/impeccable/scripts/live/generation-preflight.mjs b/.kiro/skills/impeccable/scripts/live/generation-preflight.mjsnew file mode 100644index 000000000..07a5e957e--- /dev/null+++ b/.kiro/skills/impeccable/scripts/live/generation-preflight.mjs@@ -0,0 +1,102 @@+import { execFile } from 'node:child_process';+import path from 'node:path';+import { promisify } from 'node:util';++const execFileAsync = promisify(execFile);+const PREFLIGHT_TIMEOUT_MS = 15_000;++export function buildGenerationPreflight(event, scriptsDir) {+ if (!event || event.type !== 'generate' || !event.id) return null;++ const isInsert = event.mode === 'insert';+ const target = isInsert ? insertTarget(event) : replaceTarget(event);+ if (!target.elementId && !target.classes) return null;++ const script = path.join(scriptsDir, isInsert ? 'live-insert.mjs' : 'live-wrap.mjs');+ const args = [script, '--id', event.id, '--count', String(event.count || 3)];+ if (isInsert) args.push('--position', target.position);+ if (target.elementId) args.push('--element-id', target.elementId);+ if (target.classes) args.push('--classes', target.classes);+ if (target.tag) args.push('--tag', target.tag);+ if (target.text) args.push('--text', target.text);+ if (!isInsert && event.pageUrl) args.push('--page-url', event.pageUrl);+ return { script, args, mode: isInsert ? 'insert' : 'replace' };+}++/**+ * Scaffold the source for a generate event before handing it to an agent.+ *+ * Async on purpose. This spawns `live-wrap.mjs`, which walks the project's+ * source tree and can take seconds (measured at ~7.6s on a large repo when the+ * element is not found, with a 15s ceiling). The live server is single-threaded+ * and calls this while leasing a poll, so a synchronous spawn froze the whole+ * server for that entire window: Accept and Discard POSTs, SSE progress+ * broadcasts, and every other poll stalled behind it.+ */+export async function runGenerationPreflight(event, {+ cwd = process.cwd(),+ scriptsDir,+ execFileImpl = execFileAsync,+ timeoutMs = PREFLIGHT_TIMEOUT_MS,+} = {}) {+ const command = buildGenerationPreflight(event, scriptsDir);+ if (!command) {+ return { ok: false, skipped: true, reason: 'insufficient_locator' };+ }++ const startedAt = performance.now();+ try {+ const { stdout } = await execFileImpl(process.execPath, command.args, {+ cwd,+ encoding: 'utf-8',+ timeout: timeoutMs,+ });+ const line = String(stdout).trim().split('\n').filter(Boolean).pop();+ if (!line) throw new Error('preflight returned no scaffold metadata');+ return {+ ok: true,+ mode: command.mode,+ durationMs: performance.now() - startedAt,+ scaffold: JSON.parse(line),+ };+ } catch (error) {+ return {+ ok: false,+ mode: command.mode,+ durationMs: performance.now() - startedAt,+ error: compactError(error),+ };+ }+}++function replaceTarget(event) {+ return normalizeTarget(event.element || {});+}++function insertTarget(event) {+ return {+ ...normalizeTarget(event.insert?.anchor || {}),+ position: event.insert?.position === 'before' ? 'before' : 'after',+ };+}++function normalizeTarget(target) {+ const classes = Array.isArray(target.classes)+ ? target.classes.join(' ')+ : String(target.classes || '').trim();+ const text = typeof target.textContent === 'string'+ ? target.textContent.trim().slice(0, 80)+ : '';+ return {+ elementId: target.id || target.elementId || undefined,+ classes: classes || undefined,+ tag: target.tagName || target.tag || undefined,+ text: text || undefined,+ };+}++function compactError(error) {+ const stderr = error?.stderr ? String(error.stderr).trim() : '';+ const message = stderr.split('\n').filter(Boolean).pop() || error?.message || 'preflight failed';+ return String(message).slice(0, 500);+}diff --git a/.kiro/skills/impeccable/scripts/live/poll-lanes.mjs b/.kiro/skills/impeccable/scripts/live/poll-lanes.mjsnew file mode 100644index 000000000..65f20a87a--- /dev/null+++ b/.kiro/skills/impeccable/scripts/live/poll-lanes.mjs@@ -0,0 +1,14 @@+export function eventPriority(event = {}) {+ if (event.type === 'accept' || event.type === 'discard' || event.type === 'exit') return 0;+ if (event.type === 'manual_edit_apply' || event.type === 'steer' || event.type === 'carbonize_cleanup') return 1;+ if (event.type === 'generate') return 2;+ return 3;+}++export function selectAvailablePendingEvent(entries, { now = Date.now(), types = null } = {}) {+ const allowed = types instanceof Set ? types : (Array.isArray(types) ? new Set(types) : null);+ return entries+ .filter((entry) => !(entry.leaseUntil && entry.leaseUntil > now))+ .filter((entry) => !allowed || allowed.has(entry.event?.type))+ .sort((a, b) => eventPriority(a.event) - eventPriority(b.event) || a.seq - b.seq)[0] || null;+}diff --git a/.kiro/skills/impeccable/scripts/live/session-store.mjs b/.kiro/skills/impeccable/scripts/live/session-store.mjsindex affba67c9..9d20341dd 100644--- a/.kiro/skills/impeccable/scripts/live/session-store.mjs+++ b/.kiro/skills/impeccable/scripts/live/session-store.mjs@@ -1,24 +1,26 @@import fs from 'node:fs';import path from 'node:path';-import { getLegacyLiveSessionsDir, getLiveSessionsDir } from '../lib/impeccable-paths.mjs';+import { getLegacyLiveSessionsDir, getLiveSessionsDir, safeSessionId } from '../lib/impeccable-paths.mjs';const COMPLETED_PHASES = new Set(['completed', 'discarded']);+export const GENERATION_FENCED_PHASES = new Set([+ 'accept_requested',+ 'discard_requested',+ 'carbonize_required',+ 'completed',+ 'discarded',+]);export function createLiveSessionStore({ cwd = process.cwd(), sessionId } = {}) {const rootDir = getLiveSessionsDir(cwd);const legacyRootDir = getLegacyLiveSessionsDir(cwd);fs.mkdirSync(rootDir, { recursive: true });- const snapshotCache = new Map();-- function loadCachedOrRebuild(id) {- const cached = snapshotCache.get(id);- if (cached) return cached;- const journalPath = getReadableJournalPath(id);- const rebuilt = rebuildSnapshotFromJournal(journalPath, id);- snapshotCache.set(id, rebuilt);- return rebuilt;- }+ // No snapshot cache on purpose: appendEvent and getSnapshot both rebuild from+ // the journal so sequence numbers and phase fences never come from a stale+ // in-memory copy when the publisher/complete helpers append from another+ // process. A cache written but never read would grow per session for the+ // lifetime of the server without ever saving a rebuild.function getReadableJournalPath(id) {const primary = getJournalPath(rootDir, id);if (fs.existsSync(primary)) return primary;@@ -38,7 +40,10 @@ export function createLiveSessionStore({ cwd = process.cwd(), sessionId } = {})if (!fs.existsSync(journalPath) && fs.existsSync(legacyJournalPath)) {fs.copyFileSync(legacyJournalPath, journalPath);}- const prior = loadCachedOrRebuild(normalized.id);+ // Publisher/complete helpers can append from a separate process while+ // the server is alive. Rebuild here so sequence numbers and phase+ // fences never come from a stale in-memory cache.+ const prior = rebuildSnapshotFromJournal(getReadableJournalPath(normalized.id), normalized.id);const seq = prior.nextSeq;const entry = {seq,@@ -49,7 +54,6 @@ export function createLiveSessionStore({ cwd = process.cwd(), sessionId } = {})};fs.appendFileSync(journalPath, JSON.stringify(entry) + '\n');const next = applyEvent(prior.snapshot, entry, prior.diagnostics);- snapshotCache.set(normalized.id, { snapshot: next, diagnostics: next.diagnostics || [], nextSeq: seq + 1 });writeSnapshot(snapshotPath, next);return next;},@@ -58,7 +62,6 @@ export function createLiveSessionStore({ cwd = process.cwd(), sessionId } = {})const journalPath = getReadableJournalPath(id);const snapshotPath = getSnapshotPath(rootDir, id);const rebuilt = rebuildSnapshotFromJournal(journalPath, id);- snapshotCache.set(id, rebuilt);writeSnapshot(snapshotPath, rebuilt.snapshot);if (!opts.includeCompleted && COMPLETED_PHASES.has(rebuilt.snapshot.phase)) return null;return rebuilt.snapshot;@@ -95,11 +98,6 @@ function getSnapshotPath(rootDir, id) {return path.join(rootDir, safeSessionId(id) + '.snapshot.json');}-function safeSessionId(id) {- if (!/^[A-Za-z0-9_-]{1,128}$/.test(id)) throw new Error('invalid session id: ' + id);- return id;-}-function baseSnapshot(id) {return {id,@@ -116,9 +114,18 @@ function baseSnapshot(id) {pendingEvent: null,deliveryLease: null,checkpointRevision: 0,+ browserCheckpointRevision: 0,+ publicationCheckpointRevision: 0,activeOwner: null,sourceMarkers: {},fallbackMode: null,+ generationPhase: null,+ generationCompletedAt: null,+ generationTimings: {},+ variantPlan: null,+ generationCanceled: false,+ generationCanceledAt: null,+ cancelReason: null,annotationArtifacts: [],diagnostics: [],updatedAt: null,@@ -158,6 +165,8 @@ function applyEvent(snapshot, entry, inheritedDiagnostics = []) {...snapshot,paramValues: { ...(snapshot.paramValues || {}) },sourceMarkers: { ...(snapshot.sourceMarkers || {}) },+ generationTimings: { ...(snapshot.generationTimings || {}) },+ variantPlan: snapshot.variantPlan || null,annotationArtifacts: [...(snapshot.annotationArtifacts || [])],diagnostics: [...(snapshot.diagnostics || [])],updatedAt: entry.ts || new Date().toISOString(),@@ -174,11 +183,48 @@ function applyEvent(snapshot, entry, inheritedDiagnostics = []) {next.expectedVariants = event.count ?? next.expectedVariants;next.pendingEventSeq = entry.seq ?? next.pendingEventSeq;next.pendingEvent = toPendingEvent(event);+ next.variantPlan = null;if (event.screenshotPath) upsertArtifact(next.annotationArtifacts, { type: 'screenshot', path: event.screenshotPath });break;+ case 'variant_plan':+ if (!next.generationCanceled && !GENERATION_FENCED_PHASES.has(next.phase)) {+ next.variantPlan = event.plan ?? next.variantPlan;+ }+ break;+ case 'detector_waivers':+ if (!next.generationCanceled && !GENERATION_FENCED_PHASES.has(next.phase)) {+ next.detectorWaivers = [+ ...(next.detectorWaivers || []),+ ...(Array.isArray(event.waivers) ? event.waivers : []),+ ];+ }+ break;+ case 'agent_phase':+ next.generationPhase = event.phase ?? next.generationPhase;+ if (event.phase) {+ next.generationTimings[event.phase] = {+ at: event.at ?? (Date.parse(entry.ts || '') || null),+ durationMs: event.durationMs ?? null,+ };+ }+ break;case 'variants_ready':case 'agent_done':+ if ((next.generationCanceled || GENERATION_FENCED_PHASES.has(next.phase))+ && !(event.type === 'agent_done' && event.carbonize === true && next.phase === 'accept_requested')) {+ next.diagnostics.push({+ error: 'late_generation_event_ignored',+ type: event.type,+ phase: next.phase,+ });+ break;+ }next.phase = event.carbonize === true ? 'carbonize_required' : 'variants_ready';+ // Durable completion marker: later browser checkpoints (a resumed page+ // reporting phase "generating") regress `phase`, but generation staying+ // finished is monotone — the live server keys missed-`done` redelivery+ // on this field.+ next.generationCompletedAt = event.at ?? (Date.parse(entry.ts || '') || Date.now());next.sourceFile = event.sourceFile ?? event.file ?? next.sourceFile;next.previewFile = event.previewFile ?? next.previewFile;next.previewMode = event.previewMode ?? next.previewMode;@@ -194,27 +240,45 @@ function applyEvent(snapshot, entry, inheritedDiagnostics = []) {}break;case 'checkpoint':- if (COMPLETED_PHASES.has(next.phase)) {+ if (next.generationCanceled || GENERATION_FENCED_PHASES.has(next.phase)) {next.diagnostics.push({ error: 'checkpoint_after_terminal_ignored', phase: event.phase ?? null, revision: event.revision ?? null });break;}- if ((event.revision ?? 0) >= (next.checkpointRevision ?? 0)) {- next.phase = event.phase ?? next.phase;- next.checkpointRevision = event.revision ?? next.checkpointRevision;- next.activeOwner = event.owner ?? next.activeOwner;- next.arrivedVariants = event.arrivedVariants ?? next.arrivedVariants;- next.visibleVariant = event.visibleVariant ?? next.visibleVariant;- next.sourceFile = event.sourceFile ?? next.sourceFile;- next.previewFile = event.previewFile ?? next.previewFile;- next.previewMode = event.previewMode ?? next.previewMode;- if (event.paramValues) next.paramValues = { ...event.paramValues };- } else {- next.diagnostics.push({ error: 'stale_checkpoint_ignored', revision: event.revision });+ {+ const revisionDomain = event.revisionDomain === 'publication'+ || (event.reason === 'variants_progress' && !event.owner)+ ? 'publication'+ : 'browser';+ const revisionField = revisionDomain === 'publication'+ ? 'publicationCheckpointRevision'+ : 'browserCheckpointRevision';+ const currentRevision = next[revisionField]+ ?? (revisionDomain === 'browser' ? next.checkpointRevision : 0)+ ?? 0;+ if ((event.revision ?? 0) >= currentRevision) {+ next.phase = event.phase ?? next.phase;+ next[revisionField] = event.revision ?? currentRevision;+ if (revisionDomain === 'browser') {+ next.checkpointRevision = event.revision ?? next.checkpointRevision;+ next.activeOwner = event.owner ?? next.activeOwner;+ }+ next.arrivedVariants = event.arrivedVariants ?? next.arrivedVariants;+ if (revisionDomain === 'browser') next.visibleVariant = event.visibleVariant ?? next.visibleVariant;+ next.sourceFile = event.sourceFile ?? next.sourceFile;+ next.previewFile = event.previewFile ?? next.previewFile;+ next.previewMode = event.previewMode ?? next.previewMode;+ if (revisionDomain === 'browser' && event.paramValues) next.paramValues = { ...event.paramValues };+ } else {+ next.diagnostics.push({ error: 'stale_checkpoint_ignored', revision: event.revision, revisionDomain });+ }}break;case 'accept':case 'accept_intent':next.phase = 'accept_requested';+ next.generationCanceled = true;+ next.generationCanceledAt = event.at ?? (Date.parse(entry.ts || '') || Date.now());+ next.cancelReason = 'accept';next.visibleVariant = Number(event.variantId ?? next.visibleVariant);if (event.paramValues) next.paramValues = { ...event.paramValues };next.pendingEventSeq = entry.seq ?? next.pendingEventSeq;@@ -232,6 +296,12 @@ function applyEvent(snapshot, entry, inheritedDiagnostics = []) {next.pendingEventSeq = entry.seq ?? next.pendingEventSeq;next.pendingEvent = toPendingEvent(event);break;+ case 'carbonize_cleanup':+ next.phase = 'carbonize_cleanup_requested';+ next.sourceFile = event.file ?? next.sourceFile;+ next.pendingEventSeq = entry.seq ?? next.pendingEventSeq;+ next.pendingEvent = toPendingEvent(event);+ break;case 'steer_done':next.phase = 'steer_done';next.sourceFile = event.sourceFile ?? event.file ?? next.sourceFile;@@ -243,6 +313,9 @@ function applyEvent(snapshot, entry, inheritedDiagnostics = []) {break;case 'discard':next.phase = 'discard_requested';+ next.generationCanceled = true;+ next.generationCanceledAt = event.at ?? (Date.parse(entry.ts || '') || Date.now());+ next.cancelReason = 'discard';next.pendingEventSeq = entry.seq ?? next.pendingEventSeq;next.pendingEvent = toPendingEvent(event);break;@@ -260,6 +333,10 @@ function applyEvent(snapshot, entry, inheritedDiagnostics = []) {next.pendingEvent = null;break;case 'agent_error':+ if (next.generationCanceled && event.sourceEventType === 'generate') {+ next.diagnostics.push({ error: 'late_generation_event_ignored', type: event.type, phase: next.phase });+ break;+ }next.phase = 'agent_error';next.pendingEventSeq = null;next.pendingEvent = null;diff --git a/.kiro/skills/impeccable/scripts/live/source-lock.mjs b/.kiro/skills/impeccable/scripts/live/source-lock.mjsnew file mode 100644index 000000000..9ccc557be--- /dev/null+++ b/.kiro/skills/impeccable/scripts/live/source-lock.mjs@@ -0,0 +1,105 @@+import fs from 'node:fs';+import path from 'node:path';+import { createHash, randomUUID } from 'node:crypto';+import { getLiveDir, isLiveServerPidReachable } from '../lib/impeccable-paths.mjs';++// Only used to retire a lock whose contents we cannot read (empty or truncated+// by a crash mid-write). A readable lock's fate is decided by its owner's+// liveness instead, so a slow critical section is never swept.+const UNREADABLE_LOCK_STALE_MS = 60_000;++export function sourceLockPath(file, cwd = process.cwd()) {+ const digest = createHash('sha256').update(path.resolve(cwd, file)).digest('hex').slice(0, 24);+ return path.join(getLiveDir(cwd), 'locks', digest + '.lock');+}++export function withSourceLockSync(file, owner, fn, {+ cwd = process.cwd(),+ waitMs = 0,+ retryMs = 5,+} = {}) {+ const lockPath = sourceLockPath(file, cwd);+ fs.mkdirSync(path.dirname(lockPath), { recursive: true });+ const deadline = Date.now() + Math.max(0, Number(waitMs) || 0);+ // Identifies this acquisition specifically, so release can tell our own lock+ // from a replacement that some other writer created.+ const token = randomUUID();+ let acquired = false;++ while (!acquired) {+ clearStaleLock(lockPath);+ let fd;+ try {+ fd = fs.openSync(lockPath, 'wx');+ fs.writeFileSync(fd, JSON.stringify({+ owner,+ token,+ pid: process.pid,+ at: Date.now(),+ file: path.resolve(cwd, file),+ }) + '\n');+ acquired = true;+ } catch (error) {+ if (error?.code !== 'EEXIST') throw error;+ if (Date.now() >= deadline) {+ const locked = new Error('source_locked');+ locked.code = 'SOURCE_LOCKED';+ locked.lockPath = lockPath;+ throw locked;+ }+ sleepSync(Math.max(1, Math.min(Number(retryMs) || 5, deadline - Date.now())));+ } finally {+ try { if (fd !== undefined) fs.closeSync(fd); } catch {}+ }+ }++ try {+ return fn();+ } finally {+ releaseOwnLock(lockPath, token);+ }+}++function sleepSync(ms) {+ Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, ms);+}++function readLock(lockPath) {+ try { return JSON.parse(fs.readFileSync(lockPath, 'utf-8')); } catch { return null; }+}++/**+ * Remove the lock only if it is still the one this call created. If a sweeper+ * judged our lock stale and another writer replaced it, unlinking here would+ * end *their* critical section and admit a third writer to the same file.+ */+function releaseOwnLock(lockPath, token) {+ const held = readLock(lockPath);+ if (held && held.token !== token) return;+ try { fs.unlinkSync(lockPath); } catch {}+}++/**+ * A lock is stale when its owner is gone, not when it is old.+ *+ * Age alone cuts both ways: it sweeps a live holder whose critical section+ * outran the timeout (a suspended laptop, a stopped process), letting two+ * writers into the same source file, while still making every accept on a+ * crashed holder's file wait out the full timeout. Asking the OS whether the+ * recorded pid is alive answers both correctly: a dead owner releases at once,+ * and a live owner keeps its lock however long it needs.+ */+function clearStaleLock(lockPath) {+ const held = readLock(lockPath);+ if (!held) {+ // Unreadable: either a crash truncated it, or we caught the brief window+ // between create and write in a live acquisition. mtime distinguishes them.+ try {+ const stat = fs.statSync(lockPath);+ if (Date.now() - stat.mtimeMs > UNREADABLE_LOCK_STALE_MS) fs.unlinkSync(lockPath);+ } catch { /* gone already */ }+ return;+ }+ if (typeof held.pid === 'number' && isLiveServerPidReachable(held.pid)) return;+ try { fs.unlinkSync(lockPath); } catch {}+}diff --git a/.opencode/skills/impeccable/reference/live.md b/.opencode/skills/impeccable/reference/live.mdindex bf49a7c40..a91a90db6 100644--- a/.opencode/skills/impeccable/reference/live.md+++ b/.opencode/skills/impeccable/reference/live.md@@ -10,21 +10,24 @@ Execute in order. No step skipped, no step reordered.1. `live.mjs`: boot. If the request names or implies a file, route, or app inside a monorepo, infer the concrete path and run `node .opencode/skills/impeccable/scripts/live.mjs --target <path>` instead; then run the rest of this live session from the returned `projectRoot`.2. Open the app URL that serves `pageFile` (infer from `package.json`, docs, terminal output, or an open tab). Never use `serverPort`; it's the helper, not the app. **Cursor:** `browser_navigate` to that URL before polling; do not skip. **Other harnesses:** use the available browser tool; if the URL is uncertain, ask the user once.-3. Poll loop with the default long timeout (600000 ms). After every event or `--reply`, run `live-poll.mjs` again immediately. Never pass a short `--timeout=`.+3. Poll loop with the default long timeout (600000 ms). Run `live-poll.mjs` again immediately after every event or `--reply`; Codex runs this one-shot poll in the foreground. Never pass a short `--timeout=`.The global bar **Impeccable mark** dims and shows a pulsing amber dot when no agent is long-polling `/poll`. Hover the mark for the hint; restart `live-poll.mjs` to reconnect.-4. On `generate`: read screenshot if present; load the action's reference; plan three distinct directions; write all variants in one edit; `--reply done`; poll again.+4. On `generate`: reuse `event.scaffold` when present; read the screenshot if present; load the action's reference; deliver variants using the delivery policy below; `--reply done`; poll again. Generate in this thread. You already hold the project's tokens, conventions, and file layout; that context is the job, not overhead.5. On `steer`: read the message and `pageUrl`; do the work (page edits, navigation help, or a short reply in the `--reply` message); `--reply steer_done`; poll again. No pickup ack. The Steer bar unlocks when `steer_done` arrives over SSE.-6. On `accept` / `discard`: the poll script runs `live-accept.mjs`, acknowledges the delivered event, and prints `_completionAck`. Plain accepts/discards are terminal immediately; carbonize accepts remain recoverable until you finish cleanup, run `live-complete.mjs --id EVENT_ID`, and only then poll again.+6. On `accept` / `discard`: the poll script runs `live-accept.mjs`, acknowledges the delivered event, and prints `_completionAck`. Plain accepts/discards are terminal immediately. Carbonize accepts remain recoverable until the foreground task runs `live-complete.mjs --id EVENT_ID`; finish that cleanup before polling again.7. If interrupted, run `live-status.mjs` or `live-resume.mjs` before guessing. The durable journal replays unacknowledged work after helper restart.8. On `exit`: run the cleanup at the bottom.Harness policy:-- **Claude Code**: run the poll as a **background task** (no short timeout). The harness notifies you when it completes, so the main conversation stays free. Do not block the shell.+- **Claude Code**: run the poll as a **background task** (no short timeout). The harness notifies you when it completes, so the main conversation stays free while you generate and publish in it. Do not block the shell.- **Cursor**: run **one-shot** poll in a **background terminal** with notify on `"type":"(steer|generate|accept|discard|exit)"`. After each event the poll exits; handle it, `--reply`, then start `live-poll.mjs` again. Do **not** use `--stream` on Cursor: incremental stdout notify is slower in practice than exit-based notify (~5s vs sub-second in testing).-- **Codex**: run the poll in the **foreground** (blocking shell; not a background task, not a subagent). Codex background exec sessions do not reliably surface poll stdout back into the conversation at the moment events arrive, so a "fire-and-forget" background poll will stall live mode.+- **Codex**: run the default one-shot poll in a **yielded foreground exec session**. Do not suffix it with `&`, use `--stream`, or leave Live without an active foreground poll. Handle every event in the main task; after each handler/reply, restart the foreground poll.- **Other harnesses**: one-shot foreground unless you know stdout reliably returns to this session when a shell exits.+Generation delivery policy:+- **Default (Cursor and other harnesses):** keep the established atomic single-edit delivery. Do not switch a harness to progressive until its poll loop is known not to block on the extra publish calls. This avoids trading model latency for extra tool-call latency on harnesses with different streaming behavior.+Chat is overhead. No recap, no tutorial output, no pasting PRODUCT / DESIGN bodies. Spend tokens on tools and edits; on failure, one or two short sentences.## Start@@ -92,14 +95,14 @@ Server restart rule: start `live-server.mjs` again, then poll. Startup requeues**Insert mode** (`event.mode === "insert"`): `{id, mode: "insert", count, pageUrl, insert: { position, anchor }, placeholder: { width, height }, freeformPrompt?, screenshotPath?, comments?, strokes?}`. No `action`. Requires a non-empty `freeformPrompt` **or** annotations. Screenshot is sent only when annotations exist (same rule as replace). Use `placeholder` dimensions as a soft size hint for net-new content.-Speed matters; the user is watching a spinner. Minimize tool calls by using the wrap/insert helper and writing all variants in a single edit.+Speed matters; the user is watching the selected element. Reuse server preflight metadata when available, minimize discovery calls, and follow the harness-specific delivery policy above.### Insert mode branchWhen `event.mode === "insert"`:1. Read the screenshot if `event.screenshotPath` is present (annotations only).-2. Run the insert helper instead of wrap:+2. If `event.scaffold` is present, use it as the insert-helper result and do **not** run the helper again. Otherwise run the insert helper instead of wrap:```bashnode .opencode/skills/impeccable/scripts/live-insert.mjs --id EVENT_ID --count EVENT_COUNT --position after \@@ -109,7 +112,7 @@ node .opencode/skills/impeccable/scripts/live-insert.mjs --id EVENT_ID --count E- `--position` ← `event.insert.position` (`before` | `after`)- Anchor flags ← `event.insert.anchor` (same mapping as wrap: id, classes, tag, text)-The scaffold has **no** `data-impeccable-variant="original"`. Variants are net-new HTML+CSS inserted at `insertLine`. Load `brand.md` or `product.md` (freeform only, no action sub-command). Write all variants in one edit, then `--reply done`.+The scaffold has **no** `data-impeccable-variant="original"`. Variants are net-new HTML+CSS inserted at `insertLine`. Load `brand.md` or `product.md` (freeform only, no action sub-command). Deliver using the harness policy, then `--reply done`.For Svelte/SvelteKit targets, `live-insert.mjs` returns `previewMode: "svelte-component"` with `mode: "insert"`, `file` pointing at a temporary `node_modules/.impeccable-live/<id>/manifest.json`, `componentDir` pointing at the variant component files, and `sourceFile` pointing at the real `.svelte` route. Write each inserted variant as a real Svelte component (`v1.svelte`, `v2.svelte`, …) under `componentDir`. Insert variants must be non-empty net-new content with a single top-level root, no `data-impeccable-*` attributes, and CSS in each component's `<style>` block. Do **not** edit the route source during generation; the browser mounts the temporary component before/after the live anchor while the user cycles variants. On Accept, `live-accept.mjs` inserts the selected component markup into `sourceFile` immediately and deletes the temp session after the source write succeeds.@@ -134,6 +137,8 @@ Reading annotations precisely:### 2. Wrap the element+When `event.scaffold` is present, the local helper already found and wrapped the source before the poll returned. Treat `event.scaffold` as the successful helper output and skip this command entirely. `event.scaffoldAttempted` with `scaffoldError` means local preflight could not finish; use the command/fallback path below. This optimization removes a deterministic tool round trip without changing the generated design.+```bashnode .opencode/skills/impeccable/scripts/live-wrap.mjs --id EVENT_ID --count EVENT_COUNT --element-id "ELEMENT_ID" --classes "class1,class2" --tag "div" --text "TEXT_SNIPPET"```@@ -153,7 +158,7 @@ Output on success: `{ file, insertLine, commentSyntax, styleMode, styleTag, cssSFor Svelte/SvelteKit targets, `live-wrap.mjs` returns `previewMode: "svelte-component"` with `file` pointing at a temporary `node_modules/.impeccable-live/<id>/manifest.json`, `componentDir` pointing at the variant component files, and `sourceFile` pointing at the real `.svelte` route. Write each variant as a real Svelte component (`v1.svelte`, `v2.svelte`, …) under `componentDir`; use the `propContract` prop names for dynamic text (`{propName}`), not literal snapshot strings. Put variant CSS in each component's `<style>` block with semantic class selectors (no `@scope`, no `data-impeccable-*`). Reply with `--file` set to the manifest path; the browser dynamically imports and mounts the compiled components so Svelte HMR does not reset page state while the user cycles variants. On Accept, `live-accept.mjs` inlines the accepted component back into `sourceFile` immediately after source promotion succeeds.-**Params on the Svelte component path go in a sidecar, never as an attribute.** Svelte parses `{` inside an attribute value as the start of an expression, so a `data-impeccable-params='[{…}]'` attribute on a component element fails to compile (`Expected token }`). Declare params for this path in `componentDir/params.json`, keyed by variant number, using the exact param schema from section 7:+**Params on component-preview paths go in a sidecar, never as an attribute.** Svelte parses `{` inside an attribute value as the start of an expression, and both Svelte/Vue previews mount without an HTML variant wrapper. Declare params in `componentDir/params.json`, keyed by variant number, using the exact param schema from section 7:```json{@@ -291,11 +296,13 @@ In **departure mode**, the prompt narrows the lanes you draw from, not the familWhen the prompt and PRODUCT.md anti-references conflict (the prompt asks for X, the anti-references ban X), the anti-references win; they describe the brand's standing position, the prompt is one moment.-### 6. Write all variants in a single edit+### 6. Deliver variantsComplete HTML replacement of the original element for each variant, not a CSS-only patch. Consider the element's context (computed styles, parent structure, CSS variables from `event.element`).-Write CSS + all variants in ONE edit at the `insertLine` reported by `wrap`. Colocate CSS as a `<style>` tag inside the variant wrapper; `<style>` works anywhere in modern browsers and this ensures CSS and HTML arrive atomically (no FOUC).+Colocate preview CSS as a `<style>` tag inside the variant wrapper; `<style>` works anywhere in modern browsers and keeps each delivered state internally complete (no FOUC).++**Atomic default:** write CSS + all variants + parameter manifests in one edit at `insertLine`, preserving the established behavior.Use the `cssAuthoring` object returned by `live-wrap.mjs` to author the temporary preview CSS. The style opening tag shown below is the common case; replace it with `cssAuthoring.styleTag` when the tool returns a different one. The variant markup shape is otherwise stable:@@ -319,7 +326,7 @@ Use the `cssAuthoring` object returned by `live-wrap.mjs` to author the temporarThe first variant has no `display: none` (visible by default). All others do. If variants use only inline styles and no preview CSS, omit the `<style>` tag entirely.-One edit, all variants; the browser's MutationObserver picks everything up in one pass.+The browser's MutationObserver accepts either delivery shape. On the transactional progressive path it shows arrived variants and pending dots immediately; Accept and Discard are available as soon as one variant exists. Accepting an arrived variant fences the worker before the browser releases the picker, so later publications are rejected.For `styleMode: "scoped"`, author every `:scope` rule with a descendant combinator. The `@scope` boundary is the **variant wrapper `<div data-impeccable-variant="N">`**, not the element you're designing. A bare `:scope { background: cream; }` styles the wrapper, not the inner replacement, so the cream lands on a `display: contents` shell while the actual element keeps page defaults. Always step in: `:scope > .card`, `:scope > section`, `:scope .hero-title`, etc. The fake test agent's CSS in `tests/live-e2e/agent.mjs` is a faithful template; every scoped rule starts `:scope > ...`.@@ -361,7 +368,7 @@ Each variant can expose **coarse** knobs alongside the full HTML/CSS replacement**Hard cap per variant**: at most **four** parameters so the panel stays legible; rare fifth only if the reference explicitly allows it.-**How to declare.** Put a JSON manifest on the variant wrapper (HTML/JSX path). **On the Svelte `svelte-component` path, do not use this attribute** (Svelte can't compile `{` inside an attribute value). Declare params in `componentDir/params.json` keyed by variant number instead (see the Svelte component paragraph in the wrap section). The param schema below is identical for both paths.+**How to declare.** Put a JSON manifest on the variant wrapper (HTML/JSX path). **On the `svelte-component` path, do not use this attribute.** Declare params in `componentDir/params.json` keyed by variant number instead (see the component-preview paragraphs in the wrap section). The param schema below is identical for every path.```html<div data-impeccable-variant="1" data-impeccable-params='[@@ -462,15 +469,19 @@ Event: `{id, variantId, _acceptResult, _completionAck}`. The poll script already- The accept event includes `pageUrl`; the poll script must forward it to `live-accept.mjs --page-url PAGE_URL` so accept-time cleanup only scrubs staged copy edits for the current page.- `_completionAck.ok !== true`: do not poll yet. Run `live-status.mjs` / `live-resume.mjs`, complete the cleanup manually if needed, then run `live-complete.mjs --id EVENT_ID`.- `_acceptResult.handled: true` and `carbonize: false`: nothing to do. Poll again.-- `_acceptResult.handled: true` and `carbonize: true`: **post-accept cleanup is required before the next poll.** See the "Required after accept (carbonize)" section below. The `event._acceptResult.todo` field, `_completionAck.requiresComplete`, and a stderr banner all point at this required follow-up; none are decorative. After cleanup, run `live-complete.mjs --id EVENT_ID`, then poll again.+- `_acceptResult.handled: true` and `carbonize: true`: post-accept cleanup is required, but it must not stall Codex's control lane. See "Required after accept (carbonize)" below. The `event._acceptResult.todo` field, `_completionAck.requiresComplete`, and stderr banner all point at this required follow-up; none are decorative.- `_acceptResult.handled: false, mode: "fallback"`: the session lived in a generated file and the script refused to persist there. You've already written the accepted variant into true source during Handle fallback Step 3; just clean up the temporary wrapper in the served file if any, and poll again.+- `_acceptResult.handled: false, mode: "error"`: the operation genuinely failed. **Do not hand-edit the file**; the source was not touched and editing it yourself would either double-apply or race whoever holds it.+ - `error: "source_locked"`: a generation publish holds the file. Run the same `live-accept.mjs` command again; it is idempotent and will succeed once the publisher releases. Do not poll past it.+ - `error: "accept_receipt_conflict"`: this session already resolved as `priorOperation` (on `priorVariantId` for an accept), so the request contradicts durable truth. Do not edit. Run `live-status.mjs` and tell the user what the session actually resolved to.+ - anything else: report the error briefly and run `live-status.mjs` before continuing.- `_acceptResult.handled: false` without `mode`: manual cleanup: read file, find markers, edit.### Required after accept (carbonize)When `_acceptResult.carbonize === true`, the accepted variant was stitched into source with helper markers and inline CSS so the browser can render it immediately with no visual gap. That stitch-in is **temporary**. The agent must rewrite it into permanent form before doing anything else. Skipping this leaves dead `@scope` rules for unaccepted variants, a pointless `data-impeccable-variant` wrapper, and `impeccable-carbonize-start/end` comment noise in the source file; all of which accumulate across sessions.-Do these five steps in the current thread, synchronously, before the next poll. Do not poll again until the file is clean.+Do these five steps synchronously before the next poll. The source lock, generation epoch, and expected-source hash remain the final safety gates against a generator finishing concurrently with Accept.1. **Locate the carbonize block** in the source file (`_acceptResult.file`). It's bracketed by `<!-- impeccable-carbonize-start SESSION_ID -->` and `<!-- impeccable-carbonize-end SESSION_ID -->` and contains a `<style data-impeccable-css="SESSION_ID">` element. If the variant declared parameters, an `<!-- impeccable-param-values SESSION_ID: {...} -->` comment sits alongside the style tag with the user's chosen values; read it first; it drives steps 3 and 4 below.2. **Move the CSS rules** into the project's real stylesheet. Which stylesheet depends on the project (e.g. `site/styles/workflow.css` for an Astro project, or the component's co-located CSS file for a Vite/Next project; pick whichever already owns styling for the surrounding element).@@ -478,9 +489,7 @@ Do these five steps in the current thread, synchronously, before the next poll.4. **Unwrap the accepted content.** Delete the inner `<div data-impeccable-variant="N" style="display: contents">` that wraps it. On JSX/TSX, also delete the outer `<div data-impeccable-carbonize="SESSION_ID" style={{ display: 'contents' }}>` wrapper if present (accept adds it so ternary/`return` slots keep a single root). Drop `data-impeccable-params` and any `data-p-*` attributes; those are live-mode plumbing, not source.5. **Delete the inline `<style>` block, the `<!-- impeccable-param-values -->` comment if present, and both `<!-- impeccable-carbonize-start/end -->` markers.** Also drop any `@scope` rules for variants other than the accepted one; those are dead code now.-After the file is clean, run `live-complete.mjs --id SESSION_ID`, verify it reports `phase: "completed"`, then poll again.--A background agent may be used for the rewrite, but the current thread is responsible for verifying the five steps are complete before issuing the next poll. In practice, inline is usually faster and less error-prone.+After the file is clean, the cleanup owner runs `live-complete.mjs --id SESSION_ID` and verifies `phase: "completed"`. Poll again only after that verification.## Handle `discard`diff --git a/.opencode/skills/impeccable/scripts/lib/impeccable-paths.mjs b/.opencode/skills/impeccable/scripts/lib/impeccable-paths.mjsindex 2ccbe7b74..99956c0f3 100644--- a/.opencode/skills/impeccable/scripts/lib/impeccable-paths.mjs+++ b/.opencode/skills/impeccable/scripts/lib/impeccable-paths.mjs@@ -104,6 +104,20 @@ export function removeLiveServerInfo(cwd = process.cwd(), options = {}) {}}+/**+ * Session IDs become path segments (journals, snapshots, accept receipts,+ * preview manifests, generated component dirs). They arrive from CLI `--id`+ * arguments and HTTP payloads, so anything containing a separator or `..` must+ * be rejected before it reaches path.join, which would happily escape+ * `.impeccable/live/`. Real IDs are 8 hex chars; the tests use short slugs.+ */+export function safeSessionId(id) {+ if (typeof id !== 'string' || !/^[A-Za-z0-9_-]{1,128}$/.test(id)) {+ throw new Error('invalid session id: ' + id);+ }+ return id;+}+export function getLiveSessionsDir(cwd = process.cwd(), options = {}) {return path.join(getLiveDir(cwd, options), 'sessions');}diff --git a/.opencode/skills/impeccable/scripts/live-accept.mjs b/.opencode/skills/impeccable/scripts/live-accept.mjsindex 278dfbb2e..453ddea35 100644--- a/.opencode/skills/impeccable/scripts/live-accept.mjs+++ b/.opencode/skills/impeccable/scripts/live-accept.mjs@@ -16,7 +16,9 @@import fs from 'node:fs';import path from 'node:path';import { isGeneratedFile } from './lib/is-generated.mjs';+import { IMPECCABLE_DIR, getLiveDir, safeSessionId } from './lib/impeccable-paths.mjs';import { readBuffer as readManualEditsBuffer, writeBuffer as writeManualEditsBuffer } from './live/manual-edits-buffer.mjs';+import { withSourceLockSync } from './live/source-lock.mjs';import {applyDeferredSvelteComponentAccepts,findSvelteComponentManifest,@@ -25,6 +27,46 @@ import {} from './live/svelte-component.mjs';const EXTENSIONS = ['.html', '.jsx', '.tsx', '.vue', '.svelte', '.astro'];+const ACCEPT_LOCK_WAIT_MS = 1_000;+// Mirrors VARIANT_ID_PATTERN in live/event-validation.mjs, which gates the same+// value arriving over HTTP.+const VARIANT_NUM_PATTERN = /^[0-9]{1,3}$/;++/**+ * A thrown accept/discard is a real failure, not a manual handoff.+ *+ * live/completion.mjs only classifies a result as `error` when it carries+ * `mode: 'error'`; anything else unhandled falls through to `agent_done` with a+ * successful ack, and reference/live.md then tells the agent to finish the edit+ * by hand. That is right for the documented fallback paths and wrong here: a+ * `source_locked` contention needs a retry (hand-editing races the publisher+ * holding the lock), and a crash needs surfacing, not a hand-applied guess.+ */+function operationFailure(err, extra = {}) {+ return { handled: false, mode: 'error', error: err.message, ...extra };+}++/**+ * Mark an unhandled preview-path result as a real failure.+ *+ * operationFailure only covers results built from a *thrown* error. The accept+ * implementations also return `{handled: false, error}` for their own checks+ * (variant missing, template empty, original text ambiguous), and those arrived+ * without `mode`, so completion.mjs classified them as agent_done and+ * reference/live.md routed the agent to "read file, find markers, edit".+ *+ * That handoff only makes sense for a plain wrapper session, which is the one+ * shape with markers in the user's source to edit. Component and isolated+ * artifact previews keep the source clean until Accept, so there is nothing to+ * hand-edit and an unhandled result is always a failure. `previewMode` is+ * exactly that discriminator: only the preview branches set it.+ */+function markPreviewFailure(result) {+ if (result?.handled === false && !result.mode && result.previewMode) {+ return { ...result, mode: 'error' };+ }+ return result;+}// ---------------------------------------------------------------------------// CLI@@ -63,7 +105,52 @@ Output (JSON):const isDiscard = args.includes('--discard');if (!id) { console.error('Missing --id'); process.exit(1); }+ // `id` becomes a path segment (accept receipts, preview manifests, generated+ // component dirs). Reject separators and traversal here so one check covers+ // every downstream sink.+ try { safeSessionId(id); } catch { console.error('Invalid --id'); process.exit(1); }if (!isDiscard && !variantNum) { console.error('Need --discard or --variant N'); process.exit(1); }+ // `variantNum` is interpolated into a RegExp and into the markup written back+ // to source. The browser and the /events schema both constrain it to digits;+ // enforce the same here, or `--variant '.*'` matches the `original` block+ // first and silently accepts the original while reporting success.+ if (!isDiscard && !VARIANT_NUM_PATTERN.test(variantNum)) {+ console.error('Invalid --variant');+ process.exit(1);+ }++ const requestedOperation = isDiscard ? 'discard' : 'accept';+ const priorReceipt = readAcceptReceipt(process.cwd(), id);+ if (priorReceipt) {+ const sameOperation = priorReceipt.operation === requestedOperation+ && (isDiscard || String(priorReceipt.variantId) === String(variantNum));+ console.log(JSON.stringify(sameOperation+ ? { ...priorReceipt.result, handled: true, alreadyApplied: true }+ : {+ // mode: 'error' is what marks this a real failure rather than a manual+ // handoff. Without it, live/completion.mjs classifies the reply as+ // agent_done and reference/live.md tells the agent to "read file, find+ // markers, edit" by hand — which would apply a second, conflicting+ // accept on top of the one the receipt already recorded.+ handled: false,+ mode: 'error',+ error: 'accept_receipt_conflict',+ priorOperation: priorReceipt.operation,+ priorVariantId: priorReceipt.variantId ?? null,+ }));+ return;+ }+ const emitResult = (rawResult) => {+ const result = markPreviewFailure(rawResult);+ if (result?.handled !== false) {+ writeAcceptReceipt(process.cwd(), id, {+ operation: requestedOperation,+ variantId: isDiscard ? null : String(variantNum),+ result,+ });+ }+ console.log(JSON.stringify(result));+ };let paramValues = null;if (paramValuesRaw) {@@ -82,39 +169,55 @@ Output (JSON):if (svelteComponentManifest) {if (isDiscard) {- removeSvelteComponentSession(id, process.cwd());- console.log(JSON.stringify({- handled: true,+ let result;+ try {+ result = withSourceLockSync(+ path.resolve(process.cwd(), svelteComponentManifest.sourceFile),+ 'discard:' + id,+ () => {+ removeSvelteComponentSession(id, process.cwd());+ return { handled: true };+ },+ { waitMs: ACCEPT_LOCK_WAIT_MS },+ );+ } catch (err) {+ result = operationFailure(err);+ }+ emitResult({+ ...result,file: svelteComponentManifest.sourceFile,carbonize: false,previewMode: 'svelte-component',componentDir: svelteComponentManifest.componentDir,- }));+ });return;}let result;try {- result = inlineSvelteComponentAccept(- svelteComponentManifest,- variantNum,- paramValues,- process.cwd(),+ result = withSourceLockSync(+ path.resolve(process.cwd(), svelteComponentManifest.sourceFile),+ 'accept:' + id,+ () => inlineSvelteComponentAccept(+ svelteComponentManifest,+ variantNum,+ paramValues,+ process.cwd(),+ ),+ { waitMs: ACCEPT_LOCK_WAIT_MS },);} catch (err) {- result = {- handled: false,- error: err.message,+ result = operationFailure(err, {file: svelteComponentManifest.sourceFile,sourceFile: svelteComponentManifest.sourceFile,previewMode: 'svelte-component',componentDir: svelteComponentManifest.componentDir,- };+ });}if (result.carbonize) {result.todo = 'REQUIRED before next poll: carbonize cleanup in ' + result.file + '. See reference/live.md "Required after accept".';}- console.log(JSON.stringify({ handled: result.handled !== false, ...result }));+ emitResult({ handled: result.handled !== false, ...result });return;}@@ -145,10 +248,25 @@ Output (JSON):}if (isDiscard) {- const result = handleDiscard(id, lines, targetFile);- console.log(JSON.stringify({ handled: true, file: relFile, carbonize: false, ...result }));+ let result;+ // handleDiscard takes the source lock, which throws SOURCE_LOCKED under+ // contention. Without this catch the CLI exits non-zero with empty stdout+ // and the agent gets no JSON to act on.+ try {+ result = handleDiscard(id, lines, targetFile);+ } catch (err) {+ emitResult(operationFailure(err, { file: relFile }));+ return;+ }+ emitResult({ handled: true, file: relFile, carbonize: false, ...result });} else {- const result = handleAccept(id, variantNum, lines, targetFile, paramValues);+ let result;+ try {+ result = handleAccept(id, variantNum, lines, targetFile, paramValues);+ } catch (err) {+ emitResult(operationFailure(err, { file: relFile }));+ return;+ }const acceptedOriginalText = result.acceptedOriginalText || '';delete result.acceptedOriginalText;// Single-line attention-grabber when cleanup is required. The full@@ -167,7 +285,7 @@ Output (JSON):// Non-fatal; the buffer stays as-is and the user can discard later.}}- console.log(JSON.stringify({ handled: true, file: relFile, ...result }));+ emitResult({ handled: true, file: relFile, ...result });}}@@ -235,7 +353,14 @@ function scrubManualEditsAgainstFile(_targetFile, cwd = process.cwd(), originalB// Discard// ----------------------------------------------------------------------------function handleDiscard(id, lines, targetFile) {+function handleDiscard(id, _lines, targetFile) {+ return withSourceLockSync(targetFile, 'discard:' + id, () => {+ const lines = fs.readFileSync(targetFile, 'utf-8').split('\n');+ return handleDiscardUnlocked(id, lines, targetFile);+ }, { waitMs: ACCEPT_LOCK_WAIT_MS });+}++function handleDiscardUnlocked(id, lines, targetFile) {const block = findMarkerBlock(id, lines);if (!block) return { handled: false, error: 'Markers not found' };@@ -330,7 +455,24 @@ function reindentContent(contentLines, fromIndent, toIndent) {});}-function handleAccept(id, variantNum, lines, targetFile, paramValues) {+function handleAccept(id, variantNum, _lines, targetFile, paramValues) {+ return withSourceLockSync(targetFile, 'accept:' + id, () => {+ const lines = fs.readFileSync(targetFile, 'utf-8').split('\n');+ return handleAcceptUnlocked(id, variantNum, lines, targetFile, paramValues);+ }, { waitMs: ACCEPT_LOCK_WAIT_MS });+}++function handleAcceptUnlocked(id, variantNum, lines, targetFile, paramValues) {+ const built = buildAcceptedWrappedSource(id, variantNum, lines, targetFile, paramValues);+ if (built.handled === false) return built;+ fs.writeFileSync(targetFile, built.content, 'utf-8');+ return {+ carbonize: built.carbonize,+ acceptedOriginalText: built.acceptedOriginalText,+ };+}++function buildAcceptedWrappedSource(id, variantNum, lines, targetFile, paramValues) {const block = findMarkerBlock(id, lines);if (!block) return { handled: false, error: 'Markers not found' };@@ -375,11 +517,14 @@ function handleAccept(id, variantNum, lines, targetFile, paramValues) {...replacement,...lines.slice(replaceRange.end + 1),];- fs.writeFileSync(targetFile, newLines.join('\n'), 'utf-8');-- return { carbonize: needsCarbonize, acceptedOriginalText: originalContent.join('\n') };+ return {+ content: newLines.join('\n'),+ carbonize: needsCarbonize,+ acceptedOriginalText: originalContent.join('\n'),+ };}+function readSourceShadowPreviewMeta(content, id) {const escaped = escapeRegExp(id);const wrapperRe = new RegExp('<[^>]+data-impeccable-variants=(["\'])' + escaped + '\\1[^>]*>');@@ -746,6 +891,21 @@ function detectCommentSyntax(filePath) {// File search (find the file containing session markers)// ---------------------------------------------------------------------------+/**+ * `.impeccable` is the critical entry, and it is not cosmetic.+ *+ * Progressive publication stages each revision as `.impeccable/live/artifacts/+ * <id>-r<n>.<source-ext>`, and those artifacts carry the very marker this search+ * looks for. The walk reaches `.` for any project whose source is not under one+ * of the privileged dirs above (this repo's own site lives in `site/pages/`), and+ * dot-directories sort before letters, so the artifact was found *before* the+ * real file. isGeneratedFile then declined the accept, and the agent fell back to+ * carbonizing several hundred lines of stylesheet by hand.+ *+ * Impeccable's own state directory is never project source. Never search it.+ */+const SEARCH_SKIP_DIRS = new Set(['node_modules', '.git', 'dist', 'build', IMPECCABLE_DIR]);+function findSessionFile(id, cwd) {const marker = 'impeccable-variants-start ' + id;const searchDirs = ['src', 'app', 'pages', 'components', 'public', 'views', 'templates', '.'];@@ -786,7 +946,7 @@ function searchDir(dir, query, seen, depth) {for (const entry of entries) {if (!entry.isDirectory()) continue;- if (['node_modules', '.git', 'dist', 'build'].includes(entry.name)) continue;+ if (SEARCH_SKIP_DIRS.has(entry.name)) continue;const result = searchDir(path.join(dir, entry.name), query, seen, depth + 1);if (result) return result;}@@ -798,6 +958,28 @@ function searchDir(dir, query, seen, depth) {// Utilities// ---------------------------------------------------------------------------+function acceptReceiptPath(cwd, id) {+ return path.join(getLiveDir(cwd), 'accept-receipts', `${safeSessionId(id)}.json`);+}++function readAcceptReceipt(cwd, id) {+ try { return JSON.parse(fs.readFileSync(acceptReceiptPath(cwd, id), 'utf-8')); } catch { return null; }+}++function writeAcceptReceipt(cwd, id, receipt) {+ const file = acceptReceiptPath(cwd, id);+ fs.mkdirSync(path.dirname(file), { recursive: true });+ const value = {+ id,+ ...receipt,+ completedAt: new Date().toISOString(),+ };+ const temporary = `${file}.${process.pid}.${Date.now()}.tmp`;+ fs.writeFileSync(temporary, JSON.stringify(value, null, 2) + '\n', 'utf-8');+ fs.renameSync(temporary, file);+ return value;+}+function argVal(args, flag) {const idx = args.indexOf(flag);return idx !== -1 && idx + 1 < args.length ? args[idx + 1] : null;diff --git a/.opencode/skills/impeccable/scripts/live-browser.js b/.opencode/skills/impeccable/scripts/live-browser.jsindex 616f1290a..20d875b93 100644--- a/.opencode/skills/impeccable/scripts/live-browser.js+++ b/.opencode/skills/impeccable/scripts/live-browser.js@@ -126,6 +126,9 @@let expectedVariants = 0;let arrivedVariants = 0;let visibleVariant = 0;+ let generationPhase = null;+ let parameterGenerationState = 'idle';+ let parameterReadyAnnouncedSession = null;let svelteComponentSession = null;let svelteRuntimePromise = null;let pendingSvelteComponentRetryObserver = null;@@ -134,6 +137,7 @@let currentPreviewMode = null;let recoveryWaitingForAnchor = false;let pickedAnchorSnapshot = null;+ let pickedAnchorViewportTop = null;let pendingVariantAnchorRetryObserver = null;let pendingAcceptedSession = null;let variantObserver = null;@@ -151,10 +155,12 @@// startScrollLock / stopScrollLock below.let scrollLockObserver = null;let scrollLockTargetY = null;+ let scrollLockAnchorTop = null;let scrollLockRaf = null;let scrollLockAbort = null;const SCROLL_ANCHOR_LOCK_ID = 'impeccable-scroll-anchor-lock';const VARIANT_STATE_STYLE_ID = 'impeccable-variant-state';+ const DISCARD_STATE_STYLE_ID = 'impeccable-discard-state';// Dedicated key for scroll position - SEPARATE from LS_KEY so that// saveSession's state updates don't clobber a carefully-captured scrollY.@@ -252,6 +258,13 @@barConnected: !!barEl?.isConnected,hasSvelteComponentSession: !!svelteComponentSession,mountedSvelteVariant: svelteComponentSession?.mountedVariant || 0,+ pickActive,+ pendingApplyInFlight,+ hoveredElement: hoveredElement ? {+ tag: hoveredElement.tagName,+ classes: hoveredElement.className,+ pickable: pickable(hoveredElement),+ } : null,pendingSvelteComponentRetry: !!pendingSvelteComponentRetryObserver,recoveryWaitingForAnchor,evtSourceReadyState: evtSource ? evtSource.readyState : null,@@ -1114,14 +1127,15 @@});}- function hideBar() {+ function hideBar(instant) {if (!barEl) return;const hideSeq = ++barHideSeq;stopVoice({ suppressSubmit: true });if (configureKind === 'insert') clearInsertPicking();barEl.style.opacity = '0';- barEl.style.transform = 'translateY(6px)';- setTimeout(() => { if (barEl && hideSeq === barHideSeq) barEl.style.display = 'none'; }, 250);+ barEl.style.transform = instant ? 'translateY(0)' : 'translateY(6px)';+ if (instant) barEl.style.display = 'none';+ else setTimeout(() => { if (barEl && hideSeq === barHideSeq) barEl.style.display = 'none'; }, 250);hideActionPicker();closeTunePopover();hideConfigureBarTooltip();@@ -1966,6 +1980,7 @@*/function setLiveState(next) {state = next;+ window.__IMPECCABLE_LIVE_STATE__ = next;syncPageInteractionCursor();}@@ -2516,18 +2531,27 @@fontSize: '11px', color: BP.textDim, whiteSpace: 'nowrap',marginLeft: 'auto',});- // Variants currently arrive atomically in a single file edit, so a- // per-variant counter would lie. Say what's true.status.textContent = recoveryWaitingForAnchor? 'Variants ready. Reveal the selected element to resume.'- : (arrivedVariants < expectedVariants- ? 'Generating ' + expectedVariants + ' variants...'- : 'Done');+ : generationStatusText();row.appendChild(status);return row;}+ function generationStatusText() {+ if (arrivedVariants >= expectedVariants && expectedVariants > 0) return 'Done';+ if (generationPhase === 'picked_up') return 'Agent picked up the request...';+ if (generationPhase === 'scaffolding') return 'Finding the source...';+ if (generationPhase === 'source_ready') return 'Source ready. Generating...';+ if (generationPhase === 'scaffold_fallback') return 'Agent is locating the source...';+ if (generationPhase === 'first_variant_generating') return 'Designing the first variant...';+ if (generationPhase === 'first_variant_validating') return 'Checking the first variant...';+ if (generationPhase === 'remaining_variants_generating') return 'Exploring two more directions...';+ if (generationPhase === 'remaining_variants_validating') return 'Checking the remaining variants...';+ return 'Generating ' + expectedVariants + ' variants...';+ }+// Cycling rowconst TUNE_ICON_SVG = '<svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" style="flex-shrink:0"><line x1="4" y1="8" x2="20" y2="8"/><circle cx="14" cy="8" r="2.4" fill="currentColor" stroke="none"/><line x1="4" y1="16" x2="20" y2="16"/><circle cx="10" cy="16" r="2.4" fill="currentColor" stroke="none"/></svg>';@@ -2557,7 +2581,7 @@color: BP.textDim, minWidth: '24px', textAlign: 'center',});counter.id = PREFIX + '-variant-counter';- counter.textContent = visibleVariant + '/' + arrivedVariants;+ counter.textContent = visibleVariant + '/' + expectedVariants;row.appendChild(counter);// Next@@ -2567,10 +2591,12 @@if (visibleVariant >= arrivedVariants) next.style.opacity = '0.3';row.appendChild(next);- // Tune chip - only when the visible variant exposes params+ // Tune chip stays visible while the deferred parameter phase is running,+ // then becomes interactive as soon as this variant exposes controls.const visParams = parseVariantParams(getVisibleVariantEl());const hasParams = visParams.length > 0;- if (hasParams) {+ const paramsPending = !hasParams && (parameterGenerationState === 'pending' || parameterGenerationState === 'loading');+ if (hasParams || paramsPending) {const tune = el('button', {display: 'inline-flex', alignItems: 'center', gap: '6px',padding: '4px 10px', borderRadius: '5px',@@ -2578,35 +2604,54 @@background: tuneOpen ? BP.accentSoft : 'transparent',color: tuneOpen ? BP.accent : BP.text,fontFamily: FONT, fontSize: '11px', fontWeight: '500',- cursor: 'pointer',+ cursor: paramsPending ? 'wait' : 'pointer',transition: 'color 0.12s ease, background 0.12s ease',whiteSpace: 'nowrap',});- tune.innerHTML = TUNE_ICON_SVG;+ if (paramsPending) {+ const spinner = el('span', {+ width: '11px', height: '11px', borderRadius: '50%',+ border: '1.5px solid ' + BP.hairline,+ borderTopColor: BP.accent,+ animation: 'impeccable-spin 0.6s linear infinite',+ boxSizing: 'border-box', flexShrink: '0',+ });+ spinner.setAttribute('aria-hidden', 'true');+ tune.appendChild(spinner);+ } else {+ tune.innerHTML = TUNE_ICON_SVG;+ }const tuneLabel = document.createElement('span');tuneLabel.textContent = 'Tune';tune.appendChild(tuneLabel);- const tuneBadge = document.createElement('span');- Object.assign(tuneBadge.style, {- display: 'inline-flex', alignItems: 'center', justifyContent: 'center',- minWidth: '16px', height: '16px', padding: '0 4px',- borderRadius: '999px',- background: tuneOpen ? C.brand : BP.hairline,- color: tuneOpen ? 'oklch(98% 0 0)' : 'inherit',- fontFamily: MONO, fontSize: '9.5px', fontWeight: '600',- lineHeight: '1',- boxSizing: 'border-box',- });- tuneBadge.textContent = String(visParams.length);- tune.appendChild(tuneBadge);- tune.title = 'Tune this variant (' + visParams.length + ' knob' + (visParams.length === 1 ? '' : 's') + ')';- tune.addEventListener('mouseenter', () => {- if (!tuneOpen) tune.style.background = BP.accentSoft;- });- tune.addEventListener('mouseleave', () => {- if (!tuneOpen) tune.style.background = 'transparent';- });- tune.addEventListener('click', (e) => { e.stopPropagation(); toggleTunePopover(); });+ if (hasParams) {+ const tuneBadge = document.createElement('span');+ Object.assign(tuneBadge.style, {+ display: 'inline-flex', alignItems: 'center', justifyContent: 'center',+ minWidth: '16px', height: '16px', padding: '0 4px',+ borderRadius: '999px',+ background: tuneOpen ? C.brand : BP.hairline,+ color: tuneOpen ? 'oklch(98% 0 0)' : 'inherit',+ fontFamily: MONO, fontSize: '9.5px', fontWeight: '600',+ lineHeight: '1',+ boxSizing: 'border-box',+ });+ tuneBadge.textContent = String(visParams.length);+ tune.appendChild(tuneBadge);+ tune.title = 'Tune this variant (' + visParams.length + ' knob' + (visParams.length === 1 ? '' : 's') + ')';+ tune.addEventListener('mouseenter', () => {+ if (!tuneOpen) tune.style.background = BP.accentSoft;+ });+ tune.addEventListener('mouseleave', () => {+ if (!tuneOpen) tune.style.background = 'transparent';+ });+ tune.addEventListener('click', (e) => { e.stopPropagation(); toggleTunePopover(); });+ } else {+ tune.disabled = true;+ tune.setAttribute('aria-label', 'Tune controls are still being prepared');+ tune.title = 'Tune controls are still being prepared';+ tune.style.opacity = '0.72';+ }tune.dataset.iceqTune = '1';row.appendChild(tune);}@@ -2614,6 +2659,15 @@// Spacerrow.appendChild(el('div', { flex: '1' }));+ if (arrivedVariants < expectedVariants) {+ const remaining = expectedVariants - arrivedVariants;+ const progress = el('span', {+ fontSize: '11px', color: BP.textDim, whiteSpace: 'nowrap',+ });+ progress.textContent = remaining + ' more arriving...';+ row.appendChild(progress);+ }+// Accept - primary action, kinpaku gold + lacquer-deep (matches demo .live-demo-ctx-accept)const accept = el('button', {padding: '5px 14px', borderRadius: '5px',@@ -2628,7 +2682,11 @@accept.addEventListener('mousedown', () => accept.style.transform = 'scale(0.97)');accept.addEventListener('mouseup', () => accept.style.transform = 'scale(1)');accept.addEventListener('click', (e) => { e.stopPropagation(); handleAccept(); });- if (arrivedVariants === 0) { accept.style.opacity = '0.3'; accept.style.pointerEvents = 'none'; }+ if (arrivedVariants === 0) {+ accept.style.opacity = '0.3';+ accept.style.pointerEvents = 'none';+ accept.title = 'Accept becomes available when the first variant arrives';+ }row.appendChild(accept);// Discard@@ -4743,6 +4801,32 @@}}+ function mountedParameterCount() {+ if (svelteComponentSession?.sessionId === currentSessionId) {+ return Object.values(svelteComponentSession.paramsByVariant || {})+ .reduce((total, params) => total + (Array.isArray(params) ? params.length : 0), 0);+ }+ const wrapper = document.querySelector('[data-impeccable-variants="' + currentSessionId + '"]');+ if (!wrapper) return 0;+ return [...wrapper.querySelectorAll('[data-impeccable-variant]:not([data-impeccable-variant="original"])')]+ .reduce((total, variant) => total + parseVariantParams(variant).length, 0);+ }++ function completeParameterPublication() {+ if (!currentSessionId) return;+ const ready = mountedParameterCount() > 0;+ parameterGenerationState = ready ? 'ready' : 'none';+ if (ready && parameterReadyAnnouncedSession !== currentSessionId) {+ parameterReadyAnnouncedSession = currentSessionId;+ showToast('Tune controls are ready.', 3000);+ }+ if (state === 'CYCLING') {+ refreshParamsPanel();+ showOrUpdateCyclingBar();+ }+ saveSession();+ }+function toggleTunePopover() {if (pendingApplyInFlight) { showManualApplyBusyToast(); return; }if (tuneOpen) { closeTunePopover(); return; }@@ -4835,6 +4919,10 @@return String(filePath || '').endsWith('manifest.json');}+ function isFrameworkComponentPreviewMode(mode) {+ return mode === 'svelte-component';+ }+function parseOriginalMarkupElement(originalMarkup) {const parser = new DOMParser();const doc = parser.parseFromString('<div id="impeccable-anchor">' + originalMarkup + '</div>', 'text/html');@@ -5029,9 +5117,13 @@}}- function loadSvelteRuntime(runtimeModule) {+ function resolveComponentModuleUrl(manifest, modulePath) {+ return new URL(String(modulePath || ''), location.origin).href;+ }++ function loadSvelteRuntime(runtimeModule, manifest) {const modulePath = runtimeModule || '/src/lib/impeccable/__runtime.js';- const url = new URL(modulePath, location.origin).href;+ const url = resolveComponentModuleUrl(manifest, modulePath);if (!svelteRuntimePromise) {svelteRuntimePromise = import(/* @vite-ignore */ url);}@@ -5065,7 +5157,8 @@async function loadSvelteComponentVariantSource(manifest, variantNum) {const dir = String(manifest?.componentDir || '').replace(/^\/+/, '');if (!dir || !variantNum) return '';- const sourcePath = dir + '/v' + variantNum + '.svelte';+ const extension = manifest.componentExtension || 'svelte';+ const sourcePath = dir + '/v' + variantNum + '.' + extension;const url = 'http://localhost:' + PORT + '/source?token=' + TOKEN + '&path=' + encodeURIComponent(sourcePath);try {const res = await fetch(url);@@ -5221,7 +5314,7 @@if (!sourceOriginal) return values;const map = buildSvelteExpressionTextMap(sourceOriginal, liveEl);for (const entry of contract) {- const token = '{' + entry.expr + '}';+ const token = entry.previewToken || ('{' + entry.expr + '}');values[entry.prop] = map.get(token) || '';}return values;@@ -5233,9 +5326,12 @@try {const previousAnchor = getMountedSvelteComponentAnchor(svelteComponentSession) || selectedElement;svelteComponentSession.swapAnchor = makeFrozenAnchor(previousAnchor) || svelteComponentSession.swapAnchor || null;- const runtime = await loadSvelteRuntime(manifest.runtimeModule);- const modulePath = '/' + String(manifest.componentDir || '').replace(/^\/+/, '') + '/v' + variantNum + '.svelte';- const moduleUrl = new URL(modulePath, location.origin).href + '?t=' + Date.now();+ const runtime = await loadSvelteRuntime(manifest.runtimeModule, manifest);+ const extension = manifest.componentExtension || 'svelte';+ const moduleBase = manifest.componentModuleBase+ || ('/' + String(manifest.componentDir || '').replace(/^\/+/, ''));+ const modulePath = String(moduleBase).replace(/\/+$/, '') + '/v' + variantNum + '.' + extension;+ const moduleUrl = resolveComponentModuleUrl(manifest, modulePath) + '?t=' + Date.now();const mod = await import(/* @vite-ignore */ moduleUrl);const Component = mod.default;if (svelteComponentSession.mountedInstance && runtime.unmount) {@@ -5275,7 +5371,7 @@if (svelteComponentSession?.sessionId === sessionId) {svelteComponentSession.swapAnchor = null;}- console.error('[impeccable] Failed to mount Svelte variant ' + variantNum + ' for ' + sessionId + ':', err);+ console.error('[impeccable] Failed to mount component variant ' + variantNum + ' for ' + sessionId + ':', err);return false;}}@@ -5340,40 +5436,46 @@if (manifest.id !== sessionId) return;const paramsByVariant = await loadSvelteComponentParams(manifest);+ const availableVariants = Number(manifest.arrivedVariants) || Number(manifest.count) || 1;+ const componentPreviewMode = isFrameworkComponentPreviewMode(manifest.previewMode)+ ? manifest.previewMode+ : 'svelte-component';currentSessionId = sessionId;expectedVariants = Number(manifest.count) || expectedVariants || 1;rememberSessionFileMeta({sourceFile: manifest.sourceFile,previewFile: manifestPath,- previewMode: 'svelte-component',+ previewMode: componentPreviewMode,});if (state !== 'CYCLING') setLiveState('GENERATING');const existingWrapper = document.querySelector('[data-impeccable-variants="' + sessionId + '"]');if (existingWrapper && svelteComponentSession?.sessionId === sessionId) {recoveryWaitingForAnchor = false;+ svelteComponentSession.manifest = manifest;svelteComponentSession.paramsByVariant = paramsByVariant;- arrivedVariants = Number(manifest.count) || expectedVariants || 1;- expectedVariants = arrivedVariants;+ arrivedVariants = availableVariants;+ expectedVariants = Number(manifest.count) || expectedVariants || arrivedVariants;visibleVariant = visibleVariant > 0 && visibleVariant <= arrivedVariants ? visibleVariant : 1;await mountSvelteComponentVariant(visibleVariant || 1);setLiveState('CYCLING');showOrUpdateCyclingBar();saveSession();+ if (parameterGenerationState === 'loading') completeParameterPublication();return;}const liveEl = findLiveElementForSvelteManifest(manifest);if (!liveEl?.parentElement) {console.warn('[impeccable] Could not find original element in live DOM.');- arrivedVariants = Number(manifest.count) || expectedVariants || 1;- expectedVariants = arrivedVariants;+ arrivedVariants = availableVariants;+ expectedVariants = Number(manifest.count) || expectedVariants || arrivedVariants;const saved = loadSession();const savedVisibleVariant = saved && saved.id === sessionId ? saved.visible : 0;visibleVariant = visibleVariant > 0 && visibleVariant <= arrivedVariants? visibleVariant: (savedVisibleVariant > 0 && savedVisibleVariant <= arrivedVariants ? savedVisibleVariant : 1);- enterRecoveryWaitingForAnchor({ checkpointReason: 'svelte_component_anchor_missing', trackScroll: true });+ enterRecoveryWaitingForAnchor({ checkpointReason: 'component_preview_anchor_missing', trackScroll: true });waitForSvelteComponentTargetAndRetry({ manifestPath, sessionId, manifest });return;}@@ -5381,7 +5483,7 @@const wrapper = document.createElement('div');wrapper.dataset.impeccableVariants = sessionId;wrapper.dataset.impeccableVariantCount = String(manifest.count || expectedVariants || 1);- wrapper.dataset.impeccablePreview = 'svelte-component';+ wrapper.dataset.impeccablePreview = componentPreviewMode;wrapper.style.display = 'contents';const mountTarget = document.createElement('div');@@ -5419,8 +5521,8 @@recoveryWaitingForAnchor = false;const previousVisibleVariant = currentSessionId === sessionId ? visibleVariant : 0;- arrivedVariants = Number(manifest.count) || expectedVariants || 1;- expectedVariants = arrivedVariants;+ arrivedVariants = availableVariants;+ expectedVariants = Number(manifest.count) || expectedVariants || arrivedVariants;const saved = loadSession();const savedVisibleVariant = saved && saved.id === sessionId ? saved.visible : 0;visibleVariant = previousVisibleVariant > 0 && previousVisibleVariant <= arrivedVariants@@ -5445,9 +5547,10 @@refreshParamsPanel();positionBar();saveSession();- console.log('[impeccable] Mounted ' + arrivedVariants + ' Svelte component variants.');+ if (parameterGenerationState === 'loading') completeParameterPublication();+ console.log('[impeccable] Mounted ' + arrivedVariants + ' ' + manifest.framework + ' component variants.');} catch (err) {- console.error('[impeccable] Failed to mount Svelte component variants:', err);+ console.error('[impeccable] Failed to mount component-preview variants:', err);abortSvelteComponentInjection(sessionId, 'Could not load variants. Fix the error and re-run.');}}@@ -5493,6 +5596,8 @@clearHandled();resetSessionFileMeta();currentSessionId = null;+ parameterGenerationState = 'idle';+ parameterReadyAnnouncedSession = null;expectedVariants = 0;arrivedVariants = 0;visibleVariant = 0;@@ -5502,12 +5607,24 @@if (message) showToast(message, 5000);}+ // How many delayed re-reads a completion-driven source fallback gets when+ // the fetched source still shows only the preflight scaffold, before the+ // failure is surfaced via recoverEmptyCycling.+ const COMPLETED_SOURCE_FALLBACK_RETRIES = 3;+ const COMPLETED_SOURCE_FALLBACK_RETRY_MS = 1200;+/*** No-HMR fallback: fetch the raw source file from the live server,* parse it, extract the variant wrapper, and inject it into the live DOM.* This works even when the dev server caches HTML (Bun, static servers).+ *+ * opts.generationCompleted marks callers that KNOW the agent finished (a+ * `done` arrived or the server reported a completed generation). For them an+ * empty read is a stale source view and no further event is coming, so the+ * read retries a few times and then surfaces recovery. Callers without the+ * flag may be mid-generation and wait indefinitely for the real completion.*/- function injectVariantsFromSource(filePath, sessionId) {+ function injectVariantsFromSource(filePath, sessionId, opts = {}) {if (isSvelteComponentManifestPath(filePath)) {injectSvelteComponentsFromManifest(filePath, sessionId);return;@@ -5573,6 +5690,32 @@arrivedVariants = variants.length;expectedVariants = parseInt(wrapper.dataset.impeccableVariantCount || arrivedVariants);if (arrivedVariants <= 0) {+ if (state === 'GENERATING') {+ // Mid-generation the source legitimately holds a scaffold wrapper+ // with no variants yet (the server-side preflight wraps before the+ // agent writes). Tearing the session down here would destroy an+ // in-flight generation; stay in GENERATING — the variant observer+ // is armed and the server re-delivers a missed `done`.+ if (!opts.generationCompleted) {+ console.log('[impeccable] Source has scaffold but no variants yet; still generating.');+ return;+ }+ // Generation finished, yet the read shows only the scaffold: the+ // source view is stale and no further event will fire. Re-read a+ // few times before surfacing recovery — a single silent return+ // here would strand the tab in GENERATING forever.+ const attempt = opts.attempt || 0;+ if (attempt < COMPLETED_SOURCE_FALLBACK_RETRIES) {+ console.log('[impeccable] Generation is done but source shows no variants yet; retrying read ('+ + (attempt + 1) + '/' + COMPLETED_SOURCE_FALLBACK_RETRIES + ').');+ setTimeout(() => {+ if (state !== 'GENERATING' || currentSessionId !== sessionId) return;+ if (arrivedVariants > 0) return;+ injectVariantsFromSource(filePath, sessionId, { ...opts, attempt: attempt + 1 });+ }, COMPLETED_SOURCE_FALLBACK_RETRY_MS);+ return;+ }+ }recoverEmptyCycling('source-fallback-empty');return;}@@ -5594,6 +5737,7 @@refreshParamsPanel();positionBar();saveSession();+ if (parameterGenerationState === 'loading') completeParameterPublication();console.log('[impeccable] Injected ' + arrivedVariants + ' variants from source file.');}).catch(err => {@@ -5865,13 +6009,36 @@document.getElementById(VARIANT_STATE_STYLE_ID)?.remove();}+ function showOriginalDuringDiscard(sessionId) {+ if (!sessionId) return;+ let styleEl = document.getElementById(DISCARD_STATE_STYLE_ID);+ if (!styleEl) {+ styleEl = document.createElement('style');+ styleEl.id = DISCARD_STATE_STYLE_ID;+ (document.head || document.documentElement).appendChild(styleEl);+ }+ const wrapper = '[data-impeccable-variants="' + sessionId + '"]';+ styleEl.textContent = wrapper + ' > [data-impeccable-variant]:not([data-impeccable-variant="original"]) { display:none !important; }\n'+ + wrapper + ' > [data-impeccable-variant="original"] { display:block !important; }';+ }++ function resolveScrollLockAnchorTop() {+ const anchor = resolveBarAnchor();+ if (!anchor?.isConnected) return null;+ const top = anchor.getBoundingClientRect().top;+ return Number.isFinite(top) ? top : null;+ }+// Hold window.scrollY at a fixed value across DOM mutations inside the// session's wrapper (HMR patches, variant inserts, cycle swaps).- function startScrollLock(sessionId, initialTargetY) {+ function startScrollLock(sessionId, initialTargetY, initialAnchorTop) {stopScrollLock();scrollLockTargetY = typeof initialTargetY === 'number' && isFinite(initialTargetY)? initialTargetY: window.scrollY;+ scrollLockAnchorTop = typeof initialAnchorTop === 'number' && isFinite(initialAnchorTop)+ ? initialAnchorTop+ : resolveScrollLockAnchorTop();try { history.scrollRestoration = 'manual'; } catch {}@@ -5895,6 +6062,17 @@const correct = (why) => {scrollLockRaf = null;if (scrollLockTargetY == null) return;+ const anchor = resolveBarAnchor();+ if (anchor?.isConnected && typeof scrollLockAnchorTop === 'number' && isFinite(scrollLockAnchorTop)) {+ const anchorTop = anchor.getBoundingClientRect().top;+ const anchorDelta = anchorTop - scrollLockAnchorTop;+ if (Math.abs(anchorDelta) >= 0.5) {+ window.scrollTo({ top: window.scrollY + anchorDelta, left: window.scrollX, behavior: 'instant' });+ scrollLockTargetY = window.scrollY;+ writeScrollY(scrollLockTargetY);+ return;+ }+ }const before = window.scrollY;const delta = before - scrollLockTargetY;if (Math.abs(delta) < 0.5) {@@ -5939,6 +6117,7 @@if (scrollLockRaf != null) { cancelAnimationFrame(scrollLockRaf); scrollLockRaf = null; }const prevTarget = scrollLockTargetY;scrollLockTargetY = window.scrollY;+ scrollLockAnchorTop = resolveScrollLockAnchorTop();writeScrollY(scrollLockTargetY);};const markGesture = (why) => {@@ -5976,6 +6155,7 @@if (scrollLockRaf != null) { cancelAnimationFrame(scrollLockRaf); scrollLockRaf = null; }if (scrollLockAbort) { scrollLockAbort.abort(); scrollLockAbort = null; }scrollLockTargetY = null;+ scrollLockAnchorTop = null;// NOTE: do NOT clear the persistent scroll key here. startScrollLock// calls us as a reset, and clearing the key would nuke the Go-time// scrollY that the next resume needs to read.@@ -6049,6 +6229,7 @@updating = true;arrivedVariants = count;+ generationPhase = arrivedVariants >= expectedVariants ? 'variants_ready' : 'variants_progress';if (visibleVariant === 0 && arrivedVariants > 0) {const saved = loadSession();const savedVisibleVariant = saved && saved.id === sessionId ? saved.visible : 0;@@ -6064,7 +6245,7 @@const expected = parseInt(wrapper.dataset.impeccableVariantCount || '0');if (expected > 0) expectedVariants = expected;- if (arrivedVariants >= expectedVariants && expectedVariants > 0) {+ if (arrivedVariants > 0) {setLiveState('CYCLING');recoveryWaitingForAnchor = false;hideShaderOverlay();@@ -6072,13 +6253,18 @@updateSelectedElement();showOrUpdateCyclingBar();disableInlineEdit();- refreshParamsPanel();+ if (arrivedVariants >= expectedVariants && expectedVariants > 0) refreshParamsPanel();+ else hideParamsPanel();positionBar();} else if (state === 'GENERATING') {updateBarContent('generating');}saveSession();- queueCheckpoint(state === 'CYCLING' ? 'variants_ready' : 'variants_progress');+ sendCheckpoint(+ arrivedVariants >= expectedVariants && expectedVariants > 0+ ? 'variants_ready'+ : 'variants_progress',+ );updating = false;});@@ -6151,6 +6337,7 @@syncAgentPollingUi(!!msg.agentPolling);startAgentStatusPoll();restoreFromActiveSessions(msg.activeSessions, 'sse_connected');+ recoverMissedGenerationCompletion(msg.activeSessions);if (state === 'IDLE' && (pickActive || insertActive)) setLiveState('PICKING');syncPageInteractionCursor();syncPageChatFocus('sse-connected');@@ -6158,6 +6345,42 @@case 'agent_polling':syncAgentPollingUi(!!msg.connected);break;+ case 'agent_phase':+ if (msg.id === currentSessionId && (state === 'GENERATING' || state === 'CYCLING')) {+ generationPhase = msg.phase || generationPhase;+ if (msg.phase === 'variant_parameters_generating' || msg.phase === 'variant_parameters_validating') {+ parameterGenerationState = 'loading';+ }+ if (msg.phase === 'parameters_ready' && parameterGenerationState !== 'ready') {+ parameterGenerationState = 'loading';+ }+ updateBarContent(state === 'CYCLING' ? 'cycling' : 'generating');+ saveSession();+ }+ break;+ case 'variant_progress':+ if (msg.id === currentSessionId) {+ if (msg.publicationKind === 'params') parameterGenerationState = 'loading';+ rememberSessionFileMeta(msg);+ if (isFrameworkComponentPreviewMode(msg.previewMode) && msg.previewFile) {+ injectSvelteComponentsFromManifest(msg.previewFile, msg.id);+ } else if ((msg.previewMode === 'source' || !msg.previewMode) && (msg.previewFile || msg.file)) {+ // Give normal framework HMR the first chance to reconcile its+ // own managed tree. Nuxt route-module HMR can skip intermediate+ // revisions, so fall back to source injection only when the+ // advertised progress still has not appeared after a short+ // settle. Immediate injection races React/Vue ownership and can+ // trigger removeChild errors on the next HMR commit.+ const targetArrived = Number(msg.arrivedVariants) || 1;+ setTimeout(() => {+ if (msg.id !== currentSessionId) return;+ if (state !== 'GENERATING' && state !== 'CYCLING') return;+ if (msg.publicationKind !== 'params' && arrivedVariants >= targetArrived) return;+ injectVariantsFromSource(msg.previewFile || msg.file, msg.id);+ }, 150);+ }+ }+ break;case 'steer_done':maybeCompleteSteer(msg);break;@@ -6175,6 +6398,10 @@case 'done':if (maybeCompleteSteer(msg)) break;rememberSessionFileMeta(msg);+ if (msg.id === currentSessionId && isFrameworkComponentPreviewMode(currentPreviewMode) && currentPreviewFile) {+ injectSvelteComponentsFromManifest(currentPreviewFile, msg.id);+ break;+ }// Variants already arrived via HMR → normal transition.if (arrivedVariants >= expectedVariants && expectedVariants > 0) {if (state === 'GENERATING') {@@ -6190,7 +6417,7 @@setTimeout(() => {if (arrivedVariants >= expectedVariants && expectedVariants > 0) return;if (state !== 'GENERATING' || msg.id !== currentSessionId) return;- injectVariantsFromSource(msg.file, msg.id);+ injectVariantsFromSource(msg.file, msg.id, { generationCompleted: true });}, 750);break;}@@ -6215,9 +6442,10 @@if (maybeCompleteAcceptedSession(msg)) break;break;case 'agent_done':- // Carbonize accepts are not terminal until live-complete.mjs sends- // the final complete event. Keep the browser in its recoverable- // saving state while the source cleanup is still in flight.+ // The deterministic accept has already committed the reviewed DOM+ // and fenced generation. Carbonize may continue in the background;+ // it must not hold the foreground picker hostage.+ if (msg.data?.carbonize === true && maybeCompleteAcceptedSession(msg)) break;break;case 'discarded':if (msg.id && msg.id === currentSessionId) {@@ -6306,6 +6534,7 @@type: 'checkpoint',id: currentSessionId,revision: sessionState.nextCheckpointRevision(),+ revisionDomain: 'browser',owner: browserOwner,phase: String(state || '').toLowerCase(),reason,@@ -6331,6 +6560,7 @@type: 'checkpoint',id,revision: sessionState.nextCheckpointRevision(),+ revisionDomain: 'browser',owner: browserOwner,phase: 'steer',reason,@@ -6684,6 +6914,9 @@expectedVariants = selectedCount;arrivedVariants = 0;visibleVariant = 0;+ generationPhase = 'queued';+ parameterGenerationState = 'pending';+ parameterReadyAnnouncedSession = null;resetSessionFileMeta();// Flip to GENERATING immediately so the bar morphs without waiting on@@ -6693,6 +6926,7 @@const elForCapture = selectedElement;pickedAnchorSnapshot = buildPickedAnchorSnapshot(elForCapture);const captureRect = elForCapture.getBoundingClientRect();+ pickedAnchorViewportTop = captureRect.top;const snapshot = {comments: annotState.comments.map(c => ({ x: c.x, y: c.y, text: c.text })),strokes: annotState.strokes.map(s => ({ points: s.points.map(p => [p[0], p[1]]) })),@@ -6724,7 +6958,7 @@writeScrollY(window.scrollY);if (variantObserver) variantObserver.disconnect();variantObserver = startVariantObserver(currentSessionId);- startScrollLock(currentSessionId);+ startScrollLock(currentSessionId, window.scrollY, pickedAnchorViewportTop);captureAndEmit(elForCapture, basePayload, snapshot, captureRect);}@@ -6759,12 +6993,16 @@expectedVariants = selectedCount;arrivedVariants = 0;visibleVariant = 0;+ generationPhase = 'queued';+ parameterGenerationState = 'pending';+ parameterReadyAnnouncedSession = null;resetSessionFileMeta();selectedElement = placeholderElement;insertPlaceholderSnapshot = buildInsertPlaceholderSnapshotFromDom(insertAnchorElement, placeholderElement);const elForCapture = placeholderElement;const captureRect = elForCapture.getBoundingClientRect();+ pickedAnchorViewportTop = captureRect.top;const basePayload = {type: 'generate',mode: 'insert',@@ -6795,7 +7033,7 @@writeScrollY(window.scrollY);if (variantObserver) variantObserver.disconnect();variantObserver = startVariantObserver(currentSessionId);- startScrollLock(currentSessionId);+ startScrollLock(currentSessionId, window.scrollY, pickedAnchorViewportTop);captureAndEmit(elForCapture, basePayload, snapshot, captureRect);}@@ -6975,9 +7213,9 @@// preview mounts are covered by the same shader regression checks.const adapter = String(window.__IMPECCABLE_LIVE_ADAPTER__ || '').toLowerCase();if (adapter === 'svelte' || adapter === 'sveltekit') return true;- if (currentPreviewMode === 'svelte-component' || svelteComponentSession) return true;+ if (isFrameworkComponentPreviewMode(currentPreviewMode) || svelteComponentSession) return true;const wrapper = el?.closest?.('[data-impeccable-variants]');- return wrapper?.dataset?.impeccablePreview === 'svelte-component';+ return isFrameworkComponentPreviewMode(wrapper?.dataset?.impeccablePreview);}function paintsShaderProxySurface(node) {@@ -7105,6 +7343,17 @@}async function captureAndEmit(el, basePayload, snapshot, rect) {+ const hasAnnotations = snapshot && (snapshot.comments.length > 0 || snapshot.strokes.length > 0);++ // Plain requests do not send a screenshot to the agent, so capture is+ // presentation-only. Wait only for the helper to accept the event before+ // starting CPU-heavy capture; this yields the browser task and prevents+ // rasterization from delaying the fetch itself.+ if (!hasAnnotations) {+ basePayload.clientSentAt = Date.now();+ await sendEvent(basePayload);+ }+let screenshotPath;let blob;let paper;@@ -7122,7 +7371,6 @@// are present. Without annotations the image is pure visual anchoring -// it biases the model toward the current rendering and works against the// three-distinct-directions brief.- const hasAnnotations = snapshot && (snapshot.comments.length > 0 || snapshot.strokes.length > 0);if (blob && hasAnnotations) {try {const uploadRes = await fetch(@@ -7140,7 +7388,12 @@console.warn('[impeccable] annotation upload failed:', err);}}- sendEvent(screenshotPath ? { ...basePayload, screenshotPath } : basePayload);+ // Annotated requests must wait for capture + upload because the screenshot+ // is semantic input. Plain requests were already dispatched above.+ if (hasAnnotations) {+ basePayload.clientSentAt = Date.now();+ sendEvent(screenshotPath ? { ...basePayload, screenshotPath } : basePayload);+ }}//@@ -7520,7 +7773,6 @@ void main() {if (variantSelectionPromise) {try { await variantSelectionPromise; } catch { /* failed selection falls back below */ }}- if (!currentSessionId || arrivedVariants === 0) return;const domVisibleVariant = readVisibleVariantFromDOM(currentSessionId);if (domVisibleVariant > 0) visibleVariant = domVisibleVariant;const acceptPayload = {@@ -7528,7 +7780,9 @@ void main() {id: currentSessionId,variantId: String(visibleVariant),pageUrl: location.pathname,+ clientSentAt: Date.now(),};+ if (!currentSessionId || arrivedVariants === 0) return;const acceptWrapper = document.querySelector('[data-impeccable-variants="' + currentSessionId + '"]');if (Object.keys(paramsCurrentValues).length > 0) {acceptPayload.paramValues = { ...paramsCurrentValues };@@ -7542,7 +7796,7 @@ void main() {const acceptedSessionId = currentSessionId;const acceptedVariant = visibleVariant;const acceptedIsSvelteComponent = svelteComponentSession?.sessionId === acceptedSessionId- || acceptWrapper?.dataset?.impeccablePreview === 'svelte-component';+ || isFrameworkComponentPreviewMode(acceptWrapper?.dataset?.impeccablePreview);const acceptedSnapshot = snapshotAcceptedVariantDom(acceptedSessionId, acceptedVariant);setLiveState('SAVING');@@ -7557,7 +7811,17 @@ void main() {saveSession();sendEvent(acceptPayload, { throwOnError: true })- .then(() => {})+ .then(() => {+ const pending = pendingAcceptedSession;+ if (!pending || pending.id !== acceptedSessionId) return;+ // POST /events returns only after the accept intent is durable and the+ // generation epoch is fenced. Source promotion/carbonize can finish in+ // the background; the foreground picker is free immediately.+ markSessionHandled();+ setLiveState('CONFIRMED');+ document.documentElement.dataset.impeccableAcceptToPickingMs = String(Date.now() - acceptPayload.clientSentAt);+ scheduleAcceptCleanup(pending);+ }).catch(() => {if (pendingAcceptedSession?.id === acceptedSessionId) pendingAcceptedSession = null;setLiveState('CYCLING');@@ -7586,17 +7850,26 @@ void main() {}function scheduleAcceptCleanup(accepted) {- setTimeout(function() {- if (!accepted?.isSvelteComponent && !acceptedDomAlreadyClean(accepted)) {- setTimeout(function() {- if (pendingAcceptedSession?.id !== accepted?.id) return;- if (!accepted?.isSvelteComponent) ensureAcceptedDomClean(accepted);- cleanupAcceptedSession();- }, 1800);- return;+ queueMicrotask(function() {+ if (pendingAcceptedSession?.id !== accepted?.id) return;+ // Svelte previews live in an adapter-owned mount rather than in source+ // wrapper markup. Promote the mounted variant before releasing the+ // session so the old adapter instance cannot linger behind the next+ // Pick → Go loop while carbonize finishes in the background.+ if (accepted?.isSvelteComponent) {+ commitAcceptedSvelteComponentToDom(accepted.id);}cleanupAcceptedSession();- }, 1200);+ });+ // Let React/Vue/Svelte own the HMR reconciliation. Mutating their DOM in+ // the same turn as the source update causes removeChild/NotFoundError+ // races. Static servers still need a fallback, but it must not keep Live+ // in SAVING or block the user's next pick.+ if (!accepted?.isSvelteComponent) {+ setTimeout(function() {+ if (!acceptedDomAlreadyClean(accepted)) ensureAcceptedDomClean(accepted);+ }, 1200);+ }}function snapshotAcceptedVariantDom(sessionId, variantId) {@@ -7700,7 +7973,11 @@ void main() {clearSession();resetSessionFileMeta();selectedElement = null;+ hoveredElement = null;+ pagePickSkipClick = false;currentSessionId = null;+ parameterGenerationState = 'idle';+ parameterReadyAnnouncedSession = null;selectedAction = 'impeccable';pendingAcceptedSession = null;renderEditBadge('hidden');@@ -7735,7 +8012,7 @@ void main() {sendEvent({ type: 'discard', id: currentSessionId }, { throwOnError: true }).then(() => {markSessionHandled();- cleanup();+ cleanup({ restoreOriginal: true, instantChrome: true });}).catch(() => showToast('Could not confirm discard with the live server. Session kept for recovery.', 5000));}@@ -7757,6 +8034,7 @@ void main() {currentPreviewMode = null;recoveryWaitingForAnchor = false;pickedAnchorSnapshot = null;+ pickedAnchorViewportTop = null;}function rememberSessionFileMeta(meta = {}) {@@ -7765,8 +8043,8 @@ void main() {const previewFile = normalizeSessionPath(meta.previewFile);const previewMode = meta.previewMode || (isSvelteComponentManifestPath(previewFile || file) ? 'svelte-component' : null);- if (previewMode === 'svelte-component' || isSvelteComponentManifestPath(file)) {- currentPreviewMode = 'svelte-component';+ if (isFrameworkComponentPreviewMode(previewMode) || isSvelteComponentManifestPath(file)) {+ currentPreviewMode = isFrameworkComponentPreviewMode(previewMode) ? previewMode : 'svelte-component';currentPreviewFile = previewFile || (isSvelteComponentManifestPath(file) ? file : currentPreviewFile);currentSourceFile = sourceFile || currentSourceFile;return;@@ -7782,12 +8060,15 @@ void main() {rememberSessionFileMeta(saved);if (saved.insertPlaceholder) insertPlaceholderSnapshot = saved.insertPlaceholder;if (saved.pickedAnchor) pickedAnchorSnapshot = saved.pickedAnchor;+ if (Number.isFinite(saved.pickedAnchorViewportTop)) pickedAnchorViewportTop = saved.pickedAnchorViewportTop;if (saved.action) selectedAction = saved.action;if (saved.count) selectedCount = saved.count;if (saved.previewMode) currentPreviewMode = saved.previewMode;if (saved.paramValues && typeof saved.paramValues === 'object') {paramsCurrentValues = { ...saved.paramValues };}+ if (saved.parameterState) parameterGenerationState = saved.parameterState;+ if (saved.generationPhase) generationPhase = saved.generationPhase;}function normalizePagePath(value) {@@ -7859,7 +8140,7 @@ void main() {saveSession();queueCheckpoint(reason || 'browser_restore_without_wrapper');- const restoreFile = currentPreviewMode === 'svelte-component'+ const restoreFile = isFrameworkComponentPreviewMode(currentPreviewMode)? currentPreviewFile: (currentSourceFile || currentPreviewFile);if (restoreFile) {@@ -7872,11 +8153,41 @@ void main() {function restoreFromActiveSessions(activeSessions, reason) {const wrapper = document.querySelector('[data-impeccable-variants]');- if (wrapper && wrapper.dataset.impeccablePreview !== 'svelte-component') return false;+ if (wrapper && !isFrameworkComponentPreviewMode(wrapper.dataset.impeccablePreview)) return false;if (svelteComponentSession?.sessionId === currentSessionId) return false;return restoreSessionWithoutWrapper(reason || 'sse_connected', activeSessions);}+ // Self-heal on SSE (re)connect. The preflight scaffold write triggers a+ // framework full-reload (Astro reloads pages for any .astro edit); if the+ // agent's variant write + `done` broadcast land while this page is+ // mid-reload, both the done SSE and the second HMR reload are missed and+ // the resumed page would wait in GENERATING at 0/N forever. The server's+ // session summary carries the durable generationCompletedAt marker, so on+ // every connect compare it against our own progress and pull the finished+ // variants from source when behind. Mirrors the `done` handler's source+ // fallback, including its give-HMR-the-first-chance settle delay.+ function recoverMissedGenerationCompletion(activeSessions) {+ if (!currentSessionId || state !== 'GENERATING') return;+ if (!Array.isArray(activeSessions)) return;+ const summary = activeSessions.find((session) => session?.id === currentSessionId);+ if (!summary?.generationCompletedAt || summary.generationCanceled) return;+ if (isTerminalSessionSummary(summary)) return;+ if (arrivedVariants > 0 && arrivedVariants >= expectedVariants) return;+ rememberSessionFileMeta(summary);+ const sessionId = currentSessionId;+ const file = isFrameworkComponentPreviewMode(currentPreviewMode)+ ? currentPreviewFile+ : (summary.sourceFile || summary.previewFile || currentSourceFile || currentPreviewFile);+ if (!file) return;+ console.log('[impeccable] Reconnected after generation completed; recovering variants from source.');+ setTimeout(() => {+ if (sessionId !== currentSessionId || state !== 'GENERATING') return;+ if (arrivedVariants > 0 && arrivedVariants >= expectedVariants) return;+ injectVariantsFromSource(file, sessionId, { generationCompleted: true });+ }, 750);+ }+function saveSession() {if (!currentSessionId) return;// NOTE: scrollY is stored under a separate key (writeScrollY). Storing@@ -7894,8 +8205,12 @@ void main() {previewMode: currentPreviewMode || undefined,pageUrl: location.pathname,paramValues: { ...paramsCurrentValues },+ parameterState: parameterGenerationState,insertPlaceholder: insertPlaceholderSnapshot || undefined,pickedAnchor: pickedAnchorSnapshot || undefined,+ pickedAnchorViewportTop: Number.isFinite(pickedAnchorViewportTop) ? pickedAnchorViewportTop : undefined,+ pageHash: location.hash || undefined,+ pageSearch: location.search || undefined,});}@@ -7923,20 +8238,26 @@ void main() {sessionState.clearHandled();}- function cleanup() {+ function cleanup(options) {+ const restoreOriginal = options?.restoreOriginal === true;+ const instantChrome = options?.instantChrome === true;const cleanupSessionId = currentSessionId;if (svelteComponentSession?.sessionId === cleanupSessionId) {teardownSvelteComponentSession(true);} else if (cleanupSessionId) {- // Hide the wrapper immediately so variants disappear. DON'T structurally- // mutate the DOM yet - HMR from the agent's source rewrite is on its way,+ // Switch visibility immediately without structurally mutating the DOM.+ // HMR from the agent's source rewrite may still be on its way,// and a manual replaceChild under React causes NotFoundError when the// reconciler later tries to remove a wrapper we already removed.// Schedule a 2s fallback that does the manual swap only if HMR hasn't// replaced the wrapper by then (keeps static-server / no-HMR flows alive).const wrapper = document.querySelector('[data-impeccable-variants="' + cleanupSessionId + '"]');- if (wrapper) wrapper.style.display = 'none';+ if (wrapper) {+ if (restoreOriginal) showOriginalDuringDiscard(cleanupSessionId);+ else wrapper.style.display = 'none';+ }setTimeout(function() {+ document.getElementById(DISCARD_STATE_STYLE_ID)?.remove();if (!cleanupSessionId) return;const lateWrapper = document.querySelector('[data-impeccable-variants="' + cleanupSessionId + '"]');if (!lateWrapper) return;@@ -7951,7 +8272,7 @@ void main() {lateWrapper.remove();}, 2000);}- hideBar();+ hideBar(instantChrome);hideHighlight();stopScrollTracking();if (variantObserver) { variantObserver.disconnect(); variantObserver = null; }@@ -7963,7 +8284,11 @@ void main() {clearSession();resetSessionFileMeta();selectedElement = null;+ hoveredElement = null;+ pagePickSkipClick = false;currentSessionId = null;+ parameterGenerationState = 'idle';+ parameterReadyAnnouncedSession = null;selectedAction = 'impeccable';renderEditBadge('hidden');setLiveState('PICKING');@@ -8047,7 +8372,7 @@ void main() {// would strand the bar in CYCLING at 0/0. If there's no live in-memory mount// for this wrapper, it's an orphan (reload / failed mount): drop it and let// the live-server's SSE re-inject the manifest if the session is still live.- if (wrapper.dataset.impeccablePreview === 'svelte-component'+ if (isFrameworkComponentPreviewMode(wrapper.dataset.impeccablePreview)&& svelteComponentSession?.sessionId !== sessionId) {wrapper.remove();if (restoreSessionWithoutWrapper('browser_resumed_svelte_orphan_wrapper')) return true;@@ -8056,7 +8381,7 @@ void main() {return false;}- if (wrapper.dataset.impeccablePreview === 'svelte-component') {+ if (isFrameworkComponentPreviewMode(wrapper.dataset.impeccablePreview)) {if (!svelteComponentSession?.mountedVariant) {return true;}@@ -8104,7 +8429,7 @@ void main() {insertPlaceholderSnapshot = saved.insertPlaceholder;}- const resumedState = arrivedVariants >= expectedVariants ? 'CYCLING' : 'GENERATING';+ const resumedState = arrivedVariants > 0 ? 'CYCLING' : 'GENERATING';// Find the visible variant's content element for highlight positioning.const isInsert = wrapper.dataset.impeccableMode === 'insert';@@ -8128,7 +8453,11 @@ void main() {// hid. Now that state is CYCLING, re-fire.if (state === 'CYCLING') refreshParamsPanel();saveSession();- queueCheckpoint('browser_resumed');+ if (arrivedVariants > 0 && arrivedVariants < expectedVariants) {+ sendCheckpoint('variants_progress');+ } else {+ queueCheckpoint('browser_resumed');+ }// Start observing for more variants AFTER initial setupif (variantObserver) variantObserver.disconnect();@@ -8136,7 +8465,7 @@ void main() {// Hold the target at its saved viewport top through any subsequent// HMR patches, variant inserts, or cycle swaps.- startScrollLock(currentSessionId, readScrollY());+ startScrollLock(currentSessionId, readScrollY(), pickedAnchorViewportTop);// If we reloaded mid-generation (Bun's HTML HMR destroys the shader// canvas), re-capture the original's content and restart the shader so@@ -8171,6 +8500,7 @@ void main() {let globalBarBrandEl = null;let agentPollTooltipEl = null;let agentPollingConnected = false;+ let agentStatusMessage = null;let agentStatusPollTimer = null;let steerFocusSuspended = false;let steerFocusPauseUntil = 0;@@ -8275,6 +8605,13 @@ void main() {const AGENT_STATUS_POLL_MS = 5000;const AGENT_DISCONNECTED_MARK = 'oklch(62% 0 0 / 0.78)';const AGENT_DISCONNECTED_TIP = 'Agent disconnected - run live-poll.mjs to connect';+ // The indicator tracks whether a poll is parked, which is what decides if+ // steering can reach the agent right now. That goes quiet two ways, and they+ // need different copy: nobody is polling at all, or the agent took the work+ // and is busy with it. Under one-shot foreground polling the second case is+ // every normal generation, and telling the user to start a poll loop then is+ // wrong advice about a healthy session.+ const AGENT_BUSY_TIP = 'Agent is working - steering resumes when it finishes';const GLOBAL_BAR_SECTION_GAP = 8;const GLOBAL_BAR_INNER_GAP = 2;const GLOBAL_BAR_INNER_PAD_LEFT = 2;@@ -9295,24 +9632,46 @@ void main() {</svg>`;}+ /**+ * True while the browser is waiting on work it already handed to the agent.+ * In these states a quiet poll indicator means "busy", not "absent".+ */+ function agentHasWorkInFlight() {+ return state === 'GENERATING' || state === 'SAVING';+ }++ /**+ * Derived at read time, not cached: which of the two reasons applies depends on+ * the live state, which moves between the 5s status polls. The truthiness is+ * the same either way, so the indicator's visuals can stay driven by the+ * cached value while the wording stays current.+ */+ function agentStatusText() {+ if (agentPollingConnected) return null;+ return agentHasWorkInFlight() ? AGENT_BUSY_TIP : AGENT_DISCONNECTED_TIP;+ }+function syncAgentPollingUi(connected) {agentPollingConnected = !!connected;if (!globalBarBrandEl) return;const P = barPaletteForTheme(globalBarEl?.dataset.theme || detectPageTheme());+ agentStatusMessage = agentStatusText();globalBarBrandEl.dataset.agentConnected = connected ? 'true' : 'false';- globalBarBrandEl.setAttribute('aria-label', connected- ? 'Impeccable live mode'- : 'Impeccable live mode - agent not polling');+ // The tooltip is mouse-only, so carry the same distinction in the label or+ // screen-reader users are left with the vaguer of the two readings.+ globalBarBrandEl.setAttribute('aria-label', agentStatusMessage+ ? 'Impeccable live mode - ' + (agentHasWorkInFlight() ? 'agent is working' : 'agent not polling')+ : 'Impeccable live mode');globalBarBrandEl.removeAttribute('title');- globalBarBrandEl.style.cursor = connected ? 'default' : 'help';+ globalBarBrandEl.style.cursor = agentStatusMessage ? 'help' : 'default';const mark = globalBarBrandEl.querySelector('[data-brand-mark]');if (mark) {mark.innerHTML = brandMarkSvg(connected ? P.accent : AGENT_DISCONNECTED_MARK, 18);mark.style.opacity = '1';}const dot = globalBarBrandEl.querySelector('[data-agent-dot]');- if (dot) dot.style.display = connected ? 'none' : 'block';- if (connected) hideAgentPollTooltip();+ if (dot) dot.style.display = agentStatusMessage ? 'block' : 'none';+ if (!agentStatusMessage) hideAgentPollTooltip();}function ensureAgentPollTooltip() {@@ -9339,14 +9698,17 @@ void main() {whiteSpace: 'normal',});agentPollTooltipEl.id = PREFIX + '-agent-poll-tooltip';- agentPollTooltipEl.textContent = AGENT_DISCONNECTED_TIP;+ agentPollTooltipEl.textContent = agentStatusText() || AGENT_DISCONNECTED_TIP;uiAppend(agentPollTooltipEl);return agentPollTooltipEl;}function showAgentPollTooltip(anchor) {- if (agentPollingConnected || !anchor) return;+ if (!agentStatusMessage || !anchor) return;const tip = ensureAgentPollTooltip();+ // Re-derive rather than reuse the cached copy: the live state may have moved+ // since the last status poll set it.+ tip.textContent = agentStatusText() || AGENT_DISCONNECTED_TIP;tip.style.transition = 'none';tip.style.display = 'block';tip.style.opacity = '1';@@ -9376,7 +9738,9 @@ void main() {fetch('http://localhost:' + PORT + '/status?token=' + TOKEN, { cache: 'no-store' }).then((res) => (res.ok ? res.json() : null)).then((data) => {- if (data && typeof data.agentPolling === 'boolean') syncAgentPollingUi(data.agentPolling);+ if (data && typeof data.agentPolling === 'boolean') {+ syncAgentPollingUi(data.agentPolling);+ }}).catch(() => { /* server loss handled elsewhere */ });}diff --git a/.opencode/skills/impeccable/scripts/live-inject.mjs b/.opencode/skills/impeccable/scripts/live-inject.mjsindex 7c8d91182..d99c37fd5 100644--- a/.opencode/skills/impeccable/scripts/live-inject.mjs+++ b/.opencode/skills/impeccable/scripts/live-inject.mjs@@ -27,6 +27,8 @@ const __dirname = path.dirname(fileURLToPath(import.meta.url));const CONFIG_PATH = resolveLiveConfigPath({ cwd: process.cwd(), scriptsDir: __dirname });const MARKER_OPEN_TEXT = 'impeccable-live-start';const MARKER_CLOSE_TEXT = 'impeccable-live-end';+const NUXT_PLUGIN_MARKER = 'impeccable-live-nuxt-plugin';+const NUXT_PLUGIN_NAME = 'impeccable-live.client.ts';const IGNORE_MARKER_OPEN = '# impeccable-live-ignore-start';const IGNORE_MARKER_CLOSE = '# impeccable-live-ignore-end';@@ -38,6 +40,9 @@ export const LIVE_IGNORE_PATTERNS = Object.freeze(['.impeccable/live/sessions/','.impeccable/live/previews/','.impeccable/live/annotations/',+ '.impeccable/live/artifacts/',+ '.impeccable/live/accept-receipts/',+ '.impeccable/live/locks/','.impeccable/live/cache/','.impeccable/live/manual-edit-apply-transaction.json','.impeccable/live/manual-edit-events.jsonl',@@ -46,10 +51,15 @@ export const LIVE_IGNORE_PATTERNS = Object.freeze(['.impeccable/live/deferred-svelte-component-accepts.json','.impeccable-live.json','.impeccable-live/',+ 'app/.impeccable-live/',+ 'src/.impeccable-live/','node_modules/.impeccable-live/','src/lib/impeccable/ImpeccableLiveRoot.svelte','src/lib/impeccable/__runtime.js','src/lib/impeccable/[0-9a-f]*/',+ 'plugins/impeccable-live.client.ts',+ 'app/plugins/impeccable-live.client.ts',+ 'src/plugins/impeccable-live.client.ts',]);/**@@ -113,6 +123,7 @@ Output (JSON):const resolvedFiles = resolveFiles(process.cwd(), config);const svelteKit = detectSvelteKitProject(process.cwd(), config);+ const nuxt = detectNuxtProject(process.cwd());if (args.includes('--remove')) {if (svelteKit) {@@ -120,6 +131,12 @@ Output (JSON):console.log(JSON.stringify({ ok: true, adapter: 'sveltekit', results: [adapterResult] }));return;}+ if (nuxt) {+ const adapterResult = removeNuxtLiveAdapter({ cwd: process.cwd(), project: nuxt });+ console.log(JSON.stringify({ ok: !adapterResult.error, adapter: 'nuxt', results: [adapterResult] }));+ if (adapterResult.error) process.exitCode = 1;+ return;+ }const results = resolvedFiles.map((relFile) => {const absFile = path.resolve(process.cwd(), relFile);if (!fs.existsSync(absFile)) return { file: relFile, error: 'file_not_found' };@@ -145,13 +162,28 @@ Output (JSON):console.error(JSON.stringify({ ok: false, error: 'missing_port' }));process.exit(1);}- const gitIgnore = ensureLiveGitIgnores(process.cwd());+ const gitIgnore = ensureLiveGitIgnores(+ process.cwd(),+ nuxt ? [nuxt.pluginFile] : [],+ );if (svelteKit) {const adapterResult = applySvelteKitLiveAdapter({ cwd: process.cwd(), port, config });console.log(JSON.stringify({ ok: true, port, adapter: 'sveltekit', gitIgnore, results: [adapterResult] }));return;}+ if (nuxt) {+ const adapterResult = applyNuxtLiveAdapter({ cwd: process.cwd(), port, project: nuxt });+ console.log(JSON.stringify({+ ok: !adapterResult.error,+ port,+ adapter: 'nuxt',+ gitIgnore,+ results: [adapterResult],+ }));+ if (adapterResult.error) process.exitCode = 1;+ return;+ }const results = resolvedFiles.map((relFile) => {const absFile = path.resolve(process.cwd(), relFile);@@ -175,12 +207,12 @@ Output (JSON):if (!anyInserted) process.exit(1);}-export function ensureLiveGitIgnores(cwd = process.cwd()) {+export function ensureLiveGitIgnores(cwd = process.cwd(), extraPatterns = []) {const target = resolveIgnoreTarget(cwd);const existing = fs.existsSync(target.path) ? fs.readFileSync(target.path, 'utf-8') : '';const block = [IGNORE_MARKER_OPEN,- ...LIVE_IGNORE_PATTERNS,+ ...new Set([...LIVE_IGNORE_PATTERNS, ...extraPatterns]),IGNORE_MARKER_CLOSE,].join('\n');const markerRe = new RegExp(`${escapeRegExp(IGNORE_MARKER_OPEN)}[\\s\\S]*?${escapeRegExp(IGNORE_MARKER_CLOSE)}`);@@ -202,10 +234,119 @@ export function ensureLiveGitIgnores(cwd = process.cwd()) {file: path.relative(cwd, target.path).split(path.sep).join('/'),mode: target.mode,changed: updated !== existing,- patterns: [...LIVE_IGNORE_PATTERNS],+ patterns: [...new Set([...LIVE_IGNORE_PATTERNS, ...extraPatterns])],};}+// ---------------------------------------------------------------------------+// Nuxt adapter+//+// A script element placed in app.vue is compiled as Vue-rendered DOM and is+// not executed. Nuxt instead auto-discovers client plugins. Keep the adapter+// generated, dev-only, and outside user-authored source: Live creates one+// marked .client.ts plugin on start and removes it on stop.+// ---------------------------------------------------------------------------++export function detectNuxtProject(cwd = process.cwd()) {+ const configFile = fs.readdirSync(cwd, { withFileTypes: true })+ .find((entry) => entry.isFile() && /^nuxt\.config\.(?:js|mjs|cjs|ts|mts|cts)$/.test(entry.name))+ ?.name;+ if (!configFile) return null;++ const config = fs.readFileSync(path.join(cwd, configFile), 'utf-8');+ const literalSrcDir = config.match(/\bsrcDir\s*:\s*(['"])([^'"]+)\1/);+ let appDir = '';+ if (literalSrcDir) {+ const candidate = literalSrcDir[2]+ .replace(/\\/g, '/')+ .replace(/^\.\//, '')+ .replace(/\/+$/, '');+ const normalized = path.posix.normalize(candidate);+ if (normalized !== '..' && !normalized.startsWith('../') && !path.isAbsolute(normalized)) {+ appDir = normalized === '.' ? '' : normalized;+ }+ } else if (+ fs.existsSync(path.join(cwd, 'app', 'app.vue'))+ || fs.existsSync(path.join(cwd, 'app', 'pages'))+ ) {+ appDir = 'app';+ }++ const pluginFile = [appDir, 'plugins', NUXT_PLUGIN_NAME].filter(Boolean).join('/');+ return { configFile, appDir, pluginFile };+}++export function buildNuxtPlugin(port) {+ return `/* ${NUXT_PLUGIN_MARKER} */+const liveSrc = 'http://localhost:${port}/live.js';+const liveSelector = 'script[data-impeccable-live-nuxt]';++export default defineNuxtPlugin(() => {+ if (!import.meta.dev || typeof document === 'undefined') return;++ const expectedSrc = new URL(liveSrc, window.location.href).href;+ let script = document.querySelector(liveSelector);+ if (script?.src === expectedSrc) return;+ script?.remove();++ script = document.createElement('script');+ script.src = liveSrc;+ script.async = true;+ script.dataset.impeccableLiveNuxt = '';+ document.head.appendChild(script);++ import.meta.hot?.dispose(() => {+ if (script?.isConnected) script.remove();+ });+});+/* /${NUXT_PLUGIN_MARKER} */+`;+}++export function applyNuxtLiveAdapter({ cwd = process.cwd(), port, project = detectNuxtProject(cwd) }) {+ if (!project) return { error: 'nuxt_not_detected' };+ const absFile = path.join(cwd, project.pluginFile);+ const existing = fs.existsSync(absFile) ? fs.readFileSync(absFile, 'utf-8') : null;+ if (existing !== null && !existing.includes(NUXT_PLUGIN_MARKER)) {+ return {+ file: project.pluginFile,+ error: 'nuxt_plugin_conflict',+ hint: `${project.pluginFile} already exists and is not managed by Impeccable Live`,+ };+ }++ const content = buildNuxtPlugin(port);+ fs.mkdirSync(path.dirname(absFile), { recursive: true });+ if (content !== existing) fs.writeFileSync(absFile, content, 'utf-8');+ return {+ file: project.pluginFile,+ inserted: true,+ changed: content !== existing,+ devOnly: true,+ };+}++export function removeNuxtLiveAdapter({ cwd = process.cwd(), project = detectNuxtProject(cwd) }) {+ if (!project) return { error: 'nuxt_not_detected' };+ const absFile = path.join(cwd, project.pluginFile);+ if (!fs.existsSync(absFile)) {+ return { file: project.pluginFile, removed: false, note: 'no adapter present' };+ }+ const content = fs.readFileSync(absFile, 'utf-8');+ if (!content.includes(NUXT_PLUGIN_MARKER)) {+ return {+ file: project.pluginFile,+ removed: false,+ error: 'nuxt_plugin_conflict',+ hint: `${project.pluginFile} is not managed by Impeccable Live`,+ };+ }+ fs.unlinkSync(absFile);+ const pluginDir = path.dirname(absFile);+ if (fs.readdirSync(pluginDir).length === 0) fs.rmdirSync(pluginDir);+ return { file: project.pluginFile, removed: true };+}+function resolveIgnoreTarget(cwd) {const gitExcludePath = resolveGitInfoExcludePath(cwd);if (gitExcludePath) {diff --git a/.opencode/skills/impeccable/scripts/live-poll.mjs b/.opencode/skills/impeccable/scripts/live-poll.mjsindex 740161e10..19a8b0f9b 100644--- a/.opencode/skills/impeccable/scripts/live-poll.mjs+++ b/.opencode/skills/impeccable/scripts/live-poll.mjs@@ -27,7 +27,7 @@ const scriptCmd = (name) => `node "${path.join(SELF_DIR, name)}"`;export const PER_REQUEST_TIMEOUT_MS = 270_000;export const DEFAULT_EVENT_LEASE_MS = 600_000;-const EVENT_TYPES_NEEDING_AGENT_REPLY = new Set(['generate', 'steer', 'manual_edit_apply']);+const EVENT_TYPES_NEEDING_AGENT_REPLY = new Set(['generate', 'steer', 'manual_edit_apply', 'carbonize_cleanup']);function readServerInfo() {const record = readLiveServerInfo(process.cwd());@@ -38,8 +38,8 @@ function readServerInfo() {return record.info;}-export function buildPollReplyPayload(token, { id, type, message, file, data }) {- return { token, id, type, message, file, data };+export function buildPollReplyPayload(token, { id, type, message, file, data, sourceEventType }) {+ return { token, id, type, message, file, data, sourceEventType };}export function manualApplyPollBanner(event = {}) {@@ -152,7 +152,14 @@ export async function waitForEventAck(base, token, eventId, {return false;}-export async function fetchNextEvent(base, token, { totalDeadline } = {}) {+export async function fetchNextEvent(base, token, {+ totalDeadline,+ types,+ resolveTypes,+ perRequestTimeoutMs = PER_REQUEST_TIMEOUT_MS,+ leaseMs = DEFAULT_EVENT_LEASE_MS,+ signal,+} = {}) {while (true) {if (totalDeadline && Date.now() >= totalDeadline) {return { type: 'timeout' };@@ -161,8 +168,15 @@ export async function fetchNextEvent(base, token, { totalDeadline } = {}) {const remaining = totalDeadline? totalDeadline - Date.now(): PER_REQUEST_TIMEOUT_MS;- const slice = Math.min(Math.max(remaining, 1000), PER_REQUEST_TIMEOUT_MS);- const res = await fetch(`${base}/poll?token=${token}&timeout=${slice}&leaseMs=${DEFAULT_EVENT_LEASE_MS}`);+ const slice = Math.min(Math.max(remaining, 1000), perRequestTimeoutMs);+ const query = new URLSearchParams({+ token,+ timeout: String(slice),+ leaseMs: String(leaseMs),+ });+ const normalizedTypes = normalizePollTypes(resolveTypes ? await resolveTypes() : types);+ if (normalizedTypes.length > 0) query.set('types', normalizedTypes.join(','));+ const res = await fetch(`${base}/poll?${query}`, { signal });if (res.status === 401) {const err = new Error('Authentication failed. The server token may have changed.');@@ -202,11 +216,17 @@ export async function augmentEventWithAcceptHandling(event, base, token) {event._acceptResult = { handled: false, mode: 'error', error: err.message };}+ await completeAcceptHandling(event, base, token);+ return event;+}++export async function completeAcceptHandling(event, base, token) {const completionType = completionTypeForAcceptResult(event.type, event._acceptResult);try {await postReply(base, token, {id: event.id,type: completionType,+ sourceEventType: event.type,message: event._acceptResult?.error,file: event._acceptResult?.file,data: event._acceptResult?.carbonize === true ? { carbonize: true } : undefined,@@ -217,7 +237,6 @@ export async function augmentEventWithAcceptHandling(event, base, token) {if (!event._completionAck) {event._completionAck = completionAckForAcceptResult(event.id, completionType, event._acceptResult);}-return event;}@@ -245,9 +264,9 @@ export function printPollEvent(event) {console.log(JSON.stringify(event));}-export async function runPollOnce(base, token, { totalTimeout = 600_000 } = {}) {+export async function runPollOnce(base, token, { totalTimeout = 600_000, types, resolveTypes, perRequestTimeoutMs } = {}) {const deadline = Date.now() + totalTimeout;- const event = await fetchNextEvent(base, token, { totalDeadline: deadline });+ const event = await fetchNextEvent(base, token, { totalDeadline: deadline, types, resolveTypes, perRequestTimeoutMs });await augmentEventWithAcceptHandling(event, base, token);writeCarbonizeBanner(event);printPollEvent(event);@@ -258,11 +277,14 @@ export async function runPollStream(base, token, {ackTimeoutMs = 600_000,ackPollIntervalMs = 400,shouldContinue = () => true,+ types,+ resolveTypes,+ perRequestTimeoutMs,} = {}) {process.stderr.write('[impeccable-poll] stream mode: one JSON object per line on stdout; use --reply while this process stays running\n');while (shouldContinue()) {- const event = await fetchNextEvent(base, token);+ const event = await fetchNextEvent(base, token, { types, resolveTypes, perRequestTimeoutMs });await augmentEventWithAcceptHandling(event, base, token);writeCarbonizeBanner(event);printPollEvent(event);@@ -322,14 +344,17 @@ Modes:Options:--timeout=MS One-shot poll timeout in ms (default: 600000). Ignored in --stream mode+ --types=A,B Lease only these event types--ack-timeout=MS Stream mode: max wait for --reply after generate/steer (default: 600000)--file PATH Attach a source file path to the reply (generate/steer flow)--data JSON Attach a JSON result object to the reply (manual_edit_apply flow). Must be valid JSON--help Show this help messageHarness note:- Default one-shot mode is the portable contract for Claude Code, Codex, and Cursor.- --stream is experimental for harnesses with fast incremental stdout; do not use on Cursor.`);+ Default one-shot mode is the primary contract, including Codex foreground polling.+ Claude Code may run it as a background task; Cursor uses a background terminal with exit notification.+ --stream is retained for harnesses with measured, reliable incremental stdout.+ Do not use --stream on Cursor.`);process.exit(0);}@@ -360,23 +385,30 @@ Harness note:}const streamMode = args.includes('--stream');+ const typesArg = args.find((a) => a.startsWith('--types='));+ const types = normalizePollTypes(typesArg ? typesArg.slice('--types='.length) : null);const ackTimeoutArg = args.find((a) => a.startsWith('--ack-timeout='));const ackTimeoutMs = ackTimeoutArg ? parseInt(ackTimeoutArg.split('=')[1], 10) : 600_000;try {if (streamMode) {- await runPollStream(base, info.token, { ackTimeoutMs });+ await runPollStream(base, info.token, { ackTimeoutMs, types });return;}const timeoutArg = args.find((a) => a.startsWith('--timeout='));const totalTimeout = timeoutArg ? parseInt(timeoutArg.split('=')[1], 10) : 600_000;- await runPollOnce(base, info.token, { totalTimeout });+ await runPollOnce(base, info.token, { totalTimeout, types });} catch (err) {handlePollError(err);}}+export function normalizePollTypes(value) {+ const values = Array.isArray(value) ? value : String(value || '').split(',');+ return [...new Set(values.map((type) => String(type).trim()).filter(Boolean))];+}+// Auto-execute when run directlyconst _running = process.argv[1];if (_running?.endsWith('live-poll.mjs') || _running?.endsWith('live-poll.mjs/')) {diff --git a/.opencode/skills/impeccable/scripts/live-server.mjs b/.opencode/skills/impeccable/scripts/live-server.mjsindex 5735f2aec..c6e951086 100644--- a/.opencode/skills/impeccable/scripts/live-server.mjs+++ b/.opencode/skills/impeccable/scripts/live-server.mjs@@ -28,8 +28,10 @@ import {readLiveBrowserScriptParts,resolveLiveBrowserScriptParts,} from './live/browser-script-parts.mjs';-import { createLiveSessionStore } from './live/session-store.mjs';+import { createLiveSessionStore, GENERATION_FENCED_PHASES } from './live/session-store.mjs';+import { runGenerationPreflight } from './live/generation-preflight.mjs';import { validateEvent } from './live/event-validation.mjs';+import { selectAvailablePendingEvent } from './live/poll-lanes.mjs';import { createManualEditRoutes } from './live/manual-edit-routes.mjs';import { LIVE_COMMANDS } from './live/vocabulary.mjs';import {@@ -63,6 +65,10 @@ const DESIGN_MD_PATH = PROJECT_CONTEXT.designPath: null;const DEFAULT_POLL_TIMEOUT = 600_000; // 10 min — agent re-polls on timeout anywayconst SSE_HEARTBEAT_INTERVAL = 30_000; // keepalive ping every 30s+// The browser checkpoints for several unrelated reasons (see checkpointPayload+// in live-browser.js). Only these two report that variant availability changed,+// and only they may drive variant_progress / the *_reviewable phases.+const VARIANT_PROGRESS_CHECKPOINT_REASONS = new Set(['variants_progress', 'variants_ready']);// ---------------------------------------------------------------------------// Port detection@@ -156,29 +162,206 @@ function restorePendingEventsFromStore() {}}-function findAvailablePendingEvent(now = Date.now()) {- for (const entry of state.pendingEvents) {- if (entry.leaseUntil && entry.leaseUntil > now) continue;- return entry;- }- return null;+function findAvailablePendingEvent(now = Date.now(), types = null) {+ return selectAvailablePendingEvent(state.pendingEvents, { now, types });}-function leaseEvent(entry, leaseMs) {+async function leaseEvent(entry, leaseMs) {+ // Claim the entry before awaiting anything. prepareGenerateEventForLease+ // yields to the event loop, and selectAvailablePendingEvent only skips+ // entries whose lease is in the future — an unclaimed entry would be handed+ // to a second poll in that window and generated twice.+ entry.leaseUntil = Date.now() + leaseMs;+ await prepareGenerateEventForLease(entry);if (!entry.event?.id) {const idx = state.pendingEvents.indexOf(entry);if (idx !== -1) state.pendingEvents.splice(idx, 1);return entry.event;}+ // Re-stamp so the lease window starts when the agent actually receives the+ // work, not when scaffolding began.entry.leaseUntil = Date.now() + leaseMs;+ recordGenerateDelivery(entry);scheduleLeaseFlush();broadcastAgentPollingIfChanged();return entry.event;}-function acknowledgePendingEvent(id) {+function recordGenerateDelivery(entry) {+ const event = entry?.event;+ if (!event || event.type !== 'generate' || event.generationReadyAt) return;+ const at = Date.now();+ entry.event = { ...event, generationReadyAt: at };+ state.sessionStore?.appendEvent(entry.event);+ recordAgentPhase(event.id, 'generation_ready', { at });+}++async function prepareGenerateEventForLease(entry) {+ const event = entry?.event;+ if (!event || event.type !== 'generate' || event.scaffoldAttempted) return;++ recordAgentPhase(event.id, 'picked_up');+ recordAgentPhase(event.id, 'scaffolding');+ const result = await runGenerationPreflight(event, {+ cwd: process.cwd(),+ scriptsDir: __dirname,+ });+ entry.event = {+ ...event,+ scaffoldAttempted: true,+ scaffoldDurationMs: result.durationMs ?? null,+ ...(result.ok ? { scaffold: result.scaffold } : { scaffoldError: result.error || result.reason }),+ };+ state.sessionStore?.appendEvent(entry.event);+ recordAgentPhase(event.id, result.ok ? 'source_ready' : 'scaffold_fallback', {+ durationMs: result.durationMs ?? null,+ previewMode: result.scaffold?.previewMode || 'source',+ });+}++function recordAgentPhase(id, phase, details = {}) {+ if (!id) return;+ const event = {+ type: 'agent_phase',+ id,+ phase,+ at: Date.now(),+ ...details,+ };+ state.sessionStore?.appendEvent(event);+ broadcast(event);+}++/**+ * Detect a browser that missed the generation `done` broadcast.+ *+ * The preflight scaffold write triggers a framework full-reload (Astro reloads+ * the page for any .astro edit). If the agent's variant write + `done` land+ * while the browser is mid-reload, the new page misses both the second HMR+ * reload and the SSE `done` — it resumes from the scaffold-only source and+ * sits in GENERATING at 0/N forever. That resumed page always checkpoints+ * (`browser_resumed`), so a checkpoint claiming "still generating, variants+ * missing" for a session whose generation already completed is direct+ * evidence of the miss. Rebuild the `done` payload from the snapshot so the+ * caller can re-broadcast it; the browser's done handler is idempotent and+ * falls back to injecting variants from source.+ *+ * Keys on the store's monotone `generationCompletedAt`, not `phase` — the+ * behind checkpoint itself regresses `phase` to `generating`, and a browser+ * that misses the redelivered `done` too (another reload) must still trigger+ * redelivery from its next checkpoint.+ */+function detectMissedGenerationCompletion(event) {+ if (!event?.id || event.type !== 'checkpoint') return null;+ if (event.phase !== 'generating') return null;+ if (!variantCountLooksBehind(event.arrivedVariants, event.expectedVariants)) return null;+ if (!state.sessionStore) return null;+ let snapshot = null;+ try {+ snapshot = state.sessionStore.getSnapshot(event.id);+ } catch {+ return null;+ }+ return missedCompletionFromSnapshot(snapshot);+}++function variantCountLooksBehind(arrivedValue, expectedValue) {+ const arrived = Number(arrivedValue) || 0;+ const expected = Number(expectedValue) || 0;+ return arrived <= 0 || (expected > 0 && arrived < expected);+}++function missedCompletionFromSnapshot(snapshot) {+ if (!snapshot?.id || !snapshot.generationCompletedAt) return null;+ if (snapshot.generationCanceled) return null;+ // Accept/discard already underway: the browser is no longer waiting on+ // generation, and a late `done` there would collide with teardown.+ if (GENERATION_FENCED_PHASES.has(snapshot.phase)) return null;+ const file = snapshot.sourceFile || snapshot.previewFile;+ if (!file) return null;+ return {+ type: 'done',+ id: snapshot.id,+ file,+ sourceFile: snapshot.sourceFile || undefined,+ previewFile: snapshot.previewFile || undefined,+ previewMode: snapshot.previewMode || undefined,+ redelivered: true,+ };+}++function recordGenerationCheckpoint(event) {+ if (!event?.id || event.type !== 'checkpoint') return;+ if (generationIsFenced(event.id)) return;+ // Only checkpoints that report a change in variant availability are+ // generation progress. The browser also checkpoints for durability on Tune+ // slider drags, resumes, and anchor recovery; treating those as progress+ // echoed `variant_progress` straight back to the browser that sent it, which+ // remounts the component preview mid-drag (reverting the user's live param+ // edit and detaching the popover's element), and permanently latched the+ // *_reviewable phases from the wrong trigger, corrupting generation timings.+ if (!VARIANT_PROGRESS_CHECKPOINT_REASONS.has(event.reason)) return;+ const arrived = Number(event.arrivedVariants) || 0;+ const expected = Number(event.expectedVariants) || 0;+ if (arrived <= 0 || expected <= 0) return;+ const previewMode = event.previewMode || 'source';+ const previewFile = event.previewFile || event.file;+ if (previewFile) {+ broadcast({+ type: 'variant_progress',+ id: event.id,+ file: previewFile,+ sourceFile: event.sourceFile || (previewMode === 'source' ? previewFile : undefined),+ previewFile,+ previewMode,+ arrivedVariants: arrived,+ expectedVariants: expected,+ publicationKind: event.publicationKind || 'variants',+ });+ }+ const details = {+ arrivedVariants: arrived,+ expectedVariants: expected,+ checkpointReason: event.reason || null,+ };+ const at = Date.now();+ if (!generationPhaseAlreadyRecorded(event.id, 'first_reviewable')) {+ recordAgentPhase(event.id, 'first_reviewable', { ...details, at });+ }+ if (arrived >= 2 && expected >= 3 && !generationPhaseAlreadyRecorded(event.id, 'second_reviewable')) {+ recordAgentPhase(event.id, 'second_reviewable', { ...details, at });+ }+ if (arrived >= expected && !generationPhaseAlreadyRecorded(event.id, 'all_variants_ready')) {+ recordAgentPhase(event.id, 'all_variants_ready', { ...details, at });+ }+}++function generationIsFenced(id) {+ if (!state.sessionStore || !id) return false;+ try {+ const snapshot = state.sessionStore.getSnapshot(id, { includeCompleted: true });+ return snapshot?.generationCanceled === true;+ } catch {+ return false;+ }+}++function generationPhaseAlreadyRecorded(id, phase) {+ if (!state.sessionStore) return false;+ try {+ const snapshot = state.sessionStore.getSnapshot(id, { includeCompleted: true });+ return !!snapshot?.generationTimings?.[phase];+ } catch {+ return false;+ }+}++function acknowledgePendingEvent(id, sourceEventType) {if (!id) return false;- const idx = state.pendingEvents.findIndex((entry) => entry.event?.id === id);+ const idx = state.pendingEvents.findIndex((entry) => (+ entry.event?.id === id+ && (!sourceEventType || entry.event?.type === sourceEventType)+ ));if (idx === -1) return false;const acknowledged = state.pendingEvents[idx].event;state.pendingEvents.splice(idx, 1);@@ -187,9 +370,39 @@ function acknowledgePendingEvent(id) {return acknowledged;}-function findPendingEventById(id) {+function releasePendingEvent(id, sourceEventType) {+ const entry = state.pendingEvents.find((item) => (+ item.event?.id === id+ && (!sourceEventType || item.event?.type === sourceEventType)+ ));+ if (!entry) return null;+ entry.leaseUntil = 0;+ scheduleLeaseFlush();+ return entry.event;+}++function retirePendingGeneration(id) {+ if (!id) return 0;+ let retired = 0;+ for (let index = state.pendingEvents.length - 1; index >= 0; index -= 1) {+ const event = state.pendingEvents[index]?.event;+ if (event?.id !== id || event.type !== 'generate') continue;+ state.pendingEvents.splice(index, 1);+ retired += 1;+ }+ if (retired > 0) {+ scheduleLeaseFlush();+ broadcastAgentPollingIfChanged();+ }+ return retired;+}++function findPendingEventById(id, sourceEventType) {if (!id) return null;- const entry = state.pendingEvents.find((item) => item.event?.id === id);+ const entry = state.pendingEvents.find((item) => (+ item.event?.id === id+ && (!sourceEventType || item.event?.type === sourceEventType)+ ));return entry?.event || null;}@@ -198,7 +411,7 @@ function summarizePendingEventForStatus(entry) {const summary = {id: event.id,type: event.type,- leased: !!(entry.leaseUntil && entry.leaseUntil > Date.now()),+ leased: isLeased(entry),leaseUntil: entry.leaseUntil || null,};if (event.type === 'manual_edit_apply') {@@ -224,7 +437,13 @@ function summarizeActiveSessionForClient(snapshot = {}) {arrivedVariants: snapshot.arrivedVariants ?? 0,visibleVariant: snapshot.visibleVariant ?? null,checkpointRevision: snapshot.checkpointRevision ?? 0,+ browserCheckpointRevision: snapshot.browserCheckpointRevision ?? snapshot.checkpointRevision ?? 0,+ publicationCheckpointRevision: snapshot.publicationCheckpointRevision ?? 0,paramValues: snapshot.paramValues || {},+ generationPhase: snapshot.generationPhase ?? null,+ generationCompletedAt: snapshot.generationCompletedAt ?? null,+ generationCanceled: snapshot.generationCanceled === true,+ cancelReason: snapshot.cancelReason ?? null,};}@@ -269,24 +488,46 @@ function scheduleLeaseFlush() {function flushPendingPolls() {let changed = false;while (state.pendingPolls.length > 0) {- const entry = findAvailablePendingEvent();+ let pollIndex = -1;+ let entry = null;+ for (let index = 0; index < state.pendingPolls.length; index += 1) {+ const candidate = findAvailablePendingEvent(Date.now(), state.pendingPolls[index].types);+ if (!candidate) continue;+ pollIndex = index;+ entry = candidate;+ break;+ }if (!entry) {scheduleLeaseFlush();broadcastAgentPollingIfChanged();return;}- const poll = state.pendingPolls.shift();- poll.resolve(leaseEvent(entry, poll.leaseMs));+ const [poll] = state.pendingPolls.splice(pollIndex, 1);+ // leaseEvent is async (it may scaffold source), but it claims the entry+ // synchronously, so the next loop iteration will not re-select it. Resolve+ // the poll when the lease settles rather than awaiting here, so one slow+ // scaffold never delays the other parked polls. On the exceptional failure+ // path, answer `timeout` so the agent re-polls; the claim stays until the+ // lease expires, which keeps a deterministic failure from hot-looping.+ leaseEvent(entry, poll.leaseMs).then(poll.resolve, (error) => {+ console.error('[live] lease failed for ' + (entry.event?.id || 'unknown') + ': ' + (error?.message || error));+ poll.resolve({ type: 'timeout' });+ });changed = true;}scheduleLeaseFlush();if (changed) broadcastAgentPollingIfChanged();}+function isLeased(entry) {+ return !!(entry?.leaseUntil && entry.leaseUntil > Date.now());+}+function agentPollingConnected() {- const now = Date.now();- return state.pendingPolls.length > 0- || state.pendingEvents.some((entry) => entry.leaseUntil && entry.leaseUntil > now);+ // A leased event only proves that a poll returned once. The foreground task+ // may have ended immediately afterward, so only an actively waiting poll is+ // evidence that steering can wake the task right now.+ return state.pendingPolls.length > 0;}function broadcastAgentPollingIfChanged() {@@ -689,6 +930,16 @@ function createRequestHandler({ detectScript, liveScriptParts }) {res.end(JSON.stringify({ error }));return;}+ if (msg.type === 'agent_phase') {+ recordAgentPhase(msg.id, msg.phase, {+ ...(Number.isFinite(msg.durationMs) ? { durationMs: msg.durationMs } : {}),+ owner: typeof msg.owner === 'string' ? msg.owner : undefined,+ });+ res.writeHead(200, { 'Content-Type': 'application/json' });+ res.end(JSON.stringify({ ok: true }));+ return;+ }+ const missedCompletion = detectMissedGenerationCompletion(msg);if (state.sessionStore && msg.id) {try {state.sessionStore.appendEvent(msg);@@ -698,6 +949,11 @@ function createRequestHandler({ detectScript, liveScriptParts }) {return;}}+ if (msg.type === 'accept' || msg.type === 'discard') {+ retirePendingGeneration(msg.id);+ }+ recordGenerationCheckpoint(msg);+ if (missedCompletion) broadcast(missedCompletion);if (msg.type === 'exit') {cleanupSvelteComponentSessionsBeforeExit();}@@ -738,6 +994,12 @@ function createRequestHandler({ detectScript, liveScriptParts }) {// Agent poll endpoints (unchanged from WS version)// ---------------------------------------------------------------------------+function parsePollTypes(value) {+ if (!value) return null;+ const types = String(value).split(',').map((type) => type.trim()).filter(Boolean);+ return types.length > 0 ? new Set(types) : null;+}+function handlePollGet(req, res, url) {const token = url.searchParams.get('token');if (token !== state.token) {@@ -748,13 +1010,25 @@ function handlePollGet(req, res, url) {state.lastPollAt = Date.now();const timeout = parseInt(url.searchParams.get('timeout') || DEFAULT_POLL_TIMEOUT, 10);const leaseMs = parseInt(url.searchParams.get('leaseMs') || '30000', 10);- const available = findAvailablePendingEvent();+ const types = parsePollTypes(url.searchParams.get('types'));+ const available = findAvailablePendingEvent(Date.now(), types);if (available) {- res.writeHead(200, { 'Content-Type': 'application/json' });- res.end(JSON.stringify(leaseEvent(available, leaseMs)));+ // Do not await inline: leaseEvent may scaffold source, and this handler runs+ // on the server's only thread. The client can disconnect during that window,+ // so check the socket before replying.+ leaseEvent(available, leaseMs).then((event) => {+ if (res.writableEnded || res.destroyed) return;+ res.writeHead(200, { 'Content-Type': 'application/json' });+ res.end(JSON.stringify(event));+ }, (error) => {+ console.error('[live] lease failed for ' + (available.event?.id || 'unknown') + ': ' + (error?.message || error));+ if (res.writableEnded || res.destroyed) return;+ res.writeHead(200, { 'Content-Type': 'application/json' });+ res.end(JSON.stringify({ type: 'timeout' }));+ });return;}- const poll = { resolve, leaseMs };+ const poll = { resolve, leaseMs, types };const timer = setTimeout(() => {const idx = state.pendingPolls.indexOf(poll);if (idx !== -1) state.pendingPolls.splice(idx, 1);@@ -783,12 +1057,15 @@ function sessionFileMetadataFromPollReply(file) {if (!file || typeof file !== 'string') return { file };const normalized = file.split(path.sep).join('/');const base = { file: normalized };- if (!normalized.endsWith('/manifest.json') && normalized !== 'manifest.json') return base;- if (!normalized.includes('node_modules/.impeccable-live/') && !normalized.includes('src/lib/impeccable/')) return base;+ const metadataFile = normalized;+ if (!metadataFile.endsWith('/manifest.json') && metadataFile !== 'manifest.json') return base;+ if (!metadataFile.includes('node_modules/.impeccable-live/')+ && !metadataFile.includes('src/lib/impeccable/')+ && !metadataFile.includes('/.impeccable-live/')) return base;let full;try {- full = path.resolve(process.cwd(), normalized);+ full = path.resolve(process.cwd(), metadataFile);const rel = path.relative(process.cwd(), full);if (!rel || rel.startsWith('..') || path.isAbsolute(rel)) return base;} catch {@@ -797,18 +1074,47 @@ function sessionFileMetadataFromPollReply(file) {try {const manifest = JSON.parse(fs.readFileSync(full, 'utf-8'));- if (manifest?.previewMode !== 'svelte-component' || !manifest.sourceFile) return base;+ if (manifest?.previewMode !== 'svelte-component'+ || !manifest.sourceFile) return base;return {file: String(manifest.sourceFile).split(path.sep).join('/'),sourceFile: String(manifest.sourceFile).split(path.sep).join('/'),previewFile: normalized,- previewMode: 'svelte-component',+ previewMode: manifest.previewMode,};} catch {return base;}}+function inferSourceEventType(msg = {}, pendingEvents = state.pendingEvents) {+ const entriesForId = pendingEvents.filter((entry) => entry.event?.id === msg.id);+ const pendingTypes = new Set(entriesForId.map((entry) => entry.event?.type));+ if (msg.type === 'discarded' || msg.type === 'discard') return 'discard';+ if (msg.type === 'complete') {+ if (pendingTypes.has('carbonize_cleanup')) return 'carbonize_cleanup';+ return pendingTypes.has('accept') ? 'accept' : (pendingTypes.has('generate') ? 'generate' : undefined);+ }+ if (msg.type === 'steer_done') return 'steer';+ // `agent_done` can be the automatic acknowledgement for a carbonize Accept.+ // New pollers send sourceEventType explicitly; default to generate only for+ // older callers so a late worker cannot acknowledge a queued Accept.+ if (msg.type === 'agent_done' || msg.type === 'done') return 'generate';+ // `error` is reference/live.md's documented failure reply, and parseReplyArgs+ // never sets sourceEventType on it (the poller is a fresh process that cannot+ // know what it leased). Returning undefined here makes acknowledgePendingEvent+ // match *any* event for this id: a stale generate worker's failure silently+ // consumed the user's queued Accept, which was then never delivered to any+ // agent and left the browser in SAVING forever. Attribute the failure to the+ // event this agent actually holds a lease on, and otherwise to `generate` —+ // never to a wildcard. If that generate was already retired by an Accept, the+ // ack simply finds no match, which is the correct outcome for a stale reply.+ if (msg.type === 'error') {+ return entriesForId.find(isLeased)?.event?.type || 'generate';+ }+ return undefined;+}+function handlePollPost(req, res) {let body = '';req.on('data', (c) => { body += c; });@@ -869,7 +1175,23 @@ function handlePollPost(req, res) {res.end(JSON.stringify({ error: 'stale_manual_edit_apply_reply', ...rollback }));return;}- const pendingEventBeforeAck = findPendingEventById(msg.id);+ const sourceEventType = msg.sourceEventType || inferSourceEventType(msg);+ if (msg.type === 'retry') {+ const releasedEvent = releasePendingEvent(msg.id, sourceEventType);+ if (!releasedEvent) {+ res.writeHead(msg.id ? 404 : 400, { 'Content-Type': 'application/json' });+ res.end(JSON.stringify({+ error: msg.id ? 'unknown_poll_retry_id' : 'missing_poll_retry_id',+ id: msg.id,+ }));+ return;+ }+ flushPendingPolls();+ res.writeHead(200, { 'Content-Type': 'application/json' });+ res.end(JSON.stringify({ ok: true, released: true }));+ return;+ }+ const pendingEventBeforeAck = findPendingEventById(msg.id, sourceEventType);if (pendingEventBeforeAck?.type === 'steer' && msg.type === 'steer_done'&& !msg.file && !(typeof msg.message === 'string' && msg.message.trim())) {res.writeHead(400, { 'Content-Type': 'application/json' });@@ -879,7 +1201,7 @@ function handlePollPost(req, res) {}));return;}- const acknowledgedEvent = acknowledgePendingEvent(msg.id);+ const acknowledgedEvent = acknowledgePendingEvent(msg.id, sourceEventType);let skipJournalReply = false;let existingSession = null;if (!acknowledgedEvent && state.sessionStore && msg.id) {@@ -1083,7 +1405,10 @@ if (args.includes('--background')) {process.exit(0);}} catch { /* not ready yet */ }- await new Promise(r => setTimeout(r, 200));+ // The detached child is typically listening in 35-45ms. A 200ms polling+ // floor dominated configured cold Live startup; poll cheaply and return+ // as soon as the child has written its ready record.+ await new Promise(r => setTimeout(r, 5));}console.error('Timed out waiting for live server to start.');process.exit(1);diff --git a/.opencode/skills/impeccable/scripts/live-status.mjs b/.opencode/skills/impeccable/scripts/live-status.mjsindex f7e464999..dc98b7386 100644--- a/.opencode/skills/impeccable/scripts/live-status.mjs+++ b/.opencode/skills/impeccable/scripts/live-status.mjs@@ -37,15 +37,19 @@ export async function statusCli() {pendingEvents: server.pendingEvents,} : null,activeSessions: server?.activeSessions || activeSessions,- recoveryHint: manualApply- ? manualApplyResumeHint(manualApply)- : server- ? 'Run live-poll.mjs to continue pending work, or live-complete.mjs --id <session> after manual cleanup.'- : 'Start live-server.mjs to requeue pending durable events, then run live-poll.mjs.',+ recoveryHint: recoveryHint({ server, manualApply }),};console.log(JSON.stringify(payload, null, 2));}+function recoveryHint({ server, manualApply }) {+ if (manualApply) return manualApplyResumeHint(manualApply);+ if (server) {+ return 'Run live-poll.mjs to continue pending work, or live-complete.mjs --id <session> after manual cleanup.';+ }+ return 'Start live-server.mjs to requeue pending durable events, then run live-poll.mjs.';+}+function findPendingManualApply(server, activeSessions) {const fromServer = server?.pendingEvents?.find((event) => event?.type === 'manual_edit_apply');if (fromServer) return fromServer;diff --git a/.opencode/skills/impeccable/scripts/live-wrap.mjs b/.opencode/skills/impeccable/scripts/live-wrap.mjsindex 438c01b68..48d7f7683 100644--- a/.opencode/skills/impeccable/scripts/live-wrap.mjs+++ b/.opencode/skills/impeccable/scripts/live-wrap.mjs@@ -160,11 +160,29 @@ The agent should insert variant HTML at insertLine.`);if (filtered.length === 1) {match = filtered[0];} else if (filtered.length === 0) {- // Source uses dynamic content (`<h1>{title}</h1>` etc.) so the- // browser-side textContent doesn't appear literally in source. Fall- // back to first-match rather than refusing — this is the same- // behavior unmodified callers see, just preserved.- match = candidates[0];+ const normalizedText = String(text).replace(/\s+/g, ' ').trim();+ if (normalizedText.length < 8) {+ // Very short labels cannot disambiguate siblings reliably. Preserve+ // the legacy behavior for these low-information picker events.+ match = candidates[0];+ } else {+ // Rendered text that is absent from every candidate usually means+ // the source uses expressions or component props. Picking the first+ // same-class sibling silently edits the wrong instance (observed on+ // Astro result cards), so stop and surface every candidate instead.+ console.error(JSON.stringify({+ error: 'element_ambiguous',+ fallback: 'agent-driven',+ reason: 'rendered_text_not_in_source',+ file: path.relative(process.cwd(), targetFile),+ candidates: candidates.map((c) => ({+ startLine: c.startLine + 1,+ endLine: c.endLine + 1,+ })),+ hint: 'Rendered text does not occur in any matching source branch. The element may use dynamic props or expressions; inspect the candidates and wrap the intended instance manually.',+ }));+ process.exit(1);+ }} else {// Multiple candidates ALSO match the text. Truly ambiguous — refuse// rather than pick wrong, and hand the agent the candidate locations@@ -269,6 +287,7 @@ The agent should insert variant HTML at insertLine.`);const originalIndented = reindentOriginal(' ');const relTargetFile = path.relative(process.cwd(), targetFile).split(path.sep).join('/');const useSvelteComponent = shouldUseSvelteComponentInjection(targetFile);+ const useFrameworkComponent = useSvelteComponent;// Wrapper attributes differ by syntax. HTML allows plain string attrs;// JSX requires object-literal style and parses string attrs as HTML (which@@ -288,7 +307,7 @@ The agent should insert variant HTML at insertLine.`);// replacement range to include the wrapper's `<div>` open / close lines// so the entire scaffold gets removed cleanly.const wrapperLines = isJsx ? [- indent + '<div data-impeccable-variants="' + id + '" data-impeccable-variant-count="' + count + '" ' + styleContents + '>',+ indent + '<div data-impeccable-variants="' + id + '" data-impeccable-variant-count="' + count + '"' + ' ' + styleContents + '>',indent + ' ' + commentSyntax.open + ' impeccable-variants-start ' + id + ' ' + commentSyntax.close,indent + ' ' + commentSyntax.open + ' Original ' + commentSyntax.close,indent + ' <div data-impeccable-variant="original">',@@ -299,7 +318,7 @@ The agent should insert variant HTML at insertLine.`);indent + '</div>',] : [indent + commentSyntax.open + ' impeccable-variants-start ' + id + ' ' + commentSyntax.close,- indent + '<div data-impeccable-variants="' + id + '" data-impeccable-variant-count="' + count + '" ' + styleContents + '>',+ indent + '<div data-impeccable-variants="' + id + '" data-impeccable-variant-count="' + count + '"' + ' ' + styleContents + '>',indent + ' ' + commentSyntax.open + ' Original ' + commentSyntax.close,indent + ' <div data-impeccable-variant="original">',originalIndented,@@ -356,15 +375,18 @@ The agent should insert variant HTML at insertLine.`);const outputRelFile = path.relative(process.cwd(), outputFile).split(path.sep).join('/');const svelteComponentAuthoring = useSvelteComponent ? buildSvelteComponentCssAuthoring(count) : null;+ const componentSession = svelteSession;+ const componentPreviewMode = useSvelteComponent ? 'svelte-component' : undefined;+ const previewMode = componentPreviewMode;console.log(JSON.stringify({file: outputRelFile,- sourceFile: useSvelteComponent ? relTargetFile : undefined,- previewMode: useSvelteComponent ? 'svelte-component' : undefined,- componentDir: svelteSession?.componentDir,- propContract: svelteSession?.propContract,- sourceStartLine: useSvelteComponent ? startLine + 1 : undefined,- sourceEndLine: useSvelteComponent ? endLine + 1 : undefined,+ sourceFile: useFrameworkComponent ? relTargetFile : undefined,+ previewMode,+ componentDir: componentSession?.componentDir,+ propContract: componentSession?.propContract,+ sourceStartLine: useFrameworkComponent ? startLine + 1 : undefined,+ sourceEndLine: useFrameworkComponent ? endLine + 1 : undefined,startLine: outputStartLine, // 1-indexed for the agent// wrapperLines is an array but one element (the original-content slot)// is a `\n`-joined multi-line string, so the actual file-row count is@@ -374,10 +396,10 @@ The agent should insert variant HTML at insertLine.`);endLine: outputEndLine, // 1-indexedinsertLine, // 1-indexed: where variants gocommentSyntax: commentSyntax,- styleMode: useSvelteComponent ? 'svelte-component' : styleMode.mode,- styleTag: useSvelteComponent ? null : styleMode.styleTag,- cssSelectorPrefixExamples: useSvelteComponent ? [] : buildCssSelectorPrefixExamples(styleMode.mode, count),- cssAuthoring: useSvelteComponent ? svelteComponentAuthoring : buildCssAuthoring(styleMode, count),+ styleMode: componentPreviewMode || styleMode.mode,+ styleTag: useFrameworkComponent ? null : styleMode.styleTag,+ cssSelectorPrefixExamples: useFrameworkComponent ? [] : buildCssSelectorPrefixExamples(styleMode.mode, count),+ cssAuthoring: svelteComponentAuthoring || buildCssAuthoring(styleMode, count),originalLineCount: originalLines.length,}));}diff --git a/.opencode/skills/impeccable/scripts/live.mjs b/.opencode/skills/impeccable/scripts/live.mjsindex e0bd1ad24..b21a71cc4 100644--- a/.opencode/skills/impeccable/scripts/live.mjs+++ b/.opencode/skills/impeccable/scripts/live.mjs@@ -10,7 +10,7 @@** After this, the agent's only remaining steps are:* - Open the project's live dev/preview URL in the browser (optional, if browser automation exists)—not `serverPort`; that port is the Impeccable helper for /live.js and /poll- * - Enter the poll loop: `node live-poll.mjs`+ * - Enter the harness-native poll loop: `node live-poll.mjs`** Usage:* node live.mjs # Prepare everything, print JSON, exit@@ -40,6 +40,7 @@ Prepare everything for live variant mode in a single command:- Starts (or reuses) the live server in the background- Injects the browser script tag- Reads PRODUCT.md / DESIGN.md for project context+ - Prepares the harness-native foreground/background poll loop- In monorepos, choose a child app first; --target <path> is the fallback/manual pathOn success, prints a JSON blob with:diff --git a/.opencode/skills/impeccable/scripts/live/completion.mjs b/.opencode/skills/impeccable/scripts/live/completion.mjsindex 986773066..6f539336d 100644--- a/.opencode/skills/impeccable/scripts/live/completion.mjs+++ b/.opencode/skills/impeccable/scripts/live/completion.mjs@@ -1,9 +1,18 @@+// A preview whose variants live in component modules rather than in the user's+// source. These leave no markers in the real file, so a failed accept gives the+// agent nothing to hand-edit and must be reported as a failure rather than+// reference/live.md's manual-cleanup handoff. Kept as a set: any future+// component-module preview mode belongs here the day it lands.+const PREVIEW_MODES_WITHOUT_SOURCE_MARKERS = new Set([+ 'svelte-component',+]);+export function completionTypeForAcceptResult(eventType, acceptResult) {if (eventType === 'discard') return acceptResult?.handled === true ? 'discarded' : 'error';if (acceptResult?.handled === true && acceptResult?.carbonize === true) return 'agent_done';if (acceptResult?.handled === true) return 'complete';if (acceptResult?.mode === 'error') return 'error';- if (eventType === 'accept' && acceptResult?.previewMode === 'svelte-component') return 'error';+ if (eventType === 'accept' && PREVIEW_MODES_WITHOUT_SOURCE_MARKERS.has(acceptResult?.previewMode)) return 'error';return 'agent_done';}diff --git a/.opencode/skills/impeccable/scripts/live/event-validation.mjs b/.opencode/skills/impeccable/scripts/live/event-validation.mjsindex 0897b1317..122c29836 100644--- a/.opencode/skills/impeccable/scripts/live/event-validation.mjs+++ b/.opencode/skills/impeccable/scripts/live/event-validation.mjs@@ -118,6 +118,15 @@ export function validateEvent(msg) {return 'checkpoint: paramValues must be an object';}return null;+ case 'agent_phase':+ if (!isValidId(msg.id)) return 'agent_phase: missing or malformed id';+ if (typeof msg.phase !== 'string' || !/^[a-z][a-z0-9_]{1,63}$/.test(msg.phase)) {+ return 'agent_phase: missing or malformed phase';+ }+ if (msg.durationMs !== undefined && (!Number.isFinite(msg.durationMs) || msg.durationMs < 0)) {+ return 'agent_phase: durationMs must be a non-negative number';+ }+ return null;case 'exit':return null;case 'prefetch':@@ -131,6 +140,12 @@ export function validateEvent(msg) {if (msg.message.length > 4000) return 'steer: message too long';if (msg.pageUrl !== undefined && typeof msg.pageUrl !== 'string') return 'steer: pageUrl must be string';return null;+ case 'carbonize_cleanup':+ if (!isValidId(msg.id)) return 'carbonize_cleanup: missing or malformed id';+ if (!isValidId(msg.sessionId)) return 'carbonize_cleanup: missing or malformed sessionId';+ if (!msg.file || typeof msg.file !== 'string') return 'carbonize_cleanup: missing file';+ if (!isValidVariantId(String(msg.variantId))) return 'carbonize_cleanup: missing or malformed variantId';+ return null;default:return 'Unknown event type: ' + msg.type;}diff --git a/.opencode/skills/impeccable/scripts/live/generation-preflight.mjs b/.opencode/skills/impeccable/scripts/live/generation-preflight.mjsnew file mode 100644index 000000000..07a5e957e--- /dev/null+++ b/.opencode/skills/impeccable/scripts/live/generation-preflight.mjs@@ -0,0 +1,102 @@+import { execFile } from 'node:child_process';+import path from 'node:path';+import { promisify } from 'node:util';++const execFileAsync = promisify(execFile);+const PREFLIGHT_TIMEOUT_MS = 15_000;++export function buildGenerationPreflight(event, scriptsDir) {+ if (!event || event.type !== 'generate' || !event.id) return null;++ const isInsert = event.mode === 'insert';+ const target = isInsert ? insertTarget(event) : replaceTarget(event);+ if (!target.elementId && !target.classes) return null;++ const script = path.join(scriptsDir, isInsert ? 'live-insert.mjs' : 'live-wrap.mjs');+ const args = [script, '--id', event.id, '--count', String(event.count || 3)];+ if (isInsert) args.push('--position', target.position);+ if (target.elementId) args.push('--element-id', target.elementId);+ if (target.classes) args.push('--classes', target.classes);+ if (target.tag) args.push('--tag', target.tag);+ if (target.text) args.push('--text', target.text);+ if (!isInsert && event.pageUrl) args.push('--page-url', event.pageUrl);+ return { script, args, mode: isInsert ? 'insert' : 'replace' };+}++/**+ * Scaffold the source for a generate event before handing it to an agent.+ *+ * Async on purpose. This spawns `live-wrap.mjs`, which walks the project's+ * source tree and can take seconds (measured at ~7.6s on a large repo when the+ * element is not found, with a 15s ceiling). The live server is single-threaded+ * and calls this while leasing a poll, so a synchronous spawn froze the whole+ * server for that entire window: Accept and Discard POSTs, SSE progress+ * broadcasts, and every other poll stalled behind it.+ */+export async function runGenerationPreflight(event, {+ cwd = process.cwd(),+ scriptsDir,+ execFileImpl = execFileAsync,+ timeoutMs = PREFLIGHT_TIMEOUT_MS,+} = {}) {+ const command = buildGenerationPreflight(event, scriptsDir);+ if (!command) {+ return { ok: false, skipped: true, reason: 'insufficient_locator' };+ }++ const startedAt = performance.now();+ try {+ const { stdout } = await execFileImpl(process.execPath, command.args, {+ cwd,+ encoding: 'utf-8',+ timeout: timeoutMs,+ });+ const line = String(stdout).trim().split('\n').filter(Boolean).pop();+ if (!line) throw new Error('preflight returned no scaffold metadata');+ return {+ ok: true,+ mode: command.mode,+ durationMs: performance.now() - startedAt,+ scaffold: JSON.parse(line),+ };+ } catch (error) {+ return {+ ok: false,+ mode: command.mode,+ durationMs: performance.now() - startedAt,+ error: compactError(error),+ };+ }+}++function replaceTarget(event) {+ return normalizeTarget(event.element || {});+}++function insertTarget(event) {+ return {+ ...normalizeTarget(event.insert?.anchor || {}),+ position: event.insert?.position === 'before' ? 'before' : 'after',+ };+}++function normalizeTarget(target) {+ const classes = Array.isArray(target.classes)+ ? target.classes.join(' ')+ : String(target.classes || '').trim();+ const text = typeof target.textContent === 'string'+ ? target.textContent.trim().slice(0, 80)+ : '';+ return {+ elementId: target.id || target.elementId || undefined,+ classes: classes || undefined,+ tag: target.tagName || target.tag || undefined,+ text: text || undefined,+ };+}++function compactError(error) {+ const stderr = error?.stderr ? String(error.stderr).trim() : '';+ const message = stderr.split('\n').filter(Boolean).pop() || error?.message || 'preflight failed';+ return String(message).slice(0, 500);+}diff --git a/.opencode/skills/impeccable/scripts/live/poll-lanes.mjs b/.opencode/skills/impeccable/scripts/live/poll-lanes.mjsnew file mode 100644index 000000000..65f20a87a--- /dev/null+++ b/.opencode/skills/impeccable/scripts/live/poll-lanes.mjs@@ -0,0 +1,14 @@+export function eventPriority(event = {}) {+ if (event.type === 'accept' || event.type === 'discard' || event.type === 'exit') return 0;+ if (event.type === 'manual_edit_apply' || event.type === 'steer' || event.type === 'carbonize_cleanup') return 1;+ if (event.type === 'generate') return 2;+ return 3;+}++export function selectAvailablePendingEvent(entries, { now = Date.now(), types = null } = {}) {+ const allowed = types instanceof Set ? types : (Array.isArray(types) ? new Set(types) : null);+ return entries+ .filter((entry) => !(entry.leaseUntil && entry.leaseUntil > now))+ .filter((entry) => !allowed || allowed.has(entry.event?.type))+ .sort((a, b) => eventPriority(a.event) - eventPriority(b.event) || a.seq - b.seq)[0] || null;+}diff --git a/.opencode/skills/impeccable/scripts/live/session-store.mjs b/.opencode/skills/impeccable/scripts/live/session-store.mjsindex affba67c9..9d20341dd 100644--- a/.opencode/skills/impeccable/scripts/live/session-store.mjs+++ b/.opencode/skills/impeccable/scripts/live/session-store.mjs@@ -1,24 +1,26 @@import fs from 'node:fs';import path from 'node:path';-import { getLegacyLiveSessionsDir, getLiveSessionsDir } from '../lib/impeccable-paths.mjs';+import { getLegacyLiveSessionsDir, getLiveSessionsDir, safeSessionId } from '../lib/impeccable-paths.mjs';const COMPLETED_PHASES = new Set(['completed', 'discarded']);+export const GENERATION_FENCED_PHASES = new Set([+ 'accept_requested',+ 'discard_requested',+ 'carbonize_required',+ 'completed',+ 'discarded',+]);export function createLiveSessionStore({ cwd = process.cwd(), sessionId } = {}) {const rootDir = getLiveSessionsDir(cwd);const legacyRootDir = getLegacyLiveSessionsDir(cwd);fs.mkdirSync(rootDir, { recursive: true });- const snapshotCache = new Map();-- function loadCachedOrRebuild(id) {- const cached = snapshotCache.get(id);- if (cached) return cached;- const journalPath = getReadableJournalPath(id);- const rebuilt = rebuildSnapshotFromJournal(journalPath, id);- snapshotCache.set(id, rebuilt);- return rebuilt;- }+ // No snapshot cache on purpose: appendEvent and getSnapshot both rebuild from+ // the journal so sequence numbers and phase fences never come from a stale+ // in-memory copy when the publisher/complete helpers append from another+ // process. A cache written but never read would grow per session for the+ // lifetime of the server without ever saving a rebuild.function getReadableJournalPath(id) {const primary = getJournalPath(rootDir, id);if (fs.existsSync(primary)) return primary;@@ -38,7 +40,10 @@ export function createLiveSessionStore({ cwd = process.cwd(), sessionId } = {})if (!fs.existsSync(journalPath) && fs.existsSync(legacyJournalPath)) {fs.copyFileSync(legacyJournalPath, journalPath);}- const prior = loadCachedOrRebuild(normalized.id);+ // Publisher/complete helpers can append from a separate process while+ // the server is alive. Rebuild here so sequence numbers and phase+ // fences never come from a stale in-memory cache.+ const prior = rebuildSnapshotFromJournal(getReadableJournalPath(normalized.id), normalized.id);const seq = prior.nextSeq;const entry = {seq,@@ -49,7 +54,6 @@ export function createLiveSessionStore({ cwd = process.cwd(), sessionId } = {})};fs.appendFileSync(journalPath, JSON.stringify(entry) + '\n');const next = applyEvent(prior.snapshot, entry, prior.diagnostics);- snapshotCache.set(normalized.id, { snapshot: next, diagnostics: next.diagnostics || [], nextSeq: seq + 1 });writeSnapshot(snapshotPath, next);return next;},@@ -58,7 +62,6 @@ export function createLiveSessionStore({ cwd = process.cwd(), sessionId } = {})const journalPath = getReadableJournalPath(id);const snapshotPath = getSnapshotPath(rootDir, id);const rebuilt = rebuildSnapshotFromJournal(journalPath, id);- snapshotCache.set(id, rebuilt);writeSnapshot(snapshotPath, rebuilt.snapshot);if (!opts.includeCompleted && COMPLETED_PHASES.has(rebuilt.snapshot.phase)) return null;return rebuilt.snapshot;@@ -95,11 +98,6 @@ function getSnapshotPath(rootDir, id) {return path.join(rootDir, safeSessionId(id) + '.snapshot.json');}-function safeSessionId(id) {- if (!/^[A-Za-z0-9_-]{1,128}$/.test(id)) throw new Error('invalid session id: ' + id);- return id;-}-function baseSnapshot(id) {return {id,@@ -116,9 +114,18 @@ function baseSnapshot(id) {pendingEvent: null,deliveryLease: null,checkpointRevision: 0,+ browserCheckpointRevision: 0,+ publicationCheckpointRevision: 0,activeOwner: null,sourceMarkers: {},fallbackMode: null,+ generationPhase: null,+ generationCompletedAt: null,+ generationTimings: {},+ variantPlan: null,+ generationCanceled: false,+ generationCanceledAt: null,+ cancelReason: null,annotationArtifacts: [],diagnostics: [],updatedAt: null,@@ -158,6 +165,8 @@ function applyEvent(snapshot, entry, inheritedDiagnostics = []) {...snapshot,paramValues: { ...(snapshot.paramValues || {}) },sourceMarkers: { ...(snapshot.sourceMarkers || {}) },+ generationTimings: { ...(snapshot.generationTimings || {}) },+ variantPlan: snapshot.variantPlan || null,annotationArtifacts: [...(snapshot.annotationArtifacts || [])],diagnostics: [...(snapshot.diagnostics || [])],updatedAt: entry.ts || new Date().toISOString(),@@ -174,11 +183,48 @@ function applyEvent(snapshot, entry, inheritedDiagnostics = []) {next.expectedVariants = event.count ?? next.expectedVariants;next.pendingEventSeq = entry.seq ?? next.pendingEventSeq;next.pendingEvent = toPendingEvent(event);+ next.variantPlan = null;if (event.screenshotPath) upsertArtifact(next.annotationArtifacts, { type: 'screenshot', path: event.screenshotPath });break;+ case 'variant_plan':+ if (!next.generationCanceled && !GENERATION_FENCED_PHASES.has(next.phase)) {+ next.variantPlan = event.plan ?? next.variantPlan;+ }+ break;+ case 'detector_waivers':+ if (!next.generationCanceled && !GENERATION_FENCED_PHASES.has(next.phase)) {+ next.detectorWaivers = [+ ...(next.detectorWaivers || []),+ ...(Array.isArray(event.waivers) ? event.waivers : []),+ ];+ }+ break;+ case 'agent_phase':+ next.generationPhase = event.phase ?? next.generationPhase;+ if (event.phase) {+ next.generationTimings[event.phase] = {+ at: event.at ?? (Date.parse(entry.ts || '') || null),+ durationMs: event.durationMs ?? null,+ };+ }+ break;case 'variants_ready':case 'agent_done':+ if ((next.generationCanceled || GENERATION_FENCED_PHASES.has(next.phase))+ && !(event.type === 'agent_done' && event.carbonize === true && next.phase === 'accept_requested')) {+ next.diagnostics.push({+ error: 'late_generation_event_ignored',+ type: event.type,+ phase: next.phase,+ });+ break;+ }next.phase = event.carbonize === true ? 'carbonize_required' : 'variants_ready';+ // Durable completion marker: later browser checkpoints (a resumed page+ // reporting phase "generating") regress `phase`, but generation staying+ // finished is monotone — the live server keys missed-`done` redelivery+ // on this field.+ next.generationCompletedAt = event.at ?? (Date.parse(entry.ts || '') || Date.now());next.sourceFile = event.sourceFile ?? event.file ?? next.sourceFile;next.previewFile = event.previewFile ?? next.previewFile;next.previewMode = event.previewMode ?? next.previewMode;@@ -194,27 +240,45 @@ function applyEvent(snapshot, entry, inheritedDiagnostics = []) {}break;case 'checkpoint':- if (COMPLETED_PHASES.has(next.phase)) {+ if (next.generationCanceled || GENERATION_FENCED_PHASES.has(next.phase)) {next.diagnostics.push({ error: 'checkpoint_after_terminal_ignored', phase: event.phase ?? null, revision: event.revision ?? null });break;}- if ((event.revision ?? 0) >= (next.checkpointRevision ?? 0)) {- next.phase = event.phase ?? next.phase;- next.checkpointRevision = event.revision ?? next.checkpointRevision;- next.activeOwner = event.owner ?? next.activeOwner;- next.arrivedVariants = event.arrivedVariants ?? next.arrivedVariants;- next.visibleVariant = event.visibleVariant ?? next.visibleVariant;- next.sourceFile = event.sourceFile ?? next.sourceFile;- next.previewFile = event.previewFile ?? next.previewFile;- next.previewMode = event.previewMode ?? next.previewMode;- if (event.paramValues) next.paramValues = { ...event.paramValues };- } else {- next.diagnostics.push({ error: 'stale_checkpoint_ignored', revision: event.revision });+ {+ const revisionDomain = event.revisionDomain === 'publication'+ || (event.reason === 'variants_progress' && !event.owner)+ ? 'publication'+ : 'browser';+ const revisionField = revisionDomain === 'publication'+ ? 'publicationCheckpointRevision'+ : 'browserCheckpointRevision';+ const currentRevision = next[revisionField]+ ?? (revisionDomain === 'browser' ? next.checkpointRevision : 0)+ ?? 0;+ if ((event.revision ?? 0) >= currentRevision) {+ next.phase = event.phase ?? next.phase;+ next[revisionField] = event.revision ?? currentRevision;+ if (revisionDomain === 'browser') {+ next.checkpointRevision = event.revision ?? next.checkpointRevision;+ next.activeOwner = event.owner ?? next.activeOwner;+ }+ next.arrivedVariants = event.arrivedVariants ?? next.arrivedVariants;+ if (revisionDomain === 'browser') next.visibleVariant = event.visibleVariant ?? next.visibleVariant;+ next.sourceFile = event.sourceFile ?? next.sourceFile;+ next.previewFile = event.previewFile ?? next.previewFile;+ next.previewMode = event.previewMode ?? next.previewMode;+ if (revisionDomain === 'browser' && event.paramValues) next.paramValues = { ...event.paramValues };+ } else {+ next.diagnostics.push({ error: 'stale_checkpoint_ignored', revision: event.revision, revisionDomain });+ }}break;case 'accept':case 'accept_intent':next.phase = 'accept_requested';+ next.generationCanceled = true;+ next.generationCanceledAt = event.at ?? (Date.parse(entry.ts || '') || Date.now());+ next.cancelReason = 'accept';next.visibleVariant = Number(event.variantId ?? next.visibleVariant);if (event.paramValues) next.paramValues = { ...event.paramValues };next.pendingEventSeq = entry.seq ?? next.pendingEventSeq;@@ -232,6 +296,12 @@ function applyEvent(snapshot, entry, inheritedDiagnostics = []) {next.pendingEventSeq = entry.seq ?? next.pendingEventSeq;next.pendingEvent = toPendingEvent(event);break;+ case 'carbonize_cleanup':+ next.phase = 'carbonize_cleanup_requested';+ next.sourceFile = event.file ?? next.sourceFile;+ next.pendingEventSeq = entry.seq ?? next.pendingEventSeq;+ next.pendingEvent = toPendingEvent(event);+ break;case 'steer_done':next.phase = 'steer_done';next.sourceFile = event.sourceFile ?? event.file ?? next.sourceFile;@@ -243,6 +313,9 @@ function applyEvent(snapshot, entry, inheritedDiagnostics = []) {break;case 'discard':next.phase = 'discard_requested';+ next.generationCanceled = true;+ next.generationCanceledAt = event.at ?? (Date.parse(entry.ts || '') || Date.now());+ next.cancelReason = 'discard';next.pendingEventSeq = entry.seq ?? next.pendingEventSeq;next.pendingEvent = toPendingEvent(event);break;@@ -260,6 +333,10 @@ function applyEvent(snapshot, entry, inheritedDiagnostics = []) {next.pendingEvent = null;break;case 'agent_error':+ if (next.generationCanceled && event.sourceEventType === 'generate') {+ next.diagnostics.push({ error: 'late_generation_event_ignored', type: event.type, phase: next.phase });+ break;+ }next.phase = 'agent_error';next.pendingEventSeq = null;next.pendingEvent = null;diff --git a/.opencode/skills/impeccable/scripts/live/source-lock.mjs b/.opencode/skills/impeccable/scripts/live/source-lock.mjsnew file mode 100644index 000000000..9ccc557be--- /dev/null+++ b/.opencode/skills/impeccable/scripts/live/source-lock.mjs@@ -0,0 +1,105 @@+import fs from 'node:fs';+import path from 'node:path';+import { createHash, randomUUID } from 'node:crypto';+import { getLiveDir, isLiveServerPidReachable } from '../lib/impeccable-paths.mjs';++// Only used to retire a lock whose contents we cannot read (empty or truncated+// by a crash mid-write). A readable lock's fate is decided by its owner's+// liveness instead, so a slow critical section is never swept.+const UNREADABLE_LOCK_STALE_MS = 60_000;++export function sourceLockPath(file, cwd = process.cwd()) {+ const digest = createHash('sha256').update(path.resolve(cwd, file)).digest('hex').slice(0, 24);+ return path.join(getLiveDir(cwd), 'locks', digest + '.lock');+}++export function withSourceLockSync(file, owner, fn, {+ cwd = process.cwd(),+ waitMs = 0,+ retryMs = 5,+} = {}) {+ const lockPath = sourceLockPath(file, cwd);+ fs.mkdirSync(path.dirname(lockPath), { recursive: true });+ const deadline = Date.now() + Math.max(0, Number(waitMs) || 0);+ // Identifies this acquisition specifically, so release can tell our own lock+ // from a replacement that some other writer created.+ const token = randomUUID();+ let acquired = false;++ while (!acquired) {+ clearStaleLock(lockPath);+ let fd;+ try {+ fd = fs.openSync(lockPath, 'wx');+ fs.writeFileSync(fd, JSON.stringify({+ owner,+ token,+ pid: process.pid,+ at: Date.now(),+ file: path.resolve(cwd, file),+ }) + '\n');+ acquired = true;+ } catch (error) {+ if (error?.code !== 'EEXIST') throw error;+ if (Date.now() >= deadline) {+ const locked = new Error('source_locked');+ locked.code = 'SOURCE_LOCKED';+ locked.lockPath = lockPath;+ throw locked;+ }+ sleepSync(Math.max(1, Math.min(Number(retryMs) || 5, deadline - Date.now())));+ } finally {+ try { if (fd !== undefined) fs.closeSync(fd); } catch {}+ }+ }++ try {+ return fn();+ } finally {+ releaseOwnLock(lockPath, token);+ }+}++function sleepSync(ms) {+ Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, ms);+}++function readLock(lockPath) {+ try { return JSON.parse(fs.readFileSync(lockPath, 'utf-8')); } catch { return null; }+}++/**+ * Remove the lock only if it is still the one this call created. If a sweeper+ * judged our lock stale and another writer replaced it, unlinking here would+ * end *their* critical section and admit a third writer to the same file.+ */+function releaseOwnLock(lockPath, token) {+ const held = readLock(lockPath);+ if (held && held.token !== token) return;+ try { fs.unlinkSync(lockPath); } catch {}+}++/**+ * A lock is stale when its owner is gone, not when it is old.+ *+ * Age alone cuts both ways: it sweeps a live holder whose critical section+ * outran the timeout (a suspended laptop, a stopped process), letting two+ * writers into the same source file, while still making every accept on a+ * crashed holder's file wait out the full timeout. Asking the OS whether the+ * recorded pid is alive answers both correctly: a dead owner releases at once,+ * and a live owner keeps its lock however long it needs.+ */+function clearStaleLock(lockPath) {+ const held = readLock(lockPath);+ if (!held) {+ // Unreadable: either a crash truncated it, or we caught the brief window+ // between create and write in a live acquisition. mtime distinguishes them.+ try {+ const stat = fs.statSync(lockPath);+ if (Date.now() - stat.mtimeMs > UNREADABLE_LOCK_STALE_MS) fs.unlinkSync(lockPath);+ } catch { /* gone already */ }+ return;+ }+ if (typeof held.pid === 'number' && isLiveServerPidReachable(held.pid)) return;+ try { fs.unlinkSync(lockPath); } catch {}+}diff --git a/.pi/skills/impeccable/reference/live.md b/.pi/skills/impeccable/reference/live.mdindex e8e3e1921..0e391f8ce 100644--- a/.pi/skills/impeccable/reference/live.md+++ b/.pi/skills/impeccable/reference/live.md@@ -10,21 +10,24 @@ Execute in order. No step skipped, no step reordered.1. `live.mjs`: boot. If the request names or implies a file, route, or app inside a monorepo, infer the concrete path and run `node .pi/skills/impeccable/scripts/live.mjs --target <path>` instead; then run the rest of this live session from the returned `projectRoot`.2. Open the app URL that serves `pageFile` (infer from `package.json`, docs, terminal output, or an open tab). Never use `serverPort`; it's the helper, not the app. **Cursor:** `browser_navigate` to that URL before polling; do not skip. **Other harnesses:** use the available browser tool; if the URL is uncertain, ask the user once.-3. Poll loop with the default long timeout (600000 ms). After every event or `--reply`, run `live-poll.mjs` again immediately. Never pass a short `--timeout=`.+3. Poll loop with the default long timeout (600000 ms). Run `live-poll.mjs` again immediately after every event or `--reply`; Codex runs this one-shot poll in the foreground. Never pass a short `--timeout=`.The global bar **Impeccable mark** dims and shows a pulsing amber dot when no agent is long-polling `/poll`. Hover the mark for the hint; restart `live-poll.mjs` to reconnect.-4. On `generate`: read screenshot if present; load the action's reference; plan three distinct directions; write all variants in one edit; `--reply done`; poll again.+4. On `generate`: reuse `event.scaffold` when present; read the screenshot if present; load the action's reference; deliver variants using the delivery policy below; `--reply done`; poll again. Generate in this thread. You already hold the project's tokens, conventions, and file layout; that context is the job, not overhead.5. On `steer`: read the message and `pageUrl`; do the work (page edits, navigation help, or a short reply in the `--reply` message); `--reply steer_done`; poll again. No pickup ack. The Steer bar unlocks when `steer_done` arrives over SSE.-6. On `accept` / `discard`: the poll script runs `live-accept.mjs`, acknowledges the delivered event, and prints `_completionAck`. Plain accepts/discards are terminal immediately; carbonize accepts remain recoverable until you finish cleanup, run `live-complete.mjs --id EVENT_ID`, and only then poll again.+6. On `accept` / `discard`: the poll script runs `live-accept.mjs`, acknowledges the delivered event, and prints `_completionAck`. Plain accepts/discards are terminal immediately. Carbonize accepts remain recoverable until the foreground task runs `live-complete.mjs --id EVENT_ID`; finish that cleanup before polling again.7. If interrupted, run `live-status.mjs` or `live-resume.mjs` before guessing. The durable journal replays unacknowledged work after helper restart.8. On `exit`: run the cleanup at the bottom.Harness policy:-- **Claude Code**: run the poll as a **background task** (no short timeout). The harness notifies you when it completes, so the main conversation stays free. Do not block the shell.+- **Claude Code**: run the poll as a **background task** (no short timeout). The harness notifies you when it completes, so the main conversation stays free while you generate and publish in it. Do not block the shell.- **Cursor**: run **one-shot** poll in a **background terminal** with notify on `"type":"(steer|generate|accept|discard|exit)"`. After each event the poll exits; handle it, `--reply`, then start `live-poll.mjs` again. Do **not** use `--stream` on Cursor: incremental stdout notify is slower in practice than exit-based notify (~5s vs sub-second in testing).-- **Codex**: run the poll in the **foreground** (blocking shell; not a background task, not a subagent). Codex background exec sessions do not reliably surface poll stdout back into the conversation at the moment events arrive, so a "fire-and-forget" background poll will stall live mode.+- **Codex**: run the default one-shot poll in a **yielded foreground exec session**. Do not suffix it with `&`, use `--stream`, or leave Live without an active foreground poll. Handle every event in the main task; after each handler/reply, restart the foreground poll.- **Other harnesses**: one-shot foreground unless you know stdout reliably returns to this session when a shell exits.+Generation delivery policy:+- **Default (Cursor and other harnesses):** keep the established atomic single-edit delivery. Do not switch a harness to progressive until its poll loop is known not to block on the extra publish calls. This avoids trading model latency for extra tool-call latency on harnesses with different streaming behavior.+Chat is overhead. No recap, no tutorial output, no pasting PRODUCT / DESIGN bodies. Spend tokens on tools and edits; on failure, one or two short sentences.## Start@@ -92,14 +95,14 @@ Server restart rule: start `live-server.mjs` again, then poll. Startup requeues**Insert mode** (`event.mode === "insert"`): `{id, mode: "insert", count, pageUrl, insert: { position, anchor }, placeholder: { width, height }, freeformPrompt?, screenshotPath?, comments?, strokes?}`. No `action`. Requires a non-empty `freeformPrompt` **or** annotations. Screenshot is sent only when annotations exist (same rule as replace). Use `placeholder` dimensions as a soft size hint for net-new content.-Speed matters; the user is watching a spinner. Minimize tool calls by using the wrap/insert helper and writing all variants in a single edit.+Speed matters; the user is watching the selected element. Reuse server preflight metadata when available, minimize discovery calls, and follow the harness-specific delivery policy above.### Insert mode branchWhen `event.mode === "insert"`:1. Read the screenshot if `event.screenshotPath` is present (annotations only).-2. Run the insert helper instead of wrap:+2. If `event.scaffold` is present, use it as the insert-helper result and do **not** run the helper again. Otherwise run the insert helper instead of wrap:```bashnode .pi/skills/impeccable/scripts/live-insert.mjs --id EVENT_ID --count EVENT_COUNT --position after \@@ -109,7 +112,7 @@ node .pi/skills/impeccable/scripts/live-insert.mjs --id EVENT_ID --count EVENT_C- `--position` ← `event.insert.position` (`before` | `after`)- Anchor flags ← `event.insert.anchor` (same mapping as wrap: id, classes, tag, text)-The scaffold has **no** `data-impeccable-variant="original"`. Variants are net-new HTML+CSS inserted at `insertLine`. Load `brand.md` or `product.md` (freeform only, no action sub-command). Write all variants in one edit, then `--reply done`.+The scaffold has **no** `data-impeccable-variant="original"`. Variants are net-new HTML+CSS inserted at `insertLine`. Load `brand.md` or `product.md` (freeform only, no action sub-command). Deliver using the harness policy, then `--reply done`.For Svelte/SvelteKit targets, `live-insert.mjs` returns `previewMode: "svelte-component"` with `mode: "insert"`, `file` pointing at a temporary `node_modules/.impeccable-live/<id>/manifest.json`, `componentDir` pointing at the variant component files, and `sourceFile` pointing at the real `.svelte` route. Write each inserted variant as a real Svelte component (`v1.svelte`, `v2.svelte`, …) under `componentDir`. Insert variants must be non-empty net-new content with a single top-level root, no `data-impeccable-*` attributes, and CSS in each component's `<style>` block. Do **not** edit the route source during generation; the browser mounts the temporary component before/after the live anchor while the user cycles variants. On Accept, `live-accept.mjs` inserts the selected component markup into `sourceFile` immediately and deletes the temp session after the source write succeeds.@@ -134,6 +137,8 @@ Reading annotations precisely:### 2. Wrap the element+When `event.scaffold` is present, the local helper already found and wrapped the source before the poll returned. Treat `event.scaffold` as the successful helper output and skip this command entirely. `event.scaffoldAttempted` with `scaffoldError` means local preflight could not finish; use the command/fallback path below. This optimization removes a deterministic tool round trip without changing the generated design.+```bashnode .pi/skills/impeccable/scripts/live-wrap.mjs --id EVENT_ID --count EVENT_COUNT --element-id "ELEMENT_ID" --classes "class1,class2" --tag "div" --text "TEXT_SNIPPET"```@@ -153,7 +158,7 @@ Output on success: `{ file, insertLine, commentSyntax, styleMode, styleTag, cssSFor Svelte/SvelteKit targets, `live-wrap.mjs` returns `previewMode: "svelte-component"` with `file` pointing at a temporary `node_modules/.impeccable-live/<id>/manifest.json`, `componentDir` pointing at the variant component files, and `sourceFile` pointing at the real `.svelte` route. Write each variant as a real Svelte component (`v1.svelte`, `v2.svelte`, …) under `componentDir`; use the `propContract` prop names for dynamic text (`{propName}`), not literal snapshot strings. Put variant CSS in each component's `<style>` block with semantic class selectors (no `@scope`, no `data-impeccable-*`). Reply with `--file` set to the manifest path; the browser dynamically imports and mounts the compiled components so Svelte HMR does not reset page state while the user cycles variants. On Accept, `live-accept.mjs` inlines the accepted component back into `sourceFile` immediately after source promotion succeeds.-**Params on the Svelte component path go in a sidecar, never as an attribute.** Svelte parses `{` inside an attribute value as the start of an expression, so a `data-impeccable-params='[{…}]'` attribute on a component element fails to compile (`Expected token }`). Declare params for this path in `componentDir/params.json`, keyed by variant number, using the exact param schema from section 7:+**Params on component-preview paths go in a sidecar, never as an attribute.** Svelte parses `{` inside an attribute value as the start of an expression, and both Svelte/Vue previews mount without an HTML variant wrapper. Declare params in `componentDir/params.json`, keyed by variant number, using the exact param schema from section 7:```json{@@ -291,11 +296,13 @@ In **departure mode**, the prompt narrows the lanes you draw from, not the familWhen the prompt and PRODUCT.md anti-references conflict (the prompt asks for X, the anti-references ban X), the anti-references win; they describe the brand's standing position, the prompt is one moment.-### 6. Write all variants in a single edit+### 6. Deliver variantsComplete HTML replacement of the original element for each variant, not a CSS-only patch. Consider the element's context (computed styles, parent structure, CSS variables from `event.element`).-Write CSS + all variants in ONE edit at the `insertLine` reported by `wrap`. Colocate CSS as a `<style>` tag inside the variant wrapper; `<style>` works anywhere in modern browsers and this ensures CSS and HTML arrive atomically (no FOUC).+Colocate preview CSS as a `<style>` tag inside the variant wrapper; `<style>` works anywhere in modern browsers and keeps each delivered state internally complete (no FOUC).++**Atomic default:** write CSS + all variants + parameter manifests in one edit at `insertLine`, preserving the established behavior.Use the `cssAuthoring` object returned by `live-wrap.mjs` to author the temporary preview CSS. The style opening tag shown below is the common case; replace it with `cssAuthoring.styleTag` when the tool returns a different one. The variant markup shape is otherwise stable:@@ -319,7 +326,7 @@ Use the `cssAuthoring` object returned by `live-wrap.mjs` to author the temporarThe first variant has no `display: none` (visible by default). All others do. If variants use only inline styles and no preview CSS, omit the `<style>` tag entirely.-One edit, all variants; the browser's MutationObserver picks everything up in one pass.+The browser's MutationObserver accepts either delivery shape. On the transactional progressive path it shows arrived variants and pending dots immediately; Accept and Discard are available as soon as one variant exists. Accepting an arrived variant fences the worker before the browser releases the picker, so later publications are rejected.For `styleMode: "scoped"`, author every `:scope` rule with a descendant combinator. The `@scope` boundary is the **variant wrapper `<div data-impeccable-variant="N">`**, not the element you're designing. A bare `:scope { background: cream; }` styles the wrapper, not the inner replacement, so the cream lands on a `display: contents` shell while the actual element keeps page defaults. Always step in: `:scope > .card`, `:scope > section`, `:scope .hero-title`, etc. The fake test agent's CSS in `tests/live-e2e/agent.mjs` is a faithful template; every scoped rule starts `:scope > ...`.@@ -361,7 +368,7 @@ Each variant can expose **coarse** knobs alongside the full HTML/CSS replacement**Hard cap per variant**: at most **four** parameters so the panel stays legible; rare fifth only if the reference explicitly allows it.-**How to declare.** Put a JSON manifest on the variant wrapper (HTML/JSX path). **On the Svelte `svelte-component` path, do not use this attribute** (Svelte can't compile `{` inside an attribute value). Declare params in `componentDir/params.json` keyed by variant number instead (see the Svelte component paragraph in the wrap section). The param schema below is identical for both paths.+**How to declare.** Put a JSON manifest on the variant wrapper (HTML/JSX path). **On the `svelte-component` path, do not use this attribute.** Declare params in `componentDir/params.json` keyed by variant number instead (see the component-preview paragraphs in the wrap section). The param schema below is identical for every path.```html<div data-impeccable-variant="1" data-impeccable-params='[@@ -462,15 +469,19 @@ Event: `{id, variantId, _acceptResult, _completionAck}`. The poll script already- The accept event includes `pageUrl`; the poll script must forward it to `live-accept.mjs --page-url PAGE_URL` so accept-time cleanup only scrubs staged copy edits for the current page.- `_completionAck.ok !== true`: do not poll yet. Run `live-status.mjs` / `live-resume.mjs`, complete the cleanup manually if needed, then run `live-complete.mjs --id EVENT_ID`.- `_acceptResult.handled: true` and `carbonize: false`: nothing to do. Poll again.-- `_acceptResult.handled: true` and `carbonize: true`: **post-accept cleanup is required before the next poll.** See the "Required after accept (carbonize)" section below. The `event._acceptResult.todo` field, `_completionAck.requiresComplete`, and a stderr banner all point at this required follow-up; none are decorative. After cleanup, run `live-complete.mjs --id EVENT_ID`, then poll again.+- `_acceptResult.handled: true` and `carbonize: true`: post-accept cleanup is required, but it must not stall Codex's control lane. See "Required after accept (carbonize)" below. The `event._acceptResult.todo` field, `_completionAck.requiresComplete`, and stderr banner all point at this required follow-up; none are decorative.- `_acceptResult.handled: false, mode: "fallback"`: the session lived in a generated file and the script refused to persist there. You've already written the accepted variant into true source during Handle fallback Step 3; just clean up the temporary wrapper in the served file if any, and poll again.+- `_acceptResult.handled: false, mode: "error"`: the operation genuinely failed. **Do not hand-edit the file**; the source was not touched and editing it yourself would either double-apply or race whoever holds it.+ - `error: "source_locked"`: a generation publish holds the file. Run the same `live-accept.mjs` command again; it is idempotent and will succeed once the publisher releases. Do not poll past it.+ - `error: "accept_receipt_conflict"`: this session already resolved as `priorOperation` (on `priorVariantId` for an accept), so the request contradicts durable truth. Do not edit. Run `live-status.mjs` and tell the user what the session actually resolved to.+ - anything else: report the error briefly and run `live-status.mjs` before continuing.- `_acceptResult.handled: false` without `mode`: manual cleanup: read file, find markers, edit.### Required after accept (carbonize)When `_acceptResult.carbonize === true`, the accepted variant was stitched into source with helper markers and inline CSS so the browser can render it immediately with no visual gap. That stitch-in is **temporary**. The agent must rewrite it into permanent form before doing anything else. Skipping this leaves dead `@scope` rules for unaccepted variants, a pointless `data-impeccable-variant` wrapper, and `impeccable-carbonize-start/end` comment noise in the source file; all of which accumulate across sessions.-Do these five steps in the current thread, synchronously, before the next poll. Do not poll again until the file is clean.+Do these five steps synchronously before the next poll. The source lock, generation epoch, and expected-source hash remain the final safety gates against a generator finishing concurrently with Accept.1. **Locate the carbonize block** in the source file (`_acceptResult.file`). It's bracketed by `<!-- impeccable-carbonize-start SESSION_ID -->` and `<!-- impeccable-carbonize-end SESSION_ID -->` and contains a `<style data-impeccable-css="SESSION_ID">` element. If the variant declared parameters, an `<!-- impeccable-param-values SESSION_ID: {...} -->` comment sits alongside the style tag with the user's chosen values; read it first; it drives steps 3 and 4 below.2. **Move the CSS rules** into the project's real stylesheet. Which stylesheet depends on the project (e.g. `site/styles/workflow.css` for an Astro project, or the component's co-located CSS file for a Vite/Next project; pick whichever already owns styling for the surrounding element).@@ -478,9 +489,7 @@ Do these five steps in the current thread, synchronously, before the next poll.4. **Unwrap the accepted content.** Delete the inner `<div data-impeccable-variant="N" style="display: contents">` that wraps it. On JSX/TSX, also delete the outer `<div data-impeccable-carbonize="SESSION_ID" style={{ display: 'contents' }}>` wrapper if present (accept adds it so ternary/`return` slots keep a single root). Drop `data-impeccable-params` and any `data-p-*` attributes; those are live-mode plumbing, not source.5. **Delete the inline `<style>` block, the `<!-- impeccable-param-values -->` comment if present, and both `<!-- impeccable-carbonize-start/end -->` markers.** Also drop any `@scope` rules for variants other than the accepted one; those are dead code now.-After the file is clean, run `live-complete.mjs --id SESSION_ID`, verify it reports `phase: "completed"`, then poll again.--A background agent may be used for the rewrite, but the current thread is responsible for verifying the five steps are complete before issuing the next poll. In practice, inline is usually faster and less error-prone.+After the file is clean, the cleanup owner runs `live-complete.mjs --id SESSION_ID` and verifies `phase: "completed"`. Poll again only after that verification.## Handle `discard`diff --git a/.pi/skills/impeccable/scripts/lib/impeccable-paths.mjs b/.pi/skills/impeccable/scripts/lib/impeccable-paths.mjsindex 2ccbe7b74..99956c0f3 100644--- a/.pi/skills/impeccable/scripts/lib/impeccable-paths.mjs+++ b/.pi/skills/impeccable/scripts/lib/impeccable-paths.mjs@@ -104,6 +104,20 @@ export function removeLiveServerInfo(cwd = process.cwd(), options = {}) {}}+/**+ * Session IDs become path segments (journals, snapshots, accept receipts,+ * preview manifests, generated component dirs). They arrive from CLI `--id`+ * arguments and HTTP payloads, so anything containing a separator or `..` must+ * be rejected before it reaches path.join, which would happily escape+ * `.impeccable/live/`. Real IDs are 8 hex chars; the tests use short slugs.+ */+export function safeSessionId(id) {+ if (typeof id !== 'string' || !/^[A-Za-z0-9_-]{1,128}$/.test(id)) {+ throw new Error('invalid session id: ' + id);+ }+ return id;+}+export function getLiveSessionsDir(cwd = process.cwd(), options = {}) {return path.join(getLiveDir(cwd, options), 'sessions');}diff --git a/.pi/skills/impeccable/scripts/live-accept.mjs b/.pi/skills/impeccable/scripts/live-accept.mjsindex 278dfbb2e..453ddea35 100644--- a/.pi/skills/impeccable/scripts/live-accept.mjs+++ b/.pi/skills/impeccable/scripts/live-accept.mjs@@ -16,7 +16,9 @@import fs from 'node:fs';import path from 'node:path';import { isGeneratedFile } from './lib/is-generated.mjs';+import { IMPECCABLE_DIR, getLiveDir, safeSessionId } from './lib/impeccable-paths.mjs';import { readBuffer as readManualEditsBuffer, writeBuffer as writeManualEditsBuffer } from './live/manual-edits-buffer.mjs';+import { withSourceLockSync } from './live/source-lock.mjs';import {applyDeferredSvelteComponentAccepts,findSvelteComponentManifest,@@ -25,6 +27,46 @@ import {} from './live/svelte-component.mjs';const EXTENSIONS = ['.html', '.jsx', '.tsx', '.vue', '.svelte', '.astro'];+const ACCEPT_LOCK_WAIT_MS = 1_000;+// Mirrors VARIANT_ID_PATTERN in live/event-validation.mjs, which gates the same+// value arriving over HTTP.+const VARIANT_NUM_PATTERN = /^[0-9]{1,3}$/;++/**+ * A thrown accept/discard is a real failure, not a manual handoff.+ *+ * live/completion.mjs only classifies a result as `error` when it carries+ * `mode: 'error'`; anything else unhandled falls through to `agent_done` with a+ * successful ack, and reference/live.md then tells the agent to finish the edit+ * by hand. That is right for the documented fallback paths and wrong here: a+ * `source_locked` contention needs a retry (hand-editing races the publisher+ * holding the lock), and a crash needs surfacing, not a hand-applied guess.+ */+function operationFailure(err, extra = {}) {+ return { handled: false, mode: 'error', error: err.message, ...extra };+}++/**+ * Mark an unhandled preview-path result as a real failure.+ *+ * operationFailure only covers results built from a *thrown* error. The accept+ * implementations also return `{handled: false, error}` for their own checks+ * (variant missing, template empty, original text ambiguous), and those arrived+ * without `mode`, so completion.mjs classified them as agent_done and+ * reference/live.md routed the agent to "read file, find markers, edit".+ *+ * That handoff only makes sense for a plain wrapper session, which is the one+ * shape with markers in the user's source to edit. Component and isolated+ * artifact previews keep the source clean until Accept, so there is nothing to+ * hand-edit and an unhandled result is always a failure. `previewMode` is+ * exactly that discriminator: only the preview branches set it.+ */+function markPreviewFailure(result) {+ if (result?.handled === false && !result.mode && result.previewMode) {+ return { ...result, mode: 'error' };+ }+ return result;+}// ---------------------------------------------------------------------------// CLI@@ -63,7 +105,52 @@ Output (JSON):const isDiscard = args.includes('--discard');if (!id) { console.error('Missing --id'); process.exit(1); }+ // `id` becomes a path segment (accept receipts, preview manifests, generated+ // component dirs). Reject separators and traversal here so one check covers+ // every downstream sink.+ try { safeSessionId(id); } catch { console.error('Invalid --id'); process.exit(1); }if (!isDiscard && !variantNum) { console.error('Need --discard or --variant N'); process.exit(1); }+ // `variantNum` is interpolated into a RegExp and into the markup written back+ // to source. The browser and the /events schema both constrain it to digits;+ // enforce the same here, or `--variant '.*'` matches the `original` block+ // first and silently accepts the original while reporting success.+ if (!isDiscard && !VARIANT_NUM_PATTERN.test(variantNum)) {+ console.error('Invalid --variant');+ process.exit(1);+ }++ const requestedOperation = isDiscard ? 'discard' : 'accept';+ const priorReceipt = readAcceptReceipt(process.cwd(), id);+ if (priorReceipt) {+ const sameOperation = priorReceipt.operation === requestedOperation+ && (isDiscard || String(priorReceipt.variantId) === String(variantNum));+ console.log(JSON.stringify(sameOperation+ ? { ...priorReceipt.result, handled: true, alreadyApplied: true }+ : {+ // mode: 'error' is what marks this a real failure rather than a manual+ // handoff. Without it, live/completion.mjs classifies the reply as+ // agent_done and reference/live.md tells the agent to "read file, find+ // markers, edit" by hand — which would apply a second, conflicting+ // accept on top of the one the receipt already recorded.+ handled: false,+ mode: 'error',+ error: 'accept_receipt_conflict',+ priorOperation: priorReceipt.operation,+ priorVariantId: priorReceipt.variantId ?? null,+ }));+ return;+ }+ const emitResult = (rawResult) => {+ const result = markPreviewFailure(rawResult);+ if (result?.handled !== false) {+ writeAcceptReceipt(process.cwd(), id, {+ operation: requestedOperation,+ variantId: isDiscard ? null : String(variantNum),+ result,+ });+ }+ console.log(JSON.stringify(result));+ };let paramValues = null;if (paramValuesRaw) {@@ -82,39 +169,55 @@ Output (JSON):if (svelteComponentManifest) {if (isDiscard) {- removeSvelteComponentSession(id, process.cwd());- console.log(JSON.stringify({- handled: true,+ let result;+ try {+ result = withSourceLockSync(+ path.resolve(process.cwd(), svelteComponentManifest.sourceFile),+ 'discard:' + id,+ () => {+ removeSvelteComponentSession(id, process.cwd());+ return { handled: true };+ },+ { waitMs: ACCEPT_LOCK_WAIT_MS },+ );+ } catch (err) {+ result = operationFailure(err);+ }+ emitResult({+ ...result,file: svelteComponentManifest.sourceFile,carbonize: false,previewMode: 'svelte-component',componentDir: svelteComponentManifest.componentDir,- }));+ });return;}let result;try {- result = inlineSvelteComponentAccept(- svelteComponentManifest,- variantNum,- paramValues,- process.cwd(),+ result = withSourceLockSync(+ path.resolve(process.cwd(), svelteComponentManifest.sourceFile),+ 'accept:' + id,+ () => inlineSvelteComponentAccept(+ svelteComponentManifest,+ variantNum,+ paramValues,+ process.cwd(),+ ),+ { waitMs: ACCEPT_LOCK_WAIT_MS },);} catch (err) {- result = {- handled: false,- error: err.message,+ result = operationFailure(err, {file: svelteComponentManifest.sourceFile,sourceFile: svelteComponentManifest.sourceFile,previewMode: 'svelte-component',componentDir: svelteComponentManifest.componentDir,- };+ });}if (result.carbonize) {result.todo = 'REQUIRED before next poll: carbonize cleanup in ' + result.file + '. See reference/live.md "Required after accept".';}- console.log(JSON.stringify({ handled: result.handled !== false, ...result }));+ emitResult({ handled: result.handled !== false, ...result });return;}@@ -145,10 +248,25 @@ Output (JSON):}if (isDiscard) {- const result = handleDiscard(id, lines, targetFile);- console.log(JSON.stringify({ handled: true, file: relFile, carbonize: false, ...result }));+ let result;+ // handleDiscard takes the source lock, which throws SOURCE_LOCKED under+ // contention. Without this catch the CLI exits non-zero with empty stdout+ // and the agent gets no JSON to act on.+ try {+ result = handleDiscard(id, lines, targetFile);+ } catch (err) {+ emitResult(operationFailure(err, { file: relFile }));+ return;+ }+ emitResult({ handled: true, file: relFile, carbonize: false, ...result });} else {- const result = handleAccept(id, variantNum, lines, targetFile, paramValues);+ let result;+ try {+ result = handleAccept(id, variantNum, lines, targetFile, paramValues);+ } catch (err) {+ emitResult(operationFailure(err, { file: relFile }));+ return;+ }const acceptedOriginalText = result.acceptedOriginalText || '';delete result.acceptedOriginalText;// Single-line attention-grabber when cleanup is required. The full@@ -167,7 +285,7 @@ Output (JSON):// Non-fatal; the buffer stays as-is and the user can discard later.}}- console.log(JSON.stringify({ handled: true, file: relFile, ...result }));+ emitResult({ handled: true, file: relFile, ...result });}}@@ -235,7 +353,14 @@ function scrubManualEditsAgainstFile(_targetFile, cwd = process.cwd(), originalB// Discard// ----------------------------------------------------------------------------function handleDiscard(id, lines, targetFile) {+function handleDiscard(id, _lines, targetFile) {+ return withSourceLockSync(targetFile, 'discard:' + id, () => {+ const lines = fs.readFileSync(targetFile, 'utf-8').split('\n');+ return handleDiscardUnlocked(id, lines, targetFile);+ }, { waitMs: ACCEPT_LOCK_WAIT_MS });+}++function handleDiscardUnlocked(id, lines, targetFile) {const block = findMarkerBlock(id, lines);if (!block) return { handled: false, error: 'Markers not found' };@@ -330,7 +455,24 @@ function reindentContent(contentLines, fromIndent, toIndent) {});}-function handleAccept(id, variantNum, lines, targetFile, paramValues) {+function handleAccept(id, variantNum, _lines, targetFile, paramValues) {+ return withSourceLockSync(targetFile, 'accept:' + id, () => {+ const lines = fs.readFileSync(targetFile, 'utf-8').split('\n');+ return handleAcceptUnlocked(id, variantNum, lines, targetFile, paramValues);+ }, { waitMs: ACCEPT_LOCK_WAIT_MS });+}++function handleAcceptUnlocked(id, variantNum, lines, targetFile, paramValues) {+ const built = buildAcceptedWrappedSource(id, variantNum, lines, targetFile, paramValues);+ if (built.handled === false) return built;+ fs.writeFileSync(targetFile, built.content, 'utf-8');+ return {+ carbonize: built.carbonize,+ acceptedOriginalText: built.acceptedOriginalText,+ };+}++function buildAcceptedWrappedSource(id, variantNum, lines, targetFile, paramValues) {const block = findMarkerBlock(id, lines);if (!block) return { handled: false, error: 'Markers not found' };@@ -375,11 +517,14 @@ function handleAccept(id, variantNum, lines, targetFile, paramValues) {...replacement,...lines.slice(replaceRange.end + 1),];- fs.writeFileSync(targetFile, newLines.join('\n'), 'utf-8');-- return { carbonize: needsCarbonize, acceptedOriginalText: originalContent.join('\n') };+ return {+ content: newLines.join('\n'),+ carbonize: needsCarbonize,+ acceptedOriginalText: originalContent.join('\n'),+ };}+function readSourceShadowPreviewMeta(content, id) {const escaped = escapeRegExp(id);const wrapperRe = new RegExp('<[^>]+data-impeccable-variants=(["\'])' + escaped + '\\1[^>]*>');@@ -746,6 +891,21 @@ function detectCommentSyntax(filePath) {// File search (find the file containing session markers)// ---------------------------------------------------------------------------+/**+ * `.impeccable` is the critical entry, and it is not cosmetic.+ *+ * Progressive publication stages each revision as `.impeccable/live/artifacts/+ * <id>-r<n>.<source-ext>`, and those artifacts carry the very marker this search+ * looks for. The walk reaches `.` for any project whose source is not under one+ * of the privileged dirs above (this repo's own site lives in `site/pages/`), and+ * dot-directories sort before letters, so the artifact was found *before* the+ * real file. isGeneratedFile then declined the accept, and the agent fell back to+ * carbonizing several hundred lines of stylesheet by hand.+ *+ * Impeccable's own state directory is never project source. Never search it.+ */+const SEARCH_SKIP_DIRS = new Set(['node_modules', '.git', 'dist', 'build', IMPECCABLE_DIR]);+function findSessionFile(id, cwd) {const marker = 'impeccable-variants-start ' + id;const searchDirs = ['src', 'app', 'pages', 'components', 'public', 'views', 'templates', '.'];@@ -786,7 +946,7 @@ function searchDir(dir, query, seen, depth) {for (const entry of entries) {if (!entry.isDirectory()) continue;- if (['node_modules', '.git', 'dist', 'build'].includes(entry.name)) continue;+ if (SEARCH_SKIP_DIRS.has(entry.name)) continue;const result = searchDir(path.join(dir, entry.name), query, seen, depth + 1);if (result) return result;}@@ -798,6 +958,28 @@ function searchDir(dir, query, seen, depth) {// Utilities// ---------------------------------------------------------------------------+function acceptReceiptPath(cwd, id) {+ return path.join(getLiveDir(cwd), 'accept-receipts', `${safeSessionId(id)}.json`);+}++function readAcceptReceipt(cwd, id) {+ try { return JSON.parse(fs.readFileSync(acceptReceiptPath(cwd, id), 'utf-8')); } catch { return null; }+}++function writeAcceptReceipt(cwd, id, receipt) {+ const file = acceptReceiptPath(cwd, id);+ fs.mkdirSync(path.dirname(file), { recursive: true });+ const value = {+ id,+ ...receipt,+ completedAt: new Date().toISOString(),+ };+ const temporary = `${file}.${process.pid}.${Date.now()}.tmp`;+ fs.writeFileSync(temporary, JSON.stringify(value, null, 2) + '\n', 'utf-8');+ fs.renameSync(temporary, file);+ return value;+}+function argVal(args, flag) {const idx = args.indexOf(flag);return idx !== -1 && idx + 1 < args.length ? args[idx + 1] : null;diff --git a/.pi/skills/impeccable/scripts/live-browser.js b/.pi/skills/impeccable/scripts/live-browser.jsindex 616f1290a..20d875b93 100644--- a/.pi/skills/impeccable/scripts/live-browser.js+++ b/.pi/skills/impeccable/scripts/live-browser.js@@ -126,6 +126,9 @@let expectedVariants = 0;let arrivedVariants = 0;let visibleVariant = 0;+ let generationPhase = null;+ let parameterGenerationState = 'idle';+ let parameterReadyAnnouncedSession = null;let svelteComponentSession = null;let svelteRuntimePromise = null;let pendingSvelteComponentRetryObserver = null;@@ -134,6 +137,7 @@let currentPreviewMode = null;let recoveryWaitingForAnchor = false;let pickedAnchorSnapshot = null;+ let pickedAnchorViewportTop = null;let pendingVariantAnchorRetryObserver = null;let pendingAcceptedSession = null;let variantObserver = null;@@ -151,10 +155,12 @@// startScrollLock / stopScrollLock below.let scrollLockObserver = null;let scrollLockTargetY = null;+ let scrollLockAnchorTop = null;let scrollLockRaf = null;let scrollLockAbort = null;const SCROLL_ANCHOR_LOCK_ID = 'impeccable-scroll-anchor-lock';const VARIANT_STATE_STYLE_ID = 'impeccable-variant-state';+ const DISCARD_STATE_STYLE_ID = 'impeccable-discard-state';// Dedicated key for scroll position - SEPARATE from LS_KEY so that// saveSession's state updates don't clobber a carefully-captured scrollY.@@ -252,6 +258,13 @@barConnected: !!barEl?.isConnected,hasSvelteComponentSession: !!svelteComponentSession,mountedSvelteVariant: svelteComponentSession?.mountedVariant || 0,+ pickActive,+ pendingApplyInFlight,+ hoveredElement: hoveredElement ? {+ tag: hoveredElement.tagName,+ classes: hoveredElement.className,+ pickable: pickable(hoveredElement),+ } : null,pendingSvelteComponentRetry: !!pendingSvelteComponentRetryObserver,recoveryWaitingForAnchor,evtSourceReadyState: evtSource ? evtSource.readyState : null,@@ -1114,14 +1127,15 @@});}- function hideBar() {+ function hideBar(instant) {if (!barEl) return;const hideSeq = ++barHideSeq;stopVoice({ suppressSubmit: true });if (configureKind === 'insert') clearInsertPicking();barEl.style.opacity = '0';- barEl.style.transform = 'translateY(6px)';- setTimeout(() => { if (barEl && hideSeq === barHideSeq) barEl.style.display = 'none'; }, 250);+ barEl.style.transform = instant ? 'translateY(0)' : 'translateY(6px)';+ if (instant) barEl.style.display = 'none';+ else setTimeout(() => { if (barEl && hideSeq === barHideSeq) barEl.style.display = 'none'; }, 250);hideActionPicker();closeTunePopover();hideConfigureBarTooltip();@@ -1966,6 +1980,7 @@*/function setLiveState(next) {state = next;+ window.__IMPECCABLE_LIVE_STATE__ = next;syncPageInteractionCursor();}@@ -2516,18 +2531,27 @@fontSize: '11px', color: BP.textDim, whiteSpace: 'nowrap',marginLeft: 'auto',});- // Variants currently arrive atomically in a single file edit, so a- // per-variant counter would lie. Say what's true.status.textContent = recoveryWaitingForAnchor? 'Variants ready. Reveal the selected element to resume.'- : (arrivedVariants < expectedVariants- ? 'Generating ' + expectedVariants + ' variants...'- : 'Done');+ : generationStatusText();row.appendChild(status);return row;}+ function generationStatusText() {+ if (arrivedVariants >= expectedVariants && expectedVariants > 0) return 'Done';+ if (generationPhase === 'picked_up') return 'Agent picked up the request...';+ if (generationPhase === 'scaffolding') return 'Finding the source...';+ if (generationPhase === 'source_ready') return 'Source ready. Generating...';+ if (generationPhase === 'scaffold_fallback') return 'Agent is locating the source...';+ if (generationPhase === 'first_variant_generating') return 'Designing the first variant...';+ if (generationPhase === 'first_variant_validating') return 'Checking the first variant...';+ if (generationPhase === 'remaining_variants_generating') return 'Exploring two more directions...';+ if (generationPhase === 'remaining_variants_validating') return 'Checking the remaining variants...';+ return 'Generating ' + expectedVariants + ' variants...';+ }+// Cycling rowconst TUNE_ICON_SVG = '<svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" style="flex-shrink:0"><line x1="4" y1="8" x2="20" y2="8"/><circle cx="14" cy="8" r="2.4" fill="currentColor" stroke="none"/><line x1="4" y1="16" x2="20" y2="16"/><circle cx="10" cy="16" r="2.4" fill="currentColor" stroke="none"/></svg>';@@ -2557,7 +2581,7 @@color: BP.textDim, minWidth: '24px', textAlign: 'center',});counter.id = PREFIX + '-variant-counter';- counter.textContent = visibleVariant + '/' + arrivedVariants;+ counter.textContent = visibleVariant + '/' + expectedVariants;row.appendChild(counter);// Next@@ -2567,10 +2591,12 @@if (visibleVariant >= arrivedVariants) next.style.opacity = '0.3';row.appendChild(next);- // Tune chip - only when the visible variant exposes params+ // Tune chip stays visible while the deferred parameter phase is running,+ // then becomes interactive as soon as this variant exposes controls.const visParams = parseVariantParams(getVisibleVariantEl());const hasParams = visParams.length > 0;- if (hasParams) {+ const paramsPending = !hasParams && (parameterGenerationState === 'pending' || parameterGenerationState === 'loading');+ if (hasParams || paramsPending) {const tune = el('button', {display: 'inline-flex', alignItems: 'center', gap: '6px',padding: '4px 10px', borderRadius: '5px',@@ -2578,35 +2604,54 @@background: tuneOpen ? BP.accentSoft : 'transparent',color: tuneOpen ? BP.accent : BP.text,fontFamily: FONT, fontSize: '11px', fontWeight: '500',- cursor: 'pointer',+ cursor: paramsPending ? 'wait' : 'pointer',transition: 'color 0.12s ease, background 0.12s ease',whiteSpace: 'nowrap',});- tune.innerHTML = TUNE_ICON_SVG;+ if (paramsPending) {+ const spinner = el('span', {+ width: '11px', height: '11px', borderRadius: '50%',+ border: '1.5px solid ' + BP.hairline,+ borderTopColor: BP.accent,+ animation: 'impeccable-spin 0.6s linear infinite',+ boxSizing: 'border-box', flexShrink: '0',+ });+ spinner.setAttribute('aria-hidden', 'true');+ tune.appendChild(spinner);+ } else {+ tune.innerHTML = TUNE_ICON_SVG;+ }const tuneLabel = document.createElement('span');tuneLabel.textContent = 'Tune';tune.appendChild(tuneLabel);- const tuneBadge = document.createElement('span');- Object.assign(tuneBadge.style, {- display: 'inline-flex', alignItems: 'center', justifyContent: 'center',- minWidth: '16px', height: '16px', padding: '0 4px',- borderRadius: '999px',- background: tuneOpen ? C.brand : BP.hairline,- color: tuneOpen ? 'oklch(98% 0 0)' : 'inherit',- fontFamily: MONO, fontSize: '9.5px', fontWeight: '600',- lineHeight: '1',- boxSizing: 'border-box',- });- tuneBadge.textContent = String(visParams.length);- tune.appendChild(tuneBadge);- tune.title = 'Tune this variant (' + visParams.length + ' knob' + (visParams.length === 1 ? '' : 's') + ')';- tune.addEventListener('mouseenter', () => {- if (!tuneOpen) tune.style.background = BP.accentSoft;- });- tune.addEventListener('mouseleave', () => {- if (!tuneOpen) tune.style.background = 'transparent';- });- tune.addEventListener('click', (e) => { e.stopPropagation(); toggleTunePopover(); });+ if (hasParams) {+ const tuneBadge = document.createElement('span');+ Object.assign(tuneBadge.style, {+ display: 'inline-flex', alignItems: 'center', justifyContent: 'center',+ minWidth: '16px', height: '16px', padding: '0 4px',+ borderRadius: '999px',+ background: tuneOpen ? C.brand : BP.hairline,+ color: tuneOpen ? 'oklch(98% 0 0)' : 'inherit',+ fontFamily: MONO, fontSize: '9.5px', fontWeight: '600',+ lineHeight: '1',+ boxSizing: 'border-box',+ });+ tuneBadge.textContent = String(visParams.length);+ tune.appendChild(tuneBadge);+ tune.title = 'Tune this variant (' + visParams.length + ' knob' + (visParams.length === 1 ? '' : 's') + ')';+ tune.addEventListener('mouseenter', () => {+ if (!tuneOpen) tune.style.background = BP.accentSoft;+ });+ tune.addEventListener('mouseleave', () => {+ if (!tuneOpen) tune.style.background = 'transparent';+ });+ tune.addEventListener('click', (e) => { e.stopPropagation(); toggleTunePopover(); });+ } else {+ tune.disabled = true;+ tune.setAttribute('aria-label', 'Tune controls are still being prepared');+ tune.title = 'Tune controls are still being prepared';+ tune.style.opacity = '0.72';+ }tune.dataset.iceqTune = '1';row.appendChild(tune);}@@ -2614,6 +2659,15 @@// Spacerrow.appendChild(el('div', { flex: '1' }));+ if (arrivedVariants < expectedVariants) {+ const remaining = expectedVariants - arrivedVariants;+ const progress = el('span', {+ fontSize: '11px', color: BP.textDim, whiteSpace: 'nowrap',+ });+ progress.textContent = remaining + ' more arriving...';+ row.appendChild(progress);+ }+// Accept - primary action, kinpaku gold + lacquer-deep (matches demo .live-demo-ctx-accept)const accept = el('button', {padding: '5px 14px', borderRadius: '5px',@@ -2628,7 +2682,11 @@accept.addEventListener('mousedown', () => accept.style.transform = 'scale(0.97)');accept.addEventListener('mouseup', () => accept.style.transform = 'scale(1)');accept.addEventListener('click', (e) => { e.stopPropagation(); handleAccept(); });- if (arrivedVariants === 0) { accept.style.opacity = '0.3'; accept.style.pointerEvents = 'none'; }+ if (arrivedVariants === 0) {+ accept.style.opacity = '0.3';+ accept.style.pointerEvents = 'none';+ accept.title = 'Accept becomes available when the first variant arrives';+ }row.appendChild(accept);// Discard@@ -4743,6 +4801,32 @@}}+ function mountedParameterCount() {+ if (svelteComponentSession?.sessionId === currentSessionId) {+ return Object.values(svelteComponentSession.paramsByVariant || {})+ .reduce((total, params) => total + (Array.isArray(params) ? params.length : 0), 0);+ }+ const wrapper = document.querySelector('[data-impeccable-variants="' + currentSessionId + '"]');+ if (!wrapper) return 0;+ return [...wrapper.querySelectorAll('[data-impeccable-variant]:not([data-impeccable-variant="original"])')]+ .reduce((total, variant) => total + parseVariantParams(variant).length, 0);+ }++ function completeParameterPublication() {+ if (!currentSessionId) return;+ const ready = mountedParameterCount() > 0;+ parameterGenerationState = ready ? 'ready' : 'none';+ if (ready && parameterReadyAnnouncedSession !== currentSessionId) {+ parameterReadyAnnouncedSession = currentSessionId;+ showToast('Tune controls are ready.', 3000);+ }+ if (state === 'CYCLING') {+ refreshParamsPanel();+ showOrUpdateCyclingBar();+ }+ saveSession();+ }+function toggleTunePopover() {if (pendingApplyInFlight) { showManualApplyBusyToast(); return; }if (tuneOpen) { closeTunePopover(); return; }@@ -4835,6 +4919,10 @@return String(filePath || '').endsWith('manifest.json');}+ function isFrameworkComponentPreviewMode(mode) {+ return mode === 'svelte-component';+ }+function parseOriginalMarkupElement(originalMarkup) {const parser = new DOMParser();const doc = parser.parseFromString('<div id="impeccable-anchor">' + originalMarkup + '</div>', 'text/html');@@ -5029,9 +5117,13 @@}}- function loadSvelteRuntime(runtimeModule) {+ function resolveComponentModuleUrl(manifest, modulePath) {+ return new URL(String(modulePath || ''), location.origin).href;+ }++ function loadSvelteRuntime(runtimeModule, manifest) {const modulePath = runtimeModule || '/src/lib/impeccable/__runtime.js';- const url = new URL(modulePath, location.origin).href;+ const url = resolveComponentModuleUrl(manifest, modulePath);if (!svelteRuntimePromise) {svelteRuntimePromise = import(/* @vite-ignore */ url);}@@ -5065,7 +5157,8 @@async function loadSvelteComponentVariantSource(manifest, variantNum) {const dir = String(manifest?.componentDir || '').replace(/^\/+/, '');if (!dir || !variantNum) return '';- const sourcePath = dir + '/v' + variantNum + '.svelte';+ const extension = manifest.componentExtension || 'svelte';+ const sourcePath = dir + '/v' + variantNum + '.' + extension;const url = 'http://localhost:' + PORT + '/source?token=' + TOKEN + '&path=' + encodeURIComponent(sourcePath);try {const res = await fetch(url);@@ -5221,7 +5314,7 @@if (!sourceOriginal) return values;const map = buildSvelteExpressionTextMap(sourceOriginal, liveEl);for (const entry of contract) {- const token = '{' + entry.expr + '}';+ const token = entry.previewToken || ('{' + entry.expr + '}');values[entry.prop] = map.get(token) || '';}return values;@@ -5233,9 +5326,12 @@try {const previousAnchor = getMountedSvelteComponentAnchor(svelteComponentSession) || selectedElement;svelteComponentSession.swapAnchor = makeFrozenAnchor(previousAnchor) || svelteComponentSession.swapAnchor || null;- const runtime = await loadSvelteRuntime(manifest.runtimeModule);- const modulePath = '/' + String(manifest.componentDir || '').replace(/^\/+/, '') + '/v' + variantNum + '.svelte';- const moduleUrl = new URL(modulePath, location.origin).href + '?t=' + Date.now();+ const runtime = await loadSvelteRuntime(manifest.runtimeModule, manifest);+ const extension = manifest.componentExtension || 'svelte';+ const moduleBase = manifest.componentModuleBase+ || ('/' + String(manifest.componentDir || '').replace(/^\/+/, ''));+ const modulePath = String(moduleBase).replace(/\/+$/, '') + '/v' + variantNum + '.' + extension;+ const moduleUrl = resolveComponentModuleUrl(manifest, modulePath) + '?t=' + Date.now();const mod = await import(/* @vite-ignore */ moduleUrl);const Component = mod.default;if (svelteComponentSession.mountedInstance && runtime.unmount) {@@ -5275,7 +5371,7 @@if (svelteComponentSession?.sessionId === sessionId) {svelteComponentSession.swapAnchor = null;}- console.error('[impeccable] Failed to mount Svelte variant ' + variantNum + ' for ' + sessionId + ':', err);+ console.error('[impeccable] Failed to mount component variant ' + variantNum + ' for ' + sessionId + ':', err);return false;}}@@ -5340,40 +5436,46 @@if (manifest.id !== sessionId) return;const paramsByVariant = await loadSvelteComponentParams(manifest);+ const availableVariants = Number(manifest.arrivedVariants) || Number(manifest.count) || 1;+ const componentPreviewMode = isFrameworkComponentPreviewMode(manifest.previewMode)+ ? manifest.previewMode+ : 'svelte-component';currentSessionId = sessionId;expectedVariants = Number(manifest.count) || expectedVariants || 1;rememberSessionFileMeta({sourceFile: manifest.sourceFile,previewFile: manifestPath,- previewMode: 'svelte-component',+ previewMode: componentPreviewMode,});if (state !== 'CYCLING') setLiveState('GENERATING');const existingWrapper = document.querySelector('[data-impeccable-variants="' + sessionId + '"]');if (existingWrapper && svelteComponentSession?.sessionId === sessionId) {recoveryWaitingForAnchor = false;+ svelteComponentSession.manifest = manifest;svelteComponentSession.paramsByVariant = paramsByVariant;- arrivedVariants = Number(manifest.count) || expectedVariants || 1;- expectedVariants = arrivedVariants;+ arrivedVariants = availableVariants;+ expectedVariants = Number(manifest.count) || expectedVariants || arrivedVariants;visibleVariant = visibleVariant > 0 && visibleVariant <= arrivedVariants ? visibleVariant : 1;await mountSvelteComponentVariant(visibleVariant || 1);setLiveState('CYCLING');showOrUpdateCyclingBar();saveSession();+ if (parameterGenerationState === 'loading') completeParameterPublication();return;}const liveEl = findLiveElementForSvelteManifest(manifest);if (!liveEl?.parentElement) {console.warn('[impeccable] Could not find original element in live DOM.');- arrivedVariants = Number(manifest.count) || expectedVariants || 1;- expectedVariants = arrivedVariants;+ arrivedVariants = availableVariants;+ expectedVariants = Number(manifest.count) || expectedVariants || arrivedVariants;const saved = loadSession();const savedVisibleVariant = saved && saved.id === sessionId ? saved.visible : 0;visibleVariant = visibleVariant > 0 && visibleVariant <= arrivedVariants? visibleVariant: (savedVisibleVariant > 0 && savedVisibleVariant <= arrivedVariants ? savedVisibleVariant : 1);- enterRecoveryWaitingForAnchor({ checkpointReason: 'svelte_component_anchor_missing', trackScroll: true });+ enterRecoveryWaitingForAnchor({ checkpointReason: 'component_preview_anchor_missing', trackScroll: true });waitForSvelteComponentTargetAndRetry({ manifestPath, sessionId, manifest });return;}@@ -5381,7 +5483,7 @@const wrapper = document.createElement('div');wrapper.dataset.impeccableVariants = sessionId;wrapper.dataset.impeccableVariantCount = String(manifest.count || expectedVariants || 1);- wrapper.dataset.impeccablePreview = 'svelte-component';+ wrapper.dataset.impeccablePreview = componentPreviewMode;wrapper.style.display = 'contents';const mountTarget = document.createElement('div');@@ -5419,8 +5521,8 @@recoveryWaitingForAnchor = false;const previousVisibleVariant = currentSessionId === sessionId ? visibleVariant : 0;- arrivedVariants = Number(manifest.count) || expectedVariants || 1;- expectedVariants = arrivedVariants;+ arrivedVariants = availableVariants;+ expectedVariants = Number(manifest.count) || expectedVariants || arrivedVariants;const saved = loadSession();const savedVisibleVariant = saved && saved.id === sessionId ? saved.visible : 0;visibleVariant = previousVisibleVariant > 0 && previousVisibleVariant <= arrivedVariants@@ -5445,9 +5547,10 @@refreshParamsPanel();positionBar();saveSession();- console.log('[impeccable] Mounted ' + arrivedVariants + ' Svelte component variants.');+ if (parameterGenerationState === 'loading') completeParameterPublication();+ console.log('[impeccable] Mounted ' + arrivedVariants + ' ' + manifest.framework + ' component variants.');} catch (err) {- console.error('[impeccable] Failed to mount Svelte component variants:', err);+ console.error('[impeccable] Failed to mount component-preview variants:', err);abortSvelteComponentInjection(sessionId, 'Could not load variants. Fix the error and re-run.');}}@@ -5493,6 +5596,8 @@clearHandled();resetSessionFileMeta();currentSessionId = null;+ parameterGenerationState = 'idle';+ parameterReadyAnnouncedSession = null;expectedVariants = 0;arrivedVariants = 0;visibleVariant = 0;@@ -5502,12 +5607,24 @@if (message) showToast(message, 5000);}+ // How many delayed re-reads a completion-driven source fallback gets when+ // the fetched source still shows only the preflight scaffold, before the+ // failure is surfaced via recoverEmptyCycling.+ const COMPLETED_SOURCE_FALLBACK_RETRIES = 3;+ const COMPLETED_SOURCE_FALLBACK_RETRY_MS = 1200;+/*** No-HMR fallback: fetch the raw source file from the live server,* parse it, extract the variant wrapper, and inject it into the live DOM.* This works even when the dev server caches HTML (Bun, static servers).+ *+ * opts.generationCompleted marks callers that KNOW the agent finished (a+ * `done` arrived or the server reported a completed generation). For them an+ * empty read is a stale source view and no further event is coming, so the+ * read retries a few times and then surfaces recovery. Callers without the+ * flag may be mid-generation and wait indefinitely for the real completion.*/- function injectVariantsFromSource(filePath, sessionId) {+ function injectVariantsFromSource(filePath, sessionId, opts = {}) {if (isSvelteComponentManifestPath(filePath)) {injectSvelteComponentsFromManifest(filePath, sessionId);return;@@ -5573,6 +5690,32 @@arrivedVariants = variants.length;expectedVariants = parseInt(wrapper.dataset.impeccableVariantCount || arrivedVariants);if (arrivedVariants <= 0) {+ if (state === 'GENERATING') {+ // Mid-generation the source legitimately holds a scaffold wrapper+ // with no variants yet (the server-side preflight wraps before the+ // agent writes). Tearing the session down here would destroy an+ // in-flight generation; stay in GENERATING — the variant observer+ // is armed and the server re-delivers a missed `done`.+ if (!opts.generationCompleted) {+ console.log('[impeccable] Source has scaffold but no variants yet; still generating.');+ return;+ }+ // Generation finished, yet the read shows only the scaffold: the+ // source view is stale and no further event will fire. Re-read a+ // few times before surfacing recovery — a single silent return+ // here would strand the tab in GENERATING forever.+ const attempt = opts.attempt || 0;+ if (attempt < COMPLETED_SOURCE_FALLBACK_RETRIES) {+ console.log('[impeccable] Generation is done but source shows no variants yet; retrying read ('+ + (attempt + 1) + '/' + COMPLETED_SOURCE_FALLBACK_RETRIES + ').');+ setTimeout(() => {+ if (state !== 'GENERATING' || currentSessionId !== sessionId) return;+ if (arrivedVariants > 0) return;+ injectVariantsFromSource(filePath, sessionId, { ...opts, attempt: attempt + 1 });+ }, COMPLETED_SOURCE_FALLBACK_RETRY_MS);+ return;+ }+ }recoverEmptyCycling('source-fallback-empty');return;}@@ -5594,6 +5737,7 @@refreshParamsPanel();positionBar();saveSession();+ if (parameterGenerationState === 'loading') completeParameterPublication();console.log('[impeccable] Injected ' + arrivedVariants + ' variants from source file.');}).catch(err => {@@ -5865,13 +6009,36 @@document.getElementById(VARIANT_STATE_STYLE_ID)?.remove();}+ function showOriginalDuringDiscard(sessionId) {+ if (!sessionId) return;+ let styleEl = document.getElementById(DISCARD_STATE_STYLE_ID);+ if (!styleEl) {+ styleEl = document.createElement('style');+ styleEl.id = DISCARD_STATE_STYLE_ID;+ (document.head || document.documentElement).appendChild(styleEl);+ }+ const wrapper = '[data-impeccable-variants="' + sessionId + '"]';+ styleEl.textContent = wrapper + ' > [data-impeccable-variant]:not([data-impeccable-variant="original"]) { display:none !important; }\n'+ + wrapper + ' > [data-impeccable-variant="original"] { display:block !important; }';+ }++ function resolveScrollLockAnchorTop() {+ const anchor = resolveBarAnchor();+ if (!anchor?.isConnected) return null;+ const top = anchor.getBoundingClientRect().top;+ return Number.isFinite(top) ? top : null;+ }+// Hold window.scrollY at a fixed value across DOM mutations inside the// session's wrapper (HMR patches, variant inserts, cycle swaps).- function startScrollLock(sessionId, initialTargetY) {+ function startScrollLock(sessionId, initialTargetY, initialAnchorTop) {stopScrollLock();scrollLockTargetY = typeof initialTargetY === 'number' && isFinite(initialTargetY)? initialTargetY: window.scrollY;+ scrollLockAnchorTop = typeof initialAnchorTop === 'number' && isFinite(initialAnchorTop)+ ? initialAnchorTop+ : resolveScrollLockAnchorTop();try { history.scrollRestoration = 'manual'; } catch {}@@ -5895,6 +6062,17 @@const correct = (why) => {scrollLockRaf = null;if (scrollLockTargetY == null) return;+ const anchor = resolveBarAnchor();+ if (anchor?.isConnected && typeof scrollLockAnchorTop === 'number' && isFinite(scrollLockAnchorTop)) {+ const anchorTop = anchor.getBoundingClientRect().top;+ const anchorDelta = anchorTop - scrollLockAnchorTop;+ if (Math.abs(anchorDelta) >= 0.5) {+ window.scrollTo({ top: window.scrollY + anchorDelta, left: window.scrollX, behavior: 'instant' });+ scrollLockTargetY = window.scrollY;+ writeScrollY(scrollLockTargetY);+ return;+ }+ }const before = window.scrollY;const delta = before - scrollLockTargetY;if (Math.abs(delta) < 0.5) {@@ -5939,6 +6117,7 @@if (scrollLockRaf != null) { cancelAnimationFrame(scrollLockRaf); scrollLockRaf = null; }const prevTarget = scrollLockTargetY;scrollLockTargetY = window.scrollY;+ scrollLockAnchorTop = resolveScrollLockAnchorTop();writeScrollY(scrollLockTargetY);};const markGesture = (why) => {@@ -5976,6 +6155,7 @@if (scrollLockRaf != null) { cancelAnimationFrame(scrollLockRaf); scrollLockRaf = null; }if (scrollLockAbort) { scrollLockAbort.abort(); scrollLockAbort = null; }scrollLockTargetY = null;+ scrollLockAnchorTop = null;// NOTE: do NOT clear the persistent scroll key here. startScrollLock// calls us as a reset, and clearing the key would nuke the Go-time// scrollY that the next resume needs to read.@@ -6049,6 +6229,7 @@updating = true;arrivedVariants = count;+ generationPhase = arrivedVariants >= expectedVariants ? 'variants_ready' : 'variants_progress';if (visibleVariant === 0 && arrivedVariants > 0) {const saved = loadSession();const savedVisibleVariant = saved && saved.id === sessionId ? saved.visible : 0;@@ -6064,7 +6245,7 @@const expected = parseInt(wrapper.dataset.impeccableVariantCount || '0');if (expected > 0) expectedVariants = expected;- if (arrivedVariants >= expectedVariants && expectedVariants > 0) {+ if (arrivedVariants > 0) {setLiveState('CYCLING');recoveryWaitingForAnchor = false;hideShaderOverlay();@@ -6072,13 +6253,18 @@updateSelectedElement();showOrUpdateCyclingBar();disableInlineEdit();- refreshParamsPanel();+ if (arrivedVariants >= expectedVariants && expectedVariants > 0) refreshParamsPanel();+ else hideParamsPanel();positionBar();} else if (state === 'GENERATING') {updateBarContent('generating');}saveSession();- queueCheckpoint(state === 'CYCLING' ? 'variants_ready' : 'variants_progress');+ sendCheckpoint(+ arrivedVariants >= expectedVariants && expectedVariants > 0+ ? 'variants_ready'+ : 'variants_progress',+ );updating = false;});@@ -6151,6 +6337,7 @@syncAgentPollingUi(!!msg.agentPolling);startAgentStatusPoll();restoreFromActiveSessions(msg.activeSessions, 'sse_connected');+ recoverMissedGenerationCompletion(msg.activeSessions);if (state === 'IDLE' && (pickActive || insertActive)) setLiveState('PICKING');syncPageInteractionCursor();syncPageChatFocus('sse-connected');@@ -6158,6 +6345,42 @@case 'agent_polling':syncAgentPollingUi(!!msg.connected);break;+ case 'agent_phase':+ if (msg.id === currentSessionId && (state === 'GENERATING' || state === 'CYCLING')) {+ generationPhase = msg.phase || generationPhase;+ if (msg.phase === 'variant_parameters_generating' || msg.phase === 'variant_parameters_validating') {+ parameterGenerationState = 'loading';+ }+ if (msg.phase === 'parameters_ready' && parameterGenerationState !== 'ready') {+ parameterGenerationState = 'loading';+ }+ updateBarContent(state === 'CYCLING' ? 'cycling' : 'generating');+ saveSession();+ }+ break;+ case 'variant_progress':+ if (msg.id === currentSessionId) {+ if (msg.publicationKind === 'params') parameterGenerationState = 'loading';+ rememberSessionFileMeta(msg);+ if (isFrameworkComponentPreviewMode(msg.previewMode) && msg.previewFile) {+ injectSvelteComponentsFromManifest(msg.previewFile, msg.id);+ } else if ((msg.previewMode === 'source' || !msg.previewMode) && (msg.previewFile || msg.file)) {+ // Give normal framework HMR the first chance to reconcile its+ // own managed tree. Nuxt route-module HMR can skip intermediate+ // revisions, so fall back to source injection only when the+ // advertised progress still has not appeared after a short+ // settle. Immediate injection races React/Vue ownership and can+ // trigger removeChild errors on the next HMR commit.+ const targetArrived = Number(msg.arrivedVariants) || 1;+ setTimeout(() => {+ if (msg.id !== currentSessionId) return;+ if (state !== 'GENERATING' && state !== 'CYCLING') return;+ if (msg.publicationKind !== 'params' && arrivedVariants >= targetArrived) return;+ injectVariantsFromSource(msg.previewFile || msg.file, msg.id);+ }, 150);+ }+ }+ break;case 'steer_done':maybeCompleteSteer(msg);break;@@ -6175,6 +6398,10 @@case 'done':if (maybeCompleteSteer(msg)) break;rememberSessionFileMeta(msg);+ if (msg.id === currentSessionId && isFrameworkComponentPreviewMode(currentPreviewMode) && currentPreviewFile) {+ injectSvelteComponentsFromManifest(currentPreviewFile, msg.id);+ break;+ }// Variants already arrived via HMR → normal transition.if (arrivedVariants >= expectedVariants && expectedVariants > 0) {if (state === 'GENERATING') {@@ -6190,7 +6417,7 @@setTimeout(() => {if (arrivedVariants >= expectedVariants && expectedVariants > 0) return;if (state !== 'GENERATING' || msg.id !== currentSessionId) return;- injectVariantsFromSource(msg.file, msg.id);+ injectVariantsFromSource(msg.file, msg.id, { generationCompleted: true });}, 750);break;}@@ -6215,9 +6442,10 @@if (maybeCompleteAcceptedSession(msg)) break;break;case 'agent_done':- // Carbonize accepts are not terminal until live-complete.mjs sends- // the final complete event. Keep the browser in its recoverable- // saving state while the source cleanup is still in flight.+ // The deterministic accept has already committed the reviewed DOM+ // and fenced generation. Carbonize may continue in the background;+ // it must not hold the foreground picker hostage.+ if (msg.data?.carbonize === true && maybeCompleteAcceptedSession(msg)) break;break;case 'discarded':if (msg.id && msg.id === currentSessionId) {@@ -6306,6 +6534,7 @@type: 'checkpoint',id: currentSessionId,revision: sessionState.nextCheckpointRevision(),+ revisionDomain: 'browser',owner: browserOwner,phase: String(state || '').toLowerCase(),reason,@@ -6331,6 +6560,7 @@type: 'checkpoint',id,revision: sessionState.nextCheckpointRevision(),+ revisionDomain: 'browser',owner: browserOwner,phase: 'steer',reason,@@ -6684,6 +6914,9 @@expectedVariants = selectedCount;arrivedVariants = 0;visibleVariant = 0;+ generationPhase = 'queued';+ parameterGenerationState = 'pending';+ parameterReadyAnnouncedSession = null;resetSessionFileMeta();// Flip to GENERATING immediately so the bar morphs without waiting on@@ -6693,6 +6926,7 @@const elForCapture = selectedElement;pickedAnchorSnapshot = buildPickedAnchorSnapshot(elForCapture);const captureRect = elForCapture.getBoundingClientRect();+ pickedAnchorViewportTop = captureRect.top;const snapshot = {comments: annotState.comments.map(c => ({ x: c.x, y: c.y, text: c.text })),strokes: annotState.strokes.map(s => ({ points: s.points.map(p => [p[0], p[1]]) })),@@ -6724,7 +6958,7 @@writeScrollY(window.scrollY);if (variantObserver) variantObserver.disconnect();variantObserver = startVariantObserver(currentSessionId);- startScrollLock(currentSessionId);+ startScrollLock(currentSessionId, window.scrollY, pickedAnchorViewportTop);captureAndEmit(elForCapture, basePayload, snapshot, captureRect);}@@ -6759,12 +6993,16 @@expectedVariants = selectedCount;arrivedVariants = 0;visibleVariant = 0;+ generationPhase = 'queued';+ parameterGenerationState = 'pending';+ parameterReadyAnnouncedSession = null;resetSessionFileMeta();selectedElement = placeholderElement;insertPlaceholderSnapshot = buildInsertPlaceholderSnapshotFromDom(insertAnchorElement, placeholderElement);const elForCapture = placeholderElement;const captureRect = elForCapture.getBoundingClientRect();+ pickedAnchorViewportTop = captureRect.top;const basePayload = {type: 'generate',mode: 'insert',@@ -6795,7 +7033,7 @@writeScrollY(window.scrollY);if (variantObserver) variantObserver.disconnect();variantObserver = startVariantObserver(currentSessionId);- startScrollLock(currentSessionId);+ startScrollLock(currentSessionId, window.scrollY, pickedAnchorViewportTop);captureAndEmit(elForCapture, basePayload, snapshot, captureRect);}@@ -6975,9 +7213,9 @@// preview mounts are covered by the same shader regression checks.const adapter = String(window.__IMPECCABLE_LIVE_ADAPTER__ || '').toLowerCase();if (adapter === 'svelte' || adapter === 'sveltekit') return true;- if (currentPreviewMode === 'svelte-component' || svelteComponentSession) return true;+ if (isFrameworkComponentPreviewMode(currentPreviewMode) || svelteComponentSession) return true;const wrapper = el?.closest?.('[data-impeccable-variants]');- return wrapper?.dataset?.impeccablePreview === 'svelte-component';+ return isFrameworkComponentPreviewMode(wrapper?.dataset?.impeccablePreview);}function paintsShaderProxySurface(node) {@@ -7105,6 +7343,17 @@}async function captureAndEmit(el, basePayload, snapshot, rect) {+ const hasAnnotations = snapshot && (snapshot.comments.length > 0 || snapshot.strokes.length > 0);++ // Plain requests do not send a screenshot to the agent, so capture is+ // presentation-only. Wait only for the helper to accept the event before+ // starting CPU-heavy capture; this yields the browser task and prevents+ // rasterization from delaying the fetch itself.+ if (!hasAnnotations) {+ basePayload.clientSentAt = Date.now();+ await sendEvent(basePayload);+ }+let screenshotPath;let blob;let paper;@@ -7122,7 +7371,6 @@// are present. Without annotations the image is pure visual anchoring -// it biases the model toward the current rendering and works against the// three-distinct-directions brief.- const hasAnnotations = snapshot && (snapshot.comments.length > 0 || snapshot.strokes.length > 0);if (blob && hasAnnotations) {try {const uploadRes = await fetch(@@ -7140,7 +7388,12 @@console.warn('[impeccable] annotation upload failed:', err);}}- sendEvent(screenshotPath ? { ...basePayload, screenshotPath } : basePayload);+ // Annotated requests must wait for capture + upload because the screenshot+ // is semantic input. Plain requests were already dispatched above.+ if (hasAnnotations) {+ basePayload.clientSentAt = Date.now();+ sendEvent(screenshotPath ? { ...basePayload, screenshotPath } : basePayload);+ }}//@@ -7520,7 +7773,6 @@ void main() {if (variantSelectionPromise) {try { await variantSelectionPromise; } catch { /* failed selection falls back below */ }}- if (!currentSessionId || arrivedVariants === 0) return;const domVisibleVariant = readVisibleVariantFromDOM(currentSessionId);if (domVisibleVariant > 0) visibleVariant = domVisibleVariant;const acceptPayload = {@@ -7528,7 +7780,9 @@ void main() {id: currentSessionId,variantId: String(visibleVariant),pageUrl: location.pathname,+ clientSentAt: Date.now(),};+ if (!currentSessionId || arrivedVariants === 0) return;const acceptWrapper = document.querySelector('[data-impeccable-variants="' + currentSessionId + '"]');if (Object.keys(paramsCurrentValues).length > 0) {acceptPayload.paramValues = { ...paramsCurrentValues };@@ -7542,7 +7796,7 @@ void main() {const acceptedSessionId = currentSessionId;const acceptedVariant = visibleVariant;const acceptedIsSvelteComponent = svelteComponentSession?.sessionId === acceptedSessionId- || acceptWrapper?.dataset?.impeccablePreview === 'svelte-component';+ || isFrameworkComponentPreviewMode(acceptWrapper?.dataset?.impeccablePreview);const acceptedSnapshot = snapshotAcceptedVariantDom(acceptedSessionId, acceptedVariant);setLiveState('SAVING');@@ -7557,7 +7811,17 @@ void main() {saveSession();sendEvent(acceptPayload, { throwOnError: true })- .then(() => {})+ .then(() => {+ const pending = pendingAcceptedSession;+ if (!pending || pending.id !== acceptedSessionId) return;+ // POST /events returns only after the accept intent is durable and the+ // generation epoch is fenced. Source promotion/carbonize can finish in+ // the background; the foreground picker is free immediately.+ markSessionHandled();+ setLiveState('CONFIRMED');+ document.documentElement.dataset.impeccableAcceptToPickingMs = String(Date.now() - acceptPayload.clientSentAt);+ scheduleAcceptCleanup(pending);+ }).catch(() => {if (pendingAcceptedSession?.id === acceptedSessionId) pendingAcceptedSession = null;setLiveState('CYCLING');@@ -7586,17 +7850,26 @@ void main() {}function scheduleAcceptCleanup(accepted) {- setTimeout(function() {- if (!accepted?.isSvelteComponent && !acceptedDomAlreadyClean(accepted)) {- setTimeout(function() {- if (pendingAcceptedSession?.id !== accepted?.id) return;- if (!accepted?.isSvelteComponent) ensureAcceptedDomClean(accepted);- cleanupAcceptedSession();- }, 1800);- return;+ queueMicrotask(function() {+ if (pendingAcceptedSession?.id !== accepted?.id) return;+ // Svelte previews live in an adapter-owned mount rather than in source+ // wrapper markup. Promote the mounted variant before releasing the+ // session so the old adapter instance cannot linger behind the next+ // Pick → Go loop while carbonize finishes in the background.+ if (accepted?.isSvelteComponent) {+ commitAcceptedSvelteComponentToDom(accepted.id);}cleanupAcceptedSession();- }, 1200);+ });+ // Let React/Vue/Svelte own the HMR reconciliation. Mutating their DOM in+ // the same turn as the source update causes removeChild/NotFoundError+ // races. Static servers still need a fallback, but it must not keep Live+ // in SAVING or block the user's next pick.+ if (!accepted?.isSvelteComponent) {+ setTimeout(function() {+ if (!acceptedDomAlreadyClean(accepted)) ensureAcceptedDomClean(accepted);+ }, 1200);+ }}function snapshotAcceptedVariantDom(sessionId, variantId) {@@ -7700,7 +7973,11 @@ void main() {clearSession();resetSessionFileMeta();selectedElement = null;+ hoveredElement = null;+ pagePickSkipClick = false;currentSessionId = null;+ parameterGenerationState = 'idle';+ parameterReadyAnnouncedSession = null;selectedAction = 'impeccable';pendingAcceptedSession = null;renderEditBadge('hidden');@@ -7735,7 +8012,7 @@ void main() {sendEvent({ type: 'discard', id: currentSessionId }, { throwOnError: true }).then(() => {markSessionHandled();- cleanup();+ cleanup({ restoreOriginal: true, instantChrome: true });}).catch(() => showToast('Could not confirm discard with the live server. Session kept for recovery.', 5000));}@@ -7757,6 +8034,7 @@ void main() {currentPreviewMode = null;recoveryWaitingForAnchor = false;pickedAnchorSnapshot = null;+ pickedAnchorViewportTop = null;}function rememberSessionFileMeta(meta = {}) {@@ -7765,8 +8043,8 @@ void main() {const previewFile = normalizeSessionPath(meta.previewFile);const previewMode = meta.previewMode || (isSvelteComponentManifestPath(previewFile || file) ? 'svelte-component' : null);- if (previewMode === 'svelte-component' || isSvelteComponentManifestPath(file)) {- currentPreviewMode = 'svelte-component';+ if (isFrameworkComponentPreviewMode(previewMode) || isSvelteComponentManifestPath(file)) {+ currentPreviewMode = isFrameworkComponentPreviewMode(previewMode) ? previewMode : 'svelte-component';currentPreviewFile = previewFile || (isSvelteComponentManifestPath(file) ? file : currentPreviewFile);currentSourceFile = sourceFile || currentSourceFile;return;@@ -7782,12 +8060,15 @@ void main() {rememberSessionFileMeta(saved);if (saved.insertPlaceholder) insertPlaceholderSnapshot = saved.insertPlaceholder;if (saved.pickedAnchor) pickedAnchorSnapshot = saved.pickedAnchor;+ if (Number.isFinite(saved.pickedAnchorViewportTop)) pickedAnchorViewportTop = saved.pickedAnchorViewportTop;if (saved.action) selectedAction = saved.action;if (saved.count) selectedCount = saved.count;if (saved.previewMode) currentPreviewMode = saved.previewMode;if (saved.paramValues && typeof saved.paramValues === 'object') {paramsCurrentValues = { ...saved.paramValues };}+ if (saved.parameterState) parameterGenerationState = saved.parameterState;+ if (saved.generationPhase) generationPhase = saved.generationPhase;}function normalizePagePath(value) {@@ -7859,7 +8140,7 @@ void main() {saveSession();queueCheckpoint(reason || 'browser_restore_without_wrapper');- const restoreFile = currentPreviewMode === 'svelte-component'+ const restoreFile = isFrameworkComponentPreviewMode(currentPreviewMode)? currentPreviewFile: (currentSourceFile || currentPreviewFile);if (restoreFile) {@@ -7872,11 +8153,41 @@ void main() {function restoreFromActiveSessions(activeSessions, reason) {const wrapper = document.querySelector('[data-impeccable-variants]');- if (wrapper && wrapper.dataset.impeccablePreview !== 'svelte-component') return false;+ if (wrapper && !isFrameworkComponentPreviewMode(wrapper.dataset.impeccablePreview)) return false;if (svelteComponentSession?.sessionId === currentSessionId) return false;return restoreSessionWithoutWrapper(reason || 'sse_connected', activeSessions);}+ // Self-heal on SSE (re)connect. The preflight scaffold write triggers a+ // framework full-reload (Astro reloads pages for any .astro edit); if the+ // agent's variant write + `done` broadcast land while this page is+ // mid-reload, both the done SSE and the second HMR reload are missed and+ // the resumed page would wait in GENERATING at 0/N forever. The server's+ // session summary carries the durable generationCompletedAt marker, so on+ // every connect compare it against our own progress and pull the finished+ // variants from source when behind. Mirrors the `done` handler's source+ // fallback, including its give-HMR-the-first-chance settle delay.+ function recoverMissedGenerationCompletion(activeSessions) {+ if (!currentSessionId || state !== 'GENERATING') return;+ if (!Array.isArray(activeSessions)) return;+ const summary = activeSessions.find((session) => session?.id === currentSessionId);+ if (!summary?.generationCompletedAt || summary.generationCanceled) return;+ if (isTerminalSessionSummary(summary)) return;+ if (arrivedVariants > 0 && arrivedVariants >= expectedVariants) return;+ rememberSessionFileMeta(summary);+ const sessionId = currentSessionId;+ const file = isFrameworkComponentPreviewMode(currentPreviewMode)+ ? currentPreviewFile+ : (summary.sourceFile || summary.previewFile || currentSourceFile || currentPreviewFile);+ if (!file) return;+ console.log('[impeccable] Reconnected after generation completed; recovering variants from source.');+ setTimeout(() => {+ if (sessionId !== currentSessionId || state !== 'GENERATING') return;+ if (arrivedVariants > 0 && arrivedVariants >= expectedVariants) return;+ injectVariantsFromSource(file, sessionId, { generationCompleted: true });+ }, 750);+ }+function saveSession() {if (!currentSessionId) return;// NOTE: scrollY is stored under a separate key (writeScrollY). Storing@@ -7894,8 +8205,12 @@ void main() {previewMode: currentPreviewMode || undefined,pageUrl: location.pathname,paramValues: { ...paramsCurrentValues },+ parameterState: parameterGenerationState,insertPlaceholder: insertPlaceholderSnapshot || undefined,pickedAnchor: pickedAnchorSnapshot || undefined,+ pickedAnchorViewportTop: Number.isFinite(pickedAnchorViewportTop) ? pickedAnchorViewportTop : undefined,+ pageHash: location.hash || undefined,+ pageSearch: location.search || undefined,});}@@ -7923,20 +8238,26 @@ void main() {sessionState.clearHandled();}- function cleanup() {+ function cleanup(options) {+ const restoreOriginal = options?.restoreOriginal === true;+ const instantChrome = options?.instantChrome === true;const cleanupSessionId = currentSessionId;if (svelteComponentSession?.sessionId === cleanupSessionId) {teardownSvelteComponentSession(true);} else if (cleanupSessionId) {- // Hide the wrapper immediately so variants disappear. DON'T structurally- // mutate the DOM yet - HMR from the agent's source rewrite is on its way,+ // Switch visibility immediately without structurally mutating the DOM.+ // HMR from the agent's source rewrite may still be on its way,// and a manual replaceChild under React causes NotFoundError when the// reconciler later tries to remove a wrapper we already removed.// Schedule a 2s fallback that does the manual swap only if HMR hasn't// replaced the wrapper by then (keeps static-server / no-HMR flows alive).const wrapper = document.querySelector('[data-impeccable-variants="' + cleanupSessionId + '"]');- if (wrapper) wrapper.style.display = 'none';+ if (wrapper) {+ if (restoreOriginal) showOriginalDuringDiscard(cleanupSessionId);+ else wrapper.style.display = 'none';+ }setTimeout(function() {+ document.getElementById(DISCARD_STATE_STYLE_ID)?.remove();if (!cleanupSessionId) return;const lateWrapper = document.querySelector('[data-impeccable-variants="' + cleanupSessionId + '"]');if (!lateWrapper) return;@@ -7951,7 +8272,7 @@ void main() {lateWrapper.remove();}, 2000);}- hideBar();+ hideBar(instantChrome);hideHighlight();stopScrollTracking();if (variantObserver) { variantObserver.disconnect(); variantObserver = null; }@@ -7963,7 +8284,11 @@ void main() {clearSession();resetSessionFileMeta();selectedElement = null;+ hoveredElement = null;+ pagePickSkipClick = false;currentSessionId = null;+ parameterGenerationState = 'idle';+ parameterReadyAnnouncedSession = null;selectedAction = 'impeccable';renderEditBadge('hidden');setLiveState('PICKING');@@ -8047,7 +8372,7 @@ void main() {// would strand the bar in CYCLING at 0/0. If there's no live in-memory mount// for this wrapper, it's an orphan (reload / failed mount): drop it and let// the live-server's SSE re-inject the manifest if the session is still live.- if (wrapper.dataset.impeccablePreview === 'svelte-component'+ if (isFrameworkComponentPreviewMode(wrapper.dataset.impeccablePreview)&& svelteComponentSession?.sessionId !== sessionId) {wrapper.remove();if (restoreSessionWithoutWrapper('browser_resumed_svelte_orphan_wrapper')) return true;@@ -8056,7 +8381,7 @@ void main() {return false;}- if (wrapper.dataset.impeccablePreview === 'svelte-component') {+ if (isFrameworkComponentPreviewMode(wrapper.dataset.impeccablePreview)) {if (!svelteComponentSession?.mountedVariant) {return true;}@@ -8104,7 +8429,7 @@ void main() {insertPlaceholderSnapshot = saved.insertPlaceholder;}- const resumedState = arrivedVariants >= expectedVariants ? 'CYCLING' : 'GENERATING';+ const resumedState = arrivedVariants > 0 ? 'CYCLING' : 'GENERATING';// Find the visible variant's content element for highlight positioning.const isInsert = wrapper.dataset.impeccableMode === 'insert';@@ -8128,7 +8453,11 @@ void main() {// hid. Now that state is CYCLING, re-fire.if (state === 'CYCLING') refreshParamsPanel();saveSession();- queueCheckpoint('browser_resumed');+ if (arrivedVariants > 0 && arrivedVariants < expectedVariants) {+ sendCheckpoint('variants_progress');+ } else {+ queueCheckpoint('browser_resumed');+ }// Start observing for more variants AFTER initial setupif (variantObserver) variantObserver.disconnect();@@ -8136,7 +8465,7 @@ void main() {// Hold the target at its saved viewport top through any subsequent// HMR patches, variant inserts, or cycle swaps.- startScrollLock(currentSessionId, readScrollY());+ startScrollLock(currentSessionId, readScrollY(), pickedAnchorViewportTop);// If we reloaded mid-generation (Bun's HTML HMR destroys the shader// canvas), re-capture the original's content and restart the shader so@@ -8171,6 +8500,7 @@ void main() {let globalBarBrandEl = null;let agentPollTooltipEl = null;let agentPollingConnected = false;+ let agentStatusMessage = null;let agentStatusPollTimer = null;let steerFocusSuspended = false;let steerFocusPauseUntil = 0;@@ -8275,6 +8605,13 @@ void main() {const AGENT_STATUS_POLL_MS = 5000;const AGENT_DISCONNECTED_MARK = 'oklch(62% 0 0 / 0.78)';const AGENT_DISCONNECTED_TIP = 'Agent disconnected - run live-poll.mjs to connect';+ // The indicator tracks whether a poll is parked, which is what decides if+ // steering can reach the agent right now. That goes quiet two ways, and they+ // need different copy: nobody is polling at all, or the agent took the work+ // and is busy with it. Under one-shot foreground polling the second case is+ // every normal generation, and telling the user to start a poll loop then is+ // wrong advice about a healthy session.+ const AGENT_BUSY_TIP = 'Agent is working - steering resumes when it finishes';const GLOBAL_BAR_SECTION_GAP = 8;const GLOBAL_BAR_INNER_GAP = 2;const GLOBAL_BAR_INNER_PAD_LEFT = 2;@@ -9295,24 +9632,46 @@ void main() {</svg>`;}+ /**+ * True while the browser is waiting on work it already handed to the agent.+ * In these states a quiet poll indicator means "busy", not "absent".+ */+ function agentHasWorkInFlight() {+ return state === 'GENERATING' || state === 'SAVING';+ }++ /**+ * Derived at read time, not cached: which of the two reasons applies depends on+ * the live state, which moves between the 5s status polls. The truthiness is+ * the same either way, so the indicator's visuals can stay driven by the+ * cached value while the wording stays current.+ */+ function agentStatusText() {+ if (agentPollingConnected) return null;+ return agentHasWorkInFlight() ? AGENT_BUSY_TIP : AGENT_DISCONNECTED_TIP;+ }+function syncAgentPollingUi(connected) {agentPollingConnected = !!connected;if (!globalBarBrandEl) return;const P = barPaletteForTheme(globalBarEl?.dataset.theme || detectPageTheme());+ agentStatusMessage = agentStatusText();globalBarBrandEl.dataset.agentConnected = connected ? 'true' : 'false';- globalBarBrandEl.setAttribute('aria-label', connected- ? 'Impeccable live mode'- : 'Impeccable live mode - agent not polling');+ // The tooltip is mouse-only, so carry the same distinction in the label or+ // screen-reader users are left with the vaguer of the two readings.+ globalBarBrandEl.setAttribute('aria-label', agentStatusMessage+ ? 'Impeccable live mode - ' + (agentHasWorkInFlight() ? 'agent is working' : 'agent not polling')+ : 'Impeccable live mode');globalBarBrandEl.removeAttribute('title');- globalBarBrandEl.style.cursor = connected ? 'default' : 'help';+ globalBarBrandEl.style.cursor = agentStatusMessage ? 'help' : 'default';const mark = globalBarBrandEl.querySelector('[data-brand-mark]');if (mark) {mark.innerHTML = brandMarkSvg(connected ? P.accent : AGENT_DISCONNECTED_MARK, 18);mark.style.opacity = '1';}const dot = globalBarBrandEl.querySelector('[data-agent-dot]');- if (dot) dot.style.display = connected ? 'none' : 'block';- if (connected) hideAgentPollTooltip();+ if (dot) dot.style.display = agentStatusMessage ? 'block' : 'none';+ if (!agentStatusMessage) hideAgentPollTooltip();}function ensureAgentPollTooltip() {@@ -9339,14 +9698,17 @@ void main() {whiteSpace: 'normal',});agentPollTooltipEl.id = PREFIX + '-agent-poll-tooltip';- agentPollTooltipEl.textContent = AGENT_DISCONNECTED_TIP;+ agentPollTooltipEl.textContent = agentStatusText() || AGENT_DISCONNECTED_TIP;uiAppend(agentPollTooltipEl);return agentPollTooltipEl;}function showAgentPollTooltip(anchor) {- if (agentPollingConnected || !anchor) return;+ if (!agentStatusMessage || !anchor) return;const tip = ensureAgentPollTooltip();+ // Re-derive rather than reuse the cached copy: the live state may have moved+ // since the last status poll set it.+ tip.textContent = agentStatusText() || AGENT_DISCONNECTED_TIP;tip.style.transition = 'none';tip.style.display = 'block';tip.style.opacity = '1';@@ -9376,7 +9738,9 @@ void main() {fetch('http://localhost:' + PORT + '/status?token=' + TOKEN, { cache: 'no-store' }).then((res) => (res.ok ? res.json() : null)).then((data) => {- if (data && typeof data.agentPolling === 'boolean') syncAgentPollingUi(data.agentPolling);+ if (data && typeof data.agentPolling === 'boolean') {+ syncAgentPollingUi(data.agentPolling);+ }}).catch(() => { /* server loss handled elsewhere */ });}diff --git a/.pi/skills/impeccable/scripts/live-inject.mjs b/.pi/skills/impeccable/scripts/live-inject.mjsindex 7c8d91182..d99c37fd5 100644--- a/.pi/skills/impeccable/scripts/live-inject.mjs+++ b/.pi/skills/impeccable/scripts/live-inject.mjs@@ -27,6 +27,8 @@ const __dirname = path.dirname(fileURLToPath(import.meta.url));const CONFIG_PATH = resolveLiveConfigPath({ cwd: process.cwd(), scriptsDir: __dirname });const MARKER_OPEN_TEXT = 'impeccable-live-start';const MARKER_CLOSE_TEXT = 'impeccable-live-end';+const NUXT_PLUGIN_MARKER = 'impeccable-live-nuxt-plugin';+const NUXT_PLUGIN_NAME = 'impeccable-live.client.ts';const IGNORE_MARKER_OPEN = '# impeccable-live-ignore-start';const IGNORE_MARKER_CLOSE = '# impeccable-live-ignore-end';@@ -38,6 +40,9 @@ export const LIVE_IGNORE_PATTERNS = Object.freeze(['.impeccable/live/sessions/','.impeccable/live/previews/','.impeccable/live/annotations/',+ '.impeccable/live/artifacts/',+ '.impeccable/live/accept-receipts/',+ '.impeccable/live/locks/','.impeccable/live/cache/','.impeccable/live/manual-edit-apply-transaction.json','.impeccable/live/manual-edit-events.jsonl',@@ -46,10 +51,15 @@ export const LIVE_IGNORE_PATTERNS = Object.freeze(['.impeccable/live/deferred-svelte-component-accepts.json','.impeccable-live.json','.impeccable-live/',+ 'app/.impeccable-live/',+ 'src/.impeccable-live/','node_modules/.impeccable-live/','src/lib/impeccable/ImpeccableLiveRoot.svelte','src/lib/impeccable/__runtime.js','src/lib/impeccable/[0-9a-f]*/',+ 'plugins/impeccable-live.client.ts',+ 'app/plugins/impeccable-live.client.ts',+ 'src/plugins/impeccable-live.client.ts',]);/**@@ -113,6 +123,7 @@ Output (JSON):const resolvedFiles = resolveFiles(process.cwd(), config);const svelteKit = detectSvelteKitProject(process.cwd(), config);+ const nuxt = detectNuxtProject(process.cwd());if (args.includes('--remove')) {if (svelteKit) {@@ -120,6 +131,12 @@ Output (JSON):console.log(JSON.stringify({ ok: true, adapter: 'sveltekit', results: [adapterResult] }));return;}+ if (nuxt) {+ const adapterResult = removeNuxtLiveAdapter({ cwd: process.cwd(), project: nuxt });+ console.log(JSON.stringify({ ok: !adapterResult.error, adapter: 'nuxt', results: [adapterResult] }));+ if (adapterResult.error) process.exitCode = 1;+ return;+ }const results = resolvedFiles.map((relFile) => {const absFile = path.resolve(process.cwd(), relFile);if (!fs.existsSync(absFile)) return { file: relFile, error: 'file_not_found' };@@ -145,13 +162,28 @@ Output (JSON):console.error(JSON.stringify({ ok: false, error: 'missing_port' }));process.exit(1);}- const gitIgnore = ensureLiveGitIgnores(process.cwd());+ const gitIgnore = ensureLiveGitIgnores(+ process.cwd(),+ nuxt ? [nuxt.pluginFile] : [],+ );if (svelteKit) {const adapterResult = applySvelteKitLiveAdapter({ cwd: process.cwd(), port, config });console.log(JSON.stringify({ ok: true, port, adapter: 'sveltekit', gitIgnore, results: [adapterResult] }));return;}+ if (nuxt) {+ const adapterResult = applyNuxtLiveAdapter({ cwd: process.cwd(), port, project: nuxt });+ console.log(JSON.stringify({+ ok: !adapterResult.error,+ port,+ adapter: 'nuxt',+ gitIgnore,+ results: [adapterResult],+ }));+ if (adapterResult.error) process.exitCode = 1;+ return;+ }const results = resolvedFiles.map((relFile) => {const absFile = path.resolve(process.cwd(), relFile);@@ -175,12 +207,12 @@ Output (JSON):if (!anyInserted) process.exit(1);}-export function ensureLiveGitIgnores(cwd = process.cwd()) {+export function ensureLiveGitIgnores(cwd = process.cwd(), extraPatterns = []) {const target = resolveIgnoreTarget(cwd);const existing = fs.existsSync(target.path) ? fs.readFileSync(target.path, 'utf-8') : '';const block = [IGNORE_MARKER_OPEN,- ...LIVE_IGNORE_PATTERNS,+ ...new Set([...LIVE_IGNORE_PATTERNS, ...extraPatterns]),IGNORE_MARKER_CLOSE,].join('\n');const markerRe = new RegExp(`${escapeRegExp(IGNORE_MARKER_OPEN)}[\\s\\S]*?${escapeRegExp(IGNORE_MARKER_CLOSE)}`);@@ -202,10 +234,119 @@ export function ensureLiveGitIgnores(cwd = process.cwd()) {file: path.relative(cwd, target.path).split(path.sep).join('/'),mode: target.mode,changed: updated !== existing,- patterns: [...LIVE_IGNORE_PATTERNS],+ patterns: [...new Set([...LIVE_IGNORE_PATTERNS, ...extraPatterns])],};}+// ---------------------------------------------------------------------------+// Nuxt adapter+//+// A script element placed in app.vue is compiled as Vue-rendered DOM and is+// not executed. Nuxt instead auto-discovers client plugins. Keep the adapter+// generated, dev-only, and outside user-authored source: Live creates one+// marked .client.ts plugin on start and removes it on stop.+// ---------------------------------------------------------------------------++export function detectNuxtProject(cwd = process.cwd()) {+ const configFile = fs.readdirSync(cwd, { withFileTypes: true })+ .find((entry) => entry.isFile() && /^nuxt\.config\.(?:js|mjs|cjs|ts|mts|cts)$/.test(entry.name))+ ?.name;+ if (!configFile) return null;++ const config = fs.readFileSync(path.join(cwd, configFile), 'utf-8');+ const literalSrcDir = config.match(/\bsrcDir\s*:\s*(['"])([^'"]+)\1/);+ let appDir = '';+ if (literalSrcDir) {+ const candidate = literalSrcDir[2]+ .replace(/\\/g, '/')+ .replace(/^\.\//, '')+ .replace(/\/+$/, '');+ const normalized = path.posix.normalize(candidate);+ if (normalized !== '..' && !normalized.startsWith('../') && !path.isAbsolute(normalized)) {+ appDir = normalized === '.' ? '' : normalized;+ }+ } else if (+ fs.existsSync(path.join(cwd, 'app', 'app.vue'))+ || fs.existsSync(path.join(cwd, 'app', 'pages'))+ ) {+ appDir = 'app';+ }++ const pluginFile = [appDir, 'plugins', NUXT_PLUGIN_NAME].filter(Boolean).join('/');+ return { configFile, appDir, pluginFile };+}++export function buildNuxtPlugin(port) {+ return `/* ${NUXT_PLUGIN_MARKER} */+const liveSrc = 'http://localhost:${port}/live.js';+const liveSelector = 'script[data-impeccable-live-nuxt]';++export default defineNuxtPlugin(() => {+ if (!import.meta.dev || typeof document === 'undefined') return;++ const expectedSrc = new URL(liveSrc, window.location.href).href;+ let script = document.querySelector(liveSelector);+ if (script?.src === expectedSrc) return;+ script?.remove();++ script = document.createElement('script');+ script.src = liveSrc;+ script.async = true;+ script.dataset.impeccableLiveNuxt = '';+ document.head.appendChild(script);++ import.meta.hot?.dispose(() => {+ if (script?.isConnected) script.remove();+ });+});+/* /${NUXT_PLUGIN_MARKER} */+`;+}++export function applyNuxtLiveAdapter({ cwd = process.cwd(), port, project = detectNuxtProject(cwd) }) {+ if (!project) return { error: 'nuxt_not_detected' };+ const absFile = path.join(cwd, project.pluginFile);+ const existing = fs.existsSync(absFile) ? fs.readFileSync(absFile, 'utf-8') : null;+ if (existing !== null && !existing.includes(NUXT_PLUGIN_MARKER)) {+ return {+ file: project.pluginFile,+ error: 'nuxt_plugin_conflict',+ hint: `${project.pluginFile} already exists and is not managed by Impeccable Live`,+ };+ }++ const content = buildNuxtPlugin(port);+ fs.mkdirSync(path.dirname(absFile), { recursive: true });+ if (content !== existing) fs.writeFileSync(absFile, content, 'utf-8');+ return {+ file: project.pluginFile,+ inserted: true,+ changed: content !== existing,+ devOnly: true,+ };+}++export function removeNuxtLiveAdapter({ cwd = process.cwd(), project = detectNuxtProject(cwd) }) {+ if (!project) return { error: 'nuxt_not_detected' };+ const absFile = path.join(cwd, project.pluginFile);+ if (!fs.existsSync(absFile)) {+ return { file: project.pluginFile, removed: false, note: 'no adapter present' };+ }+ const content = fs.readFileSync(absFile, 'utf-8');+ if (!content.includes(NUXT_PLUGIN_MARKER)) {+ return {+ file: project.pluginFile,+ removed: false,+ error: 'nuxt_plugin_conflict',+ hint: `${project.pluginFile} is not managed by Impeccable Live`,+ };+ }+ fs.unlinkSync(absFile);+ const pluginDir = path.dirname(absFile);+ if (fs.readdirSync(pluginDir).length === 0) fs.rmdirSync(pluginDir);+ return { file: project.pluginFile, removed: true };+}+function resolveIgnoreTarget(cwd) {const gitExcludePath = resolveGitInfoExcludePath(cwd);if (gitExcludePath) {diff --git a/.pi/skills/impeccable/scripts/live-poll.mjs b/.pi/skills/impeccable/scripts/live-poll.mjsindex 740161e10..19a8b0f9b 100644--- a/.pi/skills/impeccable/scripts/live-poll.mjs+++ b/.pi/skills/impeccable/scripts/live-poll.mjs@@ -27,7 +27,7 @@ const scriptCmd = (name) => `node "${path.join(SELF_DIR, name)}"`;export const PER_REQUEST_TIMEOUT_MS = 270_000;export const DEFAULT_EVENT_LEASE_MS = 600_000;-const EVENT_TYPES_NEEDING_AGENT_REPLY = new Set(['generate', 'steer', 'manual_edit_apply']);+const EVENT_TYPES_NEEDING_AGENT_REPLY = new Set(['generate', 'steer', 'manual_edit_apply', 'carbonize_cleanup']);function readServerInfo() {const record = readLiveServerInfo(process.cwd());@@ -38,8 +38,8 @@ function readServerInfo() {return record.info;}-export function buildPollReplyPayload(token, { id, type, message, file, data }) {- return { token, id, type, message, file, data };+export function buildPollReplyPayload(token, { id, type, message, file, data, sourceEventType }) {+ return { token, id, type, message, file, data, sourceEventType };}export function manualApplyPollBanner(event = {}) {@@ -152,7 +152,14 @@ export async function waitForEventAck(base, token, eventId, {return false;}-export async function fetchNextEvent(base, token, { totalDeadline } = {}) {+export async function fetchNextEvent(base, token, {+ totalDeadline,+ types,+ resolveTypes,+ perRequestTimeoutMs = PER_REQUEST_TIMEOUT_MS,+ leaseMs = DEFAULT_EVENT_LEASE_MS,+ signal,+} = {}) {while (true) {if (totalDeadline && Date.now() >= totalDeadline) {return { type: 'timeout' };@@ -161,8 +168,15 @@ export async function fetchNextEvent(base, token, { totalDeadline } = {}) {const remaining = totalDeadline? totalDeadline - Date.now(): PER_REQUEST_TIMEOUT_MS;- const slice = Math.min(Math.max(remaining, 1000), PER_REQUEST_TIMEOUT_MS);- const res = await fetch(`${base}/poll?token=${token}&timeout=${slice}&leaseMs=${DEFAULT_EVENT_LEASE_MS}`);+ const slice = Math.min(Math.max(remaining, 1000), perRequestTimeoutMs);+ const query = new URLSearchParams({+ token,+ timeout: String(slice),+ leaseMs: String(leaseMs),+ });+ const normalizedTypes = normalizePollTypes(resolveTypes ? await resolveTypes() : types);+ if (normalizedTypes.length > 0) query.set('types', normalizedTypes.join(','));+ const res = await fetch(`${base}/poll?${query}`, { signal });if (res.status === 401) {const err = new Error('Authentication failed. The server token may have changed.');@@ -202,11 +216,17 @@ export async function augmentEventWithAcceptHandling(event, base, token) {event._acceptResult = { handled: false, mode: 'error', error: err.message };}+ await completeAcceptHandling(event, base, token);+ return event;+}++export async function completeAcceptHandling(event, base, token) {const completionType = completionTypeForAcceptResult(event.type, event._acceptResult);try {await postReply(base, token, {id: event.id,type: completionType,+ sourceEventType: event.type,message: event._acceptResult?.error,file: event._acceptResult?.file,data: event._acceptResult?.carbonize === true ? { carbonize: true } : undefined,@@ -217,7 +237,6 @@ export async function augmentEventWithAcceptHandling(event, base, token) {if (!event._completionAck) {event._completionAck = completionAckForAcceptResult(event.id, completionType, event._acceptResult);}-return event;}@@ -245,9 +264,9 @@ export function printPollEvent(event) {console.log(JSON.stringify(event));}-export async function runPollOnce(base, token, { totalTimeout = 600_000 } = {}) {+export async function runPollOnce(base, token, { totalTimeout = 600_000, types, resolveTypes, perRequestTimeoutMs } = {}) {const deadline = Date.now() + totalTimeout;- const event = await fetchNextEvent(base, token, { totalDeadline: deadline });+ const event = await fetchNextEvent(base, token, { totalDeadline: deadline, types, resolveTypes, perRequestTimeoutMs });await augmentEventWithAcceptHandling(event, base, token);writeCarbonizeBanner(event);printPollEvent(event);@@ -258,11 +277,14 @@ export async function runPollStream(base, token, {ackTimeoutMs = 600_000,ackPollIntervalMs = 400,shouldContinue = () => true,+ types,+ resolveTypes,+ perRequestTimeoutMs,} = {}) {process.stderr.write('[impeccable-poll] stream mode: one JSON object per line on stdout; use --reply while this process stays running\n');while (shouldContinue()) {- const event = await fetchNextEvent(base, token);+ const event = await fetchNextEvent(base, token, { types, resolveTypes, perRequestTimeoutMs });await augmentEventWithAcceptHandling(event, base, token);writeCarbonizeBanner(event);printPollEvent(event);@@ -322,14 +344,17 @@ Modes:Options:--timeout=MS One-shot poll timeout in ms (default: 600000). Ignored in --stream mode+ --types=A,B Lease only these event types--ack-timeout=MS Stream mode: max wait for --reply after generate/steer (default: 600000)--file PATH Attach a source file path to the reply (generate/steer flow)--data JSON Attach a JSON result object to the reply (manual_edit_apply flow). Must be valid JSON--help Show this help messageHarness note:- Default one-shot mode is the portable contract for Claude Code, Codex, and Cursor.- --stream is experimental for harnesses with fast incremental stdout; do not use on Cursor.`);+ Default one-shot mode is the primary contract, including Codex foreground polling.+ Claude Code may run it as a background task; Cursor uses a background terminal with exit notification.+ --stream is retained for harnesses with measured, reliable incremental stdout.+ Do not use --stream on Cursor.`);process.exit(0);}@@ -360,23 +385,30 @@ Harness note:}const streamMode = args.includes('--stream');+ const typesArg = args.find((a) => a.startsWith('--types='));+ const types = normalizePollTypes(typesArg ? typesArg.slice('--types='.length) : null);const ackTimeoutArg = args.find((a) => a.startsWith('--ack-timeout='));const ackTimeoutMs = ackTimeoutArg ? parseInt(ackTimeoutArg.split('=')[1], 10) : 600_000;try {if (streamMode) {- await runPollStream(base, info.token, { ackTimeoutMs });+ await runPollStream(base, info.token, { ackTimeoutMs, types });return;}const timeoutArg = args.find((a) => a.startsWith('--timeout='));const totalTimeout = timeoutArg ? parseInt(timeoutArg.split('=')[1], 10) : 600_000;- await runPollOnce(base, info.token, { totalTimeout });+ await runPollOnce(base, info.token, { totalTimeout, types });} catch (err) {handlePollError(err);}}+export function normalizePollTypes(value) {+ const values = Array.isArray(value) ? value : String(value || '').split(',');+ return [...new Set(values.map((type) => String(type).trim()).filter(Boolean))];+}+// Auto-execute when run directlyconst _running = process.argv[1];if (_running?.endsWith('live-poll.mjs') || _running?.endsWith('live-poll.mjs/')) {diff --git a/.pi/skills/impeccable/scripts/live-server.mjs b/.pi/skills/impeccable/scripts/live-server.mjsindex 5735f2aec..c6e951086 100644--- a/.pi/skills/impeccable/scripts/live-server.mjs+++ b/.pi/skills/impeccable/scripts/live-server.mjs@@ -28,8 +28,10 @@ import {readLiveBrowserScriptParts,resolveLiveBrowserScriptParts,} from './live/browser-script-parts.mjs';-import { createLiveSessionStore } from './live/session-store.mjs';+import { createLiveSessionStore, GENERATION_FENCED_PHASES } from './live/session-store.mjs';+import { runGenerationPreflight } from './live/generation-preflight.mjs';import { validateEvent } from './live/event-validation.mjs';+import { selectAvailablePendingEvent } from './live/poll-lanes.mjs';import { createManualEditRoutes } from './live/manual-edit-routes.mjs';import { LIVE_COMMANDS } from './live/vocabulary.mjs';import {@@ -63,6 +65,10 @@ const DESIGN_MD_PATH = PROJECT_CONTEXT.designPath: null;const DEFAULT_POLL_TIMEOUT = 600_000; // 10 min — agent re-polls on timeout anywayconst SSE_HEARTBEAT_INTERVAL = 30_000; // keepalive ping every 30s+// The browser checkpoints for several unrelated reasons (see checkpointPayload+// in live-browser.js). Only these two report that variant availability changed,+// and only they may drive variant_progress / the *_reviewable phases.+const VARIANT_PROGRESS_CHECKPOINT_REASONS = new Set(['variants_progress', 'variants_ready']);// ---------------------------------------------------------------------------// Port detection@@ -156,29 +162,206 @@ function restorePendingEventsFromStore() {}}-function findAvailablePendingEvent(now = Date.now()) {- for (const entry of state.pendingEvents) {- if (entry.leaseUntil && entry.leaseUntil > now) continue;- return entry;- }- return null;+function findAvailablePendingEvent(now = Date.now(), types = null) {+ return selectAvailablePendingEvent(state.pendingEvents, { now, types });}-function leaseEvent(entry, leaseMs) {+async function leaseEvent(entry, leaseMs) {+ // Claim the entry before awaiting anything. prepareGenerateEventForLease+ // yields to the event loop, and selectAvailablePendingEvent only skips+ // entries whose lease is in the future — an unclaimed entry would be handed+ // to a second poll in that window and generated twice.+ entry.leaseUntil = Date.now() + leaseMs;+ await prepareGenerateEventForLease(entry);if (!entry.event?.id) {const idx = state.pendingEvents.indexOf(entry);if (idx !== -1) state.pendingEvents.splice(idx, 1);return entry.event;}+ // Re-stamp so the lease window starts when the agent actually receives the+ // work, not when scaffolding began.entry.leaseUntil = Date.now() + leaseMs;+ recordGenerateDelivery(entry);scheduleLeaseFlush();broadcastAgentPollingIfChanged();return entry.event;}-function acknowledgePendingEvent(id) {+function recordGenerateDelivery(entry) {+ const event = entry?.event;+ if (!event || event.type !== 'generate' || event.generationReadyAt) return;+ const at = Date.now();+ entry.event = { ...event, generationReadyAt: at };+ state.sessionStore?.appendEvent(entry.event);+ recordAgentPhase(event.id, 'generation_ready', { at });+}++async function prepareGenerateEventForLease(entry) {+ const event = entry?.event;+ if (!event || event.type !== 'generate' || event.scaffoldAttempted) return;++ recordAgentPhase(event.id, 'picked_up');+ recordAgentPhase(event.id, 'scaffolding');+ const result = await runGenerationPreflight(event, {+ cwd: process.cwd(),+ scriptsDir: __dirname,+ });+ entry.event = {+ ...event,+ scaffoldAttempted: true,+ scaffoldDurationMs: result.durationMs ?? null,+ ...(result.ok ? { scaffold: result.scaffold } : { scaffoldError: result.error || result.reason }),+ };+ state.sessionStore?.appendEvent(entry.event);+ recordAgentPhase(event.id, result.ok ? 'source_ready' : 'scaffold_fallback', {+ durationMs: result.durationMs ?? null,+ previewMode: result.scaffold?.previewMode || 'source',+ });+}++function recordAgentPhase(id, phase, details = {}) {+ if (!id) return;+ const event = {+ type: 'agent_phase',+ id,+ phase,+ at: Date.now(),+ ...details,+ };+ state.sessionStore?.appendEvent(event);+ broadcast(event);+}++/**+ * Detect a browser that missed the generation `done` broadcast.+ *+ * The preflight scaffold write triggers a framework full-reload (Astro reloads+ * the page for any .astro edit). If the agent's variant write + `done` land+ * while the browser is mid-reload, the new page misses both the second HMR+ * reload and the SSE `done` — it resumes from the scaffold-only source and+ * sits in GENERATING at 0/N forever. That resumed page always checkpoints+ * (`browser_resumed`), so a checkpoint claiming "still generating, variants+ * missing" for a session whose generation already completed is direct+ * evidence of the miss. Rebuild the `done` payload from the snapshot so the+ * caller can re-broadcast it; the browser's done handler is idempotent and+ * falls back to injecting variants from source.+ *+ * Keys on the store's monotone `generationCompletedAt`, not `phase` — the+ * behind checkpoint itself regresses `phase` to `generating`, and a browser+ * that misses the redelivered `done` too (another reload) must still trigger+ * redelivery from its next checkpoint.+ */+function detectMissedGenerationCompletion(event) {+ if (!event?.id || event.type !== 'checkpoint') return null;+ if (event.phase !== 'generating') return null;+ if (!variantCountLooksBehind(event.arrivedVariants, event.expectedVariants)) return null;+ if (!state.sessionStore) return null;+ let snapshot = null;+ try {+ snapshot = state.sessionStore.getSnapshot(event.id);+ } catch {+ return null;+ }+ return missedCompletionFromSnapshot(snapshot);+}++function variantCountLooksBehind(arrivedValue, expectedValue) {+ const arrived = Number(arrivedValue) || 0;+ const expected = Number(expectedValue) || 0;+ return arrived <= 0 || (expected > 0 && arrived < expected);+}++function missedCompletionFromSnapshot(snapshot) {+ if (!snapshot?.id || !snapshot.generationCompletedAt) return null;+ if (snapshot.generationCanceled) return null;+ // Accept/discard already underway: the browser is no longer waiting on+ // generation, and a late `done` there would collide with teardown.+ if (GENERATION_FENCED_PHASES.has(snapshot.phase)) return null;+ const file = snapshot.sourceFile || snapshot.previewFile;+ if (!file) return null;+ return {+ type: 'done',+ id: snapshot.id,+ file,+ sourceFile: snapshot.sourceFile || undefined,+ previewFile: snapshot.previewFile || undefined,+ previewMode: snapshot.previewMode || undefined,+ redelivered: true,+ };+}++function recordGenerationCheckpoint(event) {+ if (!event?.id || event.type !== 'checkpoint') return;+ if (generationIsFenced(event.id)) return;+ // Only checkpoints that report a change in variant availability are+ // generation progress. The browser also checkpoints for durability on Tune+ // slider drags, resumes, and anchor recovery; treating those as progress+ // echoed `variant_progress` straight back to the browser that sent it, which+ // remounts the component preview mid-drag (reverting the user's live param+ // edit and detaching the popover's element), and permanently latched the+ // *_reviewable phases from the wrong trigger, corrupting generation timings.+ if (!VARIANT_PROGRESS_CHECKPOINT_REASONS.has(event.reason)) return;+ const arrived = Number(event.arrivedVariants) || 0;+ const expected = Number(event.expectedVariants) || 0;+ if (arrived <= 0 || expected <= 0) return;+ const previewMode = event.previewMode || 'source';+ const previewFile = event.previewFile || event.file;+ if (previewFile) {+ broadcast({+ type: 'variant_progress',+ id: event.id,+ file: previewFile,+ sourceFile: event.sourceFile || (previewMode === 'source' ? previewFile : undefined),+ previewFile,+ previewMode,+ arrivedVariants: arrived,+ expectedVariants: expected,+ publicationKind: event.publicationKind || 'variants',+ });+ }+ const details = {+ arrivedVariants: arrived,+ expectedVariants: expected,+ checkpointReason: event.reason || null,+ };+ const at = Date.now();+ if (!generationPhaseAlreadyRecorded(event.id, 'first_reviewable')) {+ recordAgentPhase(event.id, 'first_reviewable', { ...details, at });+ }+ if (arrived >= 2 && expected >= 3 && !generationPhaseAlreadyRecorded(event.id, 'second_reviewable')) {+ recordAgentPhase(event.id, 'second_reviewable', { ...details, at });+ }+ if (arrived >= expected && !generationPhaseAlreadyRecorded(event.id, 'all_variants_ready')) {+ recordAgentPhase(event.id, 'all_variants_ready', { ...details, at });+ }+}++function generationIsFenced(id) {+ if (!state.sessionStore || !id) return false;+ try {+ const snapshot = state.sessionStore.getSnapshot(id, { includeCompleted: true });+ return snapshot?.generationCanceled === true;+ } catch {+ return false;+ }+}++function generationPhaseAlreadyRecorded(id, phase) {+ if (!state.sessionStore) return false;+ try {+ const snapshot = state.sessionStore.getSnapshot(id, { includeCompleted: true });+ return !!snapshot?.generationTimings?.[phase];+ } catch {+ return false;+ }+}++function acknowledgePendingEvent(id, sourceEventType) {if (!id) return false;- const idx = state.pendingEvents.findIndex((entry) => entry.event?.id === id);+ const idx = state.pendingEvents.findIndex((entry) => (+ entry.event?.id === id+ && (!sourceEventType || entry.event?.type === sourceEventType)+ ));if (idx === -1) return false;const acknowledged = state.pendingEvents[idx].event;state.pendingEvents.splice(idx, 1);@@ -187,9 +370,39 @@ function acknowledgePendingEvent(id) {return acknowledged;}-function findPendingEventById(id) {+function releasePendingEvent(id, sourceEventType) {+ const entry = state.pendingEvents.find((item) => (+ item.event?.id === id+ && (!sourceEventType || item.event?.type === sourceEventType)+ ));+ if (!entry) return null;+ entry.leaseUntil = 0;+ scheduleLeaseFlush();+ return entry.event;+}++function retirePendingGeneration(id) {+ if (!id) return 0;+ let retired = 0;+ for (let index = state.pendingEvents.length - 1; index >= 0; index -= 1) {+ const event = state.pendingEvents[index]?.event;+ if (event?.id !== id || event.type !== 'generate') continue;+ state.pendingEvents.splice(index, 1);+ retired += 1;+ }+ if (retired > 0) {+ scheduleLeaseFlush();+ broadcastAgentPollingIfChanged();+ }+ return retired;+}++function findPendingEventById(id, sourceEventType) {if (!id) return null;- const entry = state.pendingEvents.find((item) => item.event?.id === id);+ const entry = state.pendingEvents.find((item) => (+ item.event?.id === id+ && (!sourceEventType || item.event?.type === sourceEventType)+ ));return entry?.event || null;}@@ -198,7 +411,7 @@ function summarizePendingEventForStatus(entry) {const summary = {id: event.id,type: event.type,- leased: !!(entry.leaseUntil && entry.leaseUntil > Date.now()),+ leased: isLeased(entry),leaseUntil: entry.leaseUntil || null,};if (event.type === 'manual_edit_apply') {@@ -224,7 +437,13 @@ function summarizeActiveSessionForClient(snapshot = {}) {arrivedVariants: snapshot.arrivedVariants ?? 0,visibleVariant: snapshot.visibleVariant ?? null,checkpointRevision: snapshot.checkpointRevision ?? 0,+ browserCheckpointRevision: snapshot.browserCheckpointRevision ?? snapshot.checkpointRevision ?? 0,+ publicationCheckpointRevision: snapshot.publicationCheckpointRevision ?? 0,paramValues: snapshot.paramValues || {},+ generationPhase: snapshot.generationPhase ?? null,+ generationCompletedAt: snapshot.generationCompletedAt ?? null,+ generationCanceled: snapshot.generationCanceled === true,+ cancelReason: snapshot.cancelReason ?? null,};}@@ -269,24 +488,46 @@ function scheduleLeaseFlush() {function flushPendingPolls() {let changed = false;while (state.pendingPolls.length > 0) {- const entry = findAvailablePendingEvent();+ let pollIndex = -1;+ let entry = null;+ for (let index = 0; index < state.pendingPolls.length; index += 1) {+ const candidate = findAvailablePendingEvent(Date.now(), state.pendingPolls[index].types);+ if (!candidate) continue;+ pollIndex = index;+ entry = candidate;+ break;+ }if (!entry) {scheduleLeaseFlush();broadcastAgentPollingIfChanged();return;}- const poll = state.pendingPolls.shift();- poll.resolve(leaseEvent(entry, poll.leaseMs));+ const [poll] = state.pendingPolls.splice(pollIndex, 1);+ // leaseEvent is async (it may scaffold source), but it claims the entry+ // synchronously, so the next loop iteration will not re-select it. Resolve+ // the poll when the lease settles rather than awaiting here, so one slow+ // scaffold never delays the other parked polls. On the exceptional failure+ // path, answer `timeout` so the agent re-polls; the claim stays until the+ // lease expires, which keeps a deterministic failure from hot-looping.+ leaseEvent(entry, poll.leaseMs).then(poll.resolve, (error) => {+ console.error('[live] lease failed for ' + (entry.event?.id || 'unknown') + ': ' + (error?.message || error));+ poll.resolve({ type: 'timeout' });+ });changed = true;}scheduleLeaseFlush();if (changed) broadcastAgentPollingIfChanged();}+function isLeased(entry) {+ return !!(entry?.leaseUntil && entry.leaseUntil > Date.now());+}+function agentPollingConnected() {- const now = Date.now();- return state.pendingPolls.length > 0- || state.pendingEvents.some((entry) => entry.leaseUntil && entry.leaseUntil > now);+ // A leased event only proves that a poll returned once. The foreground task+ // may have ended immediately afterward, so only an actively waiting poll is+ // evidence that steering can wake the task right now.+ return state.pendingPolls.length > 0;}function broadcastAgentPollingIfChanged() {@@ -689,6 +930,16 @@ function createRequestHandler({ detectScript, liveScriptParts }) {res.end(JSON.stringify({ error }));return;}+ if (msg.type === 'agent_phase') {+ recordAgentPhase(msg.id, msg.phase, {+ ...(Number.isFinite(msg.durationMs) ? { durationMs: msg.durationMs } : {}),+ owner: typeof msg.owner === 'string' ? msg.owner : undefined,+ });+ res.writeHead(200, { 'Content-Type': 'application/json' });+ res.end(JSON.stringify({ ok: true }));+ return;+ }+ const missedCompletion = detectMissedGenerationCompletion(msg);if (state.sessionStore && msg.id) {try {state.sessionStore.appendEvent(msg);@@ -698,6 +949,11 @@ function createRequestHandler({ detectScript, liveScriptParts }) {return;}}+ if (msg.type === 'accept' || msg.type === 'discard') {+ retirePendingGeneration(msg.id);+ }+ recordGenerationCheckpoint(msg);+ if (missedCompletion) broadcast(missedCompletion);if (msg.type === 'exit') {cleanupSvelteComponentSessionsBeforeExit();}@@ -738,6 +994,12 @@ function createRequestHandler({ detectScript, liveScriptParts }) {// Agent poll endpoints (unchanged from WS version)// ---------------------------------------------------------------------------+function parsePollTypes(value) {+ if (!value) return null;+ const types = String(value).split(',').map((type) => type.trim()).filter(Boolean);+ return types.length > 0 ? new Set(types) : null;+}+function handlePollGet(req, res, url) {const token = url.searchParams.get('token');if (token !== state.token) {@@ -748,13 +1010,25 @@ function handlePollGet(req, res, url) {state.lastPollAt = Date.now();const timeout = parseInt(url.searchParams.get('timeout') || DEFAULT_POLL_TIMEOUT, 10);const leaseMs = parseInt(url.searchParams.get('leaseMs') || '30000', 10);- const available = findAvailablePendingEvent();+ const types = parsePollTypes(url.searchParams.get('types'));+ const available = findAvailablePendingEvent(Date.now(), types);if (available) {- res.writeHead(200, { 'Content-Type': 'application/json' });- res.end(JSON.stringify(leaseEvent(available, leaseMs)));+ // Do not await inline: leaseEvent may scaffold source, and this handler runs+ // on the server's only thread. The client can disconnect during that window,+ // so check the socket before replying.+ leaseEvent(available, leaseMs).then((event) => {+ if (res.writableEnded || res.destroyed) return;+ res.writeHead(200, { 'Content-Type': 'application/json' });+ res.end(JSON.stringify(event));+ }, (error) => {+ console.error('[live] lease failed for ' + (available.event?.id || 'unknown') + ': ' + (error?.message || error));+ if (res.writableEnded || res.destroyed) return;+ res.writeHead(200, { 'Content-Type': 'application/json' });+ res.end(JSON.stringify({ type: 'timeout' }));+ });return;}- const poll = { resolve, leaseMs };+ const poll = { resolve, leaseMs, types };const timer = setTimeout(() => {const idx = state.pendingPolls.indexOf(poll);if (idx !== -1) state.pendingPolls.splice(idx, 1);@@ -783,12 +1057,15 @@ function sessionFileMetadataFromPollReply(file) {if (!file || typeof file !== 'string') return { file };const normalized = file.split(path.sep).join('/');const base = { file: normalized };- if (!normalized.endsWith('/manifest.json') && normalized !== 'manifest.json') return base;- if (!normalized.includes('node_modules/.impeccable-live/') && !normalized.includes('src/lib/impeccable/')) return base;+ const metadataFile = normalized;+ if (!metadataFile.endsWith('/manifest.json') && metadataFile !== 'manifest.json') return base;+ if (!metadataFile.includes('node_modules/.impeccable-live/')+ && !metadataFile.includes('src/lib/impeccable/')+ && !metadataFile.includes('/.impeccable-live/')) return base;let full;try {- full = path.resolve(process.cwd(), normalized);+ full = path.resolve(process.cwd(), metadataFile);const rel = path.relative(process.cwd(), full);if (!rel || rel.startsWith('..') || path.isAbsolute(rel)) return base;} catch {@@ -797,18 +1074,47 @@ function sessionFileMetadataFromPollReply(file) {try {const manifest = JSON.parse(fs.readFileSync(full, 'utf-8'));- if (manifest?.previewMode !== 'svelte-component' || !manifest.sourceFile) return base;+ if (manifest?.previewMode !== 'svelte-component'+ || !manifest.sourceFile) return base;return {file: String(manifest.sourceFile).split(path.sep).join('/'),sourceFile: String(manifest.sourceFile).split(path.sep).join('/'),previewFile: normalized,- previewMode: 'svelte-component',+ previewMode: manifest.previewMode,};} catch {return base;}}+function inferSourceEventType(msg = {}, pendingEvents = state.pendingEvents) {+ const entriesForId = pendingEvents.filter((entry) => entry.event?.id === msg.id);+ const pendingTypes = new Set(entriesForId.map((entry) => entry.event?.type));+ if (msg.type === 'discarded' || msg.type === 'discard') return 'discard';+ if (msg.type === 'complete') {+ if (pendingTypes.has('carbonize_cleanup')) return 'carbonize_cleanup';+ return pendingTypes.has('accept') ? 'accept' : (pendingTypes.has('generate') ? 'generate' : undefined);+ }+ if (msg.type === 'steer_done') return 'steer';+ // `agent_done` can be the automatic acknowledgement for a carbonize Accept.+ // New pollers send sourceEventType explicitly; default to generate only for+ // older callers so a late worker cannot acknowledge a queued Accept.+ if (msg.type === 'agent_done' || msg.type === 'done') return 'generate';+ // `error` is reference/live.md's documented failure reply, and parseReplyArgs+ // never sets sourceEventType on it (the poller is a fresh process that cannot+ // know what it leased). Returning undefined here makes acknowledgePendingEvent+ // match *any* event for this id: a stale generate worker's failure silently+ // consumed the user's queued Accept, which was then never delivered to any+ // agent and left the browser in SAVING forever. Attribute the failure to the+ // event this agent actually holds a lease on, and otherwise to `generate` —+ // never to a wildcard. If that generate was already retired by an Accept, the+ // ack simply finds no match, which is the correct outcome for a stale reply.+ if (msg.type === 'error') {+ return entriesForId.find(isLeased)?.event?.type || 'generate';+ }+ return undefined;+}+function handlePollPost(req, res) {let body = '';req.on('data', (c) => { body += c; });@@ -869,7 +1175,23 @@ function handlePollPost(req, res) {res.end(JSON.stringify({ error: 'stale_manual_edit_apply_reply', ...rollback }));return;}- const pendingEventBeforeAck = findPendingEventById(msg.id);+ const sourceEventType = msg.sourceEventType || inferSourceEventType(msg);+ if (msg.type === 'retry') {+ const releasedEvent = releasePendingEvent(msg.id, sourceEventType);+ if (!releasedEvent) {+ res.writeHead(msg.id ? 404 : 400, { 'Content-Type': 'application/json' });+ res.end(JSON.stringify({+ error: msg.id ? 'unknown_poll_retry_id' : 'missing_poll_retry_id',+ id: msg.id,+ }));+ return;+ }+ flushPendingPolls();+ res.writeHead(200, { 'Content-Type': 'application/json' });+ res.end(JSON.stringify({ ok: true, released: true }));+ return;+ }+ const pendingEventBeforeAck = findPendingEventById(msg.id, sourceEventType);if (pendingEventBeforeAck?.type === 'steer' && msg.type === 'steer_done'&& !msg.file && !(typeof msg.message === 'string' && msg.message.trim())) {res.writeHead(400, { 'Content-Type': 'application/json' });@@ -879,7 +1201,7 @@ function handlePollPost(req, res) {}));return;}- const acknowledgedEvent = acknowledgePendingEvent(msg.id);+ const acknowledgedEvent = acknowledgePendingEvent(msg.id, sourceEventType);let skipJournalReply = false;let existingSession = null;if (!acknowledgedEvent && state.sessionStore && msg.id) {@@ -1083,7 +1405,10 @@ if (args.includes('--background')) {process.exit(0);}} catch { /* not ready yet */ }- await new Promise(r => setTimeout(r, 200));+ // The detached child is typically listening in 35-45ms. A 200ms polling+ // floor dominated configured cold Live startup; poll cheaply and return+ // as soon as the child has written its ready record.+ await new Promise(r => setTimeout(r, 5));}console.error('Timed out waiting for live server to start.');process.exit(1);diff --git a/.pi/skills/impeccable/scripts/live-status.mjs b/.pi/skills/impeccable/scripts/live-status.mjsindex f7e464999..dc98b7386 100644--- a/.pi/skills/impeccable/scripts/live-status.mjs+++ b/.pi/skills/impeccable/scripts/live-status.mjs@@ -37,15 +37,19 @@ export async function statusCli() {pendingEvents: server.pendingEvents,} : null,activeSessions: server?.activeSessions || activeSessions,- recoveryHint: manualApply- ? manualApplyResumeHint(manualApply)- : server- ? 'Run live-poll.mjs to continue pending work, or live-complete.mjs --id <session> after manual cleanup.'- : 'Start live-server.mjs to requeue pending durable events, then run live-poll.mjs.',+ recoveryHint: recoveryHint({ server, manualApply }),};console.log(JSON.stringify(payload, null, 2));}+function recoveryHint({ server, manualApply }) {+ if (manualApply) return manualApplyResumeHint(manualApply);+ if (server) {+ return 'Run live-poll.mjs to continue pending work, or live-complete.mjs --id <session> after manual cleanup.';+ }+ return 'Start live-server.mjs to requeue pending durable events, then run live-poll.mjs.';+}+function findPendingManualApply(server, activeSessions) {const fromServer = server?.pendingEvents?.find((event) => event?.type === 'manual_edit_apply');if (fromServer) return fromServer;diff --git a/.pi/skills/impeccable/scripts/live-wrap.mjs b/.pi/skills/impeccable/scripts/live-wrap.mjsindex 438c01b68..48d7f7683 100644--- a/.pi/skills/impeccable/scripts/live-wrap.mjs+++ b/.pi/skills/impeccable/scripts/live-wrap.mjs@@ -160,11 +160,29 @@ The agent should insert variant HTML at insertLine.`);if (filtered.length === 1) {match = filtered[0];} else if (filtered.length === 0) {- // Source uses dynamic content (`<h1>{title}</h1>` etc.) so the- // browser-side textContent doesn't appear literally in source. Fall- // back to first-match rather than refusing — this is the same- // behavior unmodified callers see, just preserved.- match = candidates[0];+ const normalizedText = String(text).replace(/\s+/g, ' ').trim();+ if (normalizedText.length < 8) {+ // Very short labels cannot disambiguate siblings reliably. Preserve+ // the legacy behavior for these low-information picker events.+ match = candidates[0];+ } else {+ // Rendered text that is absent from every candidate usually means+ // the source uses expressions or component props. Picking the first+ // same-class sibling silently edits the wrong instance (observed on+ // Astro result cards), so stop and surface every candidate instead.+ console.error(JSON.stringify({+ error: 'element_ambiguous',+ fallback: 'agent-driven',+ reason: 'rendered_text_not_in_source',+ file: path.relative(process.cwd(), targetFile),+ candidates: candidates.map((c) => ({+ startLine: c.startLine + 1,+ endLine: c.endLine + 1,+ })),+ hint: 'Rendered text does not occur in any matching source branch. The element may use dynamic props or expressions; inspect the candidates and wrap the intended instance manually.',+ }));+ process.exit(1);+ }} else {// Multiple candidates ALSO match the text. Truly ambiguous — refuse// rather than pick wrong, and hand the agent the candidate locations@@ -269,6 +287,7 @@ The agent should insert variant HTML at insertLine.`);const originalIndented = reindentOriginal(' ');const relTargetFile = path.relative(process.cwd(), targetFile).split(path.sep).join('/');const useSvelteComponent = shouldUseSvelteComponentInjection(targetFile);+ const useFrameworkComponent = useSvelteComponent;// Wrapper attributes differ by syntax. HTML allows plain string attrs;// JSX requires object-literal style and parses string attrs as HTML (which@@ -288,7 +307,7 @@ The agent should insert variant HTML at insertLine.`);// replacement range to include the wrapper's `<div>` open / close lines// so the entire scaffold gets removed cleanly.const wrapperLines = isJsx ? [- indent + '<div data-impeccable-variants="' + id + '" data-impeccable-variant-count="' + count + '" ' + styleContents + '>',+ indent + '<div data-impeccable-variants="' + id + '" data-impeccable-variant-count="' + count + '"' + ' ' + styleContents + '>',indent + ' ' + commentSyntax.open + ' impeccable-variants-start ' + id + ' ' + commentSyntax.close,indent + ' ' + commentSyntax.open + ' Original ' + commentSyntax.close,indent + ' <div data-impeccable-variant="original">',@@ -299,7 +318,7 @@ The agent should insert variant HTML at insertLine.`);indent + '</div>',] : [indent + commentSyntax.open + ' impeccable-variants-start ' + id + ' ' + commentSyntax.close,- indent + '<div data-impeccable-variants="' + id + '" data-impeccable-variant-count="' + count + '" ' + styleContents + '>',+ indent + '<div data-impeccable-variants="' + id + '" data-impeccable-variant-count="' + count + '"' + ' ' + styleContents + '>',indent + ' ' + commentSyntax.open + ' Original ' + commentSyntax.close,indent + ' <div data-impeccable-variant="original">',originalIndented,@@ -356,15 +375,18 @@ The agent should insert variant HTML at insertLine.`);const outputRelFile = path.relative(process.cwd(), outputFile).split(path.sep).join('/');const svelteComponentAuthoring = useSvelteComponent ? buildSvelteComponentCssAuthoring(count) : null;+ const componentSession = svelteSession;+ const componentPreviewMode = useSvelteComponent ? 'svelte-component' : undefined;+ const previewMode = componentPreviewMode;console.log(JSON.stringify({file: outputRelFile,- sourceFile: useSvelteComponent ? relTargetFile : undefined,- previewMode: useSvelteComponent ? 'svelte-component' : undefined,- componentDir: svelteSession?.componentDir,- propContract: svelteSession?.propContract,- sourceStartLine: useSvelteComponent ? startLine + 1 : undefined,- sourceEndLine: useSvelteComponent ? endLine + 1 : undefined,+ sourceFile: useFrameworkComponent ? relTargetFile : undefined,+ previewMode,+ componentDir: componentSession?.componentDir,+ propContract: componentSession?.propContract,+ sourceStartLine: useFrameworkComponent ? startLine + 1 : undefined,+ sourceEndLine: useFrameworkComponent ? endLine + 1 : undefined,startLine: outputStartLine, // 1-indexed for the agent// wrapperLines is an array but one element (the original-content slot)// is a `\n`-joined multi-line string, so the actual file-row count is@@ -374,10 +396,10 @@ The agent should insert variant HTML at insertLine.`);endLine: outputEndLine, // 1-indexedinsertLine, // 1-indexed: where variants gocommentSyntax: commentSyntax,- styleMode: useSvelteComponent ? 'svelte-component' : styleMode.mode,- styleTag: useSvelteComponent ? null : styleMode.styleTag,- cssSelectorPrefixExamples: useSvelteComponent ? [] : buildCssSelectorPrefixExamples(styleMode.mode, count),- cssAuthoring: useSvelteComponent ? svelteComponentAuthoring : buildCssAuthoring(styleMode, count),+ styleMode: componentPreviewMode || styleMode.mode,+ styleTag: useFrameworkComponent ? null : styleMode.styleTag,+ cssSelectorPrefixExamples: useFrameworkComponent ? [] : buildCssSelectorPrefixExamples(styleMode.mode, count),+ cssAuthoring: svelteComponentAuthoring || buildCssAuthoring(styleMode, count),originalLineCount: originalLines.length,}));}diff --git a/.pi/skills/impeccable/scripts/live.mjs b/.pi/skills/impeccable/scripts/live.mjsindex e0bd1ad24..b21a71cc4 100644--- a/.pi/skills/impeccable/scripts/live.mjs+++ b/.pi/skills/impeccable/scripts/live.mjs@@ -10,7 +10,7 @@** After this, the agent's only remaining steps are:* - Open the project's live dev/preview URL in the browser (optional, if browser automation exists)—not `serverPort`; that port is the Impeccable helper for /live.js and /poll- * - Enter the poll loop: `node live-poll.mjs`+ * - Enter the harness-native poll loop: `node live-poll.mjs`** Usage:* node live.mjs # Prepare everything, print JSON, exit@@ -40,6 +40,7 @@ Prepare everything for live variant mode in a single command:- Starts (or reuses) the live server in the background- Injects the browser script tag- Reads PRODUCT.md / DESIGN.md for project context+ - Prepares the harness-native foreground/background poll loop- In monorepos, choose a child app first; --target <path> is the fallback/manual pathOn success, prints a JSON blob with:diff --git a/.pi/skills/impeccable/scripts/live/completion.mjs b/.pi/skills/impeccable/scripts/live/completion.mjsindex 986773066..6f539336d 100644--- a/.pi/skills/impeccable/scripts/live/completion.mjs+++ b/.pi/skills/impeccable/scripts/live/completion.mjs@@ -1,9 +1,18 @@+// A preview whose variants live in component modules rather than in the user's+// source. These leave no markers in the real file, so a failed accept gives the+// agent nothing to hand-edit and must be reported as a failure rather than+// reference/live.md's manual-cleanup handoff. Kept as a set: any future+// component-module preview mode belongs here the day it lands.+const PREVIEW_MODES_WITHOUT_SOURCE_MARKERS = new Set([+ 'svelte-component',+]);+export function completionTypeForAcceptResult(eventType, acceptResult) {if (eventType === 'discard') return acceptResult?.handled === true ? 'discarded' : 'error';if (acceptResult?.handled === true && acceptResult?.carbonize === true) return 'agent_done';if (acceptResult?.handled === true) return 'complete';if (acceptResult?.mode === 'error') return 'error';- if (eventType === 'accept' && acceptResult?.previewMode === 'svelte-component') return 'error';+ if (eventType === 'accept' && PREVIEW_MODES_WITHOUT_SOURCE_MARKERS.has(acceptResult?.previewMode)) return 'error';return 'agent_done';}diff --git a/.pi/skills/impeccable/scripts/live/event-validation.mjs b/.pi/skills/impeccable/scripts/live/event-validation.mjsindex 0897b1317..122c29836 100644--- a/.pi/skills/impeccable/scripts/live/event-validation.mjs+++ b/.pi/skills/impeccable/scripts/live/event-validation.mjs@@ -118,6 +118,15 @@ export function validateEvent(msg) {return 'checkpoint: paramValues must be an object';}return null;+ case 'agent_phase':+ if (!isValidId(msg.id)) return 'agent_phase: missing or malformed id';+ if (typeof msg.phase !== 'string' || !/^[a-z][a-z0-9_]{1,63}$/.test(msg.phase)) {+ return 'agent_phase: missing or malformed phase';+ }+ if (msg.durationMs !== undefined && (!Number.isFinite(msg.durationMs) || msg.durationMs < 0)) {+ return 'agent_phase: durationMs must be a non-negative number';+ }+ return null;case 'exit':return null;case 'prefetch':@@ -131,6 +140,12 @@ export function validateEvent(msg) {if (msg.message.length > 4000) return 'steer: message too long';if (msg.pageUrl !== undefined && typeof msg.pageUrl !== 'string') return 'steer: pageUrl must be string';return null;+ case 'carbonize_cleanup':+ if (!isValidId(msg.id)) return 'carbonize_cleanup: missing or malformed id';+ if (!isValidId(msg.sessionId)) return 'carbonize_cleanup: missing or malformed sessionId';+ if (!msg.file || typeof msg.file !== 'string') return 'carbonize_cleanup: missing file';+ if (!isValidVariantId(String(msg.variantId))) return 'carbonize_cleanup: missing or malformed variantId';+ return null;default:return 'Unknown event type: ' + msg.type;}diff --git a/.pi/skills/impeccable/scripts/live/generation-preflight.mjs b/.pi/skills/impeccable/scripts/live/generation-preflight.mjsnew file mode 100644index 000000000..07a5e957e--- /dev/null+++ b/.pi/skills/impeccable/scripts/live/generation-preflight.mjs@@ -0,0 +1,102 @@+import { execFile } from 'node:child_process';+import path from 'node:path';+import { promisify } from 'node:util';++const execFileAsync = promisify(execFile);+const PREFLIGHT_TIMEOUT_MS = 15_000;++export function buildGenerationPreflight(event, scriptsDir) {+ if (!event || event.type !== 'generate' || !event.id) return null;++ const isInsert = event.mode === 'insert';+ const target = isInsert ? insertTarget(event) : replaceTarget(event);+ if (!target.elementId && !target.classes) return null;++ const script = path.join(scriptsDir, isInsert ? 'live-insert.mjs' : 'live-wrap.mjs');+ const args = [script, '--id', event.id, '--count', String(event.count || 3)];+ if (isInsert) args.push('--position', target.position);+ if (target.elementId) args.push('--element-id', target.elementId);+ if (target.classes) args.push('--classes', target.classes);+ if (target.tag) args.push('--tag', target.tag);+ if (target.text) args.push('--text', target.text);+ if (!isInsert && event.pageUrl) args.push('--page-url', event.pageUrl);+ return { script, args, mode: isInsert ? 'insert' : 'replace' };+}++/**+ * Scaffold the source for a generate event before handing it to an agent.+ *+ * Async on purpose. This spawns `live-wrap.mjs`, which walks the project's+ * source tree and can take seconds (measured at ~7.6s on a large repo when the+ * element is not found, with a 15s ceiling). The live server is single-threaded+ * and calls this while leasing a poll, so a synchronous spawn froze the whole+ * server for that entire window: Accept and Discard POSTs, SSE progress+ * broadcasts, and every other poll stalled behind it.+ */+export async function runGenerationPreflight(event, {+ cwd = process.cwd(),+ scriptsDir,+ execFileImpl = execFileAsync,+ timeoutMs = PREFLIGHT_TIMEOUT_MS,+} = {}) {+ const command = buildGenerationPreflight(event, scriptsDir);+ if (!command) {+ return { ok: false, skipped: true, reason: 'insufficient_locator' };+ }++ const startedAt = performance.now();+ try {+ const { stdout } = await execFileImpl(process.execPath, command.args, {+ cwd,+ encoding: 'utf-8',+ timeout: timeoutMs,+ });+ const line = String(stdout).trim().split('\n').filter(Boolean).pop();+ if (!line) throw new Error('preflight returned no scaffold metadata');+ return {+ ok: true,+ mode: command.mode,+ durationMs: performance.now() - startedAt,+ scaffold: JSON.parse(line),+ };+ } catch (error) {+ return {+ ok: false,+ mode: command.mode,+ durationMs: performance.now() - startedAt,+ error: compactError(error),+ };+ }+}++function replaceTarget(event) {+ return normalizeTarget(event.element || {});+}++function insertTarget(event) {+ return {+ ...normalizeTarget(event.insert?.anchor || {}),+ position: event.insert?.position === 'before' ? 'before' : 'after',+ };+}++function normalizeTarget(target) {+ const classes = Array.isArray(target.classes)+ ? target.classes.join(' ')+ : String(target.classes || '').trim();+ const text = typeof target.textContent === 'string'+ ? target.textContent.trim().slice(0, 80)+ : '';+ return {+ elementId: target.id || target.elementId || undefined,+ classes: classes || undefined,+ tag: target.tagName || target.tag || undefined,+ text: text || undefined,+ };+}++function compactError(error) {+ const stderr = error?.stderr ? String(error.stderr).trim() : '';+ const message = stderr.split('\n').filter(Boolean).pop() || error?.message || 'preflight failed';+ return String(message).slice(0, 500);+}diff --git a/.pi/skills/impeccable/scripts/live/poll-lanes.mjs b/.pi/skills/impeccable/scripts/live/poll-lanes.mjsnew file mode 100644index 000000000..65f20a87a--- /dev/null+++ b/.pi/skills/impeccable/scripts/live/poll-lanes.mjs@@ -0,0 +1,14 @@+export function eventPriority(event = {}) {+ if (event.type === 'accept' || event.type === 'discard' || event.type === 'exit') return 0;+ if (event.type === 'manual_edit_apply' || event.type === 'steer' || event.type === 'carbonize_cleanup') return 1;+ if (event.type === 'generate') return 2;+ return 3;+}++export function selectAvailablePendingEvent(entries, { now = Date.now(), types = null } = {}) {+ const allowed = types instanceof Set ? types : (Array.isArray(types) ? new Set(types) : null);+ return entries+ .filter((entry) => !(entry.leaseUntil && entry.leaseUntil > now))+ .filter((entry) => !allowed || allowed.has(entry.event?.type))+ .sort((a, b) => eventPriority(a.event) - eventPriority(b.event) || a.seq - b.seq)[0] || null;+}diff --git a/.pi/skills/impeccable/scripts/live/session-store.mjs b/.pi/skills/impeccable/scripts/live/session-store.mjsindex affba67c9..9d20341dd 100644--- a/.pi/skills/impeccable/scripts/live/session-store.mjs+++ b/.pi/skills/impeccable/scripts/live/session-store.mjs@@ -1,24 +1,26 @@import fs from 'node:fs';import path from 'node:path';-import { getLegacyLiveSessionsDir, getLiveSessionsDir } from '../lib/impeccable-paths.mjs';+import { getLegacyLiveSessionsDir, getLiveSessionsDir, safeSessionId } from '../lib/impeccable-paths.mjs';const COMPLETED_PHASES = new Set(['completed', 'discarded']);+export const GENERATION_FENCED_PHASES = new Set([+ 'accept_requested',+ 'discard_requested',+ 'carbonize_required',+ 'completed',+ 'discarded',+]);export function createLiveSessionStore({ cwd = process.cwd(), sessionId } = {}) {const rootDir = getLiveSessionsDir(cwd);const legacyRootDir = getLegacyLiveSessionsDir(cwd);fs.mkdirSync(rootDir, { recursive: true });- const snapshotCache = new Map();-- function loadCachedOrRebuild(id) {- const cached = snapshotCache.get(id);- if (cached) return cached;- const journalPath = getReadableJournalPath(id);- const rebuilt = rebuildSnapshotFromJournal(journalPath, id);- snapshotCache.set(id, rebuilt);- return rebuilt;- }+ // No snapshot cache on purpose: appendEvent and getSnapshot both rebuild from+ // the journal so sequence numbers and phase fences never come from a stale+ // in-memory copy when the publisher/complete helpers append from another+ // process. A cache written but never read would grow per session for the+ // lifetime of the server without ever saving a rebuild.function getReadableJournalPath(id) {const primary = getJournalPath(rootDir, id);if (fs.existsSync(primary)) return primary;@@ -38,7 +40,10 @@ export function createLiveSessionStore({ cwd = process.cwd(), sessionId } = {})if (!fs.existsSync(journalPath) && fs.existsSync(legacyJournalPath)) {fs.copyFileSync(legacyJournalPath, journalPath);}- const prior = loadCachedOrRebuild(normalized.id);+ // Publisher/complete helpers can append from a separate process while+ // the server is alive. Rebuild here so sequence numbers and phase+ // fences never come from a stale in-memory cache.+ const prior = rebuildSnapshotFromJournal(getReadableJournalPath(normalized.id), normalized.id);const seq = prior.nextSeq;const entry = {seq,@@ -49,7 +54,6 @@ export function createLiveSessionStore({ cwd = process.cwd(), sessionId } = {})};fs.appendFileSync(journalPath, JSON.stringify(entry) + '\n');const next = applyEvent(prior.snapshot, entry, prior.diagnostics);- snapshotCache.set(normalized.id, { snapshot: next, diagnostics: next.diagnostics || [], nextSeq: seq + 1 });writeSnapshot(snapshotPath, next);return next;},@@ -58,7 +62,6 @@ export function createLiveSessionStore({ cwd = process.cwd(), sessionId } = {})const journalPath = getReadableJournalPath(id);const snapshotPath = getSnapshotPath(rootDir, id);const rebuilt = rebuildSnapshotFromJournal(journalPath, id);- snapshotCache.set(id, rebuilt);writeSnapshot(snapshotPath, rebuilt.snapshot);if (!opts.includeCompleted && COMPLETED_PHASES.has(rebuilt.snapshot.phase)) return null;return rebuilt.snapshot;@@ -95,11 +98,6 @@ function getSnapshotPath(rootDir, id) {return path.join(rootDir, safeSessionId(id) + '.snapshot.json');}-function safeSessionId(id) {- if (!/^[A-Za-z0-9_-]{1,128}$/.test(id)) throw new Error('invalid session id: ' + id);- return id;-}-function baseSnapshot(id) {return {id,@@ -116,9 +114,18 @@ function baseSnapshot(id) {pendingEvent: null,deliveryLease: null,checkpointRevision: 0,+ browserCheckpointRevision: 0,+ publicationCheckpointRevision: 0,activeOwner: null,sourceMarkers: {},fallbackMode: null,+ generationPhase: null,+ generationCompletedAt: null,+ generationTimings: {},+ variantPlan: null,+ generationCanceled: false,+ generationCanceledAt: null,+ cancelReason: null,annotationArtifacts: [],diagnostics: [],updatedAt: null,@@ -158,6 +165,8 @@ function applyEvent(snapshot, entry, inheritedDiagnostics = []) {...snapshot,paramValues: { ...(snapshot.paramValues || {}) },sourceMarkers: { ...(snapshot.sourceMarkers || {}) },+ generationTimings: { ...(snapshot.generationTimings || {}) },+ variantPlan: snapshot.variantPlan || null,annotationArtifacts: [...(snapshot.annotationArtifacts || [])],diagnostics: [...(snapshot.diagnostics || [])],updatedAt: entry.ts || new Date().toISOString(),@@ -174,11 +183,48 @@ function applyEvent(snapshot, entry, inheritedDiagnostics = []) {next.expectedVariants = event.count ?? next.expectedVariants;next.pendingEventSeq = entry.seq ?? next.pendingEventSeq;next.pendingEvent = toPendingEvent(event);+ next.variantPlan = null;if (event.screenshotPath) upsertArtifact(next.annotationArtifacts, { type: 'screenshot', path: event.screenshotPath });break;+ case 'variant_plan':+ if (!next.generationCanceled && !GENERATION_FENCED_PHASES.has(next.phase)) {+ next.variantPlan = event.plan ?? next.variantPlan;+ }+ break;+ case 'detector_waivers':+ if (!next.generationCanceled && !GENERATION_FENCED_PHASES.has(next.phase)) {+ next.detectorWaivers = [+ ...(next.detectorWaivers || []),+ ...(Array.isArray(event.waivers) ? event.waivers : []),+ ];+ }+ break;+ case 'agent_phase':+ next.generationPhase = event.phase ?? next.generationPhase;+ if (event.phase) {+ next.generationTimings[event.phase] = {+ at: event.at ?? (Date.parse(entry.ts || '') || null),+ durationMs: event.durationMs ?? null,+ };+ }+ break;case 'variants_ready':case 'agent_done':+ if ((next.generationCanceled || GENERATION_FENCED_PHASES.has(next.phase))+ && !(event.type === 'agent_done' && event.carbonize === true && next.phase === 'accept_requested')) {+ next.diagnostics.push({+ error: 'late_generation_event_ignored',+ type: event.type,+ phase: next.phase,+ });+ break;+ }next.phase = event.carbonize === true ? 'carbonize_required' : 'variants_ready';+ // Durable completion marker: later browser checkpoints (a resumed page+ // reporting phase "generating") regress `phase`, but generation staying+ // finished is monotone — the live server keys missed-`done` redelivery+ // on this field.+ next.generationCompletedAt = event.at ?? (Date.parse(entry.ts || '') || Date.now());next.sourceFile = event.sourceFile ?? event.file ?? next.sourceFile;next.previewFile = event.previewFile ?? next.previewFile;next.previewMode = event.previewMode ?? next.previewMode;@@ -194,27 +240,45 @@ function applyEvent(snapshot, entry, inheritedDiagnostics = []) {}break;case 'checkpoint':- if (COMPLETED_PHASES.has(next.phase)) {+ if (next.generationCanceled || GENERATION_FENCED_PHASES.has(next.phase)) {next.diagnostics.push({ error: 'checkpoint_after_terminal_ignored', phase: event.phase ?? null, revision: event.revision ?? null });break;}- if ((event.revision ?? 0) >= (next.checkpointRevision ?? 0)) {- next.phase = event.phase ?? next.phase;- next.checkpointRevision = event.revision ?? next.checkpointRevision;- next.activeOwner = event.owner ?? next.activeOwner;- next.arrivedVariants = event.arrivedVariants ?? next.arrivedVariants;- next.visibleVariant = event.visibleVariant ?? next.visibleVariant;- next.sourceFile = event.sourceFile ?? next.sourceFile;- next.previewFile = event.previewFile ?? next.previewFile;- next.previewMode = event.previewMode ?? next.previewMode;- if (event.paramValues) next.paramValues = { ...event.paramValues };- } else {- next.diagnostics.push({ error: 'stale_checkpoint_ignored', revision: event.revision });+ {+ const revisionDomain = event.revisionDomain === 'publication'+ || (event.reason === 'variants_progress' && !event.owner)+ ? 'publication'+ : 'browser';+ const revisionField = revisionDomain === 'publication'+ ? 'publicationCheckpointRevision'+ : 'browserCheckpointRevision';+ const currentRevision = next[revisionField]+ ?? (revisionDomain === 'browser' ? next.checkpointRevision : 0)+ ?? 0;+ if ((event.revision ?? 0) >= currentRevision) {+ next.phase = event.phase ?? next.phase;+ next[revisionField] = event.revision ?? currentRevision;+ if (revisionDomain === 'browser') {+ next.checkpointRevision = event.revision ?? next.checkpointRevision;+ next.activeOwner = event.owner ?? next.activeOwner;+ }+ next.arrivedVariants = event.arrivedVariants ?? next.arrivedVariants;+ if (revisionDomain === 'browser') next.visibleVariant = event.visibleVariant ?? next.visibleVariant;+ next.sourceFile = event.sourceFile ?? next.sourceFile;+ next.previewFile = event.previewFile ?? next.previewFile;+ next.previewMode = event.previewMode ?? next.previewMode;+ if (revisionDomain === 'browser' && event.paramValues) next.paramValues = { ...event.paramValues };+ } else {+ next.diagnostics.push({ error: 'stale_checkpoint_ignored', revision: event.revision, revisionDomain });+ }}break;case 'accept':case 'accept_intent':next.phase = 'accept_requested';+ next.generationCanceled = true;+ next.generationCanceledAt = event.at ?? (Date.parse(entry.ts || '') || Date.now());+ next.cancelReason = 'accept';next.visibleVariant = Number(event.variantId ?? next.visibleVariant);if (event.paramValues) next.paramValues = { ...event.paramValues };next.pendingEventSeq = entry.seq ?? next.pendingEventSeq;@@ -232,6 +296,12 @@ function applyEvent(snapshot, entry, inheritedDiagnostics = []) {next.pendingEventSeq = entry.seq ?? next.pendingEventSeq;next.pendingEvent = toPendingEvent(event);break;+ case 'carbonize_cleanup':+ next.phase = 'carbonize_cleanup_requested';+ next.sourceFile = event.file ?? next.sourceFile;+ next.pendingEventSeq = entry.seq ?? next.pendingEventSeq;+ next.pendingEvent = toPendingEvent(event);+ break;case 'steer_done':next.phase = 'steer_done';next.sourceFile = event.sourceFile ?? event.file ?? next.sourceFile;@@ -243,6 +313,9 @@ function applyEvent(snapshot, entry, inheritedDiagnostics = []) {break;case 'discard':next.phase = 'discard_requested';+ next.generationCanceled = true;+ next.generationCanceledAt = event.at ?? (Date.parse(entry.ts || '') || Date.now());+ next.cancelReason = 'discard';next.pendingEventSeq = entry.seq ?? next.pendingEventSeq;next.pendingEvent = toPendingEvent(event);break;@@ -260,6 +333,10 @@ function applyEvent(snapshot, entry, inheritedDiagnostics = []) {next.pendingEvent = null;break;case 'agent_error':+ if (next.generationCanceled && event.sourceEventType === 'generate') {+ next.diagnostics.push({ error: 'late_generation_event_ignored', type: event.type, phase: next.phase });+ break;+ }next.phase = 'agent_error';next.pendingEventSeq = null;next.pendingEvent = null;diff --git a/.pi/skills/impeccable/scripts/live/source-lock.mjs b/.pi/skills/impeccable/scripts/live/source-lock.mjsnew file mode 100644index 000000000..9ccc557be--- /dev/null+++ b/.pi/skills/impeccable/scripts/live/source-lock.mjs@@ -0,0 +1,105 @@+import fs from 'node:fs';+import path from 'node:path';+import { createHash, randomUUID } from 'node:crypto';+import { getLiveDir, isLiveServerPidReachable } from '../lib/impeccable-paths.mjs';++// Only used to retire a lock whose contents we cannot read (empty or truncated+// by a crash mid-write). A readable lock's fate is decided by its owner's+// liveness instead, so a slow critical section is never swept.+const UNREADABLE_LOCK_STALE_MS = 60_000;++export function sourceLockPath(file, cwd = process.cwd()) {+ const digest = createHash('sha256').update(path.resolve(cwd, file)).digest('hex').slice(0, 24);+ return path.join(getLiveDir(cwd), 'locks', digest + '.lock');+}++export function withSourceLockSync(file, owner, fn, {+ cwd = process.cwd(),+ waitMs = 0,+ retryMs = 5,+} = {}) {+ const lockPath = sourceLockPath(file, cwd);+ fs.mkdirSync(path.dirname(lockPath), { recursive: true });+ const deadline = Date.now() + Math.max(0, Number(waitMs) || 0);+ // Identifies this acquisition specifically, so release can tell our own lock+ // from a replacement that some other writer created.+ const token = randomUUID();+ let acquired = false;++ while (!acquired) {+ clearStaleLock(lockPath);+ let fd;+ try {+ fd = fs.openSync(lockPath, 'wx');+ fs.writeFileSync(fd, JSON.stringify({+ owner,+ token,+ pid: process.pid,+ at: Date.now(),+ file: path.resolve(cwd, file),+ }) + '\n');+ acquired = true;+ } catch (error) {+ if (error?.code !== 'EEXIST') throw error;+ if (Date.now() >= deadline) {+ const locked = new Error('source_locked');+ locked.code = 'SOURCE_LOCKED';+ locked.lockPath = lockPath;+ throw locked;+ }+ sleepSync(Math.max(1, Math.min(Number(retryMs) || 5, deadline - Date.now())));+ } finally {+ try { if (fd !== undefined) fs.closeSync(fd); } catch {}+ }+ }++ try {+ return fn();+ } finally {+ releaseOwnLock(lockPath, token);+ }+}++function sleepSync(ms) {+ Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, ms);+}++function readLock(lockPath) {+ try { return JSON.parse(fs.readFileSync(lockPath, 'utf-8')); } catch { return null; }+}++/**+ * Remove the lock only if it is still the one this call created. If a sweeper+ * judged our lock stale and another writer replaced it, unlinking here would+ * end *their* critical section and admit a third writer to the same file.+ */+function releaseOwnLock(lockPath, token) {+ const held = readLock(lockPath);+ if (held && held.token !== token) return;+ try { fs.unlinkSync(lockPath); } catch {}+}++/**+ * A lock is stale when its owner is gone, not when it is old.+ *+ * Age alone cuts both ways: it sweeps a live holder whose critical section+ * outran the timeout (a suspended laptop, a stopped process), letting two+ * writers into the same source file, while still making every accept on a+ * crashed holder's file wait out the full timeout. Asking the OS whether the+ * recorded pid is alive answers both correctly: a dead owner releases at once,+ * and a live owner keeps its lock however long it needs.+ */+function clearStaleLock(lockPath) {+ const held = readLock(lockPath);+ if (!held) {+ // Unreadable: either a crash truncated it, or we caught the brief window+ // between create and write in a live acquisition. mtime distinguishes them.+ try {+ const stat = fs.statSync(lockPath);+ if (Date.now() - stat.mtimeMs > UNREADABLE_LOCK_STALE_MS) fs.unlinkSync(lockPath);+ } catch { /* gone already */ }+ return;+ }+ if (typeof held.pid === 'number' && isLiveServerPidReachable(held.pid)) return;+ try { fs.unlinkSync(lockPath); } catch {}+}diff --git a/.qoder/skills/impeccable/reference/live.md b/.qoder/skills/impeccable/reference/live.mdindex 2b819b64c..5830de851 100644--- a/.qoder/skills/impeccable/reference/live.md+++ b/.qoder/skills/impeccable/reference/live.md@@ -10,21 +10,24 @@ Execute in order. No step skipped, no step reordered.1. `live.mjs`: boot. If the request names or implies a file, route, or app inside a monorepo, infer the concrete path and run `node .qoder/skills/impeccable/scripts/live.mjs --target <path>` instead; then run the rest of this live session from the returned `projectRoot`.2. Open the app URL that serves `pageFile` (infer from `package.json`, docs, terminal output, or an open tab). Never use `serverPort`; it's the helper, not the app. **Cursor:** `browser_navigate` to that URL before polling; do not skip. **Other harnesses:** use the available browser tool; if the URL is uncertain, ask the user once.-3. Poll loop with the default long timeout (600000 ms). After every event or `--reply`, run `live-poll.mjs` again immediately. Never pass a short `--timeout=`.+3. Poll loop with the default long timeout (600000 ms). Run `live-poll.mjs` again immediately after every event or `--reply`; Codex runs this one-shot poll in the foreground. Never pass a short `--timeout=`.The global bar **Impeccable mark** dims and shows a pulsing amber dot when no agent is long-polling `/poll`. Hover the mark for the hint; restart `live-poll.mjs` to reconnect.-4. On `generate`: read screenshot if present; load the action's reference; plan three distinct directions; write all variants in one edit; `--reply done`; poll again.+4. On `generate`: reuse `event.scaffold` when present; read the screenshot if present; load the action's reference; deliver variants using the delivery policy below; `--reply done`; poll again. Generate in this thread. You already hold the project's tokens, conventions, and file layout; that context is the job, not overhead.5. On `steer`: read the message and `pageUrl`; do the work (page edits, navigation help, or a short reply in the `--reply` message); `--reply steer_done`; poll again. No pickup ack. The Steer bar unlocks when `steer_done` arrives over SSE.-6. On `accept` / `discard`: the poll script runs `live-accept.mjs`, acknowledges the delivered event, and prints `_completionAck`. Plain accepts/discards are terminal immediately; carbonize accepts remain recoverable until you finish cleanup, run `live-complete.mjs --id EVENT_ID`, and only then poll again.+6. On `accept` / `discard`: the poll script runs `live-accept.mjs`, acknowledges the delivered event, and prints `_completionAck`. Plain accepts/discards are terminal immediately. Carbonize accepts remain recoverable until the foreground task runs `live-complete.mjs --id EVENT_ID`; finish that cleanup before polling again.7. If interrupted, run `live-status.mjs` or `live-resume.mjs` before guessing. The durable journal replays unacknowledged work after helper restart.8. On `exit`: run the cleanup at the bottom.Harness policy:-- **Claude Code**: run the poll as a **background task** (no short timeout). The harness notifies you when it completes, so the main conversation stays free. Do not block the shell.+- **Claude Code**: run the poll as a **background task** (no short timeout). The harness notifies you when it completes, so the main conversation stays free while you generate and publish in it. Do not block the shell.- **Cursor**: run **one-shot** poll in a **background terminal** with notify on `"type":"(steer|generate|accept|discard|exit)"`. After each event the poll exits; handle it, `--reply`, then start `live-poll.mjs` again. Do **not** use `--stream` on Cursor: incremental stdout notify is slower in practice than exit-based notify (~5s vs sub-second in testing).-- **Codex**: run the poll in the **foreground** (blocking shell; not a background task, not a subagent). Codex background exec sessions do not reliably surface poll stdout back into the conversation at the moment events arrive, so a "fire-and-forget" background poll will stall live mode.+- **Codex**: run the default one-shot poll in a **yielded foreground exec session**. Do not suffix it with `&`, use `--stream`, or leave Live without an active foreground poll. Handle every event in the main task; after each handler/reply, restart the foreground poll.- **Other harnesses**: one-shot foreground unless you know stdout reliably returns to this session when a shell exits.+Generation delivery policy:+- **Default (Cursor and other harnesses):** keep the established atomic single-edit delivery. Do not switch a harness to progressive until its poll loop is known not to block on the extra publish calls. This avoids trading model latency for extra tool-call latency on harnesses with different streaming behavior.+Chat is overhead. No recap, no tutorial output, no pasting PRODUCT / DESIGN bodies. Spend tokens on tools and edits; on failure, one or two short sentences.## Start@@ -92,14 +95,14 @@ Server restart rule: start `live-server.mjs` again, then poll. Startup requeues**Insert mode** (`event.mode === "insert"`): `{id, mode: "insert", count, pageUrl, insert: { position, anchor }, placeholder: { width, height }, freeformPrompt?, screenshotPath?, comments?, strokes?}`. No `action`. Requires a non-empty `freeformPrompt` **or** annotations. Screenshot is sent only when annotations exist (same rule as replace). Use `placeholder` dimensions as a soft size hint for net-new content.-Speed matters; the user is watching a spinner. Minimize tool calls by using the wrap/insert helper and writing all variants in a single edit.+Speed matters; the user is watching the selected element. Reuse server preflight metadata when available, minimize discovery calls, and follow the harness-specific delivery policy above.### Insert mode branchWhen `event.mode === "insert"`:1. Read the screenshot if `event.screenshotPath` is present (annotations only).-2. Run the insert helper instead of wrap:+2. If `event.scaffold` is present, use it as the insert-helper result and do **not** run the helper again. Otherwise run the insert helper instead of wrap:```bashnode .qoder/skills/impeccable/scripts/live-insert.mjs --id EVENT_ID --count EVENT_COUNT --position after \@@ -109,7 +112,7 @@ node .qoder/skills/impeccable/scripts/live-insert.mjs --id EVENT_ID --count EVEN- `--position` ← `event.insert.position` (`before` | `after`)- Anchor flags ← `event.insert.anchor` (same mapping as wrap: id, classes, tag, text)-The scaffold has **no** `data-impeccable-variant="original"`. Variants are net-new HTML+CSS inserted at `insertLine`. Load `brand.md` or `product.md` (freeform only, no action sub-command). Write all variants in one edit, then `--reply done`.+The scaffold has **no** `data-impeccable-variant="original"`. Variants are net-new HTML+CSS inserted at `insertLine`. Load `brand.md` or `product.md` (freeform only, no action sub-command). Deliver using the harness policy, then `--reply done`.For Svelte/SvelteKit targets, `live-insert.mjs` returns `previewMode: "svelte-component"` with `mode: "insert"`, `file` pointing at a temporary `node_modules/.impeccable-live/<id>/manifest.json`, `componentDir` pointing at the variant component files, and `sourceFile` pointing at the real `.svelte` route. Write each inserted variant as a real Svelte component (`v1.svelte`, `v2.svelte`, …) under `componentDir`. Insert variants must be non-empty net-new content with a single top-level root, no `data-impeccable-*` attributes, and CSS in each component's `<style>` block. Do **not** edit the route source during generation; the browser mounts the temporary component before/after the live anchor while the user cycles variants. On Accept, `live-accept.mjs` inserts the selected component markup into `sourceFile` immediately and deletes the temp session after the source write succeeds.@@ -134,6 +137,8 @@ Reading annotations precisely:### 2. Wrap the element+When `event.scaffold` is present, the local helper already found and wrapped the source before the poll returned. Treat `event.scaffold` as the successful helper output and skip this command entirely. `event.scaffoldAttempted` with `scaffoldError` means local preflight could not finish; use the command/fallback path below. This optimization removes a deterministic tool round trip without changing the generated design.+```bashnode .qoder/skills/impeccable/scripts/live-wrap.mjs --id EVENT_ID --count EVENT_COUNT --element-id "ELEMENT_ID" --classes "class1,class2" --tag "div" --text "TEXT_SNIPPET"```@@ -153,7 +158,7 @@ Output on success: `{ file, insertLine, commentSyntax, styleMode, styleTag, cssSFor Svelte/SvelteKit targets, `live-wrap.mjs` returns `previewMode: "svelte-component"` with `file` pointing at a temporary `node_modules/.impeccable-live/<id>/manifest.json`, `componentDir` pointing at the variant component files, and `sourceFile` pointing at the real `.svelte` route. Write each variant as a real Svelte component (`v1.svelte`, `v2.svelte`, …) under `componentDir`; use the `propContract` prop names for dynamic text (`{propName}`), not literal snapshot strings. Put variant CSS in each component's `<style>` block with semantic class selectors (no `@scope`, no `data-impeccable-*`). Reply with `--file` set to the manifest path; the browser dynamically imports and mounts the compiled components so Svelte HMR does not reset page state while the user cycles variants. On Accept, `live-accept.mjs` inlines the accepted component back into `sourceFile` immediately after source promotion succeeds.-**Params on the Svelte component path go in a sidecar, never as an attribute.** Svelte parses `{` inside an attribute value as the start of an expression, so a `data-impeccable-params='[{…}]'` attribute on a component element fails to compile (`Expected token }`). Declare params for this path in `componentDir/params.json`, keyed by variant number, using the exact param schema from section 7:+**Params on component-preview paths go in a sidecar, never as an attribute.** Svelte parses `{` inside an attribute value as the start of an expression, and both Svelte/Vue previews mount without an HTML variant wrapper. Declare params in `componentDir/params.json`, keyed by variant number, using the exact param schema from section 7:```json{@@ -291,11 +296,13 @@ In **departure mode**, the prompt narrows the lanes you draw from, not the familWhen the prompt and PRODUCT.md anti-references conflict (the prompt asks for X, the anti-references ban X), the anti-references win; they describe the brand's standing position, the prompt is one moment.-### 6. Write all variants in a single edit+### 6. Deliver variantsComplete HTML replacement of the original element for each variant, not a CSS-only patch. Consider the element's context (computed styles, parent structure, CSS variables from `event.element`).-Write CSS + all variants in ONE edit at the `insertLine` reported by `wrap`. Colocate CSS as a `<style>` tag inside the variant wrapper; `<style>` works anywhere in modern browsers and this ensures CSS and HTML arrive atomically (no FOUC).+Colocate preview CSS as a `<style>` tag inside the variant wrapper; `<style>` works anywhere in modern browsers and keeps each delivered state internally complete (no FOUC).++**Atomic default:** write CSS + all variants + parameter manifests in one edit at `insertLine`, preserving the established behavior.Use the `cssAuthoring` object returned by `live-wrap.mjs` to author the temporary preview CSS. The style opening tag shown below is the common case; replace it with `cssAuthoring.styleTag` when the tool returns a different one. The variant markup shape is otherwise stable:@@ -319,7 +326,7 @@ Use the `cssAuthoring` object returned by `live-wrap.mjs` to author the temporarThe first variant has no `display: none` (visible by default). All others do. If variants use only inline styles and no preview CSS, omit the `<style>` tag entirely.-One edit, all variants; the browser's MutationObserver picks everything up in one pass.+The browser's MutationObserver accepts either delivery shape. On the transactional progressive path it shows arrived variants and pending dots immediately; Accept and Discard are available as soon as one variant exists. Accepting an arrived variant fences the worker before the browser releases the picker, so later publications are rejected.For `styleMode: "scoped"`, author every `:scope` rule with a descendant combinator. The `@scope` boundary is the **variant wrapper `<div data-impeccable-variant="N">`**, not the element you're designing. A bare `:scope { background: cream; }` styles the wrapper, not the inner replacement, so the cream lands on a `display: contents` shell while the actual element keeps page defaults. Always step in: `:scope > .card`, `:scope > section`, `:scope .hero-title`, etc. The fake test agent's CSS in `tests/live-e2e/agent.mjs` is a faithful template; every scoped rule starts `:scope > ...`.@@ -361,7 +368,7 @@ Each variant can expose **coarse** knobs alongside the full HTML/CSS replacement**Hard cap per variant**: at most **four** parameters so the panel stays legible; rare fifth only if the reference explicitly allows it.-**How to declare.** Put a JSON manifest on the variant wrapper (HTML/JSX path). **On the Svelte `svelte-component` path, do not use this attribute** (Svelte can't compile `{` inside an attribute value). Declare params in `componentDir/params.json` keyed by variant number instead (see the Svelte component paragraph in the wrap section). The param schema below is identical for both paths.+**How to declare.** Put a JSON manifest on the variant wrapper (HTML/JSX path). **On the `svelte-component` path, do not use this attribute.** Declare params in `componentDir/params.json` keyed by variant number instead (see the component-preview paragraphs in the wrap section). The param schema below is identical for every path.```html<div data-impeccable-variant="1" data-impeccable-params='[@@ -462,15 +469,19 @@ Event: `{id, variantId, _acceptResult, _completionAck}`. The poll script already- The accept event includes `pageUrl`; the poll script must forward it to `live-accept.mjs --page-url PAGE_URL` so accept-time cleanup only scrubs staged copy edits for the current page.- `_completionAck.ok !== true`: do not poll yet. Run `live-status.mjs` / `live-resume.mjs`, complete the cleanup manually if needed, then run `live-complete.mjs --id EVENT_ID`.- `_acceptResult.handled: true` and `carbonize: false`: nothing to do. Poll again.-- `_acceptResult.handled: true` and `carbonize: true`: **post-accept cleanup is required before the next poll.** See the "Required after accept (carbonize)" section below. The `event._acceptResult.todo` field, `_completionAck.requiresComplete`, and a stderr banner all point at this required follow-up; none are decorative. After cleanup, run `live-complete.mjs --id EVENT_ID`, then poll again.+- `_acceptResult.handled: true` and `carbonize: true`: post-accept cleanup is required, but it must not stall Codex's control lane. See "Required after accept (carbonize)" below. The `event._acceptResult.todo` field, `_completionAck.requiresComplete`, and stderr banner all point at this required follow-up; none are decorative.- `_acceptResult.handled: false, mode: "fallback"`: the session lived in a generated file and the script refused to persist there. You've already written the accepted variant into true source during Handle fallback Step 3; just clean up the temporary wrapper in the served file if any, and poll again.+- `_acceptResult.handled: false, mode: "error"`: the operation genuinely failed. **Do not hand-edit the file**; the source was not touched and editing it yourself would either double-apply or race whoever holds it.+ - `error: "source_locked"`: a generation publish holds the file. Run the same `live-accept.mjs` command again; it is idempotent and will succeed once the publisher releases. Do not poll past it.+ - `error: "accept_receipt_conflict"`: this session already resolved as `priorOperation` (on `priorVariantId` for an accept), so the request contradicts durable truth. Do not edit. Run `live-status.mjs` and tell the user what the session actually resolved to.+ - anything else: report the error briefly and run `live-status.mjs` before continuing.- `_acceptResult.handled: false` without `mode`: manual cleanup: read file, find markers, edit.### Required after accept (carbonize)When `_acceptResult.carbonize === true`, the accepted variant was stitched into source with helper markers and inline CSS so the browser can render it immediately with no visual gap. That stitch-in is **temporary**. The agent must rewrite it into permanent form before doing anything else. Skipping this leaves dead `@scope` rules for unaccepted variants, a pointless `data-impeccable-variant` wrapper, and `impeccable-carbonize-start/end` comment noise in the source file; all of which accumulate across sessions.-Do these five steps in the current thread, synchronously, before the next poll. Do not poll again until the file is clean.+Do these five steps synchronously before the next poll. The source lock, generation epoch, and expected-source hash remain the final safety gates against a generator finishing concurrently with Accept.1. **Locate the carbonize block** in the source file (`_acceptResult.file`). It's bracketed by `<!-- impeccable-carbonize-start SESSION_ID -->` and `<!-- impeccable-carbonize-end SESSION_ID -->` and contains a `<style data-impeccable-css="SESSION_ID">` element. If the variant declared parameters, an `<!-- impeccable-param-values SESSION_ID: {...} -->` comment sits alongside the style tag with the user's chosen values; read it first; it drives steps 3 and 4 below.2. **Move the CSS rules** into the project's real stylesheet. Which stylesheet depends on the project (e.g. `site/styles/workflow.css` for an Astro project, or the component's co-located CSS file for a Vite/Next project; pick whichever already owns styling for the surrounding element).@@ -478,9 +489,7 @@ Do these five steps in the current thread, synchronously, before the next poll.4. **Unwrap the accepted content.** Delete the inner `<div data-impeccable-variant="N" style="display: contents">` that wraps it. On JSX/TSX, also delete the outer `<div data-impeccable-carbonize="SESSION_ID" style={{ display: 'contents' }}>` wrapper if present (accept adds it so ternary/`return` slots keep a single root). Drop `data-impeccable-params` and any `data-p-*` attributes; those are live-mode plumbing, not source.5. **Delete the inline `<style>` block, the `<!-- impeccable-param-values -->` comment if present, and both `<!-- impeccable-carbonize-start/end -->` markers.** Also drop any `@scope` rules for variants other than the accepted one; those are dead code now.-After the file is clean, run `live-complete.mjs --id SESSION_ID`, verify it reports `phase: "completed"`, then poll again.--A background agent may be used for the rewrite, but the current thread is responsible for verifying the five steps are complete before issuing the next poll. In practice, inline is usually faster and less error-prone.+After the file is clean, the cleanup owner runs `live-complete.mjs --id SESSION_ID` and verifies `phase: "completed"`. Poll again only after that verification.## Handle `discard`diff --git a/.qoder/skills/impeccable/scripts/lib/impeccable-paths.mjs b/.qoder/skills/impeccable/scripts/lib/impeccable-paths.mjsindex 2ccbe7b74..99956c0f3 100644--- a/.qoder/skills/impeccable/scripts/lib/impeccable-paths.mjs+++ b/.qoder/skills/impeccable/scripts/lib/impeccable-paths.mjs@@ -104,6 +104,20 @@ export function removeLiveServerInfo(cwd = process.cwd(), options = {}) {}}+/**+ * Session IDs become path segments (journals, snapshots, accept receipts,+ * preview manifests, generated component dirs). They arrive from CLI `--id`+ * arguments and HTTP payloads, so anything containing a separator or `..` must+ * be rejected before it reaches path.join, which would happily escape+ * `.impeccable/live/`. Real IDs are 8 hex chars; the tests use short slugs.+ */+export function safeSessionId(id) {+ if (typeof id !== 'string' || !/^[A-Za-z0-9_-]{1,128}$/.test(id)) {+ throw new Error('invalid session id: ' + id);+ }+ return id;+}+export function getLiveSessionsDir(cwd = process.cwd(), options = {}) {return path.join(getLiveDir(cwd, options), 'sessions');}diff --git a/.qoder/skills/impeccable/scripts/live-accept.mjs b/.qoder/skills/impeccable/scripts/live-accept.mjsindex 278dfbb2e..453ddea35 100644--- a/.qoder/skills/impeccable/scripts/live-accept.mjs+++ b/.qoder/skills/impeccable/scripts/live-accept.mjs@@ -16,7 +16,9 @@import fs from 'node:fs';import path from 'node:path';import { isGeneratedFile } from './lib/is-generated.mjs';+import { IMPECCABLE_DIR, getLiveDir, safeSessionId } from './lib/impeccable-paths.mjs';import { readBuffer as readManualEditsBuffer, writeBuffer as writeManualEditsBuffer } from './live/manual-edits-buffer.mjs';+import { withSourceLockSync } from './live/source-lock.mjs';import {applyDeferredSvelteComponentAccepts,findSvelteComponentManifest,@@ -25,6 +27,46 @@ import {} from './live/svelte-component.mjs';const EXTENSIONS = ['.html', '.jsx', '.tsx', '.vue', '.svelte', '.astro'];+const ACCEPT_LOCK_WAIT_MS = 1_000;+// Mirrors VARIANT_ID_PATTERN in live/event-validation.mjs, which gates the same+// value arriving over HTTP.+const VARIANT_NUM_PATTERN = /^[0-9]{1,3}$/;++/**+ * A thrown accept/discard is a real failure, not a manual handoff.+ *+ * live/completion.mjs only classifies a result as `error` when it carries+ * `mode: 'error'`; anything else unhandled falls through to `agent_done` with a+ * successful ack, and reference/live.md then tells the agent to finish the edit+ * by hand. That is right for the documented fallback paths and wrong here: a+ * `source_locked` contention needs a retry (hand-editing races the publisher+ * holding the lock), and a crash needs surfacing, not a hand-applied guess.+ */+function operationFailure(err, extra = {}) {+ return { handled: false, mode: 'error', error: err.message, ...extra };+}++/**+ * Mark an unhandled preview-path result as a real failure.+ *+ * operationFailure only covers results built from a *thrown* error. The accept+ * implementations also return `{handled: false, error}` for their own checks+ * (variant missing, template empty, original text ambiguous), and those arrived+ * without `mode`, so completion.mjs classified them as agent_done and+ * reference/live.md routed the agent to "read file, find markers, edit".+ *+ * That handoff only makes sense for a plain wrapper session, which is the one+ * shape with markers in the user's source to edit. Component and isolated+ * artifact previews keep the source clean until Accept, so there is nothing to+ * hand-edit and an unhandled result is always a failure. `previewMode` is+ * exactly that discriminator: only the preview branches set it.+ */+function markPreviewFailure(result) {+ if (result?.handled === false && !result.mode && result.previewMode) {+ return { ...result, mode: 'error' };+ }+ return result;+}// ---------------------------------------------------------------------------// CLI@@ -63,7 +105,52 @@ Output (JSON):const isDiscard = args.includes('--discard');if (!id) { console.error('Missing --id'); process.exit(1); }+ // `id` becomes a path segment (accept receipts, preview manifests, generated+ // component dirs). Reject separators and traversal here so one check covers+ // every downstream sink.+ try { safeSessionId(id); } catch { console.error('Invalid --id'); process.exit(1); }if (!isDiscard && !variantNum) { console.error('Need --discard or --variant N'); process.exit(1); }+ // `variantNum` is interpolated into a RegExp and into the markup written back+ // to source. The browser and the /events schema both constrain it to digits;+ // enforce the same here, or `--variant '.*'` matches the `original` block+ // first and silently accepts the original while reporting success.+ if (!isDiscard && !VARIANT_NUM_PATTERN.test(variantNum)) {+ console.error('Invalid --variant');+ process.exit(1);+ }++ const requestedOperation = isDiscard ? 'discard' : 'accept';+ const priorReceipt = readAcceptReceipt(process.cwd(), id);+ if (priorReceipt) {+ const sameOperation = priorReceipt.operation === requestedOperation+ && (isDiscard || String(priorReceipt.variantId) === String(variantNum));+ console.log(JSON.stringify(sameOperation+ ? { ...priorReceipt.result, handled: true, alreadyApplied: true }+ : {+ // mode: 'error' is what marks this a real failure rather than a manual+ // handoff. Without it, live/completion.mjs classifies the reply as+ // agent_done and reference/live.md tells the agent to "read file, find+ // markers, edit" by hand — which would apply a second, conflicting+ // accept on top of the one the receipt already recorded.+ handled: false,+ mode: 'error',+ error: 'accept_receipt_conflict',+ priorOperation: priorReceipt.operation,+ priorVariantId: priorReceipt.variantId ?? null,+ }));+ return;+ }+ const emitResult = (rawResult) => {+ const result = markPreviewFailure(rawResult);+ if (result?.handled !== false) {+ writeAcceptReceipt(process.cwd(), id, {+ operation: requestedOperation,+ variantId: isDiscard ? null : String(variantNum),+ result,+ });+ }+ console.log(JSON.stringify(result));+ };let paramValues = null;if (paramValuesRaw) {@@ -82,39 +169,55 @@ Output (JSON):if (svelteComponentManifest) {if (isDiscard) {- removeSvelteComponentSession(id, process.cwd());- console.log(JSON.stringify({- handled: true,+ let result;+ try {+ result = withSourceLockSync(+ path.resolve(process.cwd(), svelteComponentManifest.sourceFile),+ 'discard:' + id,+ () => {+ removeSvelteComponentSession(id, process.cwd());+ return { handled: true };+ },+ { waitMs: ACCEPT_LOCK_WAIT_MS },+ );+ } catch (err) {+ result = operationFailure(err);+ }+ emitResult({+ ...result,file: svelteComponentManifest.sourceFile,carbonize: false,previewMode: 'svelte-component',componentDir: svelteComponentManifest.componentDir,- }));+ });return;}let result;try {- result = inlineSvelteComponentAccept(- svelteComponentManifest,- variantNum,- paramValues,- process.cwd(),+ result = withSourceLockSync(+ path.resolve(process.cwd(), svelteComponentManifest.sourceFile),+ 'accept:' + id,+ () => inlineSvelteComponentAccept(+ svelteComponentManifest,+ variantNum,+ paramValues,+ process.cwd(),+ ),+ { waitMs: ACCEPT_LOCK_WAIT_MS },);} catch (err) {- result = {- handled: false,- error: err.message,+ result = operationFailure(err, {file: svelteComponentManifest.sourceFile,sourceFile: svelteComponentManifest.sourceFile,previewMode: 'svelte-component',componentDir: svelteComponentManifest.componentDir,- };+ });}if (result.carbonize) {result.todo = 'REQUIRED before next poll: carbonize cleanup in ' + result.file + '. See reference/live.md "Required after accept".';}- console.log(JSON.stringify({ handled: result.handled !== false, ...result }));+ emitResult({ handled: result.handled !== false, ...result });return;}@@ -145,10 +248,25 @@ Output (JSON):}if (isDiscard) {- const result = handleDiscard(id, lines, targetFile);- console.log(JSON.stringify({ handled: true, file: relFile, carbonize: false, ...result }));+ let result;+ // handleDiscard takes the source lock, which throws SOURCE_LOCKED under+ // contention. Without this catch the CLI exits non-zero with empty stdout+ // and the agent gets no JSON to act on.+ try {+ result = handleDiscard(id, lines, targetFile);+ } catch (err) {+ emitResult(operationFailure(err, { file: relFile }));+ return;+ }+ emitResult({ handled: true, file: relFile, carbonize: false, ...result });} else {- const result = handleAccept(id, variantNum, lines, targetFile, paramValues);+ let result;+ try {+ result = handleAccept(id, variantNum, lines, targetFile, paramValues);+ } catch (err) {+ emitResult(operationFailure(err, { file: relFile }));+ return;+ }const acceptedOriginalText = result.acceptedOriginalText || '';delete result.acceptedOriginalText;// Single-line attention-grabber when cleanup is required. The full@@ -167,7 +285,7 @@ Output (JSON):// Non-fatal; the buffer stays as-is and the user can discard later.}}- console.log(JSON.stringify({ handled: true, file: relFile, ...result }));+ emitResult({ handled: true, file: relFile, ...result });}}@@ -235,7 +353,14 @@ function scrubManualEditsAgainstFile(_targetFile, cwd = process.cwd(), originalB// Discard// ----------------------------------------------------------------------------function handleDiscard(id, lines, targetFile) {+function handleDiscard(id, _lines, targetFile) {+ return withSourceLockSync(targetFile, 'discard:' + id, () => {+ const lines = fs.readFileSync(targetFile, 'utf-8').split('\n');+ return handleDiscardUnlocked(id, lines, targetFile);+ }, { waitMs: ACCEPT_LOCK_WAIT_MS });+}++function handleDiscardUnlocked(id, lines, targetFile) {const block = findMarkerBlock(id, lines);if (!block) return { handled: false, error: 'Markers not found' };@@ -330,7 +455,24 @@ function reindentContent(contentLines, fromIndent, toIndent) {});}-function handleAccept(id, variantNum, lines, targetFile, paramValues) {+function handleAccept(id, variantNum, _lines, targetFile, paramValues) {+ return withSourceLockSync(targetFile, 'accept:' + id, () => {+ const lines = fs.readFileSync(targetFile, 'utf-8').split('\n');+ return handleAcceptUnlocked(id, variantNum, lines, targetFile, paramValues);+ }, { waitMs: ACCEPT_LOCK_WAIT_MS });+}++function handleAcceptUnlocked(id, variantNum, lines, targetFile, paramValues) {+ const built = buildAcceptedWrappedSource(id, variantNum, lines, targetFile, paramValues);+ if (built.handled === false) return built;+ fs.writeFileSync(targetFile, built.content, 'utf-8');+ return {+ carbonize: built.carbonize,+ acceptedOriginalText: built.acceptedOriginalText,+ };+}++function buildAcceptedWrappedSource(id, variantNum, lines, targetFile, paramValues) {const block = findMarkerBlock(id, lines);if (!block) return { handled: false, error: 'Markers not found' };@@ -375,11 +517,14 @@ function handleAccept(id, variantNum, lines, targetFile, paramValues) {...replacement,...lines.slice(replaceRange.end + 1),];- fs.writeFileSync(targetFile, newLines.join('\n'), 'utf-8');-- return { carbonize: needsCarbonize, acceptedOriginalText: originalContent.join('\n') };+ return {+ content: newLines.join('\n'),+ carbonize: needsCarbonize,+ acceptedOriginalText: originalContent.join('\n'),+ };}+function readSourceShadowPreviewMeta(content, id) {const escaped = escapeRegExp(id);const wrapperRe = new RegExp('<[^>]+data-impeccable-variants=(["\'])' + escaped + '\\1[^>]*>');@@ -746,6 +891,21 @@ function detectCommentSyntax(filePath) {// File search (find the file containing session markers)// ---------------------------------------------------------------------------+/**+ * `.impeccable` is the critical entry, and it is not cosmetic.+ *+ * Progressive publication stages each revision as `.impeccable/live/artifacts/+ * <id>-r<n>.<source-ext>`, and those artifacts carry the very marker this search+ * looks for. The walk reaches `.` for any project whose source is not under one+ * of the privileged dirs above (this repo's own site lives in `site/pages/`), and+ * dot-directories sort before letters, so the artifact was found *before* the+ * real file. isGeneratedFile then declined the accept, and the agent fell back to+ * carbonizing several hundred lines of stylesheet by hand.+ *+ * Impeccable's own state directory is never project source. Never search it.+ */+const SEARCH_SKIP_DIRS = new Set(['node_modules', '.git', 'dist', 'build', IMPECCABLE_DIR]);+function findSessionFile(id, cwd) {const marker = 'impeccable-variants-start ' + id;const searchDirs = ['src', 'app', 'pages', 'components', 'public', 'views', 'templates', '.'];@@ -786,7 +946,7 @@ function searchDir(dir, query, seen, depth) {for (const entry of entries) {if (!entry.isDirectory()) continue;- if (['node_modules', '.git', 'dist', 'build'].includes(entry.name)) continue;+ if (SEARCH_SKIP_DIRS.has(entry.name)) continue;const result = searchDir(path.join(dir, entry.name), query, seen, depth + 1);if (result) return result;}@@ -798,6 +958,28 @@ function searchDir(dir, query, seen, depth) {// Utilities// ---------------------------------------------------------------------------+function acceptReceiptPath(cwd, id) {+ return path.join(getLiveDir(cwd), 'accept-receipts', `${safeSessionId(id)}.json`);+}++function readAcceptReceipt(cwd, id) {+ try { return JSON.parse(fs.readFileSync(acceptReceiptPath(cwd, id), 'utf-8')); } catch { return null; }+}++function writeAcceptReceipt(cwd, id, receipt) {+ const file = acceptReceiptPath(cwd, id);+ fs.mkdirSync(path.dirname(file), { recursive: true });+ const value = {+ id,+ ...receipt,+ completedAt: new Date().toISOString(),+ };+ const temporary = `${file}.${process.pid}.${Date.now()}.tmp`;+ fs.writeFileSync(temporary, JSON.stringify(value, null, 2) + '\n', 'utf-8');+ fs.renameSync(temporary, file);+ return value;+}+function argVal(args, flag) {const idx = args.indexOf(flag);return idx !== -1 && idx + 1 < args.length ? args[idx + 1] : null;diff --git a/.qoder/skills/impeccable/scripts/live-browser.js b/.qoder/skills/impeccable/scripts/live-browser.jsindex 616f1290a..20d875b93 100644--- a/.qoder/skills/impeccable/scripts/live-browser.js+++ b/.qoder/skills/impeccable/scripts/live-browser.js@@ -126,6 +126,9 @@let expectedVariants = 0;let arrivedVariants = 0;let visibleVariant = 0;+ let generationPhase = null;+ let parameterGenerationState = 'idle';+ let parameterReadyAnnouncedSession = null;let svelteComponentSession = null;let svelteRuntimePromise = null;let pendingSvelteComponentRetryObserver = null;@@ -134,6 +137,7 @@let currentPreviewMode = null;let recoveryWaitingForAnchor = false;let pickedAnchorSnapshot = null;+ let pickedAnchorViewportTop = null;let pendingVariantAnchorRetryObserver = null;let pendingAcceptedSession = null;let variantObserver = null;@@ -151,10 +155,12 @@// startScrollLock / stopScrollLock below.let scrollLockObserver = null;let scrollLockTargetY = null;+ let scrollLockAnchorTop = null;let scrollLockRaf = null;let scrollLockAbort = null;const SCROLL_ANCHOR_LOCK_ID = 'impeccable-scroll-anchor-lock';const VARIANT_STATE_STYLE_ID = 'impeccable-variant-state';+ const DISCARD_STATE_STYLE_ID = 'impeccable-discard-state';// Dedicated key for scroll position - SEPARATE from LS_KEY so that// saveSession's state updates don't clobber a carefully-captured scrollY.@@ -252,6 +258,13 @@barConnected: !!barEl?.isConnected,hasSvelteComponentSession: !!svelteComponentSession,mountedSvelteVariant: svelteComponentSession?.mountedVariant || 0,+ pickActive,+ pendingApplyInFlight,+ hoveredElement: hoveredElement ? {+ tag: hoveredElement.tagName,+ classes: hoveredElement.className,+ pickable: pickable(hoveredElement),+ } : null,pendingSvelteComponentRetry: !!pendingSvelteComponentRetryObserver,recoveryWaitingForAnchor,evtSourceReadyState: evtSource ? evtSource.readyState : null,@@ -1114,14 +1127,15 @@});}- function hideBar() {+ function hideBar(instant) {if (!barEl) return;const hideSeq = ++barHideSeq;stopVoice({ suppressSubmit: true });if (configureKind === 'insert') clearInsertPicking();barEl.style.opacity = '0';- barEl.style.transform = 'translateY(6px)';- setTimeout(() => { if (barEl && hideSeq === barHideSeq) barEl.style.display = 'none'; }, 250);+ barEl.style.transform = instant ? 'translateY(0)' : 'translateY(6px)';+ if (instant) barEl.style.display = 'none';+ else setTimeout(() => { if (barEl && hideSeq === barHideSeq) barEl.style.display = 'none'; }, 250);hideActionPicker();closeTunePopover();hideConfigureBarTooltip();@@ -1966,6 +1980,7 @@*/function setLiveState(next) {state = next;+ window.__IMPECCABLE_LIVE_STATE__ = next;syncPageInteractionCursor();}@@ -2516,18 +2531,27 @@fontSize: '11px', color: BP.textDim, whiteSpace: 'nowrap',marginLeft: 'auto',});- // Variants currently arrive atomically in a single file edit, so a- // per-variant counter would lie. Say what's true.status.textContent = recoveryWaitingForAnchor? 'Variants ready. Reveal the selected element to resume.'- : (arrivedVariants < expectedVariants- ? 'Generating ' + expectedVariants + ' variants...'- : 'Done');+ : generationStatusText();row.appendChild(status);return row;}+ function generationStatusText() {+ if (arrivedVariants >= expectedVariants && expectedVariants > 0) return 'Done';+ if (generationPhase === 'picked_up') return 'Agent picked up the request...';+ if (generationPhase === 'scaffolding') return 'Finding the source...';+ if (generationPhase === 'source_ready') return 'Source ready. Generating...';+ if (generationPhase === 'scaffold_fallback') return 'Agent is locating the source...';+ if (generationPhase === 'first_variant_generating') return 'Designing the first variant...';+ if (generationPhase === 'first_variant_validating') return 'Checking the first variant...';+ if (generationPhase === 'remaining_variants_generating') return 'Exploring two more directions...';+ if (generationPhase === 'remaining_variants_validating') return 'Checking the remaining variants...';+ return 'Generating ' + expectedVariants + ' variants...';+ }+// Cycling rowconst TUNE_ICON_SVG = '<svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" style="flex-shrink:0"><line x1="4" y1="8" x2="20" y2="8"/><circle cx="14" cy="8" r="2.4" fill="currentColor" stroke="none"/><line x1="4" y1="16" x2="20" y2="16"/><circle cx="10" cy="16" r="2.4" fill="currentColor" stroke="none"/></svg>';@@ -2557,7 +2581,7 @@color: BP.textDim, minWidth: '24px', textAlign: 'center',});counter.id = PREFIX + '-variant-counter';- counter.textContent = visibleVariant + '/' + arrivedVariants;+ counter.textContent = visibleVariant + '/' + expectedVariants;row.appendChild(counter);// Next@@ -2567,10 +2591,12 @@if (visibleVariant >= arrivedVariants) next.style.opacity = '0.3';row.appendChild(next);- // Tune chip - only when the visible variant exposes params+ // Tune chip stays visible while the deferred parameter phase is running,+ // then becomes interactive as soon as this variant exposes controls.const visParams = parseVariantParams(getVisibleVariantEl());const hasParams = visParams.length > 0;- if (hasParams) {+ const paramsPending = !hasParams && (parameterGenerationState === 'pending' || parameterGenerationState === 'loading');+ if (hasParams || paramsPending) {const tune = el('button', {display: 'inline-flex', alignItems: 'center', gap: '6px',padding: '4px 10px', borderRadius: '5px',@@ -2578,35 +2604,54 @@background: tuneOpen ? BP.accentSoft : 'transparent',color: tuneOpen ? BP.accent : BP.text,fontFamily: FONT, fontSize: '11px', fontWeight: '500',- cursor: 'pointer',+ cursor: paramsPending ? 'wait' : 'pointer',transition: 'color 0.12s ease, background 0.12s ease',whiteSpace: 'nowrap',});- tune.innerHTML = TUNE_ICON_SVG;+ if (paramsPending) {+ const spinner = el('span', {+ width: '11px', height: '11px', borderRadius: '50%',+ border: '1.5px solid ' + BP.hairline,+ borderTopColor: BP.accent,+ animation: 'impeccable-spin 0.6s linear infinite',+ boxSizing: 'border-box', flexShrink: '0',+ });+ spinner.setAttribute('aria-hidden', 'true');+ tune.appendChild(spinner);+ } else {+ tune.innerHTML = TUNE_ICON_SVG;+ }const tuneLabel = document.createElement('span');tuneLabel.textContent = 'Tune';tune.appendChild(tuneLabel);- const tuneBadge = document.createElement('span');- Object.assign(tuneBadge.style, {- display: 'inline-flex', alignItems: 'center', justifyContent: 'center',- minWidth: '16px', height: '16px', padding: '0 4px',- borderRadius: '999px',- background: tuneOpen ? C.brand : BP.hairline,- color: tuneOpen ? 'oklch(98% 0 0)' : 'inherit',- fontFamily: MONO, fontSize: '9.5px', fontWeight: '600',- lineHeight: '1',- boxSizing: 'border-box',- });- tuneBadge.textContent = String(visParams.length);- tune.appendChild(tuneBadge);- tune.title = 'Tune this variant (' + visParams.length + ' knob' + (visParams.length === 1 ? '' : 's') + ')';- tune.addEventListener('mouseenter', () => {- if (!tuneOpen) tune.style.background = BP.accentSoft;- });- tune.addEventListener('mouseleave', () => {- if (!tuneOpen) tune.style.background = 'transparent';- });- tune.addEventListener('click', (e) => { e.stopPropagation(); toggleTunePopover(); });+ if (hasParams) {+ const tuneBadge = document.createElement('span');+ Object.assign(tuneBadge.style, {+ display: 'inline-flex', alignItems: 'center', justifyContent: 'center',+ minWidth: '16px', height: '16px', padding: '0 4px',+ borderRadius: '999px',+ background: tuneOpen ? C.brand : BP.hairline,+ color: tuneOpen ? 'oklch(98% 0 0)' : 'inherit',+ fontFamily: MONO, fontSize: '9.5px', fontWeight: '600',+ lineHeight: '1',+ boxSizing: 'border-box',+ });+ tuneBadge.textContent = String(visParams.length);+ tune.appendChild(tuneBadge);+ tune.title = 'Tune this variant (' + visParams.length + ' knob' + (visParams.length === 1 ? '' : 's') + ')';+ tune.addEventListener('mouseenter', () => {+ if (!tuneOpen) tune.style.background = BP.accentSoft;+ });+ tune.addEventListener('mouseleave', () => {+ if (!tuneOpen) tune.style.background = 'transparent';+ });+ tune.addEventListener('click', (e) => { e.stopPropagation(); toggleTunePopover(); });+ } else {+ tune.disabled = true;+ tune.setAttribute('aria-label', 'Tune controls are still being prepared');+ tune.title = 'Tune controls are still being prepared';+ tune.style.opacity = '0.72';+ }tune.dataset.iceqTune = '1';row.appendChild(tune);}@@ -2614,6 +2659,15 @@// Spacerrow.appendChild(el('div', { flex: '1' }));+ if (arrivedVariants < expectedVariants) {+ const remaining = expectedVariants - arrivedVariants;+ const progress = el('span', {+ fontSize: '11px', color: BP.textDim, whiteSpace: 'nowrap',+ });+ progress.textContent = remaining + ' more arriving...';+ row.appendChild(progress);+ }+// Accept - primary action, kinpaku gold + lacquer-deep (matches demo .live-demo-ctx-accept)const accept = el('button', {padding: '5px 14px', borderRadius: '5px',@@ -2628,7 +2682,11 @@accept.addEventListener('mousedown', () => accept.style.transform = 'scale(0.97)');accept.addEventListener('mouseup', () => accept.style.transform = 'scale(1)');accept.addEventListener('click', (e) => { e.stopPropagation(); handleAccept(); });- if (arrivedVariants === 0) { accept.style.opacity = '0.3'; accept.style.pointerEvents = 'none'; }+ if (arrivedVariants === 0) {+ accept.style.opacity = '0.3';+ accept.style.pointerEvents = 'none';+ accept.title = 'Accept becomes available when the first variant arrives';+ }row.appendChild(accept);// Discard@@ -4743,6 +4801,32 @@}}+ function mountedParameterCount() {+ if (svelteComponentSession?.sessionId === currentSessionId) {+ return Object.values(svelteComponentSession.paramsByVariant || {})+ .reduce((total, params) => total + (Array.isArray(params) ? params.length : 0), 0);+ }+ const wrapper = document.querySelector('[data-impeccable-variants="' + currentSessionId + '"]');+ if (!wrapper) return 0;+ return [...wrapper.querySelectorAll('[data-impeccable-variant]:not([data-impeccable-variant="original"])')]+ .reduce((total, variant) => total + parseVariantParams(variant).length, 0);+ }++ function completeParameterPublication() {+ if (!currentSessionId) return;+ const ready = mountedParameterCount() > 0;+ parameterGenerationState = ready ? 'ready' : 'none';+ if (ready && parameterReadyAnnouncedSession !== currentSessionId) {+ parameterReadyAnnouncedSession = currentSessionId;+ showToast('Tune controls are ready.', 3000);+ }+ if (state === 'CYCLING') {+ refreshParamsPanel();+ showOrUpdateCyclingBar();+ }+ saveSession();+ }+function toggleTunePopover() {if (pendingApplyInFlight) { showManualApplyBusyToast(); return; }if (tuneOpen) { closeTunePopover(); return; }@@ -4835,6 +4919,10 @@return String(filePath || '').endsWith('manifest.json');}+ function isFrameworkComponentPreviewMode(mode) {+ return mode === 'svelte-component';+ }+function parseOriginalMarkupElement(originalMarkup) {const parser = new DOMParser();const doc = parser.parseFromString('<div id="impeccable-anchor">' + originalMarkup + '</div>', 'text/html');@@ -5029,9 +5117,13 @@}}- function loadSvelteRuntime(runtimeModule) {+ function resolveComponentModuleUrl(manifest, modulePath) {+ return new URL(String(modulePath || ''), location.origin).href;+ }++ function loadSvelteRuntime(runtimeModule, manifest) {const modulePath = runtimeModule || '/src/lib/impeccable/__runtime.js';- const url = new URL(modulePath, location.origin).href;+ const url = resolveComponentModuleUrl(manifest, modulePath);if (!svelteRuntimePromise) {svelteRuntimePromise = import(/* @vite-ignore */ url);}@@ -5065,7 +5157,8 @@async function loadSvelteComponentVariantSource(manifest, variantNum) {const dir = String(manifest?.componentDir || '').replace(/^\/+/, '');if (!dir || !variantNum) return '';- const sourcePath = dir + '/v' + variantNum + '.svelte';+ const extension = manifest.componentExtension || 'svelte';+ const sourcePath = dir + '/v' + variantNum + '.' + extension;const url = 'http://localhost:' + PORT + '/source?token=' + TOKEN + '&path=' + encodeURIComponent(sourcePath);try {const res = await fetch(url);@@ -5221,7 +5314,7 @@if (!sourceOriginal) return values;const map = buildSvelteExpressionTextMap(sourceOriginal, liveEl);for (const entry of contract) {- const token = '{' + entry.expr + '}';+ const token = entry.previewToken || ('{' + entry.expr + '}');values[entry.prop] = map.get(token) || '';}return values;@@ -5233,9 +5326,12 @@try {const previousAnchor = getMountedSvelteComponentAnchor(svelteComponentSession) || selectedElement;svelteComponentSession.swapAnchor = makeFrozenAnchor(previousAnchor) || svelteComponentSession.swapAnchor || null;- const runtime = await loadSvelteRuntime(manifest.runtimeModule);- const modulePath = '/' + String(manifest.componentDir || '').replace(/^\/+/, '') + '/v' + variantNum + '.svelte';- const moduleUrl = new URL(modulePath, location.origin).href + '?t=' + Date.now();+ const runtime = await loadSvelteRuntime(manifest.runtimeModule, manifest);+ const extension = manifest.componentExtension || 'svelte';+ const moduleBase = manifest.componentModuleBase+ || ('/' + String(manifest.componentDir || '').replace(/^\/+/, ''));+ const modulePath = String(moduleBase).replace(/\/+$/, '') + '/v' + variantNum + '.' + extension;+ const moduleUrl = resolveComponentModuleUrl(manifest, modulePath) + '?t=' + Date.now();const mod = await import(/* @vite-ignore */ moduleUrl);const Component = mod.default;if (svelteComponentSession.mountedInstance && runtime.unmount) {@@ -5275,7 +5371,7 @@if (svelteComponentSession?.sessionId === sessionId) {svelteComponentSession.swapAnchor = null;}- console.error('[impeccable] Failed to mount Svelte variant ' + variantNum + ' for ' + sessionId + ':', err);+ console.error('[impeccable] Failed to mount component variant ' + variantNum + ' for ' + sessionId + ':', err);return false;}}@@ -5340,40 +5436,46 @@if (manifest.id !== sessionId) return;const paramsByVariant = await loadSvelteComponentParams(manifest);+ const availableVariants = Number(manifest.arrivedVariants) || Number(manifest.count) || 1;+ const componentPreviewMode = isFrameworkComponentPreviewMode(manifest.previewMode)+ ? manifest.previewMode+ : 'svelte-component';currentSessionId = sessionId;expectedVariants = Number(manifest.count) || expectedVariants || 1;rememberSessionFileMeta({sourceFile: manifest.sourceFile,previewFile: manifestPath,- previewMode: 'svelte-component',+ previewMode: componentPreviewMode,});if (state !== 'CYCLING') setLiveState('GENERATING');const existingWrapper = document.querySelector('[data-impeccable-variants="' + sessionId + '"]');if (existingWrapper && svelteComponentSession?.sessionId === sessionId) {recoveryWaitingForAnchor = false;+ svelteComponentSession.manifest = manifest;svelteComponentSession.paramsByVariant = paramsByVariant;- arrivedVariants = Number(manifest.count) || expectedVariants || 1;- expectedVariants = arrivedVariants;+ arrivedVariants = availableVariants;+ expectedVariants = Number(manifest.count) || expectedVariants || arrivedVariants;visibleVariant = visibleVariant > 0 && visibleVariant <= arrivedVariants ? visibleVariant : 1;await mountSvelteComponentVariant(visibleVariant || 1);setLiveState('CYCLING');showOrUpdateCyclingBar();saveSession();+ if (parameterGenerationState === 'loading') completeParameterPublication();return;}const liveEl = findLiveElementForSvelteManifest(manifest);if (!liveEl?.parentElement) {console.warn('[impeccable] Could not find original element in live DOM.');- arrivedVariants = Number(manifest.count) || expectedVariants || 1;- expectedVariants = arrivedVariants;+ arrivedVariants = availableVariants;+ expectedVariants = Number(manifest.count) || expectedVariants || arrivedVariants;const saved = loadSession();const savedVisibleVariant = saved && saved.id === sessionId ? saved.visible : 0;visibleVariant = visibleVariant > 0 && visibleVariant <= arrivedVariants? visibleVariant: (savedVisibleVariant > 0 && savedVisibleVariant <= arrivedVariants ? savedVisibleVariant : 1);- enterRecoveryWaitingForAnchor({ checkpointReason: 'svelte_component_anchor_missing', trackScroll: true });+ enterRecoveryWaitingForAnchor({ checkpointReason: 'component_preview_anchor_missing', trackScroll: true });waitForSvelteComponentTargetAndRetry({ manifestPath, sessionId, manifest });return;}@@ -5381,7 +5483,7 @@const wrapper = document.createElement('div');wrapper.dataset.impeccableVariants = sessionId;wrapper.dataset.impeccableVariantCount = String(manifest.count || expectedVariants || 1);- wrapper.dataset.impeccablePreview = 'svelte-component';+ wrapper.dataset.impeccablePreview = componentPreviewMode;wrapper.style.display = 'contents';const mountTarget = document.createElement('div');@@ -5419,8 +5521,8 @@recoveryWaitingForAnchor = false;const previousVisibleVariant = currentSessionId === sessionId ? visibleVariant : 0;- arrivedVariants = Number(manifest.count) || expectedVariants || 1;- expectedVariants = arrivedVariants;+ arrivedVariants = availableVariants;+ expectedVariants = Number(manifest.count) || expectedVariants || arrivedVariants;const saved = loadSession();const savedVisibleVariant = saved && saved.id === sessionId ? saved.visible : 0;visibleVariant = previousVisibleVariant > 0 && previousVisibleVariant <= arrivedVariants@@ -5445,9 +5547,10 @@refreshParamsPanel();positionBar();saveSession();- console.log('[impeccable] Mounted ' + arrivedVariants + ' Svelte component variants.');+ if (parameterGenerationState === 'loading') completeParameterPublication();+ console.log('[impeccable] Mounted ' + arrivedVariants + ' ' + manifest.framework + ' component variants.');} catch (err) {- console.error('[impeccable] Failed to mount Svelte component variants:', err);+ console.error('[impeccable] Failed to mount component-preview variants:', err);abortSvelteComponentInjection(sessionId, 'Could not load variants. Fix the error and re-run.');}}@@ -5493,6 +5596,8 @@clearHandled();resetSessionFileMeta();currentSessionId = null;+ parameterGenerationState = 'idle';+ parameterReadyAnnouncedSession = null;expectedVariants = 0;arrivedVariants = 0;visibleVariant = 0;@@ -5502,12 +5607,24 @@if (message) showToast(message, 5000);}+ // How many delayed re-reads a completion-driven source fallback gets when+ // the fetched source still shows only the preflight scaffold, before the+ // failure is surfaced via recoverEmptyCycling.+ const COMPLETED_SOURCE_FALLBACK_RETRIES = 3;+ const COMPLETED_SOURCE_FALLBACK_RETRY_MS = 1200;+/*** No-HMR fallback: fetch the raw source file from the live server,* parse it, extract the variant wrapper, and inject it into the live DOM.* This works even when the dev server caches HTML (Bun, static servers).+ *+ * opts.generationCompleted marks callers that KNOW the agent finished (a+ * `done` arrived or the server reported a completed generation). For them an+ * empty read is a stale source view and no further event is coming, so the+ * read retries a few times and then surfaces recovery. Callers without the+ * flag may be mid-generation and wait indefinitely for the real completion.*/- function injectVariantsFromSource(filePath, sessionId) {+ function injectVariantsFromSource(filePath, sessionId, opts = {}) {if (isSvelteComponentManifestPath(filePath)) {injectSvelteComponentsFromManifest(filePath, sessionId);return;@@ -5573,6 +5690,32 @@arrivedVariants = variants.length;expectedVariants = parseInt(wrapper.dataset.impeccableVariantCount || arrivedVariants);if (arrivedVariants <= 0) {+ if (state === 'GENERATING') {+ // Mid-generation the source legitimately holds a scaffold wrapper+ // with no variants yet (the server-side preflight wraps before the+ // agent writes). Tearing the session down here would destroy an+ // in-flight generation; stay in GENERATING — the variant observer+ // is armed and the server re-delivers a missed `done`.+ if (!opts.generationCompleted) {+ console.log('[impeccable] Source has scaffold but no variants yet; still generating.');+ return;+ }+ // Generation finished, yet the read shows only the scaffold: the+ // source view is stale and no further event will fire. Re-read a+ // few times before surfacing recovery — a single silent return+ // here would strand the tab in GENERATING forever.+ const attempt = opts.attempt || 0;+ if (attempt < COMPLETED_SOURCE_FALLBACK_RETRIES) {+ console.log('[impeccable] Generation is done but source shows no variants yet; retrying read ('+ + (attempt + 1) + '/' + COMPLETED_SOURCE_FALLBACK_RETRIES + ').');+ setTimeout(() => {+ if (state !== 'GENERATING' || currentSessionId !== sessionId) return;+ if (arrivedVariants > 0) return;+ injectVariantsFromSource(filePath, sessionId, { ...opts, attempt: attempt + 1 });+ }, COMPLETED_SOURCE_FALLBACK_RETRY_MS);+ return;+ }+ }recoverEmptyCycling('source-fallback-empty');return;}@@ -5594,6 +5737,7 @@refreshParamsPanel();positionBar();saveSession();+ if (parameterGenerationState === 'loading') completeParameterPublication();console.log('[impeccable] Injected ' + arrivedVariants + ' variants from source file.');}).catch(err => {@@ -5865,13 +6009,36 @@document.getElementById(VARIANT_STATE_STYLE_ID)?.remove();}+ function showOriginalDuringDiscard(sessionId) {+ if (!sessionId) return;+ let styleEl = document.getElementById(DISCARD_STATE_STYLE_ID);+ if (!styleEl) {+ styleEl = document.createElement('style');+ styleEl.id = DISCARD_STATE_STYLE_ID;+ (document.head || document.documentElement).appendChild(styleEl);+ }+ const wrapper = '[data-impeccable-variants="' + sessionId + '"]';+ styleEl.textContent = wrapper + ' > [data-impeccable-variant]:not([data-impeccable-variant="original"]) { display:none !important; }\n'+ + wrapper + ' > [data-impeccable-variant="original"] { display:block !important; }';+ }++ function resolveScrollLockAnchorTop() {+ const anchor = resolveBarAnchor();+ if (!anchor?.isConnected) return null;+ const top = anchor.getBoundingClientRect().top;+ return Number.isFinite(top) ? top : null;+ }+// Hold window.scrollY at a fixed value across DOM mutations inside the// session's wrapper (HMR patches, variant inserts, cycle swaps).- function startScrollLock(sessionId, initialTargetY) {+ function startScrollLock(sessionId, initialTargetY, initialAnchorTop) {stopScrollLock();scrollLockTargetY = typeof initialTargetY === 'number' && isFinite(initialTargetY)? initialTargetY: window.scrollY;+ scrollLockAnchorTop = typeof initialAnchorTop === 'number' && isFinite(initialAnchorTop)+ ? initialAnchorTop+ : resolveScrollLockAnchorTop();try { history.scrollRestoration = 'manual'; } catch {}@@ -5895,6 +6062,17 @@const correct = (why) => {scrollLockRaf = null;if (scrollLockTargetY == null) return;+ const anchor = resolveBarAnchor();+ if (anchor?.isConnected && typeof scrollLockAnchorTop === 'number' && isFinite(scrollLockAnchorTop)) {+ const anchorTop = anchor.getBoundingClientRect().top;+ const anchorDelta = anchorTop - scrollLockAnchorTop;+ if (Math.abs(anchorDelta) >= 0.5) {+ window.scrollTo({ top: window.scrollY + anchorDelta, left: window.scrollX, behavior: 'instant' });+ scrollLockTargetY = window.scrollY;+ writeScrollY(scrollLockTargetY);+ return;+ }+ }const before = window.scrollY;const delta = before - scrollLockTargetY;if (Math.abs(delta) < 0.5) {@@ -5939,6 +6117,7 @@if (scrollLockRaf != null) { cancelAnimationFrame(scrollLockRaf); scrollLockRaf = null; }const prevTarget = scrollLockTargetY;scrollLockTargetY = window.scrollY;+ scrollLockAnchorTop = resolveScrollLockAnchorTop();writeScrollY(scrollLockTargetY);};const markGesture = (why) => {@@ -5976,6 +6155,7 @@if (scrollLockRaf != null) { cancelAnimationFrame(scrollLockRaf); scrollLockRaf = null; }if (scrollLockAbort) { scrollLockAbort.abort(); scrollLockAbort = null; }scrollLockTargetY = null;+ scrollLockAnchorTop = null;// NOTE: do NOT clear the persistent scroll key here. startScrollLock// calls us as a reset, and clearing the key would nuke the Go-time// scrollY that the next resume needs to read.@@ -6049,6 +6229,7 @@updating = true;arrivedVariants = count;+ generationPhase = arrivedVariants >= expectedVariants ? 'variants_ready' : 'variants_progress';if (visibleVariant === 0 && arrivedVariants > 0) {const saved = loadSession();const savedVisibleVariant = saved && saved.id === sessionId ? saved.visible : 0;@@ -6064,7 +6245,7 @@const expected = parseInt(wrapper.dataset.impeccableVariantCount || '0');if (expected > 0) expectedVariants = expected;- if (arrivedVariants >= expectedVariants && expectedVariants > 0) {+ if (arrivedVariants > 0) {setLiveState('CYCLING');recoveryWaitingForAnchor = false;hideShaderOverlay();@@ -6072,13 +6253,18 @@updateSelectedElement();showOrUpdateCyclingBar();disableInlineEdit();- refreshParamsPanel();+ if (arrivedVariants >= expectedVariants && expectedVariants > 0) refreshParamsPanel();+ else hideParamsPanel();positionBar();} else if (state === 'GENERATING') {updateBarContent('generating');}saveSession();- queueCheckpoint(state === 'CYCLING' ? 'variants_ready' : 'variants_progress');+ sendCheckpoint(+ arrivedVariants >= expectedVariants && expectedVariants > 0+ ? 'variants_ready'+ : 'variants_progress',+ );updating = false;});@@ -6151,6 +6337,7 @@syncAgentPollingUi(!!msg.agentPolling);startAgentStatusPoll();restoreFromActiveSessions(msg.activeSessions, 'sse_connected');+ recoverMissedGenerationCompletion(msg.activeSessions);if (state === 'IDLE' && (pickActive || insertActive)) setLiveState('PICKING');syncPageInteractionCursor();syncPageChatFocus('sse-connected');@@ -6158,6 +6345,42 @@case 'agent_polling':syncAgentPollingUi(!!msg.connected);break;+ case 'agent_phase':+ if (msg.id === currentSessionId && (state === 'GENERATING' || state === 'CYCLING')) {+ generationPhase = msg.phase || generationPhase;+ if (msg.phase === 'variant_parameters_generating' || msg.phase === 'variant_parameters_validating') {+ parameterGenerationState = 'loading';+ }+ if (msg.phase === 'parameters_ready' && parameterGenerationState !== 'ready') {+ parameterGenerationState = 'loading';+ }+ updateBarContent(state === 'CYCLING' ? 'cycling' : 'generating');+ saveSession();+ }+ break;+ case 'variant_progress':+ if (msg.id === currentSessionId) {+ if (msg.publicationKind === 'params') parameterGenerationState = 'loading';+ rememberSessionFileMeta(msg);+ if (isFrameworkComponentPreviewMode(msg.previewMode) && msg.previewFile) {+ injectSvelteComponentsFromManifest(msg.previewFile, msg.id);+ } else if ((msg.previewMode === 'source' || !msg.previewMode) && (msg.previewFile || msg.file)) {+ // Give normal framework HMR the first chance to reconcile its+ // own managed tree. Nuxt route-module HMR can skip intermediate+ // revisions, so fall back to source injection only when the+ // advertised progress still has not appeared after a short+ // settle. Immediate injection races React/Vue ownership and can+ // trigger removeChild errors on the next HMR commit.+ const targetArrived = Number(msg.arrivedVariants) || 1;+ setTimeout(() => {+ if (msg.id !== currentSessionId) return;+ if (state !== 'GENERATING' && state !== 'CYCLING') return;+ if (msg.publicationKind !== 'params' && arrivedVariants >= targetArrived) return;+ injectVariantsFromSource(msg.previewFile || msg.file, msg.id);+ }, 150);+ }+ }+ break;case 'steer_done':maybeCompleteSteer(msg);break;@@ -6175,6 +6398,10 @@case 'done':if (maybeCompleteSteer(msg)) break;rememberSessionFileMeta(msg);+ if (msg.id === currentSessionId && isFrameworkComponentPreviewMode(currentPreviewMode) && currentPreviewFile) {+ injectSvelteComponentsFromManifest(currentPreviewFile, msg.id);+ break;+ }// Variants already arrived via HMR → normal transition.if (arrivedVariants >= expectedVariants && expectedVariants > 0) {if (state === 'GENERATING') {@@ -6190,7 +6417,7 @@setTimeout(() => {if (arrivedVariants >= expectedVariants && expectedVariants > 0) return;if (state !== 'GENERATING' || msg.id !== currentSessionId) return;- injectVariantsFromSource(msg.file, msg.id);+ injectVariantsFromSource(msg.file, msg.id, { generationCompleted: true });}, 750);break;}@@ -6215,9 +6442,10 @@if (maybeCompleteAcceptedSession(msg)) break;break;case 'agent_done':- // Carbonize accepts are not terminal until live-complete.mjs sends- // the final complete event. Keep the browser in its recoverable- // saving state while the source cleanup is still in flight.+ // The deterministic accept has already committed the reviewed DOM+ // and fenced generation. Carbonize may continue in the background;+ // it must not hold the foreground picker hostage.+ if (msg.data?.carbonize === true && maybeCompleteAcceptedSession(msg)) break;break;case 'discarded':if (msg.id && msg.id === currentSessionId) {@@ -6306,6 +6534,7 @@type: 'checkpoint',id: currentSessionId,revision: sessionState.nextCheckpointRevision(),+ revisionDomain: 'browser',owner: browserOwner,phase: String(state || '').toLowerCase(),reason,@@ -6331,6 +6560,7 @@type: 'checkpoint',id,revision: sessionState.nextCheckpointRevision(),+ revisionDomain: 'browser',owner: browserOwner,phase: 'steer',reason,@@ -6684,6 +6914,9 @@expectedVariants = selectedCount;arrivedVariants = 0;visibleVariant = 0;+ generationPhase = 'queued';+ parameterGenerationState = 'pending';+ parameterReadyAnnouncedSession = null;resetSessionFileMeta();// Flip to GENERATING immediately so the bar morphs without waiting on@@ -6693,6 +6926,7 @@const elForCapture = selectedElement;pickedAnchorSnapshot = buildPickedAnchorSnapshot(elForCapture);const captureRect = elForCapture.getBoundingClientRect();+ pickedAnchorViewportTop = captureRect.top;const snapshot = {comments: annotState.comments.map(c => ({ x: c.x, y: c.y, text: c.text })),strokes: annotState.strokes.map(s => ({ points: s.points.map(p => [p[0], p[1]]) })),@@ -6724,7 +6958,7 @@writeScrollY(window.scrollY);if (variantObserver) variantObserver.disconnect();variantObserver = startVariantObserver(currentSessionId);- startScrollLock(currentSessionId);+ startScrollLock(currentSessionId, window.scrollY, pickedAnchorViewportTop);captureAndEmit(elForCapture, basePayload, snapshot, captureRect);}@@ -6759,12 +6993,16 @@expectedVariants = selectedCount;arrivedVariants = 0;visibleVariant = 0;+ generationPhase = 'queued';+ parameterGenerationState = 'pending';+ parameterReadyAnnouncedSession = null;resetSessionFileMeta();selectedElement = placeholderElement;insertPlaceholderSnapshot = buildInsertPlaceholderSnapshotFromDom(insertAnchorElement, placeholderElement);const elForCapture = placeholderElement;const captureRect = elForCapture.getBoundingClientRect();+ pickedAnchorViewportTop = captureRect.top;const basePayload = {type: 'generate',mode: 'insert',@@ -6795,7 +7033,7 @@writeScrollY(window.scrollY);if (variantObserver) variantObserver.disconnect();variantObserver = startVariantObserver(currentSessionId);- startScrollLock(currentSessionId);+ startScrollLock(currentSessionId, window.scrollY, pickedAnchorViewportTop);captureAndEmit(elForCapture, basePayload, snapshot, captureRect);}@@ -6975,9 +7213,9 @@// preview mounts are covered by the same shader regression checks.const adapter = String(window.__IMPECCABLE_LIVE_ADAPTER__ || '').toLowerCase();if (adapter === 'svelte' || adapter === 'sveltekit') return true;- if (currentPreviewMode === 'svelte-component' || svelteComponentSession) return true;+ if (isFrameworkComponentPreviewMode(currentPreviewMode) || svelteComponentSession) return true;const wrapper = el?.closest?.('[data-impeccable-variants]');- return wrapper?.dataset?.impeccablePreview === 'svelte-component';+ return isFrameworkComponentPreviewMode(wrapper?.dataset?.impeccablePreview);}function paintsShaderProxySurface(node) {@@ -7105,6 +7343,17 @@}async function captureAndEmit(el, basePayload, snapshot, rect) {+ const hasAnnotations = snapshot && (snapshot.comments.length > 0 || snapshot.strokes.length > 0);++ // Plain requests do not send a screenshot to the agent, so capture is+ // presentation-only. Wait only for the helper to accept the event before+ // starting CPU-heavy capture; this yields the browser task and prevents+ // rasterization from delaying the fetch itself.+ if (!hasAnnotations) {+ basePayload.clientSentAt = Date.now();+ await sendEvent(basePayload);+ }+let screenshotPath;let blob;let paper;@@ -7122,7 +7371,6 @@// are present. Without annotations the image is pure visual anchoring -// it biases the model toward the current rendering and works against the// three-distinct-directions brief.- const hasAnnotations = snapshot && (snapshot.comments.length > 0 || snapshot.strokes.length > 0);if (blob && hasAnnotations) {try {const uploadRes = await fetch(@@ -7140,7 +7388,12 @@console.warn('[impeccable] annotation upload failed:', err);}}- sendEvent(screenshotPath ? { ...basePayload, screenshotPath } : basePayload);+ // Annotated requests must wait for capture + upload because the screenshot+ // is semantic input. Plain requests were already dispatched above.+ if (hasAnnotations) {+ basePayload.clientSentAt = Date.now();+ sendEvent(screenshotPath ? { ...basePayload, screenshotPath } : basePayload);+ }}//@@ -7520,7 +7773,6 @@ void main() {if (variantSelectionPromise) {try { await variantSelectionPromise; } catch { /* failed selection falls back below */ }}- if (!currentSessionId || arrivedVariants === 0) return;const domVisibleVariant = readVisibleVariantFromDOM(currentSessionId);if (domVisibleVariant > 0) visibleVariant = domVisibleVariant;const acceptPayload = {@@ -7528,7 +7780,9 @@ void main() {id: currentSessionId,variantId: String(visibleVariant),pageUrl: location.pathname,+ clientSentAt: Date.now(),};+ if (!currentSessionId || arrivedVariants === 0) return;const acceptWrapper = document.querySelector('[data-impeccable-variants="' + currentSessionId + '"]');if (Object.keys(paramsCurrentValues).length > 0) {acceptPayload.paramValues = { ...paramsCurrentValues };@@ -7542,7 +7796,7 @@ void main() {const acceptedSessionId = currentSessionId;const acceptedVariant = visibleVariant;const acceptedIsSvelteComponent = svelteComponentSession?.sessionId === acceptedSessionId- || acceptWrapper?.dataset?.impeccablePreview === 'svelte-component';+ || isFrameworkComponentPreviewMode(acceptWrapper?.dataset?.impeccablePreview);const acceptedSnapshot = snapshotAcceptedVariantDom(acceptedSessionId, acceptedVariant);setLiveState('SAVING');@@ -7557,7 +7811,17 @@ void main() {saveSession();sendEvent(acceptPayload, { throwOnError: true })- .then(() => {})+ .then(() => {+ const pending = pendingAcceptedSession;+ if (!pending || pending.id !== acceptedSessionId) return;+ // POST /events returns only after the accept intent is durable and the+ // generation epoch is fenced. Source promotion/carbonize can finish in+ // the background; the foreground picker is free immediately.+ markSessionHandled();+ setLiveState('CONFIRMED');+ document.documentElement.dataset.impeccableAcceptToPickingMs = String(Date.now() - acceptPayload.clientSentAt);+ scheduleAcceptCleanup(pending);+ }).catch(() => {if (pendingAcceptedSession?.id === acceptedSessionId) pendingAcceptedSession = null;setLiveState('CYCLING');@@ -7586,17 +7850,26 @@ void main() {}function scheduleAcceptCleanup(accepted) {- setTimeout(function() {- if (!accepted?.isSvelteComponent && !acceptedDomAlreadyClean(accepted)) {- setTimeout(function() {- if (pendingAcceptedSession?.id !== accepted?.id) return;- if (!accepted?.isSvelteComponent) ensureAcceptedDomClean(accepted);- cleanupAcceptedSession();- }, 1800);- return;+ queueMicrotask(function() {+ if (pendingAcceptedSession?.id !== accepted?.id) return;+ // Svelte previews live in an adapter-owned mount rather than in source+ // wrapper markup. Promote the mounted variant before releasing the+ // session so the old adapter instance cannot linger behind the next+ // Pick → Go loop while carbonize finishes in the background.+ if (accepted?.isSvelteComponent) {+ commitAcceptedSvelteComponentToDom(accepted.id);}cleanupAcceptedSession();- }, 1200);+ });+ // Let React/Vue/Svelte own the HMR reconciliation. Mutating their DOM in+ // the same turn as the source update causes removeChild/NotFoundError+ // races. Static servers still need a fallback, but it must not keep Live+ // in SAVING or block the user's next pick.+ if (!accepted?.isSvelteComponent) {+ setTimeout(function() {+ if (!acceptedDomAlreadyClean(accepted)) ensureAcceptedDomClean(accepted);+ }, 1200);+ }}function snapshotAcceptedVariantDom(sessionId, variantId) {@@ -7700,7 +7973,11 @@ void main() {clearSession();resetSessionFileMeta();selectedElement = null;+ hoveredElement = null;+ pagePickSkipClick = false;currentSessionId = null;+ parameterGenerationState = 'idle';+ parameterReadyAnnouncedSession = null;selectedAction = 'impeccable';pendingAcceptedSession = null;renderEditBadge('hidden');@@ -7735,7 +8012,7 @@ void main() {sendEvent({ type: 'discard', id: currentSessionId }, { throwOnError: true }).then(() => {markSessionHandled();- cleanup();+ cleanup({ restoreOriginal: true, instantChrome: true });}).catch(() => showToast('Could not confirm discard with the live server. Session kept for recovery.', 5000));}@@ -7757,6 +8034,7 @@ void main() {currentPreviewMode = null;recoveryWaitingForAnchor = false;pickedAnchorSnapshot = null;+ pickedAnchorViewportTop = null;}function rememberSessionFileMeta(meta = {}) {@@ -7765,8 +8043,8 @@ void main() {const previewFile = normalizeSessionPath(meta.previewFile);const previewMode = meta.previewMode || (isSvelteComponentManifestPath(previewFile || file) ? 'svelte-component' : null);- if (previewMode === 'svelte-component' || isSvelteComponentManifestPath(file)) {- currentPreviewMode = 'svelte-component';+ if (isFrameworkComponentPreviewMode(previewMode) || isSvelteComponentManifestPath(file)) {+ currentPreviewMode = isFrameworkComponentPreviewMode(previewMode) ? previewMode : 'svelte-component';currentPreviewFile = previewFile || (isSvelteComponentManifestPath(file) ? file : currentPreviewFile);currentSourceFile = sourceFile || currentSourceFile;return;@@ -7782,12 +8060,15 @@ void main() {rememberSessionFileMeta(saved);if (saved.insertPlaceholder) insertPlaceholderSnapshot = saved.insertPlaceholder;if (saved.pickedAnchor) pickedAnchorSnapshot = saved.pickedAnchor;+ if (Number.isFinite(saved.pickedAnchorViewportTop)) pickedAnchorViewportTop = saved.pickedAnchorViewportTop;if (saved.action) selectedAction = saved.action;if (saved.count) selectedCount = saved.count;if (saved.previewMode) currentPreviewMode = saved.previewMode;if (saved.paramValues && typeof saved.paramValues === 'object') {paramsCurrentValues = { ...saved.paramValues };}+ if (saved.parameterState) parameterGenerationState = saved.parameterState;+ if (saved.generationPhase) generationPhase = saved.generationPhase;}function normalizePagePath(value) {@@ -7859,7 +8140,7 @@ void main() {saveSession();queueCheckpoint(reason || 'browser_restore_without_wrapper');- const restoreFile = currentPreviewMode === 'svelte-component'+ const restoreFile = isFrameworkComponentPreviewMode(currentPreviewMode)? currentPreviewFile: (currentSourceFile || currentPreviewFile);if (restoreFile) {@@ -7872,11 +8153,41 @@ void main() {function restoreFromActiveSessions(activeSessions, reason) {const wrapper = document.querySelector('[data-impeccable-variants]');- if (wrapper && wrapper.dataset.impeccablePreview !== 'svelte-component') return false;+ if (wrapper && !isFrameworkComponentPreviewMode(wrapper.dataset.impeccablePreview)) return false;if (svelteComponentSession?.sessionId === currentSessionId) return false;return restoreSessionWithoutWrapper(reason || 'sse_connected', activeSessions);}+ // Self-heal on SSE (re)connect. The preflight scaffold write triggers a+ // framework full-reload (Astro reloads pages for any .astro edit); if the+ // agent's variant write + `done` broadcast land while this page is+ // mid-reload, both the done SSE and the second HMR reload are missed and+ // the resumed page would wait in GENERATING at 0/N forever. The server's+ // session summary carries the durable generationCompletedAt marker, so on+ // every connect compare it against our own progress and pull the finished+ // variants from source when behind. Mirrors the `done` handler's source+ // fallback, including its give-HMR-the-first-chance settle delay.+ function recoverMissedGenerationCompletion(activeSessions) {+ if (!currentSessionId || state !== 'GENERATING') return;+ if (!Array.isArray(activeSessions)) return;+ const summary = activeSessions.find((session) => session?.id === currentSessionId);+ if (!summary?.generationCompletedAt || summary.generationCanceled) return;+ if (isTerminalSessionSummary(summary)) return;+ if (arrivedVariants > 0 && arrivedVariants >= expectedVariants) return;+ rememberSessionFileMeta(summary);+ const sessionId = currentSessionId;+ const file = isFrameworkComponentPreviewMode(currentPreviewMode)+ ? currentPreviewFile+ : (summary.sourceFile || summary.previewFile || currentSourceFile || currentPreviewFile);+ if (!file) return;+ console.log('[impeccable] Reconnected after generation completed; recovering variants from source.');+ setTimeout(() => {+ if (sessionId !== currentSessionId || state !== 'GENERATING') return;+ if (arrivedVariants > 0 && arrivedVariants >= expectedVariants) return;+ injectVariantsFromSource(file, sessionId, { generationCompleted: true });+ }, 750);+ }+function saveSession() {if (!currentSessionId) return;// NOTE: scrollY is stored under a separate key (writeScrollY). Storing@@ -7894,8 +8205,12 @@ void main() {previewMode: currentPreviewMode || undefined,pageUrl: location.pathname,paramValues: { ...paramsCurrentValues },+ parameterState: parameterGenerationState,insertPlaceholder: insertPlaceholderSnapshot || undefined,pickedAnchor: pickedAnchorSnapshot || undefined,+ pickedAnchorViewportTop: Number.isFinite(pickedAnchorViewportTop) ? pickedAnchorViewportTop : undefined,+ pageHash: location.hash || undefined,+ pageSearch: location.search || undefined,});}@@ -7923,20 +8238,26 @@ void main() {sessionState.clearHandled();}- function cleanup() {+ function cleanup(options) {+ const restoreOriginal = options?.restoreOriginal === true;+ const instantChrome = options?.instantChrome === true;const cleanupSessionId = currentSessionId;if (svelteComponentSession?.sessionId === cleanupSessionId) {teardownSvelteComponentSession(true);} else if (cleanupSessionId) {- // Hide the wrapper immediately so variants disappear. DON'T structurally- // mutate the DOM yet - HMR from the agent's source rewrite is on its way,+ // Switch visibility immediately without structurally mutating the DOM.+ // HMR from the agent's source rewrite may still be on its way,// and a manual replaceChild under React causes NotFoundError when the// reconciler later tries to remove a wrapper we already removed.// Schedule a 2s fallback that does the manual swap only if HMR hasn't// replaced the wrapper by then (keeps static-server / no-HMR flows alive).const wrapper = document.querySelector('[data-impeccable-variants="' + cleanupSessionId + '"]');- if (wrapper) wrapper.style.display = 'none';+ if (wrapper) {+ if (restoreOriginal) showOriginalDuringDiscard(cleanupSessionId);+ else wrapper.style.display = 'none';+ }setTimeout(function() {+ document.getElementById(DISCARD_STATE_STYLE_ID)?.remove();if (!cleanupSessionId) return;const lateWrapper = document.querySelector('[data-impeccable-variants="' + cleanupSessionId + '"]');if (!lateWrapper) return;@@ -7951,7 +8272,7 @@ void main() {lateWrapper.remove();}, 2000);}- hideBar();+ hideBar(instantChrome);hideHighlight();stopScrollTracking();if (variantObserver) { variantObserver.disconnect(); variantObserver = null; }@@ -7963,7 +8284,11 @@ void main() {clearSession();resetSessionFileMeta();selectedElement = null;+ hoveredElement = null;+ pagePickSkipClick = false;currentSessionId = null;+ parameterGenerationState = 'idle';+ parameterReadyAnnouncedSession = null;selectedAction = 'impeccable';renderEditBadge('hidden');setLiveState('PICKING');@@ -8047,7 +8372,7 @@ void main() {// would strand the bar in CYCLING at 0/0. If there's no live in-memory mount// for this wrapper, it's an orphan (reload / failed mount): drop it and let// the live-server's SSE re-inject the manifest if the session is still live.- if (wrapper.dataset.impeccablePreview === 'svelte-component'+ if (isFrameworkComponentPreviewMode(wrapper.dataset.impeccablePreview)&& svelteComponentSession?.sessionId !== sessionId) {wrapper.remove();if (restoreSessionWithoutWrapper('browser_resumed_svelte_orphan_wrapper')) return true;@@ -8056,7 +8381,7 @@ void main() {return false;}- if (wrapper.dataset.impeccablePreview === 'svelte-component') {+ if (isFrameworkComponentPreviewMode(wrapper.dataset.impeccablePreview)) {if (!svelteComponentSession?.mountedVariant) {return true;}@@ -8104,7 +8429,7 @@ void main() {insertPlaceholderSnapshot = saved.insertPlaceholder;}- const resumedState = arrivedVariants >= expectedVariants ? 'CYCLING' : 'GENERATING';+ const resumedState = arrivedVariants > 0 ? 'CYCLING' : 'GENERATING';// Find the visible variant's content element for highlight positioning.const isInsert = wrapper.dataset.impeccableMode === 'insert';@@ -8128,7 +8453,11 @@ void main() {// hid. Now that state is CYCLING, re-fire.if (state === 'CYCLING') refreshParamsPanel();saveSession();- queueCheckpoint('browser_resumed');+ if (arrivedVariants > 0 && arrivedVariants < expectedVariants) {+ sendCheckpoint('variants_progress');+ } else {+ queueCheckpoint('browser_resumed');+ }// Start observing for more variants AFTER initial setupif (variantObserver) variantObserver.disconnect();@@ -8136,7 +8465,7 @@ void main() {// Hold the target at its saved viewport top through any subsequent// HMR patches, variant inserts, or cycle swaps.- startScrollLock(currentSessionId, readScrollY());+ startScrollLock(currentSessionId, readScrollY(), pickedAnchorViewportTop);// If we reloaded mid-generation (Bun's HTML HMR destroys the shader// canvas), re-capture the original's content and restart the shader so@@ -8171,6 +8500,7 @@ void main() {let globalBarBrandEl = null;let agentPollTooltipEl = null;let agentPollingConnected = false;+ let agentStatusMessage = null;let agentStatusPollTimer = null;let steerFocusSuspended = false;let steerFocusPauseUntil = 0;@@ -8275,6 +8605,13 @@ void main() {const AGENT_STATUS_POLL_MS = 5000;const AGENT_DISCONNECTED_MARK = 'oklch(62% 0 0 / 0.78)';const AGENT_DISCONNECTED_TIP = 'Agent disconnected - run live-poll.mjs to connect';+ // The indicator tracks whether a poll is parked, which is what decides if+ // steering can reach the agent right now. That goes quiet two ways, and they+ // need different copy: nobody is polling at all, or the agent took the work+ // and is busy with it. Under one-shot foreground polling the second case is+ // every normal generation, and telling the user to start a poll loop then is+ // wrong advice about a healthy session.+ const AGENT_BUSY_TIP = 'Agent is working - steering resumes when it finishes';const GLOBAL_BAR_SECTION_GAP = 8;const GLOBAL_BAR_INNER_GAP = 2;const GLOBAL_BAR_INNER_PAD_LEFT = 2;@@ -9295,24 +9632,46 @@ void main() {</svg>`;}+ /**+ * True while the browser is waiting on work it already handed to the agent.+ * In these states a quiet poll indicator means "busy", not "absent".+ */+ function agentHasWorkInFlight() {+ return state === 'GENERATING' || state === 'SAVING';+ }++ /**+ * Derived at read time, not cached: which of the two reasons applies depends on+ * the live state, which moves between the 5s status polls. The truthiness is+ * the same either way, so the indicator's visuals can stay driven by the+ * cached value while the wording stays current.+ */+ function agentStatusText() {+ if (agentPollingConnected) return null;+ return agentHasWorkInFlight() ? AGENT_BUSY_TIP : AGENT_DISCONNECTED_TIP;+ }+function syncAgentPollingUi(connected) {agentPollingConnected = !!connected;if (!globalBarBrandEl) return;const P = barPaletteForTheme(globalBarEl?.dataset.theme || detectPageTheme());+ agentStatusMessage = agentStatusText();globalBarBrandEl.dataset.agentConnected = connected ? 'true' : 'false';- globalBarBrandEl.setAttribute('aria-label', connected- ? 'Impeccable live mode'- : 'Impeccable live mode - agent not polling');+ // The tooltip is mouse-only, so carry the same distinction in the label or+ // screen-reader users are left with the vaguer of the two readings.+ globalBarBrandEl.setAttribute('aria-label', agentStatusMessage+ ? 'Impeccable live mode - ' + (agentHasWorkInFlight() ? 'agent is working' : 'agent not polling')+ : 'Impeccable live mode');globalBarBrandEl.removeAttribute('title');- globalBarBrandEl.style.cursor = connected ? 'default' : 'help';+ globalBarBrandEl.style.cursor = agentStatusMessage ? 'help' : 'default';const mark = globalBarBrandEl.querySelector('[data-brand-mark]');if (mark) {mark.innerHTML = brandMarkSvg(connected ? P.accent : AGENT_DISCONNECTED_MARK, 18);mark.style.opacity = '1';}const dot = globalBarBrandEl.querySelector('[data-agent-dot]');- if (dot) dot.style.display = connected ? 'none' : 'block';- if (connected) hideAgentPollTooltip();+ if (dot) dot.style.display = agentStatusMessage ? 'block' : 'none';+ if (!agentStatusMessage) hideAgentPollTooltip();}function ensureAgentPollTooltip() {@@ -9339,14 +9698,17 @@ void main() {whiteSpace: 'normal',});agentPollTooltipEl.id = PREFIX + '-agent-poll-tooltip';- agentPollTooltipEl.textContent = AGENT_DISCONNECTED_TIP;+ agentPollTooltipEl.textContent = agentStatusText() || AGENT_DISCONNECTED_TIP;uiAppend(agentPollTooltipEl);return agentPollTooltipEl;}function showAgentPollTooltip(anchor) {- if (agentPollingConnected || !anchor) return;+ if (!agentStatusMessage || !anchor) return;const tip = ensureAgentPollTooltip();+ // Re-derive rather than reuse the cached copy: the live state may have moved+ // since the last status poll set it.+ tip.textContent = agentStatusText() || AGENT_DISCONNECTED_TIP;tip.style.transition = 'none';tip.style.display = 'block';tip.style.opacity = '1';@@ -9376,7 +9738,9 @@ void main() {fetch('http://localhost:' + PORT + '/status?token=' + TOKEN, { cache: 'no-store' }).then((res) => (res.ok ? res.json() : null)).then((data) => {- if (data && typeof data.agentPolling === 'boolean') syncAgentPollingUi(data.agentPolling);+ if (data && typeof data.agentPolling === 'boolean') {+ syncAgentPollingUi(data.agentPolling);+ }}).catch(() => { /* server loss handled elsewhere */ });}diff --git a/.qoder/skills/impeccable/scripts/live-inject.mjs b/.qoder/skills/impeccable/scripts/live-inject.mjsindex 7c8d91182..d99c37fd5 100644--- a/.qoder/skills/impeccable/scripts/live-inject.mjs+++ b/.qoder/skills/impeccable/scripts/live-inject.mjs@@ -27,6 +27,8 @@ const __dirname = path.dirname(fileURLToPath(import.meta.url));const CONFIG_PATH = resolveLiveConfigPath({ cwd: process.cwd(), scriptsDir: __dirname });const MARKER_OPEN_TEXT = 'impeccable-live-start';const MARKER_CLOSE_TEXT = 'impeccable-live-end';+const NUXT_PLUGIN_MARKER = 'impeccable-live-nuxt-plugin';+const NUXT_PLUGIN_NAME = 'impeccable-live.client.ts';const IGNORE_MARKER_OPEN = '# impeccable-live-ignore-start';const IGNORE_MARKER_CLOSE = '# impeccable-live-ignore-end';@@ -38,6 +40,9 @@ export const LIVE_IGNORE_PATTERNS = Object.freeze(['.impeccable/live/sessions/','.impeccable/live/previews/','.impeccable/live/annotations/',+ '.impeccable/live/artifacts/',+ '.impeccable/live/accept-receipts/',+ '.impeccable/live/locks/','.impeccable/live/cache/','.impeccable/live/manual-edit-apply-transaction.json','.impeccable/live/manual-edit-events.jsonl',@@ -46,10 +51,15 @@ export const LIVE_IGNORE_PATTERNS = Object.freeze(['.impeccable/live/deferred-svelte-component-accepts.json','.impeccable-live.json','.impeccable-live/',+ 'app/.impeccable-live/',+ 'src/.impeccable-live/','node_modules/.impeccable-live/','src/lib/impeccable/ImpeccableLiveRoot.svelte','src/lib/impeccable/__runtime.js','src/lib/impeccable/[0-9a-f]*/',+ 'plugins/impeccable-live.client.ts',+ 'app/plugins/impeccable-live.client.ts',+ 'src/plugins/impeccable-live.client.ts',]);/**@@ -113,6 +123,7 @@ Output (JSON):const resolvedFiles = resolveFiles(process.cwd(), config);const svelteKit = detectSvelteKitProject(process.cwd(), config);+ const nuxt = detectNuxtProject(process.cwd());if (args.includes('--remove')) {if (svelteKit) {@@ -120,6 +131,12 @@ Output (JSON):console.log(JSON.stringify({ ok: true, adapter: 'sveltekit', results: [adapterResult] }));return;}+ if (nuxt) {+ const adapterResult = removeNuxtLiveAdapter({ cwd: process.cwd(), project: nuxt });+ console.log(JSON.stringify({ ok: !adapterResult.error, adapter: 'nuxt', results: [adapterResult] }));+ if (adapterResult.error) process.exitCode = 1;+ return;+ }const results = resolvedFiles.map((relFile) => {const absFile = path.resolve(process.cwd(), relFile);if (!fs.existsSync(absFile)) return { file: relFile, error: 'file_not_found' };@@ -145,13 +162,28 @@ Output (JSON):console.error(JSON.stringify({ ok: false, error: 'missing_port' }));process.exit(1);}- const gitIgnore = ensureLiveGitIgnores(process.cwd());+ const gitIgnore = ensureLiveGitIgnores(+ process.cwd(),+ nuxt ? [nuxt.pluginFile] : [],+ );if (svelteKit) {const adapterResult = applySvelteKitLiveAdapter({ cwd: process.cwd(), port, config });console.log(JSON.stringify({ ok: true, port, adapter: 'sveltekit', gitIgnore, results: [adapterResult] }));return;}+ if (nuxt) {+ const adapterResult = applyNuxtLiveAdapter({ cwd: process.cwd(), port, project: nuxt });+ console.log(JSON.stringify({+ ok: !adapterResult.error,+ port,+ adapter: 'nuxt',+ gitIgnore,+ results: [adapterResult],+ }));+ if (adapterResult.error) process.exitCode = 1;+ return;+ }const results = resolvedFiles.map((relFile) => {const absFile = path.resolve(process.cwd(), relFile);@@ -175,12 +207,12 @@ Output (JSON):if (!anyInserted) process.exit(1);}-export function ensureLiveGitIgnores(cwd = process.cwd()) {+export function ensureLiveGitIgnores(cwd = process.cwd(), extraPatterns = []) {const target = resolveIgnoreTarget(cwd);const existing = fs.existsSync(target.path) ? fs.readFileSync(target.path, 'utf-8') : '';const block = [IGNORE_MARKER_OPEN,- ...LIVE_IGNORE_PATTERNS,+ ...new Set([...LIVE_IGNORE_PATTERNS, ...extraPatterns]),IGNORE_MARKER_CLOSE,].join('\n');const markerRe = new RegExp(`${escapeRegExp(IGNORE_MARKER_OPEN)}[\\s\\S]*?${escapeRegExp(IGNORE_MARKER_CLOSE)}`);@@ -202,10 +234,119 @@ export function ensureLiveGitIgnores(cwd = process.cwd()) {file: path.relative(cwd, target.path).split(path.sep).join('/'),mode: target.mode,changed: updated !== existing,- patterns: [...LIVE_IGNORE_PATTERNS],+ patterns: [...new Set([...LIVE_IGNORE_PATTERNS, ...extraPatterns])],};}+// ---------------------------------------------------------------------------+// Nuxt adapter+//+// A script element placed in app.vue is compiled as Vue-rendered DOM and is+// not executed. Nuxt instead auto-discovers client plugins. Keep the adapter+// generated, dev-only, and outside user-authored source: Live creates one+// marked .client.ts plugin on start and removes it on stop.+// ---------------------------------------------------------------------------++export function detectNuxtProject(cwd = process.cwd()) {+ const configFile = fs.readdirSync(cwd, { withFileTypes: true })+ .find((entry) => entry.isFile() && /^nuxt\.config\.(?:js|mjs|cjs|ts|mts|cts)$/.test(entry.name))+ ?.name;+ if (!configFile) return null;++ const config = fs.readFileSync(path.join(cwd, configFile), 'utf-8');+ const literalSrcDir = config.match(/\bsrcDir\s*:\s*(['"])([^'"]+)\1/);+ let appDir = '';+ if (literalSrcDir) {+ const candidate = literalSrcDir[2]+ .replace(/\\/g, '/')+ .replace(/^\.\//, '')+ .replace(/\/+$/, '');+ const normalized = path.posix.normalize(candidate);+ if (normalized !== '..' && !normalized.startsWith('../') && !path.isAbsolute(normalized)) {+ appDir = normalized === '.' ? '' : normalized;+ }+ } else if (+ fs.existsSync(path.join(cwd, 'app', 'app.vue'))+ || fs.existsSync(path.join(cwd, 'app', 'pages'))+ ) {+ appDir = 'app';+ }++ const pluginFile = [appDir, 'plugins', NUXT_PLUGIN_NAME].filter(Boolean).join('/');+ return { configFile, appDir, pluginFile };+}++export function buildNuxtPlugin(port) {+ return `/* ${NUXT_PLUGIN_MARKER} */+const liveSrc = 'http://localhost:${port}/live.js';+const liveSelector = 'script[data-impeccable-live-nuxt]';++export default defineNuxtPlugin(() => {+ if (!import.meta.dev || typeof document === 'undefined') return;++ const expectedSrc = new URL(liveSrc, window.location.href).href;+ let script = document.querySelector(liveSelector);+ if (script?.src === expectedSrc) return;+ script?.remove();++ script = document.createElement('script');+ script.src = liveSrc;+ script.async = true;+ script.dataset.impeccableLiveNuxt = '';+ document.head.appendChild(script);++ import.meta.hot?.dispose(() => {+ if (script?.isConnected) script.remove();+ });+});+/* /${NUXT_PLUGIN_MARKER} */+`;+}++export function applyNuxtLiveAdapter({ cwd = process.cwd(), port, project = detectNuxtProject(cwd) }) {+ if (!project) return { error: 'nuxt_not_detected' };+ const absFile = path.join(cwd, project.pluginFile);+ const existing = fs.existsSync(absFile) ? fs.readFileSync(absFile, 'utf-8') : null;+ if (existing !== null && !existing.includes(NUXT_PLUGIN_MARKER)) {+ return {+ file: project.pluginFile,+ error: 'nuxt_plugin_conflict',+ hint: `${project.pluginFile} already exists and is not managed by Impeccable Live`,+ };+ }++ const content = buildNuxtPlugin(port);+ fs.mkdirSync(path.dirname(absFile), { recursive: true });+ if (content !== existing) fs.writeFileSync(absFile, content, 'utf-8');+ return {+ file: project.pluginFile,+ inserted: true,+ changed: content !== existing,+ devOnly: true,+ };+}++export function removeNuxtLiveAdapter({ cwd = process.cwd(), project = detectNuxtProject(cwd) }) {+ if (!project) return { error: 'nuxt_not_detected' };+ const absFile = path.join(cwd, project.pluginFile);+ if (!fs.existsSync(absFile)) {+ return { file: project.pluginFile, removed: false, note: 'no adapter present' };+ }+ const content = fs.readFileSync(absFile, 'utf-8');+ if (!content.includes(NUXT_PLUGIN_MARKER)) {+ return {+ file: project.pluginFile,+ removed: false,+ error: 'nuxt_plugin_conflict',+ hint: `${project.pluginFile} is not managed by Impeccable Live`,+ };+ }+ fs.unlinkSync(absFile);+ const pluginDir = path.dirname(absFile);+ if (fs.readdirSync(pluginDir).length === 0) fs.rmdirSync(pluginDir);+ return { file: project.pluginFile, removed: true };+}+function resolveIgnoreTarget(cwd) {const gitExcludePath = resolveGitInfoExcludePath(cwd);if (gitExcludePath) {diff --git a/.qoder/skills/impeccable/scripts/live-poll.mjs b/.qoder/skills/impeccable/scripts/live-poll.mjsindex 740161e10..19a8b0f9b 100644--- a/.qoder/skills/impeccable/scripts/live-poll.mjs+++ b/.qoder/skills/impeccable/scripts/live-poll.mjs@@ -27,7 +27,7 @@ const scriptCmd = (name) => `node "${path.join(SELF_DIR, name)}"`;export const PER_REQUEST_TIMEOUT_MS = 270_000;export const DEFAULT_EVENT_LEASE_MS = 600_000;-const EVENT_TYPES_NEEDING_AGENT_REPLY = new Set(['generate', 'steer', 'manual_edit_apply']);+const EVENT_TYPES_NEEDING_AGENT_REPLY = new Set(['generate', 'steer', 'manual_edit_apply', 'carbonize_cleanup']);function readServerInfo() {const record = readLiveServerInfo(process.cwd());@@ -38,8 +38,8 @@ function readServerInfo() {return record.info;}-export function buildPollReplyPayload(token, { id, type, message, file, data }) {- return { token, id, type, message, file, data };+export function buildPollReplyPayload(token, { id, type, message, file, data, sourceEventType }) {+ return { token, id, type, message, file, data, sourceEventType };}export function manualApplyPollBanner(event = {}) {@@ -152,7 +152,14 @@ export async function waitForEventAck(base, token, eventId, {return false;}-export async function fetchNextEvent(base, token, { totalDeadline } = {}) {+export async function fetchNextEvent(base, token, {+ totalDeadline,+ types,+ resolveTypes,+ perRequestTimeoutMs = PER_REQUEST_TIMEOUT_MS,+ leaseMs = DEFAULT_EVENT_LEASE_MS,+ signal,+} = {}) {while (true) {if (totalDeadline && Date.now() >= totalDeadline) {return { type: 'timeout' };@@ -161,8 +168,15 @@ export async function fetchNextEvent(base, token, { totalDeadline } = {}) {const remaining = totalDeadline? totalDeadline - Date.now(): PER_REQUEST_TIMEOUT_MS;- const slice = Math.min(Math.max(remaining, 1000), PER_REQUEST_TIMEOUT_MS);- const res = await fetch(`${base}/poll?token=${token}&timeout=${slice}&leaseMs=${DEFAULT_EVENT_LEASE_MS}`);+ const slice = Math.min(Math.max(remaining, 1000), perRequestTimeoutMs);+ const query = new URLSearchParams({+ token,+ timeout: String(slice),+ leaseMs: String(leaseMs),+ });+ const normalizedTypes = normalizePollTypes(resolveTypes ? await resolveTypes() : types);+ if (normalizedTypes.length > 0) query.set('types', normalizedTypes.join(','));+ const res = await fetch(`${base}/poll?${query}`, { signal });if (res.status === 401) {const err = new Error('Authentication failed. The server token may have changed.');@@ -202,11 +216,17 @@ export async function augmentEventWithAcceptHandling(event, base, token) {event._acceptResult = { handled: false, mode: 'error', error: err.message };}+ await completeAcceptHandling(event, base, token);+ return event;+}++export async function completeAcceptHandling(event, base, token) {const completionType = completionTypeForAcceptResult(event.type, event._acceptResult);try {await postReply(base, token, {id: event.id,type: completionType,+ sourceEventType: event.type,message: event._acceptResult?.error,file: event._acceptResult?.file,data: event._acceptResult?.carbonize === true ? { carbonize: true } : undefined,@@ -217,7 +237,6 @@ export async function augmentEventWithAcceptHandling(event, base, token) {if (!event._completionAck) {event._completionAck = completionAckForAcceptResult(event.id, completionType, event._acceptResult);}-return event;}@@ -245,9 +264,9 @@ export function printPollEvent(event) {console.log(JSON.stringify(event));}-export async function runPollOnce(base, token, { totalTimeout = 600_000 } = {}) {+export async function runPollOnce(base, token, { totalTimeout = 600_000, types, resolveTypes, perRequestTimeoutMs } = {}) {const deadline = Date.now() + totalTimeout;- const event = await fetchNextEvent(base, token, { totalDeadline: deadline });+ const event = await fetchNextEvent(base, token, { totalDeadline: deadline, types, resolveTypes, perRequestTimeoutMs });await augmentEventWithAcceptHandling(event, base, token);writeCarbonizeBanner(event);printPollEvent(event);@@ -258,11 +277,14 @@ export async function runPollStream(base, token, {ackTimeoutMs = 600_000,ackPollIntervalMs = 400,shouldContinue = () => true,+ types,+ resolveTypes,+ perRequestTimeoutMs,} = {}) {process.stderr.write('[impeccable-poll] stream mode: one JSON object per line on stdout; use --reply while this process stays running\n');while (shouldContinue()) {- const event = await fetchNextEvent(base, token);+ const event = await fetchNextEvent(base, token, { types, resolveTypes, perRequestTimeoutMs });await augmentEventWithAcceptHandling(event, base, token);writeCarbonizeBanner(event);printPollEvent(event);@@ -322,14 +344,17 @@ Modes:Options:--timeout=MS One-shot poll timeout in ms (default: 600000). Ignored in --stream mode+ --types=A,B Lease only these event types--ack-timeout=MS Stream mode: max wait for --reply after generate/steer (default: 600000)--file PATH Attach a source file path to the reply (generate/steer flow)--data JSON Attach a JSON result object to the reply (manual_edit_apply flow). Must be valid JSON--help Show this help messageHarness note:- Default one-shot mode is the portable contract for Claude Code, Codex, and Cursor.- --stream is experimental for harnesses with fast incremental stdout; do not use on Cursor.`);+ Default one-shot mode is the primary contract, including Codex foreground polling.+ Claude Code may run it as a background task; Cursor uses a background terminal with exit notification.+ --stream is retained for harnesses with measured, reliable incremental stdout.+ Do not use --stream on Cursor.`);process.exit(0);}@@ -360,23 +385,30 @@ Harness note:}const streamMode = args.includes('--stream');+ const typesArg = args.find((a) => a.startsWith('--types='));+ const types = normalizePollTypes(typesArg ? typesArg.slice('--types='.length) : null);const ackTimeoutArg = args.find((a) => a.startsWith('--ack-timeout='));const ackTimeoutMs = ackTimeoutArg ? parseInt(ackTimeoutArg.split('=')[1], 10) : 600_000;try {if (streamMode) {- await runPollStream(base, info.token, { ackTimeoutMs });+ await runPollStream(base, info.token, { ackTimeoutMs, types });return;}const timeoutArg = args.find((a) => a.startsWith('--timeout='));const totalTimeout = timeoutArg ? parseInt(timeoutArg.split('=')[1], 10) : 600_000;- await runPollOnce(base, info.token, { totalTimeout });+ await runPollOnce(base, info.token, { totalTimeout, types });} catch (err) {handlePollError(err);}}+export function normalizePollTypes(value) {+ const values = Array.isArray(value) ? value : String(value || '').split(',');+ return [...new Set(values.map((type) => String(type).trim()).filter(Boolean))];+}+// Auto-execute when run directlyconst _running = process.argv[1];if (_running?.endsWith('live-poll.mjs') || _running?.endsWith('live-poll.mjs/')) {diff --git a/.qoder/skills/impeccable/scripts/live-server.mjs b/.qoder/skills/impeccable/scripts/live-server.mjsindex 5735f2aec..c6e951086 100644--- a/.qoder/skills/impeccable/scripts/live-server.mjs+++ b/.qoder/skills/impeccable/scripts/live-server.mjs@@ -28,8 +28,10 @@ import {readLiveBrowserScriptParts,resolveLiveBrowserScriptParts,} from './live/browser-script-parts.mjs';-import { createLiveSessionStore } from './live/session-store.mjs';+import { createLiveSessionStore, GENERATION_FENCED_PHASES } from './live/session-store.mjs';+import { runGenerationPreflight } from './live/generation-preflight.mjs';import { validateEvent } from './live/event-validation.mjs';+import { selectAvailablePendingEvent } from './live/poll-lanes.mjs';import { createManualEditRoutes } from './live/manual-edit-routes.mjs';import { LIVE_COMMANDS } from './live/vocabulary.mjs';import {@@ -63,6 +65,10 @@ const DESIGN_MD_PATH = PROJECT_CONTEXT.designPath: null;const DEFAULT_POLL_TIMEOUT = 600_000; // 10 min — agent re-polls on timeout anywayconst SSE_HEARTBEAT_INTERVAL = 30_000; // keepalive ping every 30s+// The browser checkpoints for several unrelated reasons (see checkpointPayload+// in live-browser.js). Only these two report that variant availability changed,+// and only they may drive variant_progress / the *_reviewable phases.+const VARIANT_PROGRESS_CHECKPOINT_REASONS = new Set(['variants_progress', 'variants_ready']);// ---------------------------------------------------------------------------// Port detection@@ -156,29 +162,206 @@ function restorePendingEventsFromStore() {}}-function findAvailablePendingEvent(now = Date.now()) {- for (const entry of state.pendingEvents) {- if (entry.leaseUntil && entry.leaseUntil > now) continue;- return entry;- }- return null;+function findAvailablePendingEvent(now = Date.now(), types = null) {+ return selectAvailablePendingEvent(state.pendingEvents, { now, types });}-function leaseEvent(entry, leaseMs) {+async function leaseEvent(entry, leaseMs) {+ // Claim the entry before awaiting anything. prepareGenerateEventForLease+ // yields to the event loop, and selectAvailablePendingEvent only skips+ // entries whose lease is in the future — an unclaimed entry would be handed+ // to a second poll in that window and generated twice.+ entry.leaseUntil = Date.now() + leaseMs;+ await prepareGenerateEventForLease(entry);if (!entry.event?.id) {const idx = state.pendingEvents.indexOf(entry);if (idx !== -1) state.pendingEvents.splice(idx, 1);return entry.event;}+ // Re-stamp so the lease window starts when the agent actually receives the+ // work, not when scaffolding began.entry.leaseUntil = Date.now() + leaseMs;+ recordGenerateDelivery(entry);scheduleLeaseFlush();broadcastAgentPollingIfChanged();return entry.event;}-function acknowledgePendingEvent(id) {+function recordGenerateDelivery(entry) {+ const event = entry?.event;+ if (!event || event.type !== 'generate' || event.generationReadyAt) return;+ const at = Date.now();+ entry.event = { ...event, generationReadyAt: at };+ state.sessionStore?.appendEvent(entry.event);+ recordAgentPhase(event.id, 'generation_ready', { at });+}++async function prepareGenerateEventForLease(entry) {+ const event = entry?.event;+ if (!event || event.type !== 'generate' || event.scaffoldAttempted) return;++ recordAgentPhase(event.id, 'picked_up');+ recordAgentPhase(event.id, 'scaffolding');+ const result = await runGenerationPreflight(event, {+ cwd: process.cwd(),+ scriptsDir: __dirname,+ });+ entry.event = {+ ...event,+ scaffoldAttempted: true,+ scaffoldDurationMs: result.durationMs ?? null,+ ...(result.ok ? { scaffold: result.scaffold } : { scaffoldError: result.error || result.reason }),+ };+ state.sessionStore?.appendEvent(entry.event);+ recordAgentPhase(event.id, result.ok ? 'source_ready' : 'scaffold_fallback', {+ durationMs: result.durationMs ?? null,+ previewMode: result.scaffold?.previewMode || 'source',+ });+}++function recordAgentPhase(id, phase, details = {}) {+ if (!id) return;+ const event = {+ type: 'agent_phase',+ id,+ phase,+ at: Date.now(),+ ...details,+ };+ state.sessionStore?.appendEvent(event);+ broadcast(event);+}++/**+ * Detect a browser that missed the generation `done` broadcast.+ *+ * The preflight scaffold write triggers a framework full-reload (Astro reloads+ * the page for any .astro edit). If the agent's variant write + `done` land+ * while the browser is mid-reload, the new page misses both the second HMR+ * reload and the SSE `done` — it resumes from the scaffold-only source and+ * sits in GENERATING at 0/N forever. That resumed page always checkpoints+ * (`browser_resumed`), so a checkpoint claiming "still generating, variants+ * missing" for a session whose generation already completed is direct+ * evidence of the miss. Rebuild the `done` payload from the snapshot so the+ * caller can re-broadcast it; the browser's done handler is idempotent and+ * falls back to injecting variants from source.+ *+ * Keys on the store's monotone `generationCompletedAt`, not `phase` — the+ * behind checkpoint itself regresses `phase` to `generating`, and a browser+ * that misses the redelivered `done` too (another reload) must still trigger+ * redelivery from its next checkpoint.+ */+function detectMissedGenerationCompletion(event) {+ if (!event?.id || event.type !== 'checkpoint') return null;+ if (event.phase !== 'generating') return null;+ if (!variantCountLooksBehind(event.arrivedVariants, event.expectedVariants)) return null;+ if (!state.sessionStore) return null;+ let snapshot = null;+ try {+ snapshot = state.sessionStore.getSnapshot(event.id);+ } catch {+ return null;+ }+ return missedCompletionFromSnapshot(snapshot);+}++function variantCountLooksBehind(arrivedValue, expectedValue) {+ const arrived = Number(arrivedValue) || 0;+ const expected = Number(expectedValue) || 0;+ return arrived <= 0 || (expected > 0 && arrived < expected);+}++function missedCompletionFromSnapshot(snapshot) {+ if (!snapshot?.id || !snapshot.generationCompletedAt) return null;+ if (snapshot.generationCanceled) return null;+ // Accept/discard already underway: the browser is no longer waiting on+ // generation, and a late `done` there would collide with teardown.+ if (GENERATION_FENCED_PHASES.has(snapshot.phase)) return null;+ const file = snapshot.sourceFile || snapshot.previewFile;+ if (!file) return null;+ return {+ type: 'done',+ id: snapshot.id,+ file,+ sourceFile: snapshot.sourceFile || undefined,+ previewFile: snapshot.previewFile || undefined,+ previewMode: snapshot.previewMode || undefined,+ redelivered: true,+ };+}++function recordGenerationCheckpoint(event) {+ if (!event?.id || event.type !== 'checkpoint') return;+ if (generationIsFenced(event.id)) return;+ // Only checkpoints that report a change in variant availability are+ // generation progress. The browser also checkpoints for durability on Tune+ // slider drags, resumes, and anchor recovery; treating those as progress+ // echoed `variant_progress` straight back to the browser that sent it, which+ // remounts the component preview mid-drag (reverting the user's live param+ // edit and detaching the popover's element), and permanently latched the+ // *_reviewable phases from the wrong trigger, corrupting generation timings.+ if (!VARIANT_PROGRESS_CHECKPOINT_REASONS.has(event.reason)) return;+ const arrived = Number(event.arrivedVariants) || 0;+ const expected = Number(event.expectedVariants) || 0;+ if (arrived <= 0 || expected <= 0) return;+ const previewMode = event.previewMode || 'source';+ const previewFile = event.previewFile || event.file;+ if (previewFile) {+ broadcast({+ type: 'variant_progress',+ id: event.id,+ file: previewFile,+ sourceFile: event.sourceFile || (previewMode === 'source' ? previewFile : undefined),+ previewFile,+ previewMode,+ arrivedVariants: arrived,+ expectedVariants: expected,+ publicationKind: event.publicationKind || 'variants',+ });+ }+ const details = {+ arrivedVariants: arrived,+ expectedVariants: expected,+ checkpointReason: event.reason || null,+ };+ const at = Date.now();+ if (!generationPhaseAlreadyRecorded(event.id, 'first_reviewable')) {+ recordAgentPhase(event.id, 'first_reviewable', { ...details, at });+ }+ if (arrived >= 2 && expected >= 3 && !generationPhaseAlreadyRecorded(event.id, 'second_reviewable')) {+ recordAgentPhase(event.id, 'second_reviewable', { ...details, at });+ }+ if (arrived >= expected && !generationPhaseAlreadyRecorded(event.id, 'all_variants_ready')) {+ recordAgentPhase(event.id, 'all_variants_ready', { ...details, at });+ }+}++function generationIsFenced(id) {+ if (!state.sessionStore || !id) return false;+ try {+ const snapshot = state.sessionStore.getSnapshot(id, { includeCompleted: true });+ return snapshot?.generationCanceled === true;+ } catch {+ return false;+ }+}++function generationPhaseAlreadyRecorded(id, phase) {+ if (!state.sessionStore) return false;+ try {+ const snapshot = state.sessionStore.getSnapshot(id, { includeCompleted: true });+ return !!snapshot?.generationTimings?.[phase];+ } catch {+ return false;+ }+}++function acknowledgePendingEvent(id, sourceEventType) {if (!id) return false;- const idx = state.pendingEvents.findIndex((entry) => entry.event?.id === id);+ const idx = state.pendingEvents.findIndex((entry) => (+ entry.event?.id === id+ && (!sourceEventType || entry.event?.type === sourceEventType)+ ));if (idx === -1) return false;const acknowledged = state.pendingEvents[idx].event;state.pendingEvents.splice(idx, 1);@@ -187,9 +370,39 @@ function acknowledgePendingEvent(id) {return acknowledged;}-function findPendingEventById(id) {+function releasePendingEvent(id, sourceEventType) {+ const entry = state.pendingEvents.find((item) => (+ item.event?.id === id+ && (!sourceEventType || item.event?.type === sourceEventType)+ ));+ if (!entry) return null;+ entry.leaseUntil = 0;+ scheduleLeaseFlush();+ return entry.event;+}++function retirePendingGeneration(id) {+ if (!id) return 0;+ let retired = 0;+ for (let index = state.pendingEvents.length - 1; index >= 0; index -= 1) {+ const event = state.pendingEvents[index]?.event;+ if (event?.id !== id || event.type !== 'generate') continue;+ state.pendingEvents.splice(index, 1);+ retired += 1;+ }+ if (retired > 0) {+ scheduleLeaseFlush();+ broadcastAgentPollingIfChanged();+ }+ return retired;+}++function findPendingEventById(id, sourceEventType) {if (!id) return null;- const entry = state.pendingEvents.find((item) => item.event?.id === id);+ const entry = state.pendingEvents.find((item) => (+ item.event?.id === id+ && (!sourceEventType || item.event?.type === sourceEventType)+ ));return entry?.event || null;}@@ -198,7 +411,7 @@ function summarizePendingEventForStatus(entry) {const summary = {id: event.id,type: event.type,- leased: !!(entry.leaseUntil && entry.leaseUntil > Date.now()),+ leased: isLeased(entry),leaseUntil: entry.leaseUntil || null,};if (event.type === 'manual_edit_apply') {@@ -224,7 +437,13 @@ function summarizeActiveSessionForClient(snapshot = {}) {arrivedVariants: snapshot.arrivedVariants ?? 0,visibleVariant: snapshot.visibleVariant ?? null,checkpointRevision: snapshot.checkpointRevision ?? 0,+ browserCheckpointRevision: snapshot.browserCheckpointRevision ?? snapshot.checkpointRevision ?? 0,+ publicationCheckpointRevision: snapshot.publicationCheckpointRevision ?? 0,paramValues: snapshot.paramValues || {},+ generationPhase: snapshot.generationPhase ?? null,+ generationCompletedAt: snapshot.generationCompletedAt ?? null,+ generationCanceled: snapshot.generationCanceled === true,+ cancelReason: snapshot.cancelReason ?? null,};}@@ -269,24 +488,46 @@ function scheduleLeaseFlush() {function flushPendingPolls() {let changed = false;while (state.pendingPolls.length > 0) {- const entry = findAvailablePendingEvent();+ let pollIndex = -1;+ let entry = null;+ for (let index = 0; index < state.pendingPolls.length; index += 1) {+ const candidate = findAvailablePendingEvent(Date.now(), state.pendingPolls[index].types);+ if (!candidate) continue;+ pollIndex = index;+ entry = candidate;+ break;+ }if (!entry) {scheduleLeaseFlush();broadcastAgentPollingIfChanged();return;}- const poll = state.pendingPolls.shift();- poll.resolve(leaseEvent(entry, poll.leaseMs));+ const [poll] = state.pendingPolls.splice(pollIndex, 1);+ // leaseEvent is async (it may scaffold source), but it claims the entry+ // synchronously, so the next loop iteration will not re-select it. Resolve+ // the poll when the lease settles rather than awaiting here, so one slow+ // scaffold never delays the other parked polls. On the exceptional failure+ // path, answer `timeout` so the agent re-polls; the claim stays until the+ // lease expires, which keeps a deterministic failure from hot-looping.+ leaseEvent(entry, poll.leaseMs).then(poll.resolve, (error) => {+ console.error('[live] lease failed for ' + (entry.event?.id || 'unknown') + ': ' + (error?.message || error));+ poll.resolve({ type: 'timeout' });+ });changed = true;}scheduleLeaseFlush();if (changed) broadcastAgentPollingIfChanged();}+function isLeased(entry) {+ return !!(entry?.leaseUntil && entry.leaseUntil > Date.now());+}+function agentPollingConnected() {- const now = Date.now();- return state.pendingPolls.length > 0- || state.pendingEvents.some((entry) => entry.leaseUntil && entry.leaseUntil > now);+ // A leased event only proves that a poll returned once. The foreground task+ // may have ended immediately afterward, so only an actively waiting poll is+ // evidence that steering can wake the task right now.+ return state.pendingPolls.length > 0;}function broadcastAgentPollingIfChanged() {@@ -689,6 +930,16 @@ function createRequestHandler({ detectScript, liveScriptParts }) {res.end(JSON.stringify({ error }));return;}+ if (msg.type === 'agent_phase') {+ recordAgentPhase(msg.id, msg.phase, {+ ...(Number.isFinite(msg.durationMs) ? { durationMs: msg.durationMs } : {}),+ owner: typeof msg.owner === 'string' ? msg.owner : undefined,+ });+ res.writeHead(200, { 'Content-Type': 'application/json' });+ res.end(JSON.stringify({ ok: true }));+ return;+ }+ const missedCompletion = detectMissedGenerationCompletion(msg);if (state.sessionStore && msg.id) {try {state.sessionStore.appendEvent(msg);@@ -698,6 +949,11 @@ function createRequestHandler({ detectScript, liveScriptParts }) {return;}}+ if (msg.type === 'accept' || msg.type === 'discard') {+ retirePendingGeneration(msg.id);+ }+ recordGenerationCheckpoint(msg);+ if (missedCompletion) broadcast(missedCompletion);if (msg.type === 'exit') {cleanupSvelteComponentSessionsBeforeExit();}@@ -738,6 +994,12 @@ function createRequestHandler({ detectScript, liveScriptParts }) {// Agent poll endpoints (unchanged from WS version)// ---------------------------------------------------------------------------+function parsePollTypes(value) {+ if (!value) return null;+ const types = String(value).split(',').map((type) => type.trim()).filter(Boolean);+ return types.length > 0 ? new Set(types) : null;+}+function handlePollGet(req, res, url) {const token = url.searchParams.get('token');if (token !== state.token) {@@ -748,13 +1010,25 @@ function handlePollGet(req, res, url) {state.lastPollAt = Date.now();const timeout = parseInt(url.searchParams.get('timeout') || DEFAULT_POLL_TIMEOUT, 10);const leaseMs = parseInt(url.searchParams.get('leaseMs') || '30000', 10);- const available = findAvailablePendingEvent();+ const types = parsePollTypes(url.searchParams.get('types'));+ const available = findAvailablePendingEvent(Date.now(), types);if (available) {- res.writeHead(200, { 'Content-Type': 'application/json' });- res.end(JSON.stringify(leaseEvent(available, leaseMs)));+ // Do not await inline: leaseEvent may scaffold source, and this handler runs+ // on the server's only thread. The client can disconnect during that window,+ // so check the socket before replying.+ leaseEvent(available, leaseMs).then((event) => {+ if (res.writableEnded || res.destroyed) return;+ res.writeHead(200, { 'Content-Type': 'application/json' });+ res.end(JSON.stringify(event));+ }, (error) => {+ console.error('[live] lease failed for ' + (available.event?.id || 'unknown') + ': ' + (error?.message || error));+ if (res.writableEnded || res.destroyed) return;+ res.writeHead(200, { 'Content-Type': 'application/json' });+ res.end(JSON.stringify({ type: 'timeout' }));+ });return;}- const poll = { resolve, leaseMs };+ const poll = { resolve, leaseMs, types };const timer = setTimeout(() => {const idx = state.pendingPolls.indexOf(poll);if (idx !== -1) state.pendingPolls.splice(idx, 1);@@ -783,12 +1057,15 @@ function sessionFileMetadataFromPollReply(file) {if (!file || typeof file !== 'string') return { file };const normalized = file.split(path.sep).join('/');const base = { file: normalized };- if (!normalized.endsWith('/manifest.json') && normalized !== 'manifest.json') return base;- if (!normalized.includes('node_modules/.impeccable-live/') && !normalized.includes('src/lib/impeccable/')) return base;+ const metadataFile = normalized;+ if (!metadataFile.endsWith('/manifest.json') && metadataFile !== 'manifest.json') return base;+ if (!metadataFile.includes('node_modules/.impeccable-live/')+ && !metadataFile.includes('src/lib/impeccable/')+ && !metadataFile.includes('/.impeccable-live/')) return base;let full;try {- full = path.resolve(process.cwd(), normalized);+ full = path.resolve(process.cwd(), metadataFile);const rel = path.relative(process.cwd(), full);if (!rel || rel.startsWith('..') || path.isAbsolute(rel)) return base;} catch {@@ -797,18 +1074,47 @@ function sessionFileMetadataFromPollReply(file) {try {const manifest = JSON.parse(fs.readFileSync(full, 'utf-8'));- if (manifest?.previewMode !== 'svelte-component' || !manifest.sourceFile) return base;+ if (manifest?.previewMode !== 'svelte-component'+ || !manifest.sourceFile) return base;return {file: String(manifest.sourceFile).split(path.sep).join('/'),sourceFile: String(manifest.sourceFile).split(path.sep).join('/'),previewFile: normalized,- previewMode: 'svelte-component',+ previewMode: manifest.previewMode,};} catch {return base;}}+function inferSourceEventType(msg = {}, pendingEvents = state.pendingEvents) {+ const entriesForId = pendingEvents.filter((entry) => entry.event?.id === msg.id);+ const pendingTypes = new Set(entriesForId.map((entry) => entry.event?.type));+ if (msg.type === 'discarded' || msg.type === 'discard') return 'discard';+ if (msg.type === 'complete') {+ if (pendingTypes.has('carbonize_cleanup')) return 'carbonize_cleanup';+ return pendingTypes.has('accept') ? 'accept' : (pendingTypes.has('generate') ? 'generate' : undefined);+ }+ if (msg.type === 'steer_done') return 'steer';+ // `agent_done` can be the automatic acknowledgement for a carbonize Accept.+ // New pollers send sourceEventType explicitly; default to generate only for+ // older callers so a late worker cannot acknowledge a queued Accept.+ if (msg.type === 'agent_done' || msg.type === 'done') return 'generate';+ // `error` is reference/live.md's documented failure reply, and parseReplyArgs+ // never sets sourceEventType on it (the poller is a fresh process that cannot+ // know what it leased). Returning undefined here makes acknowledgePendingEvent+ // match *any* event for this id: a stale generate worker's failure silently+ // consumed the user's queued Accept, which was then never delivered to any+ // agent and left the browser in SAVING forever. Attribute the failure to the+ // event this agent actually holds a lease on, and otherwise to `generate` —+ // never to a wildcard. If that generate was already retired by an Accept, the+ // ack simply finds no match, which is the correct outcome for a stale reply.+ if (msg.type === 'error') {+ return entriesForId.find(isLeased)?.event?.type || 'generate';+ }+ return undefined;+}+function handlePollPost(req, res) {let body = '';req.on('data', (c) => { body += c; });@@ -869,7 +1175,23 @@ function handlePollPost(req, res) {res.end(JSON.stringify({ error: 'stale_manual_edit_apply_reply', ...rollback }));return;}- const pendingEventBeforeAck = findPendingEventById(msg.id);+ const sourceEventType = msg.sourceEventType || inferSourceEventType(msg);+ if (msg.type === 'retry') {+ const releasedEvent = releasePendingEvent(msg.id, sourceEventType);+ if (!releasedEvent) {+ res.writeHead(msg.id ? 404 : 400, { 'Content-Type': 'application/json' });+ res.end(JSON.stringify({+ error: msg.id ? 'unknown_poll_retry_id' : 'missing_poll_retry_id',+ id: msg.id,+ }));+ return;+ }+ flushPendingPolls();+ res.writeHead(200, { 'Content-Type': 'application/json' });+ res.end(JSON.stringify({ ok: true, released: true }));+ return;+ }+ const pendingEventBeforeAck = findPendingEventById(msg.id, sourceEventType);if (pendingEventBeforeAck?.type === 'steer' && msg.type === 'steer_done'&& !msg.file && !(typeof msg.message === 'string' && msg.message.trim())) {res.writeHead(400, { 'Content-Type': 'application/json' });@@ -879,7 +1201,7 @@ function handlePollPost(req, res) {}));return;}- const acknowledgedEvent = acknowledgePendingEvent(msg.id);+ const acknowledgedEvent = acknowledgePendingEvent(msg.id, sourceEventType);let skipJournalReply = false;let existingSession = null;if (!acknowledgedEvent && state.sessionStore && msg.id) {@@ -1083,7 +1405,10 @@ if (args.includes('--background')) {process.exit(0);}} catch { /* not ready yet */ }- await new Promise(r => setTimeout(r, 200));+ // The detached child is typically listening in 35-45ms. A 200ms polling+ // floor dominated configured cold Live startup; poll cheaply and return+ // as soon as the child has written its ready record.+ await new Promise(r => setTimeout(r, 5));}console.error('Timed out waiting for live server to start.');process.exit(1);diff --git a/.qoder/skills/impeccable/scripts/live-status.mjs b/.qoder/skills/impeccable/scripts/live-status.mjsindex f7e464999..dc98b7386 100644--- a/.qoder/skills/impeccable/scripts/live-status.mjs+++ b/.qoder/skills/impeccable/scripts/live-status.mjs@@ -37,15 +37,19 @@ export async function statusCli() {pendingEvents: server.pendingEvents,} : null,activeSessions: server?.activeSessions || activeSessions,- recoveryHint: manualApply- ? manualApplyResumeHint(manualApply)- : server- ? 'Run live-poll.mjs to continue pending work, or live-complete.mjs --id <session> after manual cleanup.'- : 'Start live-server.mjs to requeue pending durable events, then run live-poll.mjs.',+ recoveryHint: recoveryHint({ server, manualApply }),};console.log(JSON.stringify(payload, null, 2));}+function recoveryHint({ server, manualApply }) {+ if (manualApply) return manualApplyResumeHint(manualApply);+ if (server) {+ return 'Run live-poll.mjs to continue pending work, or live-complete.mjs --id <session> after manual cleanup.';+ }+ return 'Start live-server.mjs to requeue pending durable events, then run live-poll.mjs.';+}+function findPendingManualApply(server, activeSessions) {const fromServer = server?.pendingEvents?.find((event) => event?.type === 'manual_edit_apply');if (fromServer) return fromServer;diff --git a/.qoder/skills/impeccable/scripts/live-wrap.mjs b/.qoder/skills/impeccable/scripts/live-wrap.mjsindex 438c01b68..48d7f7683 100644--- a/.qoder/skills/impeccable/scripts/live-wrap.mjs+++ b/.qoder/skills/impeccable/scripts/live-wrap.mjs@@ -160,11 +160,29 @@ The agent should insert variant HTML at insertLine.`);if (filtered.length === 1) {match = filtered[0];} else if (filtered.length === 0) {- // Source uses dynamic content (`<h1>{title}</h1>` etc.) so the- // browser-side textContent doesn't appear literally in source. Fall- // back to first-match rather than refusing — this is the same- // behavior unmodified callers see, just preserved.- match = candidates[0];+ const normalizedText = String(text).replace(/\s+/g, ' ').trim();+ if (normalizedText.length < 8) {+ // Very short labels cannot disambiguate siblings reliably. Preserve+ // the legacy behavior for these low-information picker events.+ match = candidates[0];+ } else {+ // Rendered text that is absent from every candidate usually means+ // the source uses expressions or component props. Picking the first+ // same-class sibling silently edits the wrong instance (observed on+ // Astro result cards), so stop and surface every candidate instead.+ console.error(JSON.stringify({+ error: 'element_ambiguous',+ fallback: 'agent-driven',+ reason: 'rendered_text_not_in_source',+ file: path.relative(process.cwd(), targetFile),+ candidates: candidates.map((c) => ({+ startLine: c.startLine + 1,+ endLine: c.endLine + 1,+ })),+ hint: 'Rendered text does not occur in any matching source branch. The element may use dynamic props or expressions; inspect the candidates and wrap the intended instance manually.',+ }));+ process.exit(1);+ }} else {// Multiple candidates ALSO match the text. Truly ambiguous — refuse// rather than pick wrong, and hand the agent the candidate locations@@ -269,6 +287,7 @@ The agent should insert variant HTML at insertLine.`);const originalIndented = reindentOriginal(' ');const relTargetFile = path.relative(process.cwd(), targetFile).split(path.sep).join('/');const useSvelteComponent = shouldUseSvelteComponentInjection(targetFile);+ const useFrameworkComponent = useSvelteComponent;// Wrapper attributes differ by syntax. HTML allows plain string attrs;// JSX requires object-literal style and parses string attrs as HTML (which@@ -288,7 +307,7 @@ The agent should insert variant HTML at insertLine.`);// replacement range to include the wrapper's `<div>` open / close lines// so the entire scaffold gets removed cleanly.const wrapperLines = isJsx ? [- indent + '<div data-impeccable-variants="' + id + '" data-impeccable-variant-count="' + count + '" ' + styleContents + '>',+ indent + '<div data-impeccable-variants="' + id + '" data-impeccable-variant-count="' + count + '"' + ' ' + styleContents + '>',indent + ' ' + commentSyntax.open + ' impeccable-variants-start ' + id + ' ' + commentSyntax.close,indent + ' ' + commentSyntax.open + ' Original ' + commentSyntax.close,indent + ' <div data-impeccable-variant="original">',@@ -299,7 +318,7 @@ The agent should insert variant HTML at insertLine.`);indent + '</div>',] : [indent + commentSyntax.open + ' impeccable-variants-start ' + id + ' ' + commentSyntax.close,- indent + '<div data-impeccable-variants="' + id + '" data-impeccable-variant-count="' + count + '" ' + styleContents + '>',+ indent + '<div data-impeccable-variants="' + id + '" data-impeccable-variant-count="' + count + '"' + ' ' + styleContents + '>',indent + ' ' + commentSyntax.open + ' Original ' + commentSyntax.close,indent + ' <div data-impeccable-variant="original">',originalIndented,@@ -356,15 +375,18 @@ The agent should insert variant HTML at insertLine.`);const outputRelFile = path.relative(process.cwd(), outputFile).split(path.sep).join('/');const svelteComponentAuthoring = useSvelteComponent ? buildSvelteComponentCssAuthoring(count) : null;+ const componentSession = svelteSession;+ const componentPreviewMode = useSvelteComponent ? 'svelte-component' : undefined;+ const previewMode = componentPreviewMode;console.log(JSON.stringify({file: outputRelFile,- sourceFile: useSvelteComponent ? relTargetFile : undefined,- previewMode: useSvelteComponent ? 'svelte-component' : undefined,- componentDir: svelteSession?.componentDir,- propContract: svelteSession?.propContract,- sourceStartLine: useSvelteComponent ? startLine + 1 : undefined,- sourceEndLine: useSvelteComponent ? endLine + 1 : undefined,+ sourceFile: useFrameworkComponent ? relTargetFile : undefined,+ previewMode,+ componentDir: componentSession?.componentDir,+ propContract: componentSession?.propContract,+ sourceStartLine: useFrameworkComponent ? startLine + 1 : undefined,+ sourceEndLine: useFrameworkComponent ? endLine + 1 : undefined,startLine: outputStartLine, // 1-indexed for the agent// wrapperLines is an array but one element (the original-content slot)// is a `\n`-joined multi-line string, so the actual file-row count is@@ -374,10 +396,10 @@ The agent should insert variant HTML at insertLine.`);endLine: outputEndLine, // 1-indexedinsertLine, // 1-indexed: where variants gocommentSyntax: commentSyntax,- styleMode: useSvelteComponent ? 'svelte-component' : styleMode.mode,- styleTag: useSvelteComponent ? null : styleMode.styleTag,- cssSelectorPrefixExamples: useSvelteComponent ? [] : buildCssSelectorPrefixExamples(styleMode.mode, count),- cssAuthoring: useSvelteComponent ? svelteComponentAuthoring : buildCssAuthoring(styleMode, count),+ styleMode: componentPreviewMode || styleMode.mode,+ styleTag: useFrameworkComponent ? null : styleMode.styleTag,+ cssSelectorPrefixExamples: useFrameworkComponent ? [] : buildCssSelectorPrefixExamples(styleMode.mode, count),+ cssAuthoring: svelteComponentAuthoring || buildCssAuthoring(styleMode, count),originalLineCount: originalLines.length,}));}diff --git a/.qoder/skills/impeccable/scripts/live.mjs b/.qoder/skills/impeccable/scripts/live.mjsindex e0bd1ad24..b21a71cc4 100644--- a/.qoder/skills/impeccable/scripts/live.mjs+++ b/.qoder/skills/impeccable/scripts/live.mjs@@ -10,7 +10,7 @@** After this, the agent's only remaining steps are:* - Open the project's live dev/preview URL in the browser (optional, if browser automation exists)—not `serverPort`; that port is the Impeccable helper for /live.js and /poll- * - Enter the poll loop: `node live-poll.mjs`+ * - Enter the harness-native poll loop: `node live-poll.mjs`** Usage:* node live.mjs # Prepare everything, print JSON, exit@@ -40,6 +40,7 @@ Prepare everything for live variant mode in a single command:- Starts (or reuses) the live server in the background- Injects the browser script tag- Reads PRODUCT.md / DESIGN.md for project context+ - Prepares the harness-native foreground/background poll loop- In monorepos, choose a child app first; --target <path> is the fallback/manual pathOn success, prints a JSON blob with:diff --git a/.qoder/skills/impeccable/scripts/live/completion.mjs b/.qoder/skills/impeccable/scripts/live/completion.mjsindex 986773066..6f539336d 100644--- a/.qoder/skills/impeccable/scripts/live/completion.mjs+++ b/.qoder/skills/impeccable/scripts/live/completion.mjs@@ -1,9 +1,18 @@+// A preview whose variants live in component modules rather than in the user's+// source. These leave no markers in the real file, so a failed accept gives the+// agent nothing to hand-edit and must be reported as a failure rather than+// reference/live.md's manual-cleanup handoff. Kept as a set: any future+// component-module preview mode belongs here the day it lands.+const PREVIEW_MODES_WITHOUT_SOURCE_MARKERS = new Set([+ 'svelte-component',+]);+export function completionTypeForAcceptResult(eventType, acceptResult) {if (eventType === 'discard') return acceptResult?.handled === true ? 'discarded' : 'error';if (acceptResult?.handled === true && acceptResult?.carbonize === true) return 'agent_done';if (acceptResult?.handled === true) return 'complete';if (acceptResult?.mode === 'error') return 'error';- if (eventType === 'accept' && acceptResult?.previewMode === 'svelte-component') return 'error';+ if (eventType === 'accept' && PREVIEW_MODES_WITHOUT_SOURCE_MARKERS.has(acceptResult?.previewMode)) return 'error';return 'agent_done';}diff --git a/.qoder/skills/impeccable/scripts/live/event-validation.mjs b/.qoder/skills/impeccable/scripts/live/event-validation.mjsindex 0897b1317..122c29836 100644--- a/.qoder/skills/impeccable/scripts/live/event-validation.mjs+++ b/.qoder/skills/impeccable/scripts/live/event-validation.mjs@@ -118,6 +118,15 @@ export function validateEvent(msg) {return 'checkpoint: paramValues must be an object';}return null;+ case 'agent_phase':+ if (!isValidId(msg.id)) return 'agent_phase: missing or malformed id';+ if (typeof msg.phase !== 'string' || !/^[a-z][a-z0-9_]{1,63}$/.test(msg.phase)) {+ return 'agent_phase: missing or malformed phase';+ }+ if (msg.durationMs !== undefined && (!Number.isFinite(msg.durationMs) || msg.durationMs < 0)) {+ return 'agent_phase: durationMs must be a non-negative number';+ }+ return null;case 'exit':return null;case 'prefetch':@@ -131,6 +140,12 @@ export function validateEvent(msg) {if (msg.message.length > 4000) return 'steer: message too long';if (msg.pageUrl !== undefined && typeof msg.pageUrl !== 'string') return 'steer: pageUrl must be string';return null;+ case 'carbonize_cleanup':+ if (!isValidId(msg.id)) return 'carbonize_cleanup: missing or malformed id';+ if (!isValidId(msg.sessionId)) return 'carbonize_cleanup: missing or malformed sessionId';+ if (!msg.file || typeof msg.file !== 'string') return 'carbonize_cleanup: missing file';+ if (!isValidVariantId(String(msg.variantId))) return 'carbonize_cleanup: missing or malformed variantId';+ return null;default:return 'Unknown event type: ' + msg.type;}diff --git a/.qoder/skills/impeccable/scripts/live/generation-preflight.mjs b/.qoder/skills/impeccable/scripts/live/generation-preflight.mjsnew file mode 100644index 000000000..07a5e957e--- /dev/null+++ b/.qoder/skills/impeccable/scripts/live/generation-preflight.mjs@@ -0,0 +1,102 @@+import { execFile } from 'node:child_process';+import path from 'node:path';+import { promisify } from 'node:util';++const execFileAsync = promisify(execFile);+const PREFLIGHT_TIMEOUT_MS = 15_000;++export function buildGenerationPreflight(event, scriptsDir) {+ if (!event || event.type !== 'generate' || !event.id) return null;++ const isInsert = event.mode === 'insert';+ const target = isInsert ? insertTarget(event) : replaceTarget(event);+ if (!target.elementId && !target.classes) return null;++ const script = path.join(scriptsDir, isInsert ? 'live-insert.mjs' : 'live-wrap.mjs');+ const args = [script, '--id', event.id, '--count', String(event.count || 3)];+ if (isInsert) args.push('--position', target.position);+ if (target.elementId) args.push('--element-id', target.elementId);+ if (target.classes) args.push('--classes', target.classes);+ if (target.tag) args.push('--tag', target.tag);+ if (target.text) args.push('--text', target.text);+ if (!isInsert && event.pageUrl) args.push('--page-url', event.pageUrl);+ return { script, args, mode: isInsert ? 'insert' : 'replace' };+}++/**+ * Scaffold the source for a generate event before handing it to an agent.+ *+ * Async on purpose. This spawns `live-wrap.mjs`, which walks the project's+ * source tree and can take seconds (measured at ~7.6s on a large repo when the+ * element is not found, with a 15s ceiling). The live server is single-threaded+ * and calls this while leasing a poll, so a synchronous spawn froze the whole+ * server for that entire window: Accept and Discard POSTs, SSE progress+ * broadcasts, and every other poll stalled behind it.+ */+export async function runGenerationPreflight(event, {+ cwd = process.cwd(),+ scriptsDir,+ execFileImpl = execFileAsync,+ timeoutMs = PREFLIGHT_TIMEOUT_MS,+} = {}) {+ const command = buildGenerationPreflight(event, scriptsDir);+ if (!command) {+ return { ok: false, skipped: true, reason: 'insufficient_locator' };+ }++ const startedAt = performance.now();+ try {+ const { stdout } = await execFileImpl(process.execPath, command.args, {+ cwd,+ encoding: 'utf-8',+ timeout: timeoutMs,+ });+ const line = String(stdout).trim().split('\n').filter(Boolean).pop();+ if (!line) throw new Error('preflight returned no scaffold metadata');+ return {+ ok: true,+ mode: command.mode,+ durationMs: performance.now() - startedAt,+ scaffold: JSON.parse(line),+ };+ } catch (error) {+ return {+ ok: false,+ mode: command.mode,+ durationMs: performance.now() - startedAt,+ error: compactError(error),+ };+ }+}++function replaceTarget(event) {+ return normalizeTarget(event.element || {});+}++function insertTarget(event) {+ return {+ ...normalizeTarget(event.insert?.anchor || {}),+ position: event.insert?.position === 'before' ? 'before' : 'after',+ };+}++function normalizeTarget(target) {+ const classes = Array.isArray(target.classes)+ ? target.classes.join(' ')+ : String(target.classes || '').trim();+ const text = typeof target.textContent === 'string'+ ? target.textContent.trim().slice(0, 80)+ : '';+ return {+ elementId: target.id || target.elementId || undefined,+ classes: classes || undefined,+ tag: target.tagName || target.tag || undefined,+ text: text || undefined,+ };+}++function compactError(error) {+ const stderr = error?.stderr ? String(error.stderr).trim() : '';+ const message = stderr.split('\n').filter(Boolean).pop() || error?.message || 'preflight failed';+ return String(message).slice(0, 500);+}diff --git a/.qoder/skills/impeccable/scripts/live/poll-lanes.mjs b/.qoder/skills/impeccable/scripts/live/poll-lanes.mjsnew file mode 100644index 000000000..65f20a87a--- /dev/null+++ b/.qoder/skills/impeccable/scripts/live/poll-lanes.mjs@@ -0,0 +1,14 @@+export function eventPriority(event = {}) {+ if (event.type === 'accept' || event.type === 'discard' || event.type === 'exit') return 0;+ if (event.type === 'manual_edit_apply' || event.type === 'steer' || event.type === 'carbonize_cleanup') return 1;+ if (event.type === 'generate') return 2;+ return 3;+}++export function selectAvailablePendingEvent(entries, { now = Date.now(), types = null } = {}) {+ const allowed = types instanceof Set ? types : (Array.isArray(types) ? new Set(types) : null);+ return entries+ .filter((entry) => !(entry.leaseUntil && entry.leaseUntil > now))+ .filter((entry) => !allowed || allowed.has(entry.event?.type))+ .sort((a, b) => eventPriority(a.event) - eventPriority(b.event) || a.seq - b.seq)[0] || null;+}diff --git a/.qoder/skills/impeccable/scripts/live/session-store.mjs b/.qoder/skills/impeccable/scripts/live/session-store.mjsindex affba67c9..9d20341dd 100644--- a/.qoder/skills/impeccable/scripts/live/session-store.mjs+++ b/.qoder/skills/impeccable/scripts/live/session-store.mjs@@ -1,24 +1,26 @@import fs from 'node:fs';import path from 'node:path';-import { getLegacyLiveSessionsDir, getLiveSessionsDir } from '../lib/impeccable-paths.mjs';+import { getLegacyLiveSessionsDir, getLiveSessionsDir, safeSessionId } from '../lib/impeccable-paths.mjs';const COMPLETED_PHASES = new Set(['completed', 'discarded']);+export const GENERATION_FENCED_PHASES = new Set([+ 'accept_requested',+ 'discard_requested',+ 'carbonize_required',+ 'completed',+ 'discarded',+]);export function createLiveSessionStore({ cwd = process.cwd(), sessionId } = {}) {const rootDir = getLiveSessionsDir(cwd);const legacyRootDir = getLegacyLiveSessionsDir(cwd);fs.mkdirSync(rootDir, { recursive: true });- const snapshotCache = new Map();-- function loadCachedOrRebuild(id) {- const cached = snapshotCache.get(id);- if (cached) return cached;- const journalPath = getReadableJournalPath(id);- const rebuilt = rebuildSnapshotFromJournal(journalPath, id);- snapshotCache.set(id, rebuilt);- return rebuilt;- }+ // No snapshot cache on purpose: appendEvent and getSnapshot both rebuild from+ // the journal so sequence numbers and phase fences never come from a stale+ // in-memory copy when the publisher/complete helpers append from another+ // process. A cache written but never read would grow per session for the+ // lifetime of the server without ever saving a rebuild.function getReadableJournalPath(id) {const primary = getJournalPath(rootDir, id);if (fs.existsSync(primary)) return primary;@@ -38,7 +40,10 @@ export function createLiveSessionStore({ cwd = process.cwd(), sessionId } = {})if (!fs.existsSync(journalPath) && fs.existsSync(legacyJournalPath)) {fs.copyFileSync(legacyJournalPath, journalPath);}- const prior = loadCachedOrRebuild(normalized.id);+ // Publisher/complete helpers can append from a separate process while+ // the server is alive. Rebuild here so sequence numbers and phase+ // fences never come from a stale in-memory cache.+ const prior = rebuildSnapshotFromJournal(getReadableJournalPath(normalized.id), normalized.id);const seq = prior.nextSeq;const entry = {seq,@@ -49,7 +54,6 @@ export function createLiveSessionStore({ cwd = process.cwd(), sessionId } = {})};fs.appendFileSync(journalPath, JSON.stringify(entry) + '\n');const next = applyEvent(prior.snapshot, entry, prior.diagnostics);- snapshotCache.set(normalized.id, { snapshot: next, diagnostics: next.diagnostics || [], nextSeq: seq + 1 });writeSnapshot(snapshotPath, next);return next;},@@ -58,7 +62,6 @@ export function createLiveSessionStore({ cwd = process.cwd(), sessionId } = {})const journalPath = getReadableJournalPath(id);const snapshotPath = getSnapshotPath(rootDir, id);const rebuilt = rebuildSnapshotFromJournal(journalPath, id);- snapshotCache.set(id, rebuilt);writeSnapshot(snapshotPath, rebuilt.snapshot);if (!opts.includeCompleted && COMPLETED_PHASES.has(rebuilt.snapshot.phase)) return null;return rebuilt.snapshot;@@ -95,11 +98,6 @@ function getSnapshotPath(rootDir, id) {return path.join(rootDir, safeSessionId(id) + '.snapshot.json');}-function safeSessionId(id) {- if (!/^[A-Za-z0-9_-]{1,128}$/.test(id)) throw new Error('invalid session id: ' + id);- return id;-}-function baseSnapshot(id) {return {id,@@ -116,9 +114,18 @@ function baseSnapshot(id) {pendingEvent: null,deliveryLease: null,checkpointRevision: 0,+ browserCheckpointRevision: 0,+ publicationCheckpointRevision: 0,activeOwner: null,sourceMarkers: {},fallbackMode: null,+ generationPhase: null,+ generationCompletedAt: null,+ generationTimings: {},+ variantPlan: null,+ generationCanceled: false,+ generationCanceledAt: null,+ cancelReason: null,annotationArtifacts: [],diagnostics: [],updatedAt: null,@@ -158,6 +165,8 @@ function applyEvent(snapshot, entry, inheritedDiagnostics = []) {...snapshot,paramValues: { ...(snapshot.paramValues || {}) },sourceMarkers: { ...(snapshot.sourceMarkers || {}) },+ generationTimings: { ...(snapshot.generationTimings || {}) },+ variantPlan: snapshot.variantPlan || null,annotationArtifacts: [...(snapshot.annotationArtifacts || [])],diagnostics: [...(snapshot.diagnostics || [])],updatedAt: entry.ts || new Date().toISOString(),@@ -174,11 +183,48 @@ function applyEvent(snapshot, entry, inheritedDiagnostics = []) {next.expectedVariants = event.count ?? next.expectedVariants;next.pendingEventSeq = entry.seq ?? next.pendingEventSeq;next.pendingEvent = toPendingEvent(event);+ next.variantPlan = null;if (event.screenshotPath) upsertArtifact(next.annotationArtifacts, { type: 'screenshot', path: event.screenshotPath });break;+ case 'variant_plan':+ if (!next.generationCanceled && !GENERATION_FENCED_PHASES.has(next.phase)) {+ next.variantPlan = event.plan ?? next.variantPlan;+ }+ break;+ case 'detector_waivers':+ if (!next.generationCanceled && !GENERATION_FENCED_PHASES.has(next.phase)) {+ next.detectorWaivers = [+ ...(next.detectorWaivers || []),+ ...(Array.isArray(event.waivers) ? event.waivers : []),+ ];+ }+ break;+ case 'agent_phase':+ next.generationPhase = event.phase ?? next.generationPhase;+ if (event.phase) {+ next.generationTimings[event.phase] = {+ at: event.at ?? (Date.parse(entry.ts || '') || null),+ durationMs: event.durationMs ?? null,+ };+ }+ break;case 'variants_ready':case 'agent_done':+ if ((next.generationCanceled || GENERATION_FENCED_PHASES.has(next.phase))+ && !(event.type === 'agent_done' && event.carbonize === true && next.phase === 'accept_requested')) {+ next.diagnostics.push({+ error: 'late_generation_event_ignored',+ type: event.type,+ phase: next.phase,+ });+ break;+ }next.phase = event.carbonize === true ? 'carbonize_required' : 'variants_ready';+ // Durable completion marker: later browser checkpoints (a resumed page+ // reporting phase "generating") regress `phase`, but generation staying+ // finished is monotone — the live server keys missed-`done` redelivery+ // on this field.+ next.generationCompletedAt = event.at ?? (Date.parse(entry.ts || '') || Date.now());next.sourceFile = event.sourceFile ?? event.file ?? next.sourceFile;next.previewFile = event.previewFile ?? next.previewFile;next.previewMode = event.previewMode ?? next.previewMode;@@ -194,27 +240,45 @@ function applyEvent(snapshot, entry, inheritedDiagnostics = []) {}break;case 'checkpoint':- if (COMPLETED_PHASES.has(next.phase)) {+ if (next.generationCanceled || GENERATION_FENCED_PHASES.has(next.phase)) {next.diagnostics.push({ error: 'checkpoint_after_terminal_ignored', phase: event.phase ?? null, revision: event.revision ?? null });break;}- if ((event.revision ?? 0) >= (next.checkpointRevision ?? 0)) {- next.phase = event.phase ?? next.phase;- next.checkpointRevision = event.revision ?? next.checkpointRevision;- next.activeOwner = event.owner ?? next.activeOwner;- next.arrivedVariants = event.arrivedVariants ?? next.arrivedVariants;- next.visibleVariant = event.visibleVariant ?? next.visibleVariant;- next.sourceFile = event.sourceFile ?? next.sourceFile;- next.previewFile = event.previewFile ?? next.previewFile;- next.previewMode = event.previewMode ?? next.previewMode;- if (event.paramValues) next.paramValues = { ...event.paramValues };- } else {- next.diagnostics.push({ error: 'stale_checkpoint_ignored', revision: event.revision });+ {+ const revisionDomain = event.revisionDomain === 'publication'+ || (event.reason === 'variants_progress' && !event.owner)+ ? 'publication'+ : 'browser';+ const revisionField = revisionDomain === 'publication'+ ? 'publicationCheckpointRevision'+ : 'browserCheckpointRevision';+ const currentRevision = next[revisionField]+ ?? (revisionDomain === 'browser' ? next.checkpointRevision : 0)+ ?? 0;+ if ((event.revision ?? 0) >= currentRevision) {+ next.phase = event.phase ?? next.phase;+ next[revisionField] = event.revision ?? currentRevision;+ if (revisionDomain === 'browser') {+ next.checkpointRevision = event.revision ?? next.checkpointRevision;+ next.activeOwner = event.owner ?? next.activeOwner;+ }+ next.arrivedVariants = event.arrivedVariants ?? next.arrivedVariants;+ if (revisionDomain === 'browser') next.visibleVariant = event.visibleVariant ?? next.visibleVariant;+ next.sourceFile = event.sourceFile ?? next.sourceFile;+ next.previewFile = event.previewFile ?? next.previewFile;+ next.previewMode = event.previewMode ?? next.previewMode;+ if (revisionDomain === 'browser' && event.paramValues) next.paramValues = { ...event.paramValues };+ } else {+ next.diagnostics.push({ error: 'stale_checkpoint_ignored', revision: event.revision, revisionDomain });+ }}break;case 'accept':case 'accept_intent':next.phase = 'accept_requested';+ next.generationCanceled = true;+ next.generationCanceledAt = event.at ?? (Date.parse(entry.ts || '') || Date.now());+ next.cancelReason = 'accept';next.visibleVariant = Number(event.variantId ?? next.visibleVariant);if (event.paramValues) next.paramValues = { ...event.paramValues };next.pendingEventSeq = entry.seq ?? next.pendingEventSeq;@@ -232,6 +296,12 @@ function applyEvent(snapshot, entry, inheritedDiagnostics = []) {next.pendingEventSeq = entry.seq ?? next.pendingEventSeq;next.pendingEvent = toPendingEvent(event);break;+ case 'carbonize_cleanup':+ next.phase = 'carbonize_cleanup_requested';+ next.sourceFile = event.file ?? next.sourceFile;+ next.pendingEventSeq = entry.seq ?? next.pendingEventSeq;+ next.pendingEvent = toPendingEvent(event);+ break;case 'steer_done':next.phase = 'steer_done';next.sourceFile = event.sourceFile ?? event.file ?? next.sourceFile;@@ -243,6 +313,9 @@ function applyEvent(snapshot, entry, inheritedDiagnostics = []) {break;case 'discard':next.phase = 'discard_requested';+ next.generationCanceled = true;+ next.generationCanceledAt = event.at ?? (Date.parse(entry.ts || '') || Date.now());+ next.cancelReason = 'discard';next.pendingEventSeq = entry.seq ?? next.pendingEventSeq;next.pendingEvent = toPendingEvent(event);break;@@ -260,6 +333,10 @@ function applyEvent(snapshot, entry, inheritedDiagnostics = []) {next.pendingEvent = null;break;case 'agent_error':+ if (next.generationCanceled && event.sourceEventType === 'generate') {+ next.diagnostics.push({ error: 'late_generation_event_ignored', type: event.type, phase: next.phase });+ break;+ }next.phase = 'agent_error';next.pendingEventSeq = null;next.pendingEvent = null;diff --git a/.qoder/skills/impeccable/scripts/live/source-lock.mjs b/.qoder/skills/impeccable/scripts/live/source-lock.mjsnew file mode 100644index 000000000..9ccc557be--- /dev/null+++ b/.qoder/skills/impeccable/scripts/live/source-lock.mjs@@ -0,0 +1,105 @@+import fs from 'node:fs';+import path from 'node:path';+import { createHash, randomUUID } from 'node:crypto';+import { getLiveDir, isLiveServerPidReachable } from '../lib/impeccable-paths.mjs';++// Only used to retire a lock whose contents we cannot read (empty or truncated+// by a crash mid-write). A readable lock's fate is decided by its owner's+// liveness instead, so a slow critical section is never swept.+const UNREADABLE_LOCK_STALE_MS = 60_000;++export function sourceLockPath(file, cwd = process.cwd()) {+ const digest = createHash('sha256').update(path.resolve(cwd, file)).digest('hex').slice(0, 24);+ return path.join(getLiveDir(cwd), 'locks', digest + '.lock');+}++export function withSourceLockSync(file, owner, fn, {+ cwd = process.cwd(),+ waitMs = 0,+ retryMs = 5,+} = {}) {+ const lockPath = sourceLockPath(file, cwd);+ fs.mkdirSync(path.dirname(lockPath), { recursive: true });+ const deadline = Date.now() + Math.max(0, Number(waitMs) || 0);+ // Identifies this acquisition specifically, so release can tell our own lock+ // from a replacement that some other writer created.+ const token = randomUUID();+ let acquired = false;++ while (!acquired) {+ clearStaleLock(lockPath);+ let fd;+ try {+ fd = fs.openSync(lockPath, 'wx');+ fs.writeFileSync(fd, JSON.stringify({+ owner,+ token,+ pid: process.pid,+ at: Date.now(),+ file: path.resolve(cwd, file),+ }) + '\n');+ acquired = true;+ } catch (error) {+ if (error?.code !== 'EEXIST') throw error;+ if (Date.now() >= deadline) {+ const locked = new Error('source_locked');+ locked.code = 'SOURCE_LOCKED';+ locked.lockPath = lockPath;+ throw locked;+ }+ sleepSync(Math.max(1, Math.min(Number(retryMs) || 5, deadline - Date.now())));+ } finally {+ try { if (fd !== undefined) fs.closeSync(fd); } catch {}+ }+ }++ try {+ return fn();+ } finally {+ releaseOwnLock(lockPath, token);+ }+}++function sleepSync(ms) {+ Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, ms);+}++function readLock(lockPath) {+ try { return JSON.parse(fs.readFileSync(lockPath, 'utf-8')); } catch { return null; }+}++/**+ * Remove the lock only if it is still the one this call created. If a sweeper+ * judged our lock stale and another writer replaced it, unlinking here would+ * end *their* critical section and admit a third writer to the same file.+ */+function releaseOwnLock(lockPath, token) {+ const held = readLock(lockPath);+ if (held && held.token !== token) return;+ try { fs.unlinkSync(lockPath); } catch {}+}++/**+ * A lock is stale when its owner is gone, not when it is old.+ *+ * Age alone cuts both ways: it sweeps a live holder whose critical section+ * outran the timeout (a suspended laptop, a stopped process), letting two+ * writers into the same source file, while still making every accept on a+ * crashed holder's file wait out the full timeout. Asking the OS whether the+ * recorded pid is alive answers both correctly: a dead owner releases at once,+ * and a live owner keeps its lock however long it needs.+ */+function clearStaleLock(lockPath) {+ const held = readLock(lockPath);+ if (!held) {+ // Unreadable: either a crash truncated it, or we caught the brief window+ // between create and write in a live acquisition. mtime distinguishes them.+ try {+ const stat = fs.statSync(lockPath);+ if (Date.now() - stat.mtimeMs > UNREADABLE_LOCK_STALE_MS) fs.unlinkSync(lockPath);+ } catch { /* gone already */ }+ return;+ }+ if (typeof held.pid === 'number' && isLiveServerPidReachable(held.pid)) return;+ try { fs.unlinkSync(lockPath); } catch {}+}diff --git a/.rovodev/skills/impeccable/reference/live.md b/.rovodev/skills/impeccable/reference/live.mdindex d3d4f5caa..77d77e9b9 100644--- a/.rovodev/skills/impeccable/reference/live.md+++ b/.rovodev/skills/impeccable/reference/live.md@@ -10,21 +10,24 @@ Execute in order. No step skipped, no step reordered.1. `live.mjs`: boot. If the request names or implies a file, route, or app inside a monorepo, infer the concrete path and run `node .rovodev/skills/impeccable/scripts/live.mjs --target <path>` instead; then run the rest of this live session from the returned `projectRoot`.2. Open the app URL that serves `pageFile` (infer from `package.json`, docs, terminal output, or an open tab). Never use `serverPort`; it's the helper, not the app. **Cursor:** `browser_navigate` to that URL before polling; do not skip. **Other harnesses:** use the available browser tool; if the URL is uncertain, ask the user once.-3. Poll loop with the default long timeout (600000 ms). After every event or `--reply`, run `live-poll.mjs` again immediately. Never pass a short `--timeout=`.+3. Poll loop with the default long timeout (600000 ms). Run `live-poll.mjs` again immediately after every event or `--reply`; Codex runs this one-shot poll in the foreground. Never pass a short `--timeout=`.The global bar **Impeccable mark** dims and shows a pulsing amber dot when no agent is long-polling `/poll`. Hover the mark for the hint; restart `live-poll.mjs` to reconnect.-4. On `generate`: read screenshot if present; load the action's reference; plan three distinct directions; write all variants in one edit; `--reply done`; poll again.+4. On `generate`: reuse `event.scaffold` when present; read the screenshot if present; load the action's reference; deliver variants using the delivery policy below; `--reply done`; poll again. Generate in this thread. You already hold the project's tokens, conventions, and file layout; that context is the job, not overhead.5. On `steer`: read the message and `pageUrl`; do the work (page edits, navigation help, or a short reply in the `--reply` message); `--reply steer_done`; poll again. No pickup ack. The Steer bar unlocks when `steer_done` arrives over SSE.-6. On `accept` / `discard`: the poll script runs `live-accept.mjs`, acknowledges the delivered event, and prints `_completionAck`. Plain accepts/discards are terminal immediately; carbonize accepts remain recoverable until you finish cleanup, run `live-complete.mjs --id EVENT_ID`, and only then poll again.+6. On `accept` / `discard`: the poll script runs `live-accept.mjs`, acknowledges the delivered event, and prints `_completionAck`. Plain accepts/discards are terminal immediately. Carbonize accepts remain recoverable until the foreground task runs `live-complete.mjs --id EVENT_ID`; finish that cleanup before polling again.7. If interrupted, run `live-status.mjs` or `live-resume.mjs` before guessing. The durable journal replays unacknowledged work after helper restart.8. On `exit`: run the cleanup at the bottom.Harness policy:-- **Claude Code**: run the poll as a **background task** (no short timeout). The harness notifies you when it completes, so the main conversation stays free. Do not block the shell.+- **Claude Code**: run the poll as a **background task** (no short timeout). The harness notifies you when it completes, so the main conversation stays free while you generate and publish in it. Do not block the shell.- **Cursor**: run **one-shot** poll in a **background terminal** with notify on `"type":"(steer|generate|accept|discard|exit)"`. After each event the poll exits; handle it, `--reply`, then start `live-poll.mjs` again. Do **not** use `--stream` on Cursor: incremental stdout notify is slower in practice than exit-based notify (~5s vs sub-second in testing).-- **Codex**: run the poll in the **foreground** (blocking shell; not a background task, not a subagent). Codex background exec sessions do not reliably surface poll stdout back into the conversation at the moment events arrive, so a "fire-and-forget" background poll will stall live mode.+- **Codex**: run the default one-shot poll in a **yielded foreground exec session**. Do not suffix it with `&`, use `--stream`, or leave Live without an active foreground poll. Handle every event in the main task; after each handler/reply, restart the foreground poll.- **Other harnesses**: one-shot foreground unless you know stdout reliably returns to this session when a shell exits.+Generation delivery policy:+- **Default (Cursor and other harnesses):** keep the established atomic single-edit delivery. Do not switch a harness to progressive until its poll loop is known not to block on the extra publish calls. This avoids trading model latency for extra tool-call latency on harnesses with different streaming behavior.+Chat is overhead. No recap, no tutorial output, no pasting PRODUCT / DESIGN bodies. Spend tokens on tools and edits; on failure, one or two short sentences.## Start@@ -92,14 +95,14 @@ Server restart rule: start `live-server.mjs` again, then poll. Startup requeues**Insert mode** (`event.mode === "insert"`): `{id, mode: "insert", count, pageUrl, insert: { position, anchor }, placeholder: { width, height }, freeformPrompt?, screenshotPath?, comments?, strokes?}`. No `action`. Requires a non-empty `freeformPrompt` **or** annotations. Screenshot is sent only when annotations exist (same rule as replace). Use `placeholder` dimensions as a soft size hint for net-new content.-Speed matters; the user is watching a spinner. Minimize tool calls by using the wrap/insert helper and writing all variants in a single edit.+Speed matters; the user is watching the selected element. Reuse server preflight metadata when available, minimize discovery calls, and follow the harness-specific delivery policy above.### Insert mode branchWhen `event.mode === "insert"`:1. Read the screenshot if `event.screenshotPath` is present (annotations only).-2. Run the insert helper instead of wrap:+2. If `event.scaffold` is present, use it as the insert-helper result and do **not** run the helper again. Otherwise run the insert helper instead of wrap:```bashnode .rovodev/skills/impeccable/scripts/live-insert.mjs --id EVENT_ID --count EVENT_COUNT --position after \@@ -109,7 +112,7 @@ node .rovodev/skills/impeccable/scripts/live-insert.mjs --id EVENT_ID --count EV- `--position` ← `event.insert.position` (`before` | `after`)- Anchor flags ← `event.insert.anchor` (same mapping as wrap: id, classes, tag, text)-The scaffold has **no** `data-impeccable-variant="original"`. Variants are net-new HTML+CSS inserted at `insertLine`. Load `brand.md` or `product.md` (freeform only, no action sub-command). Write all variants in one edit, then `--reply done`.+The scaffold has **no** `data-impeccable-variant="original"`. Variants are net-new HTML+CSS inserted at `insertLine`. Load `brand.md` or `product.md` (freeform only, no action sub-command). Deliver using the harness policy, then `--reply done`.For Svelte/SvelteKit targets, `live-insert.mjs` returns `previewMode: "svelte-component"` with `mode: "insert"`, `file` pointing at a temporary `node_modules/.impeccable-live/<id>/manifest.json`, `componentDir` pointing at the variant component files, and `sourceFile` pointing at the real `.svelte` route. Write each inserted variant as a real Svelte component (`v1.svelte`, `v2.svelte`, …) under `componentDir`. Insert variants must be non-empty net-new content with a single top-level root, no `data-impeccable-*` attributes, and CSS in each component's `<style>` block. Do **not** edit the route source during generation; the browser mounts the temporary component before/after the live anchor while the user cycles variants. On Accept, `live-accept.mjs` inserts the selected component markup into `sourceFile` immediately and deletes the temp session after the source write succeeds.@@ -134,6 +137,8 @@ Reading annotations precisely:### 2. Wrap the element+When `event.scaffold` is present, the local helper already found and wrapped the source before the poll returned. Treat `event.scaffold` as the successful helper output and skip this command entirely. `event.scaffoldAttempted` with `scaffoldError` means local preflight could not finish; use the command/fallback path below. This optimization removes a deterministic tool round trip without changing the generated design.+```bashnode .rovodev/skills/impeccable/scripts/live-wrap.mjs --id EVENT_ID --count EVENT_COUNT --element-id "ELEMENT_ID" --classes "class1,class2" --tag "div" --text "TEXT_SNIPPET"```@@ -153,7 +158,7 @@ Output on success: `{ file, insertLine, commentSyntax, styleMode, styleTag, cssSFor Svelte/SvelteKit targets, `live-wrap.mjs` returns `previewMode: "svelte-component"` with `file` pointing at a temporary `node_modules/.impeccable-live/<id>/manifest.json`, `componentDir` pointing at the variant component files, and `sourceFile` pointing at the real `.svelte` route. Write each variant as a real Svelte component (`v1.svelte`, `v2.svelte`, …) under `componentDir`; use the `propContract` prop names for dynamic text (`{propName}`), not literal snapshot strings. Put variant CSS in each component's `<style>` block with semantic class selectors (no `@scope`, no `data-impeccable-*`). Reply with `--file` set to the manifest path; the browser dynamically imports and mounts the compiled components so Svelte HMR does not reset page state while the user cycles variants. On Accept, `live-accept.mjs` inlines the accepted component back into `sourceFile` immediately after source promotion succeeds.-**Params on the Svelte component path go in a sidecar, never as an attribute.** Svelte parses `{` inside an attribute value as the start of an expression, so a `data-impeccable-params='[{…}]'` attribute on a component element fails to compile (`Expected token }`). Declare params for this path in `componentDir/params.json`, keyed by variant number, using the exact param schema from section 7:+**Params on component-preview paths go in a sidecar, never as an attribute.** Svelte parses `{` inside an attribute value as the start of an expression, and both Svelte/Vue previews mount without an HTML variant wrapper. Declare params in `componentDir/params.json`, keyed by variant number, using the exact param schema from section 7:```json{@@ -291,11 +296,13 @@ In **departure mode**, the prompt narrows the lanes you draw from, not the familWhen the prompt and PRODUCT.md anti-references conflict (the prompt asks for X, the anti-references ban X), the anti-references win; they describe the brand's standing position, the prompt is one moment.-### 6. Write all variants in a single edit+### 6. Deliver variantsComplete HTML replacement of the original element for each variant, not a CSS-only patch. Consider the element's context (computed styles, parent structure, CSS variables from `event.element`).-Write CSS + all variants in ONE edit at the `insertLine` reported by `wrap`. Colocate CSS as a `<style>` tag inside the variant wrapper; `<style>` works anywhere in modern browsers and this ensures CSS and HTML arrive atomically (no FOUC).+Colocate preview CSS as a `<style>` tag inside the variant wrapper; `<style>` works anywhere in modern browsers and keeps each delivered state internally complete (no FOUC).++**Atomic default:** write CSS + all variants + parameter manifests in one edit at `insertLine`, preserving the established behavior.Use the `cssAuthoring` object returned by `live-wrap.mjs` to author the temporary preview CSS. The style opening tag shown below is the common case; replace it with `cssAuthoring.styleTag` when the tool returns a different one. The variant markup shape is otherwise stable:@@ -319,7 +326,7 @@ Use the `cssAuthoring` object returned by `live-wrap.mjs` to author the temporarThe first variant has no `display: none` (visible by default). All others do. If variants use only inline styles and no preview CSS, omit the `<style>` tag entirely.-One edit, all variants; the browser's MutationObserver picks everything up in one pass.+The browser's MutationObserver accepts either delivery shape. On the transactional progressive path it shows arrived variants and pending dots immediately; Accept and Discard are available as soon as one variant exists. Accepting an arrived variant fences the worker before the browser releases the picker, so later publications are rejected.For `styleMode: "scoped"`, author every `:scope` rule with a descendant combinator. The `@scope` boundary is the **variant wrapper `<div data-impeccable-variant="N">`**, not the element you're designing. A bare `:scope { background: cream; }` styles the wrapper, not the inner replacement, so the cream lands on a `display: contents` shell while the actual element keeps page defaults. Always step in: `:scope > .card`, `:scope > section`, `:scope .hero-title`, etc. The fake test agent's CSS in `tests/live-e2e/agent.mjs` is a faithful template; every scoped rule starts `:scope > ...`.@@ -361,7 +368,7 @@ Each variant can expose **coarse** knobs alongside the full HTML/CSS replacement**Hard cap per variant**: at most **four** parameters so the panel stays legible; rare fifth only if the reference explicitly allows it.-**How to declare.** Put a JSON manifest on the variant wrapper (HTML/JSX path). **On the Svelte `svelte-component` path, do not use this attribute** (Svelte can't compile `{` inside an attribute value). Declare params in `componentDir/params.json` keyed by variant number instead (see the Svelte component paragraph in the wrap section). The param schema below is identical for both paths.+**How to declare.** Put a JSON manifest on the variant wrapper (HTML/JSX path). **On the `svelte-component` path, do not use this attribute.** Declare params in `componentDir/params.json` keyed by variant number instead (see the component-preview paragraphs in the wrap section). The param schema below is identical for every path.```html<div data-impeccable-variant="1" data-impeccable-params='[@@ -462,15 +469,19 @@ Event: `{id, variantId, _acceptResult, _completionAck}`. The poll script already- The accept event includes `pageUrl`; the poll script must forward it to `live-accept.mjs --page-url PAGE_URL` so accept-time cleanup only scrubs staged copy edits for the current page.- `_completionAck.ok !== true`: do not poll yet. Run `live-status.mjs` / `live-resume.mjs`, complete the cleanup manually if needed, then run `live-complete.mjs --id EVENT_ID`.- `_acceptResult.handled: true` and `carbonize: false`: nothing to do. Poll again.-- `_acceptResult.handled: true` and `carbonize: true`: **post-accept cleanup is required before the next poll.** See the "Required after accept (carbonize)" section below. The `event._acceptResult.todo` field, `_completionAck.requiresComplete`, and a stderr banner all point at this required follow-up; none are decorative. After cleanup, run `live-complete.mjs --id EVENT_ID`, then poll again.+- `_acceptResult.handled: true` and `carbonize: true`: post-accept cleanup is required, but it must not stall Codex's control lane. See "Required after accept (carbonize)" below. The `event._acceptResult.todo` field, `_completionAck.requiresComplete`, and stderr banner all point at this required follow-up; none are decorative.- `_acceptResult.handled: false, mode: "fallback"`: the session lived in a generated file and the script refused to persist there. You've already written the accepted variant into true source during Handle fallback Step 3; just clean up the temporary wrapper in the served file if any, and poll again.+- `_acceptResult.handled: false, mode: "error"`: the operation genuinely failed. **Do not hand-edit the file**; the source was not touched and editing it yourself would either double-apply or race whoever holds it.+ - `error: "source_locked"`: a generation publish holds the file. Run the same `live-accept.mjs` command again; it is idempotent and will succeed once the publisher releases. Do not poll past it.+ - `error: "accept_receipt_conflict"`: this session already resolved as `priorOperation` (on `priorVariantId` for an accept), so the request contradicts durable truth. Do not edit. Run `live-status.mjs` and tell the user what the session actually resolved to.+ - anything else: report the error briefly and run `live-status.mjs` before continuing.- `_acceptResult.handled: false` without `mode`: manual cleanup: read file, find markers, edit.### Required after accept (carbonize)When `_acceptResult.carbonize === true`, the accepted variant was stitched into source with helper markers and inline CSS so the browser can render it immediately with no visual gap. That stitch-in is **temporary**. The agent must rewrite it into permanent form before doing anything else. Skipping this leaves dead `@scope` rules for unaccepted variants, a pointless `data-impeccable-variant` wrapper, and `impeccable-carbonize-start/end` comment noise in the source file; all of which accumulate across sessions.-Do these five steps in the current thread, synchronously, before the next poll. Do not poll again until the file is clean.+Do these five steps synchronously before the next poll. The source lock, generation epoch, and expected-source hash remain the final safety gates against a generator finishing concurrently with Accept.1. **Locate the carbonize block** in the source file (`_acceptResult.file`). It's bracketed by `<!-- impeccable-carbonize-start SESSION_ID -->` and `<!-- impeccable-carbonize-end SESSION_ID -->` and contains a `<style data-impeccable-css="SESSION_ID">` element. If the variant declared parameters, an `<!-- impeccable-param-values SESSION_ID: {...} -->` comment sits alongside the style tag with the user's chosen values; read it first; it drives steps 3 and 4 below.2. **Move the CSS rules** into the project's real stylesheet. Which stylesheet depends on the project (e.g. `site/styles/workflow.css` for an Astro project, or the component's co-located CSS file for a Vite/Next project; pick whichever already owns styling for the surrounding element).@@ -478,9 +489,7 @@ Do these five steps in the current thread, synchronously, before the next poll.4. **Unwrap the accepted content.** Delete the inner `<div data-impeccable-variant="N" style="display: contents">` that wraps it. On JSX/TSX, also delete the outer `<div data-impeccable-carbonize="SESSION_ID" style={{ display: 'contents' }}>` wrapper if present (accept adds it so ternary/`return` slots keep a single root). Drop `data-impeccable-params` and any `data-p-*` attributes; those are live-mode plumbing, not source.5. **Delete the inline `<style>` block, the `<!-- impeccable-param-values -->` comment if present, and both `<!-- impeccable-carbonize-start/end -->` markers.** Also drop any `@scope` rules for variants other than the accepted one; those are dead code now.-After the file is clean, run `live-complete.mjs --id SESSION_ID`, verify it reports `phase: "completed"`, then poll again.--A background agent may be used for the rewrite, but the current thread is responsible for verifying the five steps are complete before issuing the next poll. In practice, inline is usually faster and less error-prone.+After the file is clean, the cleanup owner runs `live-complete.mjs --id SESSION_ID` and verifies `phase: "completed"`. Poll again only after that verification.## Handle `discard`diff --git a/.rovodev/skills/impeccable/scripts/lib/impeccable-paths.mjs b/.rovodev/skills/impeccable/scripts/lib/impeccable-paths.mjsindex 2ccbe7b74..99956c0f3 100644--- a/.rovodev/skills/impeccable/scripts/lib/impeccable-paths.mjs+++ b/.rovodev/skills/impeccable/scripts/lib/impeccable-paths.mjs@@ -104,6 +104,20 @@ export function removeLiveServerInfo(cwd = process.cwd(), options = {}) {}}+/**+ * Session IDs become path segments (journals, snapshots, accept receipts,+ * preview manifests, generated component dirs). They arrive from CLI `--id`+ * arguments and HTTP payloads, so anything containing a separator or `..` must+ * be rejected before it reaches path.join, which would happily escape+ * `.impeccable/live/`. Real IDs are 8 hex chars; the tests use short slugs.+ */+export function safeSessionId(id) {+ if (typeof id !== 'string' || !/^[A-Za-z0-9_-]{1,128}$/.test(id)) {+ throw new Error('invalid session id: ' + id);+ }+ return id;+}+export function getLiveSessionsDir(cwd = process.cwd(), options = {}) {return path.join(getLiveDir(cwd, options), 'sessions');}diff --git a/.rovodev/skills/impeccable/scripts/live-accept.mjs b/.rovodev/skills/impeccable/scripts/live-accept.mjsindex 278dfbb2e..453ddea35 100644--- a/.rovodev/skills/impeccable/scripts/live-accept.mjs+++ b/.rovodev/skills/impeccable/scripts/live-accept.mjs@@ -16,7 +16,9 @@import fs from 'node:fs';import path from 'node:path';import { isGeneratedFile } from './lib/is-generated.mjs';+import { IMPECCABLE_DIR, getLiveDir, safeSessionId } from './lib/impeccable-paths.mjs';import { readBuffer as readManualEditsBuffer, writeBuffer as writeManualEditsBuffer } from './live/manual-edits-buffer.mjs';+import { withSourceLockSync } from './live/source-lock.mjs';import {applyDeferredSvelteComponentAccepts,findSvelteComponentManifest,@@ -25,6 +27,46 @@ import {} from './live/svelte-component.mjs';const EXTENSIONS = ['.html', '.jsx', '.tsx', '.vue', '.svelte', '.astro'];+const ACCEPT_LOCK_WAIT_MS = 1_000;+// Mirrors VARIANT_ID_PATTERN in live/event-validation.mjs, which gates the same+// value arriving over HTTP.+const VARIANT_NUM_PATTERN = /^[0-9]{1,3}$/;++/**+ * A thrown accept/discard is a real failure, not a manual handoff.+ *+ * live/completion.mjs only classifies a result as `error` when it carries+ * `mode: 'error'`; anything else unhandled falls through to `agent_done` with a+ * successful ack, and reference/live.md then tells the agent to finish the edit+ * by hand. That is right for the documented fallback paths and wrong here: a+ * `source_locked` contention needs a retry (hand-editing races the publisher+ * holding the lock), and a crash needs surfacing, not a hand-applied guess.+ */+function operationFailure(err, extra = {}) {+ return { handled: false, mode: 'error', error: err.message, ...extra };+}++/**+ * Mark an unhandled preview-path result as a real failure.+ *+ * operationFailure only covers results built from a *thrown* error. The accept+ * implementations also return `{handled: false, error}` for their own checks+ * (variant missing, template empty, original text ambiguous), and those arrived+ * without `mode`, so completion.mjs classified them as agent_done and+ * reference/live.md routed the agent to "read file, find markers, edit".+ *+ * That handoff only makes sense for a plain wrapper session, which is the one+ * shape with markers in the user's source to edit. Component and isolated+ * artifact previews keep the source clean until Accept, so there is nothing to+ * hand-edit and an unhandled result is always a failure. `previewMode` is+ * exactly that discriminator: only the preview branches set it.+ */+function markPreviewFailure(result) {+ if (result?.handled === false && !result.mode && result.previewMode) {+ return { ...result, mode: 'error' };+ }+ return result;+}// ---------------------------------------------------------------------------// CLI@@ -63,7 +105,52 @@ Output (JSON):const isDiscard = args.includes('--discard');if (!id) { console.error('Missing --id'); process.exit(1); }+ // `id` becomes a path segment (accept receipts, preview manifests, generated+ // component dirs). Reject separators and traversal here so one check covers+ // every downstream sink.+ try { safeSessionId(id); } catch { console.error('Invalid --id'); process.exit(1); }if (!isDiscard && !variantNum) { console.error('Need --discard or --variant N'); process.exit(1); }+ // `variantNum` is interpolated into a RegExp and into the markup written back+ // to source. The browser and the /events schema both constrain it to digits;+ // enforce the same here, or `--variant '.*'` matches the `original` block+ // first and silently accepts the original while reporting success.+ if (!isDiscard && !VARIANT_NUM_PATTERN.test(variantNum)) {+ console.error('Invalid --variant');+ process.exit(1);+ }++ const requestedOperation = isDiscard ? 'discard' : 'accept';+ const priorReceipt = readAcceptReceipt(process.cwd(), id);+ if (priorReceipt) {+ const sameOperation = priorReceipt.operation === requestedOperation+ && (isDiscard || String(priorReceipt.variantId) === String(variantNum));+ console.log(JSON.stringify(sameOperation+ ? { ...priorReceipt.result, handled: true, alreadyApplied: true }+ : {+ // mode: 'error' is what marks this a real failure rather than a manual+ // handoff. Without it, live/completion.mjs classifies the reply as+ // agent_done and reference/live.md tells the agent to "read file, find+ // markers, edit" by hand — which would apply a second, conflicting+ // accept on top of the one the receipt already recorded.+ handled: false,+ mode: 'error',+ error: 'accept_receipt_conflict',+ priorOperation: priorReceipt.operation,+ priorVariantId: priorReceipt.variantId ?? null,+ }));+ return;+ }+ const emitResult = (rawResult) => {+ const result = markPreviewFailure(rawResult);+ if (result?.handled !== false) {+ writeAcceptReceipt(process.cwd(), id, {+ operation: requestedOperation,+ variantId: isDiscard ? null : String(variantNum),+ result,+ });+ }+ console.log(JSON.stringify(result));+ };let paramValues = null;if (paramValuesRaw) {@@ -82,39 +169,55 @@ Output (JSON):if (svelteComponentManifest) {if (isDiscard) {- removeSvelteComponentSession(id, process.cwd());- console.log(JSON.stringify({- handled: true,+ let result;+ try {+ result = withSourceLockSync(+ path.resolve(process.cwd(), svelteComponentManifest.sourceFile),+ 'discard:' + id,+ () => {+ removeSvelteComponentSession(id, process.cwd());+ return { handled: true };+ },+ { waitMs: ACCEPT_LOCK_WAIT_MS },+ );+ } catch (err) {+ result = operationFailure(err);+ }+ emitResult({+ ...result,file: svelteComponentManifest.sourceFile,carbonize: false,previewMode: 'svelte-component',componentDir: svelteComponentManifest.componentDir,- }));+ });return;}let result;try {- result = inlineSvelteComponentAccept(- svelteComponentManifest,- variantNum,- paramValues,- process.cwd(),+ result = withSourceLockSync(+ path.resolve(process.cwd(), svelteComponentManifest.sourceFile),+ 'accept:' + id,+ () => inlineSvelteComponentAccept(+ svelteComponentManifest,+ variantNum,+ paramValues,+ process.cwd(),+ ),+ { waitMs: ACCEPT_LOCK_WAIT_MS },);} catch (err) {- result = {- handled: false,- error: err.message,+ result = operationFailure(err, {file: svelteComponentManifest.sourceFile,sourceFile: svelteComponentManifest.sourceFile,previewMode: 'svelte-component',componentDir: svelteComponentManifest.componentDir,- };+ });}if (result.carbonize) {result.todo = 'REQUIRED before next poll: carbonize cleanup in ' + result.file + '. See reference/live.md "Required after accept".';}- console.log(JSON.stringify({ handled: result.handled !== false, ...result }));+ emitResult({ handled: result.handled !== false, ...result });return;}@@ -145,10 +248,25 @@ Output (JSON):}if (isDiscard) {- const result = handleDiscard(id, lines, targetFile);- console.log(JSON.stringify({ handled: true, file: relFile, carbonize: false, ...result }));+ let result;+ // handleDiscard takes the source lock, which throws SOURCE_LOCKED under+ // contention. Without this catch the CLI exits non-zero with empty stdout+ // and the agent gets no JSON to act on.+ try {+ result = handleDiscard(id, lines, targetFile);+ } catch (err) {+ emitResult(operationFailure(err, { file: relFile }));+ return;+ }+ emitResult({ handled: true, file: relFile, carbonize: false, ...result });} else {- const result = handleAccept(id, variantNum, lines, targetFile, paramValues);+ let result;+ try {+ result = handleAccept(id, variantNum, lines, targetFile, paramValues);+ } catch (err) {+ emitResult(operationFailure(err, { file: relFile }));+ return;+ }const acceptedOriginalText = result.acceptedOriginalText || '';delete result.acceptedOriginalText;// Single-line attention-grabber when cleanup is required. The full@@ -167,7 +285,7 @@ Output (JSON):// Non-fatal; the buffer stays as-is and the user can discard later.}}- console.log(JSON.stringify({ handled: true, file: relFile, ...result }));+ emitResult({ handled: true, file: relFile, ...result });}}@@ -235,7 +353,14 @@ function scrubManualEditsAgainstFile(_targetFile, cwd = process.cwd(), originalB// Discard// ----------------------------------------------------------------------------function handleDiscard(id, lines, targetFile) {+function handleDiscard(id, _lines, targetFile) {+ return withSourceLockSync(targetFile, 'discard:' + id, () => {+ const lines = fs.readFileSync(targetFile, 'utf-8').split('\n');+ return handleDiscardUnlocked(id, lines, targetFile);+ }, { waitMs: ACCEPT_LOCK_WAIT_MS });+}++function handleDiscardUnlocked(id, lines, targetFile) {const block = findMarkerBlock(id, lines);if (!block) return { handled: false, error: 'Markers not found' };@@ -330,7 +455,24 @@ function reindentContent(contentLines, fromIndent, toIndent) {});}-function handleAccept(id, variantNum, lines, targetFile, paramValues) {+function handleAccept(id, variantNum, _lines, targetFile, paramValues) {+ return withSourceLockSync(targetFile, 'accept:' + id, () => {+ const lines = fs.readFileSync(targetFile, 'utf-8').split('\n');+ return handleAcceptUnlocked(id, variantNum, lines, targetFile, paramValues);+ }, { waitMs: ACCEPT_LOCK_WAIT_MS });+}++function handleAcceptUnlocked(id, variantNum, lines, targetFile, paramValues) {+ const built = buildAcceptedWrappedSource(id, variantNum, lines, targetFile, paramValues);+ if (built.handled === false) return built;+ fs.writeFileSync(targetFile, built.content, 'utf-8');+ return {+ carbonize: built.carbonize,+ acceptedOriginalText: built.acceptedOriginalText,+ };+}++function buildAcceptedWrappedSource(id, variantNum, lines, targetFile, paramValues) {const block = findMarkerBlock(id, lines);if (!block) return { handled: false, error: 'Markers not found' };@@ -375,11 +517,14 @@ function handleAccept(id, variantNum, lines, targetFile, paramValues) {...replacement,...lines.slice(replaceRange.end + 1),];- fs.writeFileSync(targetFile, newLines.join('\n'), 'utf-8');-- return { carbonize: needsCarbonize, acceptedOriginalText: originalContent.join('\n') };+ return {+ content: newLines.join('\n'),+ carbonize: needsCarbonize,+ acceptedOriginalText: originalContent.join('\n'),+ };}+function readSourceShadowPreviewMeta(content, id) {const escaped = escapeRegExp(id);const wrapperRe = new RegExp('<[^>]+data-impeccable-variants=(["\'])' + escaped + '\\1[^>]*>');@@ -746,6 +891,21 @@ function detectCommentSyntax(filePath) {// File search (find the file containing session markers)// ---------------------------------------------------------------------------+/**+ * `.impeccable` is the critical entry, and it is not cosmetic.+ *+ * Progressive publication stages each revision as `.impeccable/live/artifacts/+ * <id>-r<n>.<source-ext>`, and those artifacts carry the very marker this search+ * looks for. The walk reaches `.` for any project whose source is not under one+ * of the privileged dirs above (this repo's own site lives in `site/pages/`), and+ * dot-directories sort before letters, so the artifact was found *before* the+ * real file. isGeneratedFile then declined the accept, and the agent fell back to+ * carbonizing several hundred lines of stylesheet by hand.+ *+ * Impeccable's own state directory is never project source. Never search it.+ */+const SEARCH_SKIP_DIRS = new Set(['node_modules', '.git', 'dist', 'build', IMPECCABLE_DIR]);+function findSessionFile(id, cwd) {const marker = 'impeccable-variants-start ' + id;const searchDirs = ['src', 'app', 'pages', 'components', 'public', 'views', 'templates', '.'];@@ -786,7 +946,7 @@ function searchDir(dir, query, seen, depth) {for (const entry of entries) {if (!entry.isDirectory()) continue;- if (['node_modules', '.git', 'dist', 'build'].includes(entry.name)) continue;+ if (SEARCH_SKIP_DIRS.has(entry.name)) continue;const result = searchDir(path.join(dir, entry.name), query, seen, depth + 1);if (result) return result;}@@ -798,6 +958,28 @@ function searchDir(dir, query, seen, depth) {// Utilities// ---------------------------------------------------------------------------+function acceptReceiptPath(cwd, id) {+ return path.join(getLiveDir(cwd), 'accept-receipts', `${safeSessionId(id)}.json`);+}++function readAcceptReceipt(cwd, id) {+ try { return JSON.parse(fs.readFileSync(acceptReceiptPath(cwd, id), 'utf-8')); } catch { return null; }+}++function writeAcceptReceipt(cwd, id, receipt) {+ const file = acceptReceiptPath(cwd, id);+ fs.mkdirSync(path.dirname(file), { recursive: true });+ const value = {+ id,+ ...receipt,+ completedAt: new Date().toISOString(),+ };+ const temporary = `${file}.${process.pid}.${Date.now()}.tmp`;+ fs.writeFileSync(temporary, JSON.stringify(value, null, 2) + '\n', 'utf-8');+ fs.renameSync(temporary, file);+ return value;+}+function argVal(args, flag) {const idx = args.indexOf(flag);return idx !== -1 && idx + 1 < args.length ? args[idx + 1] : null;diff --git a/.rovodev/skills/impeccable/scripts/live-browser.js b/.rovodev/skills/impeccable/scripts/live-browser.jsindex 616f1290a..20d875b93 100644--- a/.rovodev/skills/impeccable/scripts/live-browser.js+++ b/.rovodev/skills/impeccable/scripts/live-browser.js@@ -126,6 +126,9 @@let expectedVariants = 0;let arrivedVariants = 0;let visibleVariant = 0;+ let generationPhase = null;+ let parameterGenerationState = 'idle';+ let parameterReadyAnnouncedSession = null;let svelteComponentSession = null;let svelteRuntimePromise = null;let pendingSvelteComponentRetryObserver = null;@@ -134,6 +137,7 @@let currentPreviewMode = null;let recoveryWaitingForAnchor = false;let pickedAnchorSnapshot = null;+ let pickedAnchorViewportTop = null;let pendingVariantAnchorRetryObserver = null;let pendingAcceptedSession = null;let variantObserver = null;@@ -151,10 +155,12 @@// startScrollLock / stopScrollLock below.let scrollLockObserver = null;let scrollLockTargetY = null;+ let scrollLockAnchorTop = null;let scrollLockRaf = null;let scrollLockAbort = null;const SCROLL_ANCHOR_LOCK_ID = 'impeccable-scroll-anchor-lock';const VARIANT_STATE_STYLE_ID = 'impeccable-variant-state';+ const DISCARD_STATE_STYLE_ID = 'impeccable-discard-state';// Dedicated key for scroll position - SEPARATE from LS_KEY so that// saveSession's state updates don't clobber a carefully-captured scrollY.@@ -252,6 +258,13 @@barConnected: !!barEl?.isConnected,hasSvelteComponentSession: !!svelteComponentSession,mountedSvelteVariant: svelteComponentSession?.mountedVariant || 0,+ pickActive,+ pendingApplyInFlight,+ hoveredElement: hoveredElement ? {+ tag: hoveredElement.tagName,+ classes: hoveredElement.className,+ pickable: pickable(hoveredElement),+ } : null,pendingSvelteComponentRetry: !!pendingSvelteComponentRetryObserver,recoveryWaitingForAnchor,evtSourceReadyState: evtSource ? evtSource.readyState : null,@@ -1114,14 +1127,15 @@});}- function hideBar() {+ function hideBar(instant) {if (!barEl) return;const hideSeq = ++barHideSeq;stopVoice({ suppressSubmit: true });if (configureKind === 'insert') clearInsertPicking();barEl.style.opacity = '0';- barEl.style.transform = 'translateY(6px)';- setTimeout(() => { if (barEl && hideSeq === barHideSeq) barEl.style.display = 'none'; }, 250);+ barEl.style.transform = instant ? 'translateY(0)' : 'translateY(6px)';+ if (instant) barEl.style.display = 'none';+ else setTimeout(() => { if (barEl && hideSeq === barHideSeq) barEl.style.display = 'none'; }, 250);hideActionPicker();closeTunePopover();hideConfigureBarTooltip();@@ -1966,6 +1980,7 @@*/function setLiveState(next) {state = next;+ window.__IMPECCABLE_LIVE_STATE__ = next;syncPageInteractionCursor();}@@ -2516,18 +2531,27 @@fontSize: '11px', color: BP.textDim, whiteSpace: 'nowrap',marginLeft: 'auto',});- // Variants currently arrive atomically in a single file edit, so a- // per-variant counter would lie. Say what's true.status.textContent = recoveryWaitingForAnchor? 'Variants ready. Reveal the selected element to resume.'- : (arrivedVariants < expectedVariants- ? 'Generating ' + expectedVariants + ' variants...'- : 'Done');+ : generationStatusText();row.appendChild(status);return row;}+ function generationStatusText() {+ if (arrivedVariants >= expectedVariants && expectedVariants > 0) return 'Done';+ if (generationPhase === 'picked_up') return 'Agent picked up the request...';+ if (generationPhase === 'scaffolding') return 'Finding the source...';+ if (generationPhase === 'source_ready') return 'Source ready. Generating...';+ if (generationPhase === 'scaffold_fallback') return 'Agent is locating the source...';+ if (generationPhase === 'first_variant_generating') return 'Designing the first variant...';+ if (generationPhase === 'first_variant_validating') return 'Checking the first variant...';+ if (generationPhase === 'remaining_variants_generating') return 'Exploring two more directions...';+ if (generationPhase === 'remaining_variants_validating') return 'Checking the remaining variants...';+ return 'Generating ' + expectedVariants + ' variants...';+ }+// Cycling rowconst TUNE_ICON_SVG = '<svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" style="flex-shrink:0"><line x1="4" y1="8" x2="20" y2="8"/><circle cx="14" cy="8" r="2.4" fill="currentColor" stroke="none"/><line x1="4" y1="16" x2="20" y2="16"/><circle cx="10" cy="16" r="2.4" fill="currentColor" stroke="none"/></svg>';@@ -2557,7 +2581,7 @@color: BP.textDim, minWidth: '24px', textAlign: 'center',});counter.id = PREFIX + '-variant-counter';- counter.textContent = visibleVariant + '/' + arrivedVariants;+ counter.textContent = visibleVariant + '/' + expectedVariants;row.appendChild(counter);// Next@@ -2567,10 +2591,12 @@if (visibleVariant >= arrivedVariants) next.style.opacity = '0.3';row.appendChild(next);- // Tune chip - only when the visible variant exposes params+ // Tune chip stays visible while the deferred parameter phase is running,+ // then becomes interactive as soon as this variant exposes controls.const visParams = parseVariantParams(getVisibleVariantEl());const hasParams = visParams.length > 0;- if (hasParams) {+ const paramsPending = !hasParams && (parameterGenerationState === 'pending' || parameterGenerationState === 'loading');+ if (hasParams || paramsPending) {const tune = el('button', {display: 'inline-flex', alignItems: 'center', gap: '6px',padding: '4px 10px', borderRadius: '5px',@@ -2578,35 +2604,54 @@background: tuneOpen ? BP.accentSoft : 'transparent',color: tuneOpen ? BP.accent : BP.text,fontFamily: FONT, fontSize: '11px', fontWeight: '500',- cursor: 'pointer',+ cursor: paramsPending ? 'wait' : 'pointer',transition: 'color 0.12s ease, background 0.12s ease',whiteSpace: 'nowrap',});- tune.innerHTML = TUNE_ICON_SVG;+ if (paramsPending) {+ const spinner = el('span', {+ width: '11px', height: '11px', borderRadius: '50%',+ border: '1.5px solid ' + BP.hairline,+ borderTopColor: BP.accent,+ animation: 'impeccable-spin 0.6s linear infinite',+ boxSizing: 'border-box', flexShrink: '0',+ });+ spinner.setAttribute('aria-hidden', 'true');+ tune.appendChild(spinner);+ } else {+ tune.innerHTML = TUNE_ICON_SVG;+ }const tuneLabel = document.createElement('span');tuneLabel.textContent = 'Tune';tune.appendChild(tuneLabel);- const tuneBadge = document.createElement('span');- Object.assign(tuneBadge.style, {- display: 'inline-flex', alignItems: 'center', justifyContent: 'center',- minWidth: '16px', height: '16px', padding: '0 4px',- borderRadius: '999px',- background: tuneOpen ? C.brand : BP.hairline,- color: tuneOpen ? 'oklch(98% 0 0)' : 'inherit',- fontFamily: MONO, fontSize: '9.5px', fontWeight: '600',- lineHeight: '1',- boxSizing: 'border-box',- });- tuneBadge.textContent = String(visParams.length);- tune.appendChild(tuneBadge);- tune.title = 'Tune this variant (' + visParams.length + ' knob' + (visParams.length === 1 ? '' : 's') + ')';- tune.addEventListener('mouseenter', () => {- if (!tuneOpen) tune.style.background = BP.accentSoft;- });- tune.addEventListener('mouseleave', () => {- if (!tuneOpen) tune.style.background = 'transparent';- });- tune.addEventListener('click', (e) => { e.stopPropagation(); toggleTunePopover(); });+ if (hasParams) {+ const tuneBadge = document.createElement('span');+ Object.assign(tuneBadge.style, {+ display: 'inline-flex', alignItems: 'center', justifyContent: 'center',+ minWidth: '16px', height: '16px', padding: '0 4px',+ borderRadius: '999px',+ background: tuneOpen ? C.brand : BP.hairline,+ color: tuneOpen ? 'oklch(98% 0 0)' : 'inherit',+ fontFamily: MONO, fontSize: '9.5px', fontWeight: '600',+ lineHeight: '1',+ boxSizing: 'border-box',+ });+ tuneBadge.textContent = String(visParams.length);+ tune.appendChild(tuneBadge);+ tune.title = 'Tune this variant (' + visParams.length + ' knob' + (visParams.length === 1 ? '' : 's') + ')';+ tune.addEventListener('mouseenter', () => {+ if (!tuneOpen) tune.style.background = BP.accentSoft;+ });+ tune.addEventListener('mouseleave', () => {+ if (!tuneOpen) tune.style.background = 'transparent';+ });+ tune.addEventListener('click', (e) => { e.stopPropagation(); toggleTunePopover(); });+ } else {+ tune.disabled = true;+ tune.setAttribute('aria-label', 'Tune controls are still being prepared');+ tune.title = 'Tune controls are still being prepared';+ tune.style.opacity = '0.72';+ }tune.dataset.iceqTune = '1';row.appendChild(tune);}@@ -2614,6 +2659,15 @@// Spacerrow.appendChild(el('div', { flex: '1' }));+ if (arrivedVariants < expectedVariants) {+ const remaining = expectedVariants - arrivedVariants;+ const progress = el('span', {+ fontSize: '11px', color: BP.textDim, whiteSpace: 'nowrap',+ });+ progress.textContent = remaining + ' more arriving...';+ row.appendChild(progress);+ }+// Accept - primary action, kinpaku gold + lacquer-deep (matches demo .live-demo-ctx-accept)const accept = el('button', {padding: '5px 14px', borderRadius: '5px',@@ -2628,7 +2682,11 @@accept.addEventListener('mousedown', () => accept.style.transform = 'scale(0.97)');accept.addEventListener('mouseup', () => accept.style.transform = 'scale(1)');accept.addEventListener('click', (e) => { e.stopPropagation(); handleAccept(); });- if (arrivedVariants === 0) { accept.style.opacity = '0.3'; accept.style.pointerEvents = 'none'; }+ if (arrivedVariants === 0) {+ accept.style.opacity = '0.3';+ accept.style.pointerEvents = 'none';+ accept.title = 'Accept becomes available when the first variant arrives';+ }row.appendChild(accept);// Discard@@ -4743,6 +4801,32 @@}}+ function mountedParameterCount() {+ if (svelteComponentSession?.sessionId === currentSessionId) {+ return Object.values(svelteComponentSession.paramsByVariant || {})+ .reduce((total, params) => total + (Array.isArray(params) ? params.length : 0), 0);+ }+ const wrapper = document.querySelector('[data-impeccable-variants="' + currentSessionId + '"]');+ if (!wrapper) return 0;+ return [...wrapper.querySelectorAll('[data-impeccable-variant]:not([data-impeccable-variant="original"])')]+ .reduce((total, variant) => total + parseVariantParams(variant).length, 0);+ }++ function completeParameterPublication() {+ if (!currentSessionId) return;+ const ready = mountedParameterCount() > 0;+ parameterGenerationState = ready ? 'ready' : 'none';+ if (ready && parameterReadyAnnouncedSession !== currentSessionId) {+ parameterReadyAnnouncedSession = currentSessionId;+ showToast('Tune controls are ready.', 3000);+ }+ if (state === 'CYCLING') {+ refreshParamsPanel();+ showOrUpdateCyclingBar();+ }+ saveSession();+ }+function toggleTunePopover() {if (pendingApplyInFlight) { showManualApplyBusyToast(); return; }if (tuneOpen) { closeTunePopover(); return; }@@ -4835,6 +4919,10 @@return String(filePath || '').endsWith('manifest.json');}+ function isFrameworkComponentPreviewMode(mode) {+ return mode === 'svelte-component';+ }+function parseOriginalMarkupElement(originalMarkup) {const parser = new DOMParser();const doc = parser.parseFromString('<div id="impeccable-anchor">' + originalMarkup + '</div>', 'text/html');@@ -5029,9 +5117,13 @@}}- function loadSvelteRuntime(runtimeModule) {+ function resolveComponentModuleUrl(manifest, modulePath) {+ return new URL(String(modulePath || ''), location.origin).href;+ }++ function loadSvelteRuntime(runtimeModule, manifest) {const modulePath = runtimeModule || '/src/lib/impeccable/__runtime.js';- const url = new URL(modulePath, location.origin).href;+ const url = resolveComponentModuleUrl(manifest, modulePath);if (!svelteRuntimePromise) {svelteRuntimePromise = import(/* @vite-ignore */ url);}@@ -5065,7 +5157,8 @@async function loadSvelteComponentVariantSource(manifest, variantNum) {const dir = String(manifest?.componentDir || '').replace(/^\/+/, '');if (!dir || !variantNum) return '';- const sourcePath = dir + '/v' + variantNum + '.svelte';+ const extension = manifest.componentExtension || 'svelte';+ const sourcePath = dir + '/v' + variantNum + '.' + extension;const url = 'http://localhost:' + PORT + '/source?token=' + TOKEN + '&path=' + encodeURIComponent(sourcePath);try {const res = await fetch(url);@@ -5221,7 +5314,7 @@if (!sourceOriginal) return values;const map = buildSvelteExpressionTextMap(sourceOriginal, liveEl);for (const entry of contract) {- const token = '{' + entry.expr + '}';+ const token = entry.previewToken || ('{' + entry.expr + '}');values[entry.prop] = map.get(token) || '';}return values;@@ -5233,9 +5326,12 @@try {const previousAnchor = getMountedSvelteComponentAnchor(svelteComponentSession) || selectedElement;svelteComponentSession.swapAnchor = makeFrozenAnchor(previousAnchor) || svelteComponentSession.swapAnchor || null;- const runtime = await loadSvelteRuntime(manifest.runtimeModule);- const modulePath = '/' + String(manifest.componentDir || '').replace(/^\/+/, '') + '/v' + variantNum + '.svelte';- const moduleUrl = new URL(modulePath, location.origin).href + '?t=' + Date.now();+ const runtime = await loadSvelteRuntime(manifest.runtimeModule, manifest);+ const extension = manifest.componentExtension || 'svelte';+ const moduleBase = manifest.componentModuleBase+ || ('/' + String(manifest.componentDir || '').replace(/^\/+/, ''));+ const modulePath = String(moduleBase).replace(/\/+$/, '') + '/v' + variantNum + '.' + extension;+ const moduleUrl = resolveComponentModuleUrl(manifest, modulePath) + '?t=' + Date.now();const mod = await import(/* @vite-ignore */ moduleUrl);const Component = mod.default;if (svelteComponentSession.mountedInstance && runtime.unmount) {@@ -5275,7 +5371,7 @@if (svelteComponentSession?.sessionId === sessionId) {svelteComponentSession.swapAnchor = null;}- console.error('[impeccable] Failed to mount Svelte variant ' + variantNum + ' for ' + sessionId + ':', err);+ console.error('[impeccable] Failed to mount component variant ' + variantNum + ' for ' + sessionId + ':', err);return false;}}@@ -5340,40 +5436,46 @@if (manifest.id !== sessionId) return;const paramsByVariant = await loadSvelteComponentParams(manifest);+ const availableVariants = Number(manifest.arrivedVariants) || Number(manifest.count) || 1;+ const componentPreviewMode = isFrameworkComponentPreviewMode(manifest.previewMode)+ ? manifest.previewMode+ : 'svelte-component';currentSessionId = sessionId;expectedVariants = Number(manifest.count) || expectedVariants || 1;rememberSessionFileMeta({sourceFile: manifest.sourceFile,previewFile: manifestPath,- previewMode: 'svelte-component',+ previewMode: componentPreviewMode,});if (state !== 'CYCLING') setLiveState('GENERATING');const existingWrapper = document.querySelector('[data-impeccable-variants="' + sessionId + '"]');if (existingWrapper && svelteComponentSession?.sessionId === sessionId) {recoveryWaitingForAnchor = false;+ svelteComponentSession.manifest = manifest;svelteComponentSession.paramsByVariant = paramsByVariant;- arrivedVariants = Number(manifest.count) || expectedVariants || 1;- expectedVariants = arrivedVariants;+ arrivedVariants = availableVariants;+ expectedVariants = Number(manifest.count) || expectedVariants || arrivedVariants;visibleVariant = visibleVariant > 0 && visibleVariant <= arrivedVariants ? visibleVariant : 1;await mountSvelteComponentVariant(visibleVariant || 1);setLiveState('CYCLING');showOrUpdateCyclingBar();saveSession();+ if (parameterGenerationState === 'loading') completeParameterPublication();return;}const liveEl = findLiveElementForSvelteManifest(manifest);if (!liveEl?.parentElement) {console.warn('[impeccable] Could not find original element in live DOM.');- arrivedVariants = Number(manifest.count) || expectedVariants || 1;- expectedVariants = arrivedVariants;+ arrivedVariants = availableVariants;+ expectedVariants = Number(manifest.count) || expectedVariants || arrivedVariants;const saved = loadSession();const savedVisibleVariant = saved && saved.id === sessionId ? saved.visible : 0;visibleVariant = visibleVariant > 0 && visibleVariant <= arrivedVariants? visibleVariant: (savedVisibleVariant > 0 && savedVisibleVariant <= arrivedVariants ? savedVisibleVariant : 1);- enterRecoveryWaitingForAnchor({ checkpointReason: 'svelte_component_anchor_missing', trackScroll: true });+ enterRecoveryWaitingForAnchor({ checkpointReason: 'component_preview_anchor_missing', trackScroll: true });waitForSvelteComponentTargetAndRetry({ manifestPath, sessionId, manifest });return;}@@ -5381,7 +5483,7 @@const wrapper = document.createElement('div');wrapper.dataset.impeccableVariants = sessionId;wrapper.dataset.impeccableVariantCount = String(manifest.count || expectedVariants || 1);- wrapper.dataset.impeccablePreview = 'svelte-component';+ wrapper.dataset.impeccablePreview = componentPreviewMode;wrapper.style.display = 'contents';const mountTarget = document.createElement('div');@@ -5419,8 +5521,8 @@recoveryWaitingForAnchor = false;const previousVisibleVariant = currentSessionId === sessionId ? visibleVariant : 0;- arrivedVariants = Number(manifest.count) || expectedVariants || 1;- expectedVariants = arrivedVariants;+ arrivedVariants = availableVariants;+ expectedVariants = Number(manifest.count) || expectedVariants || arrivedVariants;const saved = loadSession();const savedVisibleVariant = saved && saved.id === sessionId ? saved.visible : 0;visibleVariant = previousVisibleVariant > 0 && previousVisibleVariant <= arrivedVariants@@ -5445,9 +5547,10 @@refreshParamsPanel();positionBar();saveSession();- console.log('[impeccable] Mounted ' + arrivedVariants + ' Svelte component variants.');+ if (parameterGenerationState === 'loading') completeParameterPublication();+ console.log('[impeccable] Mounted ' + arrivedVariants + ' ' + manifest.framework + ' component variants.');} catch (err) {- console.error('[impeccable] Failed to mount Svelte component variants:', err);+ console.error('[impeccable] Failed to mount component-preview variants:', err);abortSvelteComponentInjection(sessionId, 'Could not load variants. Fix the error and re-run.');}}@@ -5493,6 +5596,8 @@clearHandled();resetSessionFileMeta();currentSessionId = null;+ parameterGenerationState = 'idle';+ parameterReadyAnnouncedSession = null;expectedVariants = 0;arrivedVariants = 0;visibleVariant = 0;@@ -5502,12 +5607,24 @@if (message) showToast(message, 5000);}+ // How many delayed re-reads a completion-driven source fallback gets when+ // the fetched source still shows only the preflight scaffold, before the+ // failure is surfaced via recoverEmptyCycling.+ const COMPLETED_SOURCE_FALLBACK_RETRIES = 3;+ const COMPLETED_SOURCE_FALLBACK_RETRY_MS = 1200;+/*** No-HMR fallback: fetch the raw source file from the live server,* parse it, extract the variant wrapper, and inject it into the live DOM.* This works even when the dev server caches HTML (Bun, static servers).+ *+ * opts.generationCompleted marks callers that KNOW the agent finished (a+ * `done` arrived or the server reported a completed generation). For them an+ * empty read is a stale source view and no further event is coming, so the+ * read retries a few times and then surfaces recovery. Callers without the+ * flag may be mid-generation and wait indefinitely for the real completion.*/- function injectVariantsFromSource(filePath, sessionId) {+ function injectVariantsFromSource(filePath, sessionId, opts = {}) {if (isSvelteComponentManifestPath(filePath)) {injectSvelteComponentsFromManifest(filePath, sessionId);return;@@ -5573,6 +5690,32 @@arrivedVariants = variants.length;expectedVariants = parseInt(wrapper.dataset.impeccableVariantCount || arrivedVariants);if (arrivedVariants <= 0) {+ if (state === 'GENERATING') {+ // Mid-generation the source legitimately holds a scaffold wrapper+ // with no variants yet (the server-side preflight wraps before the+ // agent writes). Tearing the session down here would destroy an+ // in-flight generation; stay in GENERATING — the variant observer+ // is armed and the server re-delivers a missed `done`.+ if (!opts.generationCompleted) {+ console.log('[impeccable] Source has scaffold but no variants yet; still generating.');+ return;+ }+ // Generation finished, yet the read shows only the scaffold: the+ // source view is stale and no further event will fire. Re-read a+ // few times before surfacing recovery — a single silent return+ // here would strand the tab in GENERATING forever.+ const attempt = opts.attempt || 0;+ if (attempt < COMPLETED_SOURCE_FALLBACK_RETRIES) {+ console.log('[impeccable] Generation is done but source shows no variants yet; retrying read ('+ + (attempt + 1) + '/' + COMPLETED_SOURCE_FALLBACK_RETRIES + ').');+ setTimeout(() => {+ if (state !== 'GENERATING' || currentSessionId !== sessionId) return;+ if (arrivedVariants > 0) return;+ injectVariantsFromSource(filePath, sessionId, { ...opts, attempt: attempt + 1 });+ }, COMPLETED_SOURCE_FALLBACK_RETRY_MS);+ return;+ }+ }recoverEmptyCycling('source-fallback-empty');return;}@@ -5594,6 +5737,7 @@refreshParamsPanel();positionBar();saveSession();+ if (parameterGenerationState === 'loading') completeParameterPublication();console.log('[impeccable] Injected ' + arrivedVariants + ' variants from source file.');}).catch(err => {@@ -5865,13 +6009,36 @@document.getElementById(VARIANT_STATE_STYLE_ID)?.remove();}+ function showOriginalDuringDiscard(sessionId) {+ if (!sessionId) return;+ let styleEl = document.getElementById(DISCARD_STATE_STYLE_ID);+ if (!styleEl) {+ styleEl = document.createElement('style');+ styleEl.id = DISCARD_STATE_STYLE_ID;+ (document.head || document.documentElement).appendChild(styleEl);+ }+ const wrapper = '[data-impeccable-variants="' + sessionId + '"]';+ styleEl.textContent = wrapper + ' > [data-impeccable-variant]:not([data-impeccable-variant="original"]) { display:none !important; }\n'+ + wrapper + ' > [data-impeccable-variant="original"] { display:block !important; }';+ }++ function resolveScrollLockAnchorTop() {+ const anchor = resolveBarAnchor();+ if (!anchor?.isConnected) return null;+ const top = anchor.getBoundingClientRect().top;+ return Number.isFinite(top) ? top : null;+ }+// Hold window.scrollY at a fixed value across DOM mutations inside the// session's wrapper (HMR patches, variant inserts, cycle swaps).- function startScrollLock(sessionId, initialTargetY) {+ function startScrollLock(sessionId, initialTargetY, initialAnchorTop) {stopScrollLock();scrollLockTargetY = typeof initialTargetY === 'number' && isFinite(initialTargetY)? initialTargetY: window.scrollY;+ scrollLockAnchorTop = typeof initialAnchorTop === 'number' && isFinite(initialAnchorTop)+ ? initialAnchorTop+ : resolveScrollLockAnchorTop();try { history.scrollRestoration = 'manual'; } catch {}@@ -5895,6 +6062,17 @@const correct = (why) => {scrollLockRaf = null;if (scrollLockTargetY == null) return;+ const anchor = resolveBarAnchor();+ if (anchor?.isConnected && typeof scrollLockAnchorTop === 'number' && isFinite(scrollLockAnchorTop)) {+ const anchorTop = anchor.getBoundingClientRect().top;+ const anchorDelta = anchorTop - scrollLockAnchorTop;+ if (Math.abs(anchorDelta) >= 0.5) {+ window.scrollTo({ top: window.scrollY + anchorDelta, left: window.scrollX, behavior: 'instant' });+ scrollLockTargetY = window.scrollY;+ writeScrollY(scrollLockTargetY);+ return;+ }+ }const before = window.scrollY;const delta = before - scrollLockTargetY;if (Math.abs(delta) < 0.5) {@@ -5939,6 +6117,7 @@if (scrollLockRaf != null) { cancelAnimationFrame(scrollLockRaf); scrollLockRaf = null; }const prevTarget = scrollLockTargetY;scrollLockTargetY = window.scrollY;+ scrollLockAnchorTop = resolveScrollLockAnchorTop();writeScrollY(scrollLockTargetY);};const markGesture = (why) => {@@ -5976,6 +6155,7 @@if (scrollLockRaf != null) { cancelAnimationFrame(scrollLockRaf); scrollLockRaf = null; }if (scrollLockAbort) { scrollLockAbort.abort(); scrollLockAbort = null; }scrollLockTargetY = null;+ scrollLockAnchorTop = null;// NOTE: do NOT clear the persistent scroll key here. startScrollLock// calls us as a reset, and clearing the key would nuke the Go-time// scrollY that the next resume needs to read.@@ -6049,6 +6229,7 @@updating = true;arrivedVariants = count;+ generationPhase = arrivedVariants >= expectedVariants ? 'variants_ready' : 'variants_progress';if (visibleVariant === 0 && arrivedVariants > 0) {const saved = loadSession();const savedVisibleVariant = saved && saved.id === sessionId ? saved.visible : 0;@@ -6064,7 +6245,7 @@const expected = parseInt(wrapper.dataset.impeccableVariantCount || '0');if (expected > 0) expectedVariants = expected;- if (arrivedVariants >= expectedVariants && expectedVariants > 0) {+ if (arrivedVariants > 0) {setLiveState('CYCLING');recoveryWaitingForAnchor = false;hideShaderOverlay();@@ -6072,13 +6253,18 @@updateSelectedElement();showOrUpdateCyclingBar();disableInlineEdit();- refreshParamsPanel();+ if (arrivedVariants >= expectedVariants && expectedVariants > 0) refreshParamsPanel();+ else hideParamsPanel();positionBar();} else if (state === 'GENERATING') {updateBarContent('generating');}saveSession();- queueCheckpoint(state === 'CYCLING' ? 'variants_ready' : 'variants_progress');+ sendCheckpoint(+ arrivedVariants >= expectedVariants && expectedVariants > 0+ ? 'variants_ready'+ : 'variants_progress',+ );updating = false;});@@ -6151,6 +6337,7 @@syncAgentPollingUi(!!msg.agentPolling);startAgentStatusPoll();restoreFromActiveSessions(msg.activeSessions, 'sse_connected');+ recoverMissedGenerationCompletion(msg.activeSessions);if (state === 'IDLE' && (pickActive || insertActive)) setLiveState('PICKING');syncPageInteractionCursor();syncPageChatFocus('sse-connected');@@ -6158,6 +6345,42 @@case 'agent_polling':syncAgentPollingUi(!!msg.connected);break;+ case 'agent_phase':+ if (msg.id === currentSessionId && (state === 'GENERATING' || state === 'CYCLING')) {+ generationPhase = msg.phase || generationPhase;+ if (msg.phase === 'variant_parameters_generating' || msg.phase === 'variant_parameters_validating') {+ parameterGenerationState = 'loading';+ }+ if (msg.phase === 'parameters_ready' && parameterGenerationState !== 'ready') {+ parameterGenerationState = 'loading';+ }+ updateBarContent(state === 'CYCLING' ? 'cycling' : 'generating');+ saveSession();+ }+ break;+ case 'variant_progress':+ if (msg.id === currentSessionId) {+ if (msg.publicationKind === 'params') parameterGenerationState = 'loading';+ rememberSessionFileMeta(msg);+ if (isFrameworkComponentPreviewMode(msg.previewMode) && msg.previewFile) {+ injectSvelteComponentsFromManifest(msg.previewFile, msg.id);+ } else if ((msg.previewMode === 'source' || !msg.previewMode) && (msg.previewFile || msg.file)) {+ // Give normal framework HMR the first chance to reconcile its+ // own managed tree. Nuxt route-module HMR can skip intermediate+ // revisions, so fall back to source injection only when the+ // advertised progress still has not appeared after a short+ // settle. Immediate injection races React/Vue ownership and can+ // trigger removeChild errors on the next HMR commit.+ const targetArrived = Number(msg.arrivedVariants) || 1;+ setTimeout(() => {+ if (msg.id !== currentSessionId) return;+ if (state !== 'GENERATING' && state !== 'CYCLING') return;+ if (msg.publicationKind !== 'params' && arrivedVariants >= targetArrived) return;+ injectVariantsFromSource(msg.previewFile || msg.file, msg.id);+ }, 150);+ }+ }+ break;case 'steer_done':maybeCompleteSteer(msg);break;@@ -6175,6 +6398,10 @@case 'done':if (maybeCompleteSteer(msg)) break;rememberSessionFileMeta(msg);+ if (msg.id === currentSessionId && isFrameworkComponentPreviewMode(currentPreviewMode) && currentPreviewFile) {+ injectSvelteComponentsFromManifest(currentPreviewFile, msg.id);+ break;+ }// Variants already arrived via HMR → normal transition.if (arrivedVariants >= expectedVariants && expectedVariants > 0) {if (state === 'GENERATING') {@@ -6190,7 +6417,7 @@setTimeout(() => {if (arrivedVariants >= expectedVariants && expectedVariants > 0) return;if (state !== 'GENERATING' || msg.id !== currentSessionId) return;- injectVariantsFromSource(msg.file, msg.id);+ injectVariantsFromSource(msg.file, msg.id, { generationCompleted: true });}, 750);break;}@@ -6215,9 +6442,10 @@if (maybeCompleteAcceptedSession(msg)) break;break;case 'agent_done':- // Carbonize accepts are not terminal until live-complete.mjs sends- // the final complete event. Keep the browser in its recoverable- // saving state while the source cleanup is still in flight.+ // The deterministic accept has already committed the reviewed DOM+ // and fenced generation. Carbonize may continue in the background;+ // it must not hold the foreground picker hostage.+ if (msg.data?.carbonize === true && maybeCompleteAcceptedSession(msg)) break;break;case 'discarded':if (msg.id && msg.id === currentSessionId) {@@ -6306,6 +6534,7 @@type: 'checkpoint',id: currentSessionId,revision: sessionState.nextCheckpointRevision(),+ revisionDomain: 'browser',owner: browserOwner,phase: String(state || '').toLowerCase(),reason,@@ -6331,6 +6560,7 @@type: 'checkpoint',id,revision: sessionState.nextCheckpointRevision(),+ revisionDomain: 'browser',owner: browserOwner,phase: 'steer',reason,@@ -6684,6 +6914,9 @@expectedVariants = selectedCount;arrivedVariants = 0;visibleVariant = 0;+ generationPhase = 'queued';+ parameterGenerationState = 'pending';+ parameterReadyAnnouncedSession = null;resetSessionFileMeta();// Flip to GENERATING immediately so the bar morphs without waiting on@@ -6693,6 +6926,7 @@const elForCapture = selectedElement;pickedAnchorSnapshot = buildPickedAnchorSnapshot(elForCapture);const captureRect = elForCapture.getBoundingClientRect();+ pickedAnchorViewportTop = captureRect.top;const snapshot = {comments: annotState.comments.map(c => ({ x: c.x, y: c.y, text: c.text })),strokes: annotState.strokes.map(s => ({ points: s.points.map(p => [p[0], p[1]]) })),@@ -6724,7 +6958,7 @@writeScrollY(window.scrollY);if (variantObserver) variantObserver.disconnect();variantObserver = startVariantObserver(currentSessionId);- startScrollLock(currentSessionId);+ startScrollLock(currentSessionId, window.scrollY, pickedAnchorViewportTop);captureAndEmit(elForCapture, basePayload, snapshot, captureRect);}@@ -6759,12 +6993,16 @@expectedVariants = selectedCount;arrivedVariants = 0;visibleVariant = 0;+ generationPhase = 'queued';+ parameterGenerationState = 'pending';+ parameterReadyAnnouncedSession = null;resetSessionFileMeta();selectedElement = placeholderElement;insertPlaceholderSnapshot = buildInsertPlaceholderSnapshotFromDom(insertAnchorElement, placeholderElement);const elForCapture = placeholderElement;const captureRect = elForCapture.getBoundingClientRect();+ pickedAnchorViewportTop = captureRect.top;const basePayload = {type: 'generate',mode: 'insert',@@ -6795,7 +7033,7 @@writeScrollY(window.scrollY);if (variantObserver) variantObserver.disconnect();variantObserver = startVariantObserver(currentSessionId);- startScrollLock(currentSessionId);+ startScrollLock(currentSessionId, window.scrollY, pickedAnchorViewportTop);captureAndEmit(elForCapture, basePayload, snapshot, captureRect);}@@ -6975,9 +7213,9 @@// preview mounts are covered by the same shader regression checks.const adapter = String(window.__IMPECCABLE_LIVE_ADAPTER__ || '').toLowerCase();if (adapter === 'svelte' || adapter === 'sveltekit') return true;- if (currentPreviewMode === 'svelte-component' || svelteComponentSession) return true;+ if (isFrameworkComponentPreviewMode(currentPreviewMode) || svelteComponentSession) return true;const wrapper = el?.closest?.('[data-impeccable-variants]');- return wrapper?.dataset?.impeccablePreview === 'svelte-component';+ return isFrameworkComponentPreviewMode(wrapper?.dataset?.impeccablePreview);}function paintsShaderProxySurface(node) {@@ -7105,6 +7343,17 @@}async function captureAndEmit(el, basePayload, snapshot, rect) {+ const hasAnnotations = snapshot && (snapshot.comments.length > 0 || snapshot.strokes.length > 0);++ // Plain requests do not send a screenshot to the agent, so capture is+ // presentation-only. Wait only for the helper to accept the event before+ // starting CPU-heavy capture; this yields the browser task and prevents+ // rasterization from delaying the fetch itself.+ if (!hasAnnotations) {+ basePayload.clientSentAt = Date.now();+ await sendEvent(basePayload);+ }+let screenshotPath;let blob;let paper;@@ -7122,7 +7371,6 @@// are present. Without annotations the image is pure visual anchoring -// it biases the model toward the current rendering and works against the// three-distinct-directions brief.- const hasAnnotations = snapshot && (snapshot.comments.length > 0 || snapshot.strokes.length > 0);if (blob && hasAnnotations) {try {const uploadRes = await fetch(@@ -7140,7 +7388,12 @@console.warn('[impeccable] annotation upload failed:', err);}}- sendEvent(screenshotPath ? { ...basePayload, screenshotPath } : basePayload);+ // Annotated requests must wait for capture + upload because the screenshot+ // is semantic input. Plain requests were already dispatched above.+ if (hasAnnotations) {+ basePayload.clientSentAt = Date.now();+ sendEvent(screenshotPath ? { ...basePayload, screenshotPath } : basePayload);+ }}//@@ -7520,7 +7773,6 @@ void main() {if (variantSelectionPromise) {try { await variantSelectionPromise; } catch { /* failed selection falls back below */ }}- if (!currentSessionId || arrivedVariants === 0) return;const domVisibleVariant = readVisibleVariantFromDOM(currentSessionId);if (domVisibleVariant > 0) visibleVariant = domVisibleVariant;const acceptPayload = {@@ -7528,7 +7780,9 @@ void main() {id: currentSessionId,variantId: String(visibleVariant),pageUrl: location.pathname,+ clientSentAt: Date.now(),};+ if (!currentSessionId || arrivedVariants === 0) return;const acceptWrapper = document.querySelector('[data-impeccable-variants="' + currentSessionId + '"]');if (Object.keys(paramsCurrentValues).length > 0) {acceptPayload.paramValues = { ...paramsCurrentValues };@@ -7542,7 +7796,7 @@ void main() {const acceptedSessionId = currentSessionId;const acceptedVariant = visibleVariant;const acceptedIsSvelteComponent = svelteComponentSession?.sessionId === acceptedSessionId- || acceptWrapper?.dataset?.impeccablePreview === 'svelte-component';+ || isFrameworkComponentPreviewMode(acceptWrapper?.dataset?.impeccablePreview);const acceptedSnapshot = snapshotAcceptedVariantDom(acceptedSessionId, acceptedVariant);setLiveState('SAVING');@@ -7557,7 +7811,17 @@ void main() {saveSession();sendEvent(acceptPayload, { throwOnError: true })- .then(() => {})+ .then(() => {+ const pending = pendingAcceptedSession;+ if (!pending || pending.id !== acceptedSessionId) return;+ // POST /events returns only after the accept intent is durable and the+ // generation epoch is fenced. Source promotion/carbonize can finish in+ // the background; the foreground picker is free immediately.+ markSessionHandled();+ setLiveState('CONFIRMED');+ document.documentElement.dataset.impeccableAcceptToPickingMs = String(Date.now() - acceptPayload.clientSentAt);+ scheduleAcceptCleanup(pending);+ }).catch(() => {if (pendingAcceptedSession?.id === acceptedSessionId) pendingAcceptedSession = null;setLiveState('CYCLING');@@ -7586,17 +7850,26 @@ void main() {}function scheduleAcceptCleanup(accepted) {- setTimeout(function() {- if (!accepted?.isSvelteComponent && !acceptedDomAlreadyClean(accepted)) {- setTimeout(function() {- if (pendingAcceptedSession?.id !== accepted?.id) return;- if (!accepted?.isSvelteComponent) ensureAcceptedDomClean(accepted);- cleanupAcceptedSession();- }, 1800);- return;+ queueMicrotask(function() {+ if (pendingAcceptedSession?.id !== accepted?.id) return;+ // Svelte previews live in an adapter-owned mount rather than in source+ // wrapper markup. Promote the mounted variant before releasing the+ // session so the old adapter instance cannot linger behind the next+ // Pick → Go loop while carbonize finishes in the background.+ if (accepted?.isSvelteComponent) {+ commitAcceptedSvelteComponentToDom(accepted.id);}cleanupAcceptedSession();- }, 1200);+ });+ // Let React/Vue/Svelte own the HMR reconciliation. Mutating their DOM in+ // the same turn as the source update causes removeChild/NotFoundError+ // races. Static servers still need a fallback, but it must not keep Live+ // in SAVING or block the user's next pick.+ if (!accepted?.isSvelteComponent) {+ setTimeout(function() {+ if (!acceptedDomAlreadyClean(accepted)) ensureAcceptedDomClean(accepted);+ }, 1200);+ }}function snapshotAcceptedVariantDom(sessionId, variantId) {@@ -7700,7 +7973,11 @@ void main() {clearSession();resetSessionFileMeta();selectedElement = null;+ hoveredElement = null;+ pagePickSkipClick = false;currentSessionId = null;+ parameterGenerationState = 'idle';+ parameterReadyAnnouncedSession = null;selectedAction = 'impeccable';pendingAcceptedSession = null;renderEditBadge('hidden');@@ -7735,7 +8012,7 @@ void main() {sendEvent({ type: 'discard', id: currentSessionId }, { throwOnError: true }).then(() => {markSessionHandled();- cleanup();+ cleanup({ restoreOriginal: true, instantChrome: true });}).catch(() => showToast('Could not confirm discard with the live server. Session kept for recovery.', 5000));}@@ -7757,6 +8034,7 @@ void main() {currentPreviewMode = null;recoveryWaitingForAnchor = false;pickedAnchorSnapshot = null;+ pickedAnchorViewportTop = null;}function rememberSessionFileMeta(meta = {}) {@@ -7765,8 +8043,8 @@ void main() {const previewFile = normalizeSessionPath(meta.previewFile);const previewMode = meta.previewMode || (isSvelteComponentManifestPath(previewFile || file) ? 'svelte-component' : null);- if (previewMode === 'svelte-component' || isSvelteComponentManifestPath(file)) {- currentPreviewMode = 'svelte-component';+ if (isFrameworkComponentPreviewMode(previewMode) || isSvelteComponentManifestPath(file)) {+ currentPreviewMode = isFrameworkComponentPreviewMode(previewMode) ? previewMode : 'svelte-component';currentPreviewFile = previewFile || (isSvelteComponentManifestPath(file) ? file : currentPreviewFile);currentSourceFile = sourceFile || currentSourceFile;return;@@ -7782,12 +8060,15 @@ void main() {rememberSessionFileMeta(saved);if (saved.insertPlaceholder) insertPlaceholderSnapshot = saved.insertPlaceholder;if (saved.pickedAnchor) pickedAnchorSnapshot = saved.pickedAnchor;+ if (Number.isFinite(saved.pickedAnchorViewportTop)) pickedAnchorViewportTop = saved.pickedAnchorViewportTop;if (saved.action) selectedAction = saved.action;if (saved.count) selectedCount = saved.count;if (saved.previewMode) currentPreviewMode = saved.previewMode;if (saved.paramValues && typeof saved.paramValues === 'object') {paramsCurrentValues = { ...saved.paramValues };}+ if (saved.parameterState) parameterGenerationState = saved.parameterState;+ if (saved.generationPhase) generationPhase = saved.generationPhase;}function normalizePagePath(value) {@@ -7859,7 +8140,7 @@ void main() {saveSession();queueCheckpoint(reason || 'browser_restore_without_wrapper');- const restoreFile = currentPreviewMode === 'svelte-component'+ const restoreFile = isFrameworkComponentPreviewMode(currentPreviewMode)? currentPreviewFile: (currentSourceFile || currentPreviewFile);if (restoreFile) {@@ -7872,11 +8153,41 @@ void main() {function restoreFromActiveSessions(activeSessions, reason) {const wrapper = document.querySelector('[data-impeccable-variants]');- if (wrapper && wrapper.dataset.impeccablePreview !== 'svelte-component') return false;+ if (wrapper && !isFrameworkComponentPreviewMode(wrapper.dataset.impeccablePreview)) return false;if (svelteComponentSession?.sessionId === currentSessionId) return false;return restoreSessionWithoutWrapper(reason || 'sse_connected', activeSessions);}+ // Self-heal on SSE (re)connect. The preflight scaffold write triggers a+ // framework full-reload (Astro reloads pages for any .astro edit); if the+ // agent's variant write + `done` broadcast land while this page is+ // mid-reload, both the done SSE and the second HMR reload are missed and+ // the resumed page would wait in GENERATING at 0/N forever. The server's+ // session summary carries the durable generationCompletedAt marker, so on+ // every connect compare it against our own progress and pull the finished+ // variants from source when behind. Mirrors the `done` handler's source+ // fallback, including its give-HMR-the-first-chance settle delay.+ function recoverMissedGenerationCompletion(activeSessions) {+ if (!currentSessionId || state !== 'GENERATING') return;+ if (!Array.isArray(activeSessions)) return;+ const summary = activeSessions.find((session) => session?.id === currentSessionId);+ if (!summary?.generationCompletedAt || summary.generationCanceled) return;+ if (isTerminalSessionSummary(summary)) return;+ if (arrivedVariants > 0 && arrivedVariants >= expectedVariants) return;+ rememberSessionFileMeta(summary);+ const sessionId = currentSessionId;+ const file = isFrameworkComponentPreviewMode(currentPreviewMode)+ ? currentPreviewFile+ : (summary.sourceFile || summary.previewFile || currentSourceFile || currentPreviewFile);+ if (!file) return;+ console.log('[impeccable] Reconnected after generation completed; recovering variants from source.');+ setTimeout(() => {+ if (sessionId !== currentSessionId || state !== 'GENERATING') return;+ if (arrivedVariants > 0 && arrivedVariants >= expectedVariants) return;+ injectVariantsFromSource(file, sessionId, { generationCompleted: true });+ }, 750);+ }+function saveSession() {if (!currentSessionId) return;// NOTE: scrollY is stored under a separate key (writeScrollY). Storing@@ -7894,8 +8205,12 @@ void main() {previewMode: currentPreviewMode || undefined,pageUrl: location.pathname,paramValues: { ...paramsCurrentValues },+ parameterState: parameterGenerationState,insertPlaceholder: insertPlaceholderSnapshot || undefined,pickedAnchor: pickedAnchorSnapshot || undefined,+ pickedAnchorViewportTop: Number.isFinite(pickedAnchorViewportTop) ? pickedAnchorViewportTop : undefined,+ pageHash: location.hash || undefined,+ pageSearch: location.search || undefined,});}@@ -7923,20 +8238,26 @@ void main() {sessionState.clearHandled();}- function cleanup() {+ function cleanup(options) {+ const restoreOriginal = options?.restoreOriginal === true;+ const instantChrome = options?.instantChrome === true;const cleanupSessionId = currentSessionId;if (svelteComponentSession?.sessionId === cleanupSessionId) {teardownSvelteComponentSession(true);} else if (cleanupSessionId) {- // Hide the wrapper immediately so variants disappear. DON'T structurally- // mutate the DOM yet - HMR from the agent's source rewrite is on its way,+ // Switch visibility immediately without structurally mutating the DOM.+ // HMR from the agent's source rewrite may still be on its way,// and a manual replaceChild under React causes NotFoundError when the// reconciler later tries to remove a wrapper we already removed.// Schedule a 2s fallback that does the manual swap only if HMR hasn't// replaced the wrapper by then (keeps static-server / no-HMR flows alive).const wrapper = document.querySelector('[data-impeccable-variants="' + cleanupSessionId + '"]');- if (wrapper) wrapper.style.display = 'none';+ if (wrapper) {+ if (restoreOriginal) showOriginalDuringDiscard(cleanupSessionId);+ else wrapper.style.display = 'none';+ }setTimeout(function() {+ document.getElementById(DISCARD_STATE_STYLE_ID)?.remove();if (!cleanupSessionId) return;const lateWrapper = document.querySelector('[data-impeccable-variants="' + cleanupSessionId + '"]');if (!lateWrapper) return;@@ -7951,7 +8272,7 @@ void main() {lateWrapper.remove();}, 2000);}- hideBar();+ hideBar(instantChrome);hideHighlight();stopScrollTracking();if (variantObserver) { variantObserver.disconnect(); variantObserver = null; }@@ -7963,7 +8284,11 @@ void main() {clearSession();resetSessionFileMeta();selectedElement = null;+ hoveredElement = null;+ pagePickSkipClick = false;currentSessionId = null;+ parameterGenerationState = 'idle';+ parameterReadyAnnouncedSession = null;selectedAction = 'impeccable';renderEditBadge('hidden');setLiveState('PICKING');@@ -8047,7 +8372,7 @@ void main() {// would strand the bar in CYCLING at 0/0. If there's no live in-memory mount// for this wrapper, it's an orphan (reload / failed mount): drop it and let// the live-server's SSE re-inject the manifest if the session is still live.- if (wrapper.dataset.impeccablePreview === 'svelte-component'+ if (isFrameworkComponentPreviewMode(wrapper.dataset.impeccablePreview)&& svelteComponentSession?.sessionId !== sessionId) {wrapper.remove();if (restoreSessionWithoutWrapper('browser_resumed_svelte_orphan_wrapper')) return true;@@ -8056,7 +8381,7 @@ void main() {return false;}- if (wrapper.dataset.impeccablePreview === 'svelte-component') {+ if (isFrameworkComponentPreviewMode(wrapper.dataset.impeccablePreview)) {if (!svelteComponentSession?.mountedVariant) {return true;}@@ -8104,7 +8429,7 @@ void main() {insertPlaceholderSnapshot = saved.insertPlaceholder;}- const resumedState = arrivedVariants >= expectedVariants ? 'CYCLING' : 'GENERATING';+ const resumedState = arrivedVariants > 0 ? 'CYCLING' : 'GENERATING';// Find the visible variant's content element for highlight positioning.const isInsert = wrapper.dataset.impeccableMode === 'insert';@@ -8128,7 +8453,11 @@ void main() {// hid. Now that state is CYCLING, re-fire.if (state === 'CYCLING') refreshParamsPanel();saveSession();- queueCheckpoint('browser_resumed');+ if (arrivedVariants > 0 && arrivedVariants < expectedVariants) {+ sendCheckpoint('variants_progress');+ } else {+ queueCheckpoint('browser_resumed');+ }// Start observing for more variants AFTER initial setupif (variantObserver) variantObserver.disconnect();@@ -8136,7 +8465,7 @@ void main() {// Hold the target at its saved viewport top through any subsequent// HMR patches, variant inserts, or cycle swaps.- startScrollLock(currentSessionId, readScrollY());+ startScrollLock(currentSessionId, readScrollY(), pickedAnchorViewportTop);// If we reloaded mid-generation (Bun's HTML HMR destroys the shader// canvas), re-capture the original's content and restart the shader so@@ -8171,6 +8500,7 @@ void main() {let globalBarBrandEl = null;let agentPollTooltipEl = null;let agentPollingConnected = false;+ let agentStatusMessage = null;let agentStatusPollTimer = null;let steerFocusSuspended = false;let steerFocusPauseUntil = 0;@@ -8275,6 +8605,13 @@ void main() {const AGENT_STATUS_POLL_MS = 5000;const AGENT_DISCONNECTED_MARK = 'oklch(62% 0 0 / 0.78)';const AGENT_DISCONNECTED_TIP = 'Agent disconnected - run live-poll.mjs to connect';+ // The indicator tracks whether a poll is parked, which is what decides if+ // steering can reach the agent right now. That goes quiet two ways, and they+ // need different copy: nobody is polling at all, or the agent took the work+ // and is busy with it. Under one-shot foreground polling the second case is+ // every normal generation, and telling the user to start a poll loop then is+ // wrong advice about a healthy session.+ const AGENT_BUSY_TIP = 'Agent is working - steering resumes when it finishes';const GLOBAL_BAR_SECTION_GAP = 8;const GLOBAL_BAR_INNER_GAP = 2;const GLOBAL_BAR_INNER_PAD_LEFT = 2;@@ -9295,24 +9632,46 @@ void main() {</svg>`;}+ /**+ * True while the browser is waiting on work it already handed to the agent.+ * In these states a quiet poll indicator means "busy", not "absent".+ */+ function agentHasWorkInFlight() {+ return state === 'GENERATING' || state === 'SAVING';+ }++ /**+ * Derived at read time, not cached: which of the two reasons applies depends on+ * the live state, which moves between the 5s status polls. The truthiness is+ * the same either way, so the indicator's visuals can stay driven by the+ * cached value while the wording stays current.+ */+ function agentStatusText() {+ if (agentPollingConnected) return null;+ return agentHasWorkInFlight() ? AGENT_BUSY_TIP : AGENT_DISCONNECTED_TIP;+ }+function syncAgentPollingUi(connected) {agentPollingConnected = !!connected;if (!globalBarBrandEl) return;const P = barPaletteForTheme(globalBarEl?.dataset.theme || detectPageTheme());+ agentStatusMessage = agentStatusText();globalBarBrandEl.dataset.agentConnected = connected ? 'true' : 'false';- globalBarBrandEl.setAttribute('aria-label', connected- ? 'Impeccable live mode'- : 'Impeccable live mode - agent not polling');+ // The tooltip is mouse-only, so carry the same distinction in the label or+ // screen-reader users are left with the vaguer of the two readings.+ globalBarBrandEl.setAttribute('aria-label', agentStatusMessage+ ? 'Impeccable live mode - ' + (agentHasWorkInFlight() ? 'agent is working' : 'agent not polling')+ : 'Impeccable live mode');globalBarBrandEl.removeAttribute('title');- globalBarBrandEl.style.cursor = connected ? 'default' : 'help';+ globalBarBrandEl.style.cursor = agentStatusMessage ? 'help' : 'default';const mark = globalBarBrandEl.querySelector('[data-brand-mark]');if (mark) {mark.innerHTML = brandMarkSvg(connected ? P.accent : AGENT_DISCONNECTED_MARK, 18);mark.style.opacity = '1';}const dot = globalBarBrandEl.querySelector('[data-agent-dot]');- if (dot) dot.style.display = connected ? 'none' : 'block';- if (connected) hideAgentPollTooltip();+ if (dot) dot.style.display = agentStatusMessage ? 'block' : 'none';+ if (!agentStatusMessage) hideAgentPollTooltip();}function ensureAgentPollTooltip() {@@ -9339,14 +9698,17 @@ void main() {whiteSpace: 'normal',});agentPollTooltipEl.id = PREFIX + '-agent-poll-tooltip';- agentPollTooltipEl.textContent = AGENT_DISCONNECTED_TIP;+ agentPollTooltipEl.textContent = agentStatusText() || AGENT_DISCONNECTED_TIP;uiAppend(agentPollTooltipEl);return agentPollTooltipEl;}function showAgentPollTooltip(anchor) {- if (agentPollingConnected || !anchor) return;+ if (!agentStatusMessage || !anchor) return;const tip = ensureAgentPollTooltip();+ // Re-derive rather than reuse the cached copy: the live state may have moved+ // since the last status poll set it.+ tip.textContent = agentStatusText() || AGENT_DISCONNECTED_TIP;tip.style.transition = 'none';tip.style.display = 'block';tip.style.opacity = '1';@@ -9376,7 +9738,9 @@ void main() {fetch('http://localhost:' + PORT + '/status?token=' + TOKEN, { cache: 'no-store' }).then((res) => (res.ok ? res.json() : null)).then((data) => {- if (data && typeof data.agentPolling === 'boolean') syncAgentPollingUi(data.agentPolling);+ if (data && typeof data.agentPolling === 'boolean') {+ syncAgentPollingUi(data.agentPolling);+ }}).catch(() => { /* server loss handled elsewhere */ });}diff --git a/.rovodev/skills/impeccable/scripts/live-inject.mjs b/.rovodev/skills/impeccable/scripts/live-inject.mjsindex 7c8d91182..d99c37fd5 100644--- a/.rovodev/skills/impeccable/scripts/live-inject.mjs+++ b/.rovodev/skills/impeccable/scripts/live-inject.mjs@@ -27,6 +27,8 @@ const __dirname = path.dirname(fileURLToPath(import.meta.url));const CONFIG_PATH = resolveLiveConfigPath({ cwd: process.cwd(), scriptsDir: __dirname });const MARKER_OPEN_TEXT = 'impeccable-live-start';const MARKER_CLOSE_TEXT = 'impeccable-live-end';+const NUXT_PLUGIN_MARKER = 'impeccable-live-nuxt-plugin';+const NUXT_PLUGIN_NAME = 'impeccable-live.client.ts';const IGNORE_MARKER_OPEN = '# impeccable-live-ignore-start';const IGNORE_MARKER_CLOSE = '# impeccable-live-ignore-end';@@ -38,6 +40,9 @@ export const LIVE_IGNORE_PATTERNS = Object.freeze(['.impeccable/live/sessions/','.impeccable/live/previews/','.impeccable/live/annotations/',+ '.impeccable/live/artifacts/',+ '.impeccable/live/accept-receipts/',+ '.impeccable/live/locks/','.impeccable/live/cache/','.impeccable/live/manual-edit-apply-transaction.json','.impeccable/live/manual-edit-events.jsonl',@@ -46,10 +51,15 @@ export const LIVE_IGNORE_PATTERNS = Object.freeze(['.impeccable/live/deferred-svelte-component-accepts.json','.impeccable-live.json','.impeccable-live/',+ 'app/.impeccable-live/',+ 'src/.impeccable-live/','node_modules/.impeccable-live/','src/lib/impeccable/ImpeccableLiveRoot.svelte','src/lib/impeccable/__runtime.js','src/lib/impeccable/[0-9a-f]*/',+ 'plugins/impeccable-live.client.ts',+ 'app/plugins/impeccable-live.client.ts',+ 'src/plugins/impeccable-live.client.ts',]);/**@@ -113,6 +123,7 @@ Output (JSON):const resolvedFiles = resolveFiles(process.cwd(), config);const svelteKit = detectSvelteKitProject(process.cwd(), config);+ const nuxt = detectNuxtProject(process.cwd());if (args.includes('--remove')) {if (svelteKit) {@@ -120,6 +131,12 @@ Output (JSON):console.log(JSON.stringify({ ok: true, adapter: 'sveltekit', results: [adapterResult] }));return;}+ if (nuxt) {+ const adapterResult = removeNuxtLiveAdapter({ cwd: process.cwd(), project: nuxt });+ console.log(JSON.stringify({ ok: !adapterResult.error, adapter: 'nuxt', results: [adapterResult] }));+ if (adapterResult.error) process.exitCode = 1;+ return;+ }const results = resolvedFiles.map((relFile) => {const absFile = path.resolve(process.cwd(), relFile);if (!fs.existsSync(absFile)) return { file: relFile, error: 'file_not_found' };@@ -145,13 +162,28 @@ Output (JSON):console.error(JSON.stringify({ ok: false, error: 'missing_port' }));process.exit(1);}- const gitIgnore = ensureLiveGitIgnores(process.cwd());+ const gitIgnore = ensureLiveGitIgnores(+ process.cwd(),+ nuxt ? [nuxt.pluginFile] : [],+ );if (svelteKit) {const adapterResult = applySvelteKitLiveAdapter({ cwd: process.cwd(), port, config });console.log(JSON.stringify({ ok: true, port, adapter: 'sveltekit', gitIgnore, results: [adapterResult] }));return;}+ if (nuxt) {+ const adapterResult = applyNuxtLiveAdapter({ cwd: process.cwd(), port, project: nuxt });+ console.log(JSON.stringify({+ ok: !adapterResult.error,+ port,+ adapter: 'nuxt',+ gitIgnore,+ results: [adapterResult],+ }));+ if (adapterResult.error) process.exitCode = 1;+ return;+ }const results = resolvedFiles.map((relFile) => {const absFile = path.resolve(process.cwd(), relFile);@@ -175,12 +207,12 @@ Output (JSON):if (!anyInserted) process.exit(1);}-export function ensureLiveGitIgnores(cwd = process.cwd()) {+export function ensureLiveGitIgnores(cwd = process.cwd(), extraPatterns = []) {const target = resolveIgnoreTarget(cwd);const existing = fs.existsSync(target.path) ? fs.readFileSync(target.path, 'utf-8') : '';const block = [IGNORE_MARKER_OPEN,- ...LIVE_IGNORE_PATTERNS,+ ...new Set([...LIVE_IGNORE_PATTERNS, ...extraPatterns]),IGNORE_MARKER_CLOSE,].join('\n');const markerRe = new RegExp(`${escapeRegExp(IGNORE_MARKER_OPEN)}[\\s\\S]*?${escapeRegExp(IGNORE_MARKER_CLOSE)}`);@@ -202,10 +234,119 @@ export function ensureLiveGitIgnores(cwd = process.cwd()) {file: path.relative(cwd, target.path).split(path.sep).join('/'),mode: target.mode,changed: updated !== existing,- patterns: [...LIVE_IGNORE_PATTERNS],+ patterns: [...new Set([...LIVE_IGNORE_PATTERNS, ...extraPatterns])],};}+// ---------------------------------------------------------------------------+// Nuxt adapter+//+// A script element placed in app.vue is compiled as Vue-rendered DOM and is+// not executed. Nuxt instead auto-discovers client plugins. Keep the adapter+// generated, dev-only, and outside user-authored source: Live creates one+// marked .client.ts plugin on start and removes it on stop.+// ---------------------------------------------------------------------------++export function detectNuxtProject(cwd = process.cwd()) {+ const configFile = fs.readdirSync(cwd, { withFileTypes: true })+ .find((entry) => entry.isFile() && /^nuxt\.config\.(?:js|mjs|cjs|ts|mts|cts)$/.test(entry.name))+ ?.name;+ if (!configFile) return null;++ const config = fs.readFileSync(path.join(cwd, configFile), 'utf-8');+ const literalSrcDir = config.match(/\bsrcDir\s*:\s*(['"])([^'"]+)\1/);+ let appDir = '';+ if (literalSrcDir) {+ const candidate = literalSrcDir[2]+ .replace(/\\/g, '/')+ .replace(/^\.\//, '')+ .replace(/\/+$/, '');+ const normalized = path.posix.normalize(candidate);+ if (normalized !== '..' && !normalized.startsWith('../') && !path.isAbsolute(normalized)) {+ appDir = normalized === '.' ? '' : normalized;+ }+ } else if (+ fs.existsSync(path.join(cwd, 'app', 'app.vue'))+ || fs.existsSync(path.join(cwd, 'app', 'pages'))+ ) {+ appDir = 'app';+ }++ const pluginFile = [appDir, 'plugins', NUXT_PLUGIN_NAME].filter(Boolean).join('/');+ return { configFile, appDir, pluginFile };+}++export function buildNuxtPlugin(port) {+ return `/* ${NUXT_PLUGIN_MARKER} */+const liveSrc = 'http://localhost:${port}/live.js';+const liveSelector = 'script[data-impeccable-live-nuxt]';++export default defineNuxtPlugin(() => {+ if (!import.meta.dev || typeof document === 'undefined') return;++ const expectedSrc = new URL(liveSrc, window.location.href).href;+ let script = document.querySelector(liveSelector);+ if (script?.src === expectedSrc) return;+ script?.remove();++ script = document.createElement('script');+ script.src = liveSrc;+ script.async = true;+ script.dataset.impeccableLiveNuxt = '';+ document.head.appendChild(script);++ import.meta.hot?.dispose(() => {+ if (script?.isConnected) script.remove();+ });+});+/* /${NUXT_PLUGIN_MARKER} */+`;+}++export function applyNuxtLiveAdapter({ cwd = process.cwd(), port, project = detectNuxtProject(cwd) }) {+ if (!project) return { error: 'nuxt_not_detected' };+ const absFile = path.join(cwd, project.pluginFile);+ const existing = fs.existsSync(absFile) ? fs.readFileSync(absFile, 'utf-8') : null;+ if (existing !== null && !existing.includes(NUXT_PLUGIN_MARKER)) {+ return {+ file: project.pluginFile,+ error: 'nuxt_plugin_conflict',+ hint: `${project.pluginFile} already exists and is not managed by Impeccable Live`,+ };+ }++ const content = buildNuxtPlugin(port);+ fs.mkdirSync(path.dirname(absFile), { recursive: true });+ if (content !== existing) fs.writeFileSync(absFile, content, 'utf-8');+ return {+ file: project.pluginFile,+ inserted: true,+ changed: content !== existing,+ devOnly: true,+ };+}++export function removeNuxtLiveAdapter({ cwd = process.cwd(), project = detectNuxtProject(cwd) }) {+ if (!project) return { error: 'nuxt_not_detected' };+ const absFile = path.join(cwd, project.pluginFile);+ if (!fs.existsSync(absFile)) {+ return { file: project.pluginFile, removed: false, note: 'no adapter present' };+ }+ const content = fs.readFileSync(absFile, 'utf-8');+ if (!content.includes(NUXT_PLUGIN_MARKER)) {+ return {+ file: project.pluginFile,+ removed: false,+ error: 'nuxt_plugin_conflict',+ hint: `${project.pluginFile} is not managed by Impeccable Live`,+ };+ }+ fs.unlinkSync(absFile);+ const pluginDir = path.dirname(absFile);+ if (fs.readdirSync(pluginDir).length === 0) fs.rmdirSync(pluginDir);+ return { file: project.pluginFile, removed: true };+}+function resolveIgnoreTarget(cwd) {const gitExcludePath = resolveGitInfoExcludePath(cwd);if (gitExcludePath) {diff --git a/.rovodev/skills/impeccable/scripts/live-poll.mjs b/.rovodev/skills/impeccable/scripts/live-poll.mjsindex 740161e10..19a8b0f9b 100644--- a/.rovodev/skills/impeccable/scripts/live-poll.mjs+++ b/.rovodev/skills/impeccable/scripts/live-poll.mjs@@ -27,7 +27,7 @@ const scriptCmd = (name) => `node "${path.join(SELF_DIR, name)}"`;export const PER_REQUEST_TIMEOUT_MS = 270_000;export const DEFAULT_EVENT_LEASE_MS = 600_000;-const EVENT_TYPES_NEEDING_AGENT_REPLY = new Set(['generate', 'steer', 'manual_edit_apply']);+const EVENT_TYPES_NEEDING_AGENT_REPLY = new Set(['generate', 'steer', 'manual_edit_apply', 'carbonize_cleanup']);function readServerInfo() {const record = readLiveServerInfo(process.cwd());@@ -38,8 +38,8 @@ function readServerInfo() {return record.info;}-export function buildPollReplyPayload(token, { id, type, message, file, data }) {- return { token, id, type, message, file, data };+export function buildPollReplyPayload(token, { id, type, message, file, data, sourceEventType }) {+ return { token, id, type, message, file, data, sourceEventType };}export function manualApplyPollBanner(event = {}) {@@ -152,7 +152,14 @@ export async function waitForEventAck(base, token, eventId, {return false;}-export async function fetchNextEvent(base, token, { totalDeadline } = {}) {+export async function fetchNextEvent(base, token, {+ totalDeadline,+ types,+ resolveTypes,+ perRequestTimeoutMs = PER_REQUEST_TIMEOUT_MS,+ leaseMs = DEFAULT_EVENT_LEASE_MS,+ signal,+} = {}) {while (true) {if (totalDeadline && Date.now() >= totalDeadline) {return { type: 'timeout' };@@ -161,8 +168,15 @@ export async function fetchNextEvent(base, token, { totalDeadline } = {}) {const remaining = totalDeadline? totalDeadline - Date.now(): PER_REQUEST_TIMEOUT_MS;- const slice = Math.min(Math.max(remaining, 1000), PER_REQUEST_TIMEOUT_MS);- const res = await fetch(`${base}/poll?token=${token}&timeout=${slice}&leaseMs=${DEFAULT_EVENT_LEASE_MS}`);+ const slice = Math.min(Math.max(remaining, 1000), perRequestTimeoutMs);+ const query = new URLSearchParams({+ token,+ timeout: String(slice),+ leaseMs: String(leaseMs),+ });+ const normalizedTypes = normalizePollTypes(resolveTypes ? await resolveTypes() : types);+ if (normalizedTypes.length > 0) query.set('types', normalizedTypes.join(','));+ const res = await fetch(`${base}/poll?${query}`, { signal });if (res.status === 401) {const err = new Error('Authentication failed. The server token may have changed.');@@ -202,11 +216,17 @@ export async function augmentEventWithAcceptHandling(event, base, token) {event._acceptResult = { handled: false, mode: 'error', error: err.message };}+ await completeAcceptHandling(event, base, token);+ return event;+}++export async function completeAcceptHandling(event, base, token) {const completionType = completionTypeForAcceptResult(event.type, event._acceptResult);try {await postReply(base, token, {id: event.id,type: completionType,+ sourceEventType: event.type,message: event._acceptResult?.error,file: event._acceptResult?.file,data: event._acceptResult?.carbonize === true ? { carbonize: true } : undefined,@@ -217,7 +237,6 @@ export async function augmentEventWithAcceptHandling(event, base, token) {if (!event._completionAck) {event._completionAck = completionAckForAcceptResult(event.id, completionType, event._acceptResult);}-return event;}@@ -245,9 +264,9 @@ export function printPollEvent(event) {console.log(JSON.stringify(event));}-export async function runPollOnce(base, token, { totalTimeout = 600_000 } = {}) {+export async function runPollOnce(base, token, { totalTimeout = 600_000, types, resolveTypes, perRequestTimeoutMs } = {}) {const deadline = Date.now() + totalTimeout;- const event = await fetchNextEvent(base, token, { totalDeadline: deadline });+ const event = await fetchNextEvent(base, token, { totalDeadline: deadline, types, resolveTypes, perRequestTimeoutMs });await augmentEventWithAcceptHandling(event, base, token);writeCarbonizeBanner(event);printPollEvent(event);@@ -258,11 +277,14 @@ export async function runPollStream(base, token, {ackTimeoutMs = 600_000,ackPollIntervalMs = 400,shouldContinue = () => true,+ types,+ resolveTypes,+ perRequestTimeoutMs,} = {}) {process.stderr.write('[impeccable-poll] stream mode: one JSON object per line on stdout; use --reply while this process stays running\n');while (shouldContinue()) {- const event = await fetchNextEvent(base, token);+ const event = await fetchNextEvent(base, token, { types, resolveTypes, perRequestTimeoutMs });await augmentEventWithAcceptHandling(event, base, token);writeCarbonizeBanner(event);printPollEvent(event);@@ -322,14 +344,17 @@ Modes:Options:--timeout=MS One-shot poll timeout in ms (default: 600000). Ignored in --stream mode+ --types=A,B Lease only these event types--ack-timeout=MS Stream mode: max wait for --reply after generate/steer (default: 600000)--file PATH Attach a source file path to the reply (generate/steer flow)--data JSON Attach a JSON result object to the reply (manual_edit_apply flow). Must be valid JSON--help Show this help messageHarness note:- Default one-shot mode is the portable contract for Claude Code, Codex, and Cursor.- --stream is experimental for harnesses with fast incremental stdout; do not use on Cursor.`);+ Default one-shot mode is the primary contract, including Codex foreground polling.+ Claude Code may run it as a background task; Cursor uses a background terminal with exit notification.+ --stream is retained for harnesses with measured, reliable incremental stdout.+ Do not use --stream on Cursor.`);process.exit(0);}@@ -360,23 +385,30 @@ Harness note:}const streamMode = args.includes('--stream');+ const typesArg = args.find((a) => a.startsWith('--types='));+ const types = normalizePollTypes(typesArg ? typesArg.slice('--types='.length) : null);const ackTimeoutArg = args.find((a) => a.startsWith('--ack-timeout='));const ackTimeoutMs = ackTimeoutArg ? parseInt(ackTimeoutArg.split('=')[1], 10) : 600_000;try {if (streamMode) {- await runPollStream(base, info.token, { ackTimeoutMs });+ await runPollStream(base, info.token, { ackTimeoutMs, types });return;}const timeoutArg = args.find((a) => a.startsWith('--timeout='));const totalTimeout = timeoutArg ? parseInt(timeoutArg.split('=')[1], 10) : 600_000;- await runPollOnce(base, info.token, { totalTimeout });+ await runPollOnce(base, info.token, { totalTimeout, types });} catch (err) {handlePollError(err);}}+export function normalizePollTypes(value) {+ const values = Array.isArray(value) ? value : String(value || '').split(',');+ return [...new Set(values.map((type) => String(type).trim()).filter(Boolean))];+}+// Auto-execute when run directlyconst _running = process.argv[1];if (_running?.endsWith('live-poll.mjs') || _running?.endsWith('live-poll.mjs/')) {diff --git a/.rovodev/skills/impeccable/scripts/live-server.mjs b/.rovodev/skills/impeccable/scripts/live-server.mjsindex 5735f2aec..c6e951086 100644--- a/.rovodev/skills/impeccable/scripts/live-server.mjs+++ b/.rovodev/skills/impeccable/scripts/live-server.mjs@@ -28,8 +28,10 @@ import {readLiveBrowserScriptParts,resolveLiveBrowserScriptParts,} from './live/browser-script-parts.mjs';-import { createLiveSessionStore } from './live/session-store.mjs';+import { createLiveSessionStore, GENERATION_FENCED_PHASES } from './live/session-store.mjs';+import { runGenerationPreflight } from './live/generation-preflight.mjs';import { validateEvent } from './live/event-validation.mjs';+import { selectAvailablePendingEvent } from './live/poll-lanes.mjs';import { createManualEditRoutes } from './live/manual-edit-routes.mjs';import { LIVE_COMMANDS } from './live/vocabulary.mjs';import {@@ -63,6 +65,10 @@ const DESIGN_MD_PATH = PROJECT_CONTEXT.designPath: null;const DEFAULT_POLL_TIMEOUT = 600_000; // 10 min — agent re-polls on timeout anywayconst SSE_HEARTBEAT_INTERVAL = 30_000; // keepalive ping every 30s+// The browser checkpoints for several unrelated reasons (see checkpointPayload+// in live-browser.js). Only these two report that variant availability changed,+// and only they may drive variant_progress / the *_reviewable phases.+const VARIANT_PROGRESS_CHECKPOINT_REASONS = new Set(['variants_progress', 'variants_ready']);// ---------------------------------------------------------------------------// Port detection@@ -156,29 +162,206 @@ function restorePendingEventsFromStore() {}}-function findAvailablePendingEvent(now = Date.now()) {- for (const entry of state.pendingEvents) {- if (entry.leaseUntil && entry.leaseUntil > now) continue;- return entry;- }- return null;+function findAvailablePendingEvent(now = Date.now(), types = null) {+ return selectAvailablePendingEvent(state.pendingEvents, { now, types });}-function leaseEvent(entry, leaseMs) {+async function leaseEvent(entry, leaseMs) {+ // Claim the entry before awaiting anything. prepareGenerateEventForLease+ // yields to the event loop, and selectAvailablePendingEvent only skips+ // entries whose lease is in the future — an unclaimed entry would be handed+ // to a second poll in that window and generated twice.+ entry.leaseUntil = Date.now() + leaseMs;+ await prepareGenerateEventForLease(entry);if (!entry.event?.id) {const idx = state.pendingEvents.indexOf(entry);if (idx !== -1) state.pendingEvents.splice(idx, 1);return entry.event;}+ // Re-stamp so the lease window starts when the agent actually receives the+ // work, not when scaffolding began.entry.leaseUntil = Date.now() + leaseMs;+ recordGenerateDelivery(entry);scheduleLeaseFlush();broadcastAgentPollingIfChanged();return entry.event;}-function acknowledgePendingEvent(id) {+function recordGenerateDelivery(entry) {+ const event = entry?.event;+ if (!event || event.type !== 'generate' || event.generationReadyAt) return;+ const at = Date.now();+ entry.event = { ...event, generationReadyAt: at };+ state.sessionStore?.appendEvent(entry.event);+ recordAgentPhase(event.id, 'generation_ready', { at });+}++async function prepareGenerateEventForLease(entry) {+ const event = entry?.event;+ if (!event || event.type !== 'generate' || event.scaffoldAttempted) return;++ recordAgentPhase(event.id, 'picked_up');+ recordAgentPhase(event.id, 'scaffolding');+ const result = await runGenerationPreflight(event, {+ cwd: process.cwd(),+ scriptsDir: __dirname,+ });+ entry.event = {+ ...event,+ scaffoldAttempted: true,+ scaffoldDurationMs: result.durationMs ?? null,+ ...(result.ok ? { scaffold: result.scaffold } : { scaffoldError: result.error || result.reason }),+ };+ state.sessionStore?.appendEvent(entry.event);+ recordAgentPhase(event.id, result.ok ? 'source_ready' : 'scaffold_fallback', {+ durationMs: result.durationMs ?? null,+ previewMode: result.scaffold?.previewMode || 'source',+ });+}++function recordAgentPhase(id, phase, details = {}) {+ if (!id) return;+ const event = {+ type: 'agent_phase',+ id,+ phase,+ at: Date.now(),+ ...details,+ };+ state.sessionStore?.appendEvent(event);+ broadcast(event);+}++/**+ * Detect a browser that missed the generation `done` broadcast.+ *+ * The preflight scaffold write triggers a framework full-reload (Astro reloads+ * the page for any .astro edit). If the agent's variant write + `done` land+ * while the browser is mid-reload, the new page misses both the second HMR+ * reload and the SSE `done` — it resumes from the scaffold-only source and+ * sits in GENERATING at 0/N forever. That resumed page always checkpoints+ * (`browser_resumed`), so a checkpoint claiming "still generating, variants+ * missing" for a session whose generation already completed is direct+ * evidence of the miss. Rebuild the `done` payload from the snapshot so the+ * caller can re-broadcast it; the browser's done handler is idempotent and+ * falls back to injecting variants from source.+ *+ * Keys on the store's monotone `generationCompletedAt`, not `phase` — the+ * behind checkpoint itself regresses `phase` to `generating`, and a browser+ * that misses the redelivered `done` too (another reload) must still trigger+ * redelivery from its next checkpoint.+ */+function detectMissedGenerationCompletion(event) {+ if (!event?.id || event.type !== 'checkpoint') return null;+ if (event.phase !== 'generating') return null;+ if (!variantCountLooksBehind(event.arrivedVariants, event.expectedVariants)) return null;+ if (!state.sessionStore) return null;+ let snapshot = null;+ try {+ snapshot = state.sessionStore.getSnapshot(event.id);+ } catch {+ return null;+ }+ return missedCompletionFromSnapshot(snapshot);+}++function variantCountLooksBehind(arrivedValue, expectedValue) {+ const arrived = Number(arrivedValue) || 0;+ const expected = Number(expectedValue) || 0;+ return arrived <= 0 || (expected > 0 && arrived < expected);+}++function missedCompletionFromSnapshot(snapshot) {+ if (!snapshot?.id || !snapshot.generationCompletedAt) return null;+ if (snapshot.generationCanceled) return null;+ // Accept/discard already underway: the browser is no longer waiting on+ // generation, and a late `done` there would collide with teardown.+ if (GENERATION_FENCED_PHASES.has(snapshot.phase)) return null;+ const file = snapshot.sourceFile || snapshot.previewFile;+ if (!file) return null;+ return {+ type: 'done',+ id: snapshot.id,+ file,+ sourceFile: snapshot.sourceFile || undefined,+ previewFile: snapshot.previewFile || undefined,+ previewMode: snapshot.previewMode || undefined,+ redelivered: true,+ };+}++function recordGenerationCheckpoint(event) {+ if (!event?.id || event.type !== 'checkpoint') return;+ if (generationIsFenced(event.id)) return;+ // Only checkpoints that report a change in variant availability are+ // generation progress. The browser also checkpoints for durability on Tune+ // slider drags, resumes, and anchor recovery; treating those as progress+ // echoed `variant_progress` straight back to the browser that sent it, which+ // remounts the component preview mid-drag (reverting the user's live param+ // edit and detaching the popover's element), and permanently latched the+ // *_reviewable phases from the wrong trigger, corrupting generation timings.+ if (!VARIANT_PROGRESS_CHECKPOINT_REASONS.has(event.reason)) return;+ const arrived = Number(event.arrivedVariants) || 0;+ const expected = Number(event.expectedVariants) || 0;+ if (arrived <= 0 || expected <= 0) return;+ const previewMode = event.previewMode || 'source';+ const previewFile = event.previewFile || event.file;+ if (previewFile) {+ broadcast({+ type: 'variant_progress',+ id: event.id,+ file: previewFile,+ sourceFile: event.sourceFile || (previewMode === 'source' ? previewFile : undefined),+ previewFile,+ previewMode,+ arrivedVariants: arrived,+ expectedVariants: expected,+ publicationKind: event.publicationKind || 'variants',+ });+ }+ const details = {+ arrivedVariants: arrived,+ expectedVariants: expected,+ checkpointReason: event.reason || null,+ };+ const at = Date.now();+ if (!generationPhaseAlreadyRecorded(event.id, 'first_reviewable')) {+ recordAgentPhase(event.id, 'first_reviewable', { ...details, at });+ }+ if (arrived >= 2 && expected >= 3 && !generationPhaseAlreadyRecorded(event.id, 'second_reviewable')) {+ recordAgentPhase(event.id, 'second_reviewable', { ...details, at });+ }+ if (arrived >= expected && !generationPhaseAlreadyRecorded(event.id, 'all_variants_ready')) {+ recordAgentPhase(event.id, 'all_variants_ready', { ...details, at });+ }+}++function generationIsFenced(id) {+ if (!state.sessionStore || !id) return false;+ try {+ const snapshot = state.sessionStore.getSnapshot(id, { includeCompleted: true });+ return snapshot?.generationCanceled === true;+ } catch {+ return false;+ }+}++function generationPhaseAlreadyRecorded(id, phase) {+ if (!state.sessionStore) return false;+ try {+ const snapshot = state.sessionStore.getSnapshot(id, { includeCompleted: true });+ return !!snapshot?.generationTimings?.[phase];+ } catch {+ return false;+ }+}++function acknowledgePendingEvent(id, sourceEventType) {if (!id) return false;- const idx = state.pendingEvents.findIndex((entry) => entry.event?.id === id);+ const idx = state.pendingEvents.findIndex((entry) => (+ entry.event?.id === id+ && (!sourceEventType || entry.event?.type === sourceEventType)+ ));if (idx === -1) return false;const acknowledged = state.pendingEvents[idx].event;state.pendingEvents.splice(idx, 1);@@ -187,9 +370,39 @@ function acknowledgePendingEvent(id) {return acknowledged;}-function findPendingEventById(id) {+function releasePendingEvent(id, sourceEventType) {+ const entry = state.pendingEvents.find((item) => (+ item.event?.id === id+ && (!sourceEventType || item.event?.type === sourceEventType)+ ));+ if (!entry) return null;+ entry.leaseUntil = 0;+ scheduleLeaseFlush();+ return entry.event;+}++function retirePendingGeneration(id) {+ if (!id) return 0;+ let retired = 0;+ for (let index = state.pendingEvents.length - 1; index >= 0; index -= 1) {+ const event = state.pendingEvents[index]?.event;+ if (event?.id !== id || event.type !== 'generate') continue;+ state.pendingEvents.splice(index, 1);+ retired += 1;+ }+ if (retired > 0) {+ scheduleLeaseFlush();+ broadcastAgentPollingIfChanged();+ }+ return retired;+}++function findPendingEventById(id, sourceEventType) {if (!id) return null;- const entry = state.pendingEvents.find((item) => item.event?.id === id);+ const entry = state.pendingEvents.find((item) => (+ item.event?.id === id+ && (!sourceEventType || item.event?.type === sourceEventType)+ ));return entry?.event || null;}@@ -198,7 +411,7 @@ function summarizePendingEventForStatus(entry) {const summary = {id: event.id,type: event.type,- leased: !!(entry.leaseUntil && entry.leaseUntil > Date.now()),+ leased: isLeased(entry),leaseUntil: entry.leaseUntil || null,};if (event.type === 'manual_edit_apply') {@@ -224,7 +437,13 @@ function summarizeActiveSessionForClient(snapshot = {}) {arrivedVariants: snapshot.arrivedVariants ?? 0,visibleVariant: snapshot.visibleVariant ?? null,checkpointRevision: snapshot.checkpointRevision ?? 0,+ browserCheckpointRevision: snapshot.browserCheckpointRevision ?? snapshot.checkpointRevision ?? 0,+ publicationCheckpointRevision: snapshot.publicationCheckpointRevision ?? 0,paramValues: snapshot.paramValues || {},+ generationPhase: snapshot.generationPhase ?? null,+ generationCompletedAt: snapshot.generationCompletedAt ?? null,+ generationCanceled: snapshot.generationCanceled === true,+ cancelReason: snapshot.cancelReason ?? null,};}@@ -269,24 +488,46 @@ function scheduleLeaseFlush() {function flushPendingPolls() {let changed = false;while (state.pendingPolls.length > 0) {- const entry = findAvailablePendingEvent();+ let pollIndex = -1;+ let entry = null;+ for (let index = 0; index < state.pendingPolls.length; index += 1) {+ const candidate = findAvailablePendingEvent(Date.now(), state.pendingPolls[index].types);+ if (!candidate) continue;+ pollIndex = index;+ entry = candidate;+ break;+ }if (!entry) {scheduleLeaseFlush();broadcastAgentPollingIfChanged();return;}- const poll = state.pendingPolls.shift();- poll.resolve(leaseEvent(entry, poll.leaseMs));+ const [poll] = state.pendingPolls.splice(pollIndex, 1);+ // leaseEvent is async (it may scaffold source), but it claims the entry+ // synchronously, so the next loop iteration will not re-select it. Resolve+ // the poll when the lease settles rather than awaiting here, so one slow+ // scaffold never delays the other parked polls. On the exceptional failure+ // path, answer `timeout` so the agent re-polls; the claim stays until the+ // lease expires, which keeps a deterministic failure from hot-looping.+ leaseEvent(entry, poll.leaseMs).then(poll.resolve, (error) => {+ console.error('[live] lease failed for ' + (entry.event?.id || 'unknown') + ': ' + (error?.message || error));+ poll.resolve({ type: 'timeout' });+ });changed = true;}scheduleLeaseFlush();if (changed) broadcastAgentPollingIfChanged();}+function isLeased(entry) {+ return !!(entry?.leaseUntil && entry.leaseUntil > Date.now());+}+function agentPollingConnected() {- const now = Date.now();- return state.pendingPolls.length > 0- || state.pendingEvents.some((entry) => entry.leaseUntil && entry.leaseUntil > now);+ // A leased event only proves that a poll returned once. The foreground task+ // may have ended immediately afterward, so only an actively waiting poll is+ // evidence that steering can wake the task right now.+ return state.pendingPolls.length > 0;}function broadcastAgentPollingIfChanged() {@@ -689,6 +930,16 @@ function createRequestHandler({ detectScript, liveScriptParts }) {res.end(JSON.stringify({ error }));return;}+ if (msg.type === 'agent_phase') {+ recordAgentPhase(msg.id, msg.phase, {+ ...(Number.isFinite(msg.durationMs) ? { durationMs: msg.durationMs } : {}),+ owner: typeof msg.owner === 'string' ? msg.owner : undefined,+ });+ res.writeHead(200, { 'Content-Type': 'application/json' });+ res.end(JSON.stringify({ ok: true }));+ return;+ }+ const missedCompletion = detectMissedGenerationCompletion(msg);if (state.sessionStore && msg.id) {try {state.sessionStore.appendEvent(msg);@@ -698,6 +949,11 @@ function createRequestHandler({ detectScript, liveScriptParts }) {return;}}+ if (msg.type === 'accept' || msg.type === 'discard') {+ retirePendingGeneration(msg.id);+ }+ recordGenerationCheckpoint(msg);+ if (missedCompletion) broadcast(missedCompletion);if (msg.type === 'exit') {cleanupSvelteComponentSessionsBeforeExit();}@@ -738,6 +994,12 @@ function createRequestHandler({ detectScript, liveScriptParts }) {// Agent poll endpoints (unchanged from WS version)// ---------------------------------------------------------------------------+function parsePollTypes(value) {+ if (!value) return null;+ const types = String(value).split(',').map((type) => type.trim()).filter(Boolean);+ return types.length > 0 ? new Set(types) : null;+}+function handlePollGet(req, res, url) {const token = url.searchParams.get('token');if (token !== state.token) {@@ -748,13 +1010,25 @@ function handlePollGet(req, res, url) {state.lastPollAt = Date.now();const timeout = parseInt(url.searchParams.get('timeout') || DEFAULT_POLL_TIMEOUT, 10);const leaseMs = parseInt(url.searchParams.get('leaseMs') || '30000', 10);- const available = findAvailablePendingEvent();+ const types = parsePollTypes(url.searchParams.get('types'));+ const available = findAvailablePendingEvent(Date.now(), types);if (available) {- res.writeHead(200, { 'Content-Type': 'application/json' });- res.end(JSON.stringify(leaseEvent(available, leaseMs)));+ // Do not await inline: leaseEvent may scaffold source, and this handler runs+ // on the server's only thread. The client can disconnect during that window,+ // so check the socket before replying.+ leaseEvent(available, leaseMs).then((event) => {+ if (res.writableEnded || res.destroyed) return;+ res.writeHead(200, { 'Content-Type': 'application/json' });+ res.end(JSON.stringify(event));+ }, (error) => {+ console.error('[live] lease failed for ' + (available.event?.id || 'unknown') + ': ' + (error?.message || error));+ if (res.writableEnded || res.destroyed) return;+ res.writeHead(200, { 'Content-Type': 'application/json' });+ res.end(JSON.stringify({ type: 'timeout' }));+ });return;}- const poll = { resolve, leaseMs };+ const poll = { resolve, leaseMs, types };const timer = setTimeout(() => {const idx = state.pendingPolls.indexOf(poll);if (idx !== -1) state.pendingPolls.splice(idx, 1);@@ -783,12 +1057,15 @@ function sessionFileMetadataFromPollReply(file) {if (!file || typeof file !== 'string') return { file };const normalized = file.split(path.sep).join('/');const base = { file: normalized };- if (!normalized.endsWith('/manifest.json') && normalized !== 'manifest.json') return base;- if (!normalized.includes('node_modules/.impeccable-live/') && !normalized.includes('src/lib/impeccable/')) return base;+ const metadataFile = normalized;+ if (!metadataFile.endsWith('/manifest.json') && metadataFile !== 'manifest.json') return base;+ if (!metadataFile.includes('node_modules/.impeccable-live/')+ && !metadataFile.includes('src/lib/impeccable/')+ && !metadataFile.includes('/.impeccable-live/')) return base;let full;try {- full = path.resolve(process.cwd(), normalized);+ full = path.resolve(process.cwd(), metadataFile);const rel = path.relative(process.cwd(), full);if (!rel || rel.startsWith('..') || path.isAbsolute(rel)) return base;} catch {@@ -797,18 +1074,47 @@ function sessionFileMetadataFromPollReply(file) {try {const manifest = JSON.parse(fs.readFileSync(full, 'utf-8'));- if (manifest?.previewMode !== 'svelte-component' || !manifest.sourceFile) return base;+ if (manifest?.previewMode !== 'svelte-component'+ || !manifest.sourceFile) return base;return {file: String(manifest.sourceFile).split(path.sep).join('/'),sourceFile: String(manifest.sourceFile).split(path.sep).join('/'),previewFile: normalized,- previewMode: 'svelte-component',+ previewMode: manifest.previewMode,};} catch {return base;}}+function inferSourceEventType(msg = {}, pendingEvents = state.pendingEvents) {+ const entriesForId = pendingEvents.filter((entry) => entry.event?.id === msg.id);+ const pendingTypes = new Set(entriesForId.map((entry) => entry.event?.type));+ if (msg.type === 'discarded' || msg.type === 'discard') return 'discard';+ if (msg.type === 'complete') {+ if (pendingTypes.has('carbonize_cleanup')) return 'carbonize_cleanup';+ return pendingTypes.has('accept') ? 'accept' : (pendingTypes.has('generate') ? 'generate' : undefined);+ }+ if (msg.type === 'steer_done') return 'steer';+ // `agent_done` can be the automatic acknowledgement for a carbonize Accept.+ // New pollers send sourceEventType explicitly; default to generate only for+ // older callers so a late worker cannot acknowledge a queued Accept.+ if (msg.type === 'agent_done' || msg.type === 'done') return 'generate';+ // `error` is reference/live.md's documented failure reply, and parseReplyArgs+ // never sets sourceEventType on it (the poller is a fresh process that cannot+ // know what it leased). Returning undefined here makes acknowledgePendingEvent+ // match *any* event for this id: a stale generate worker's failure silently+ // consumed the user's queued Accept, which was then never delivered to any+ // agent and left the browser in SAVING forever. Attribute the failure to the+ // event this agent actually holds a lease on, and otherwise to `generate` —+ // never to a wildcard. If that generate was already retired by an Accept, the+ // ack simply finds no match, which is the correct outcome for a stale reply.+ if (msg.type === 'error') {+ return entriesForId.find(isLeased)?.event?.type || 'generate';+ }+ return undefined;+}+function handlePollPost(req, res) {let body = '';req.on('data', (c) => { body += c; });@@ -869,7 +1175,23 @@ function handlePollPost(req, res) {res.end(JSON.stringify({ error: 'stale_manual_edit_apply_reply', ...rollback }));return;}- const pendingEventBeforeAck = findPendingEventById(msg.id);+ const sourceEventType = msg.sourceEventType || inferSourceEventType(msg);+ if (msg.type === 'retry') {+ const releasedEvent = releasePendingEvent(msg.id, sourceEventType);+ if (!releasedEvent) {+ res.writeHead(msg.id ? 404 : 400, { 'Content-Type': 'application/json' });+ res.end(JSON.stringify({+ error: msg.id ? 'unknown_poll_retry_id' : 'missing_poll_retry_id',+ id: msg.id,+ }));+ return;+ }+ flushPendingPolls();+ res.writeHead(200, { 'Content-Type': 'application/json' });+ res.end(JSON.stringify({ ok: true, released: true }));+ return;+ }+ const pendingEventBeforeAck = findPendingEventById(msg.id, sourceEventType);if (pendingEventBeforeAck?.type === 'steer' && msg.type === 'steer_done'&& !msg.file && !(typeof msg.message === 'string' && msg.message.trim())) {res.writeHead(400, { 'Content-Type': 'application/json' });@@ -879,7 +1201,7 @@ function handlePollPost(req, res) {}));return;}- const acknowledgedEvent = acknowledgePendingEvent(msg.id);+ const acknowledgedEvent = acknowledgePendingEvent(msg.id, sourceEventType);let skipJournalReply = false;let existingSession = null;if (!acknowledgedEvent && state.sessionStore && msg.id) {@@ -1083,7 +1405,10 @@ if (args.includes('--background')) {process.exit(0);}} catch { /* not ready yet */ }- await new Promise(r => setTimeout(r, 200));+ // The detached child is typically listening in 35-45ms. A 200ms polling+ // floor dominated configured cold Live startup; poll cheaply and return+ // as soon as the child has written its ready record.+ await new Promise(r => setTimeout(r, 5));}console.error('Timed out waiting for live server to start.');process.exit(1);diff --git a/.rovodev/skills/impeccable/scripts/live-status.mjs b/.rovodev/skills/impeccable/scripts/live-status.mjsindex f7e464999..dc98b7386 100644--- a/.rovodev/skills/impeccable/scripts/live-status.mjs+++ b/.rovodev/skills/impeccable/scripts/live-status.mjs@@ -37,15 +37,19 @@ export async function statusCli() {pendingEvents: server.pendingEvents,} : null,activeSessions: server?.activeSessions || activeSessions,- recoveryHint: manualApply- ? manualApplyResumeHint(manualApply)- : server- ? 'Run live-poll.mjs to continue pending work, or live-complete.mjs --id <session> after manual cleanup.'- : 'Start live-server.mjs to requeue pending durable events, then run live-poll.mjs.',+ recoveryHint: recoveryHint({ server, manualApply }),};console.log(JSON.stringify(payload, null, 2));}+function recoveryHint({ server, manualApply }) {+ if (manualApply) return manualApplyResumeHint(manualApply);+ if (server) {+ return 'Run live-poll.mjs to continue pending work, or live-complete.mjs --id <session> after manual cleanup.';+ }+ return 'Start live-server.mjs to requeue pending durable events, then run live-poll.mjs.';+}+function findPendingManualApply(server, activeSessions) {const fromServer = server?.pendingEvents?.find((event) => event?.type === 'manual_edit_apply');if (fromServer) return fromServer;diff --git a/.rovodev/skills/impeccable/scripts/live-wrap.mjs b/.rovodev/skills/impeccable/scripts/live-wrap.mjsindex 438c01b68..48d7f7683 100644--- a/.rovodev/skills/impeccable/scripts/live-wrap.mjs+++ b/.rovodev/skills/impeccable/scripts/live-wrap.mjs@@ -160,11 +160,29 @@ The agent should insert variant HTML at insertLine.`);if (filtered.length === 1) {match = filtered[0];} else if (filtered.length === 0) {- // Source uses dynamic content (`<h1>{title}</h1>` etc.) so the- // browser-side textContent doesn't appear literally in source. Fall- // back to first-match rather than refusing — this is the same- // behavior unmodified callers see, just preserved.- match = candidates[0];+ const normalizedText = String(text).replace(/\s+/g, ' ').trim();+ if (normalizedText.length < 8) {+ // Very short labels cannot disambiguate siblings reliably. Preserve+ // the legacy behavior for these low-information picker events.+ match = candidates[0];+ } else {+ // Rendered text that is absent from every candidate usually means+ // the source uses expressions or component props. Picking the first+ // same-class sibling silently edits the wrong instance (observed on+ // Astro result cards), so stop and surface every candidate instead.+ console.error(JSON.stringify({+ error: 'element_ambiguous',+ fallback: 'agent-driven',+ reason: 'rendered_text_not_in_source',+ file: path.relative(process.cwd(), targetFile),+ candidates: candidates.map((c) => ({+ startLine: c.startLine + 1,+ endLine: c.endLine + 1,+ })),+ hint: 'Rendered text does not occur in any matching source branch. The element may use dynamic props or expressions; inspect the candidates and wrap the intended instance manually.',+ }));+ process.exit(1);+ }} else {// Multiple candidates ALSO match the text. Truly ambiguous — refuse// rather than pick wrong, and hand the agent the candidate locations@@ -269,6 +287,7 @@ The agent should insert variant HTML at insertLine.`);const originalIndented = reindentOriginal(' ');const relTargetFile = path.relative(process.cwd(), targetFile).split(path.sep).join('/');const useSvelteComponent = shouldUseSvelteComponentInjection(targetFile);+ const useFrameworkComponent = useSvelteComponent;// Wrapper attributes differ by syntax. HTML allows plain string attrs;// JSX requires object-literal style and parses string attrs as HTML (which@@ -288,7 +307,7 @@ The agent should insert variant HTML at insertLine.`);// replacement range to include the wrapper's `<div>` open / close lines// so the entire scaffold gets removed cleanly.const wrapperLines = isJsx ? [- indent + '<div data-impeccable-variants="' + id + '" data-impeccable-variant-count="' + count + '" ' + styleContents + '>',+ indent + '<div data-impeccable-variants="' + id + '" data-impeccable-variant-count="' + count + '"' + ' ' + styleContents + '>',indent + ' ' + commentSyntax.open + ' impeccable-variants-start ' + id + ' ' + commentSyntax.close,indent + ' ' + commentSyntax.open + ' Original ' + commentSyntax.close,indent + ' <div data-impeccable-variant="original">',@@ -299,7 +318,7 @@ The agent should insert variant HTML at insertLine.`);indent + '</div>',] : [indent + commentSyntax.open + ' impeccable-variants-start ' + id + ' ' + commentSyntax.close,- indent + '<div data-impeccable-variants="' + id + '" data-impeccable-variant-count="' + count + '" ' + styleContents + '>',+ indent + '<div data-impeccable-variants="' + id + '" data-impeccable-variant-count="' + count + '"' + ' ' + styleContents + '>',indent + ' ' + commentSyntax.open + ' Original ' + commentSyntax.close,indent + ' <div data-impeccable-variant="original">',originalIndented,@@ -356,15 +375,18 @@ The agent should insert variant HTML at insertLine.`);const outputRelFile = path.relative(process.cwd(), outputFile).split(path.sep).join('/');const svelteComponentAuthoring = useSvelteComponent ? buildSvelteComponentCssAuthoring(count) : null;+ const componentSession = svelteSession;+ const componentPreviewMode = useSvelteComponent ? 'svelte-component' : undefined;+ const previewMode = componentPreviewMode;console.log(JSON.stringify({file: outputRelFile,- sourceFile: useSvelteComponent ? relTargetFile : undefined,- previewMode: useSvelteComponent ? 'svelte-component' : undefined,- componentDir: svelteSession?.componentDir,- propContract: svelteSession?.propContract,- sourceStartLine: useSvelteComponent ? startLine + 1 : undefined,- sourceEndLine: useSvelteComponent ? endLine + 1 : undefined,+ sourceFile: useFrameworkComponent ? relTargetFile : undefined,+ previewMode,+ componentDir: componentSession?.componentDir,+ propContract: componentSession?.propContract,+ sourceStartLine: useFrameworkComponent ? startLine + 1 : undefined,+ sourceEndLine: useFrameworkComponent ? endLine + 1 : undefined,startLine: outputStartLine, // 1-indexed for the agent// wrapperLines is an array but one element (the original-content slot)// is a `\n`-joined multi-line string, so the actual file-row count is@@ -374,10 +396,10 @@ The agent should insert variant HTML at insertLine.`);endLine: outputEndLine, // 1-indexedinsertLine, // 1-indexed: where variants gocommentSyntax: commentSyntax,- styleMode: useSvelteComponent ? 'svelte-component' : styleMode.mode,- styleTag: useSvelteComponent ? null : styleMode.styleTag,- cssSelectorPrefixExamples: useSvelteComponent ? [] : buildCssSelectorPrefixExamples(styleMode.mode, count),- cssAuthoring: useSvelteComponent ? svelteComponentAuthoring : buildCssAuthoring(styleMode, count),+ styleMode: componentPreviewMode || styleMode.mode,+ styleTag: useFrameworkComponent ? null : styleMode.styleTag,+ cssSelectorPrefixExamples: useFrameworkComponent ? [] : buildCssSelectorPrefixExamples(styleMode.mode, count),+ cssAuthoring: svelteComponentAuthoring || buildCssAuthoring(styleMode, count),originalLineCount: originalLines.length,}));}diff --git a/.rovodev/skills/impeccable/scripts/live.mjs b/.rovodev/skills/impeccable/scripts/live.mjsindex e0bd1ad24..b21a71cc4 100644--- a/.rovodev/skills/impeccable/scripts/live.mjs+++ b/.rovodev/skills/impeccable/scripts/live.mjs@@ -10,7 +10,7 @@** After this, the agent's only remaining steps are:* - Open the project's live dev/preview URL in the browser (optional, if browser automation exists)—not `serverPort`; that port is the Impeccable helper for /live.js and /poll- * - Enter the poll loop: `node live-poll.mjs`+ * - Enter the harness-native poll loop: `node live-poll.mjs`** Usage:* node live.mjs # Prepare everything, print JSON, exit@@ -40,6 +40,7 @@ Prepare everything for live variant mode in a single command:- Starts (or reuses) the live server in the background- Injects the browser script tag- Reads PRODUCT.md / DESIGN.md for project context+ - Prepares the harness-native foreground/background poll loop- In monorepos, choose a child app first; --target <path> is the fallback/manual pathOn success, prints a JSON blob with:diff --git a/.rovodev/skills/impeccable/scripts/live/completion.mjs b/.rovodev/skills/impeccable/scripts/live/completion.mjsindex 986773066..6f539336d 100644--- a/.rovodev/skills/impeccable/scripts/live/completion.mjs+++ b/.rovodev/skills/impeccable/scripts/live/completion.mjs@@ -1,9 +1,18 @@+// A preview whose variants live in component modules rather than in the user's+// source. These leave no markers in the real file, so a failed accept gives the+// agent nothing to hand-edit and must be reported as a failure rather than+// reference/live.md's manual-cleanup handoff. Kept as a set: any future+// component-module preview mode belongs here the day it lands.+const PREVIEW_MODES_WITHOUT_SOURCE_MARKERS = new Set([+ 'svelte-component',+]);+export function completionTypeForAcceptResult(eventType, acceptResult) {if (eventType === 'discard') return acceptResult?.handled === true ? 'discarded' : 'error';if (acceptResult?.handled === true && acceptResult?.carbonize === true) return 'agent_done';if (acceptResult?.handled === true) return 'complete';if (acceptResult?.mode === 'error') return 'error';- if (eventType === 'accept' && acceptResult?.previewMode === 'svelte-component') return 'error';+ if (eventType === 'accept' && PREVIEW_MODES_WITHOUT_SOURCE_MARKERS.has(acceptResult?.previewMode)) return 'error';return 'agent_done';}diff --git a/.rovodev/skills/impeccable/scripts/live/event-validation.mjs b/.rovodev/skills/impeccable/scripts/live/event-validation.mjsindex 0897b1317..122c29836 100644--- a/.rovodev/skills/impeccable/scripts/live/event-validation.mjs+++ b/.rovodev/skills/impeccable/scripts/live/event-validation.mjs@@ -118,6 +118,15 @@ export function validateEvent(msg) {return 'checkpoint: paramValues must be an object';}return null;+ case 'agent_phase':+ if (!isValidId(msg.id)) return 'agent_phase: missing or malformed id';+ if (typeof msg.phase !== 'string' || !/^[a-z][a-z0-9_]{1,63}$/.test(msg.phase)) {+ return 'agent_phase: missing or malformed phase';+ }+ if (msg.durationMs !== undefined && (!Number.isFinite(msg.durationMs) || msg.durationMs < 0)) {+ return 'agent_phase: durationMs must be a non-negative number';+ }+ return null;case 'exit':return null;case 'prefetch':@@ -131,6 +140,12 @@ export function validateEvent(msg) {if (msg.message.length > 4000) return 'steer: message too long';if (msg.pageUrl !== undefined && typeof msg.pageUrl !== 'string') return 'steer: pageUrl must be string';return null;+ case 'carbonize_cleanup':+ if (!isValidId(msg.id)) return 'carbonize_cleanup: missing or malformed id';+ if (!isValidId(msg.sessionId)) return 'carbonize_cleanup: missing or malformed sessionId';+ if (!msg.file || typeof msg.file !== 'string') return 'carbonize_cleanup: missing file';+ if (!isValidVariantId(String(msg.variantId))) return 'carbonize_cleanup: missing or malformed variantId';+ return null;default:return 'Unknown event type: ' + msg.type;}diff --git a/.rovodev/skills/impeccable/scripts/live/generation-preflight.mjs b/.rovodev/skills/impeccable/scripts/live/generation-preflight.mjsnew file mode 100644index 000000000..07a5e957e--- /dev/null+++ b/.rovodev/skills/impeccable/scripts/live/generation-preflight.mjs@@ -0,0 +1,102 @@+import { execFile } from 'node:child_process';+import path from 'node:path';+import { promisify } from 'node:util';++const execFileAsync = promisify(execFile);+const PREFLIGHT_TIMEOUT_MS = 15_000;++export function buildGenerationPreflight(event, scriptsDir) {+ if (!event || event.type !== 'generate' || !event.id) return null;++ const isInsert = event.mode === 'insert';+ const target = isInsert ? insertTarget(event) : replaceTarget(event);+ if (!target.elementId && !target.classes) return null;++ const script = path.join(scriptsDir, isInsert ? 'live-insert.mjs' : 'live-wrap.mjs');+ const args = [script, '--id', event.id, '--count', String(event.count || 3)];+ if (isInsert) args.push('--position', target.position);+ if (target.elementId) args.push('--element-id', target.elementId);+ if (target.classes) args.push('--classes', target.classes);+ if (target.tag) args.push('--tag', target.tag);+ if (target.text) args.push('--text', target.text);+ if (!isInsert && event.pageUrl) args.push('--page-url', event.pageUrl);+ return { script, args, mode: isInsert ? 'insert' : 'replace' };+}++/**+ * Scaffold the source for a generate event before handing it to an agent.+ *+ * Async on purpose. This spawns `live-wrap.mjs`, which walks the project's+ * source tree and can take seconds (measured at ~7.6s on a large repo when the+ * element is not found, with a 15s ceiling). The live server is single-threaded+ * and calls this while leasing a poll, so a synchronous spawn froze the whole+ * server for that entire window: Accept and Discard POSTs, SSE progress+ * broadcasts, and every other poll stalled behind it.+ */+export async function runGenerationPreflight(event, {+ cwd = process.cwd(),+ scriptsDir,+ execFileImpl = execFileAsync,+ timeoutMs = PREFLIGHT_TIMEOUT_MS,+} = {}) {+ const command = buildGenerationPreflight(event, scriptsDir);+ if (!command) {+ return { ok: false, skipped: true, reason: 'insufficient_locator' };+ }++ const startedAt = performance.now();+ try {+ const { stdout } = await execFileImpl(process.execPath, command.args, {+ cwd,+ encoding: 'utf-8',+ timeout: timeoutMs,+ });+ const line = String(stdout).trim().split('\n').filter(Boolean).pop();+ if (!line) throw new Error('preflight returned no scaffold metadata');+ return {+ ok: true,+ mode: command.mode,+ durationMs: performance.now() - startedAt,+ scaffold: JSON.parse(line),+ };+ } catch (error) {+ return {+ ok: false,+ mode: command.mode,+ durationMs: performance.now() - startedAt,+ error: compactError(error),+ };+ }+}++function replaceTarget(event) {+ return normalizeTarget(event.element || {});+}++function insertTarget(event) {+ return {+ ...normalizeTarget(event.insert?.anchor || {}),+ position: event.insert?.position === 'before' ? 'before' : 'after',+ };+}++function normalizeTarget(target) {+ const classes = Array.isArray(target.classes)+ ? target.classes.join(' ')+ : String(target.classes || '').trim();+ const text = typeof target.textContent === 'string'+ ? target.textContent.trim().slice(0, 80)+ : '';+ return {+ elementId: target.id || target.elementId || undefined,+ classes: classes || undefined,+ tag: target.tagName || target.tag || undefined,+ text: text || undefined,+ };+}++function compactError(error) {+ const stderr = error?.stderr ? String(error.stderr).trim() : '';+ const message = stderr.split('\n').filter(Boolean).pop() || error?.message || 'preflight failed';+ return String(message).slice(0, 500);+}diff --git a/.rovodev/skills/impeccable/scripts/live/poll-lanes.mjs b/.rovodev/skills/impeccable/scripts/live/poll-lanes.mjsnew file mode 100644index 000000000..65f20a87a--- /dev/null+++ b/.rovodev/skills/impeccable/scripts/live/poll-lanes.mjs@@ -0,0 +1,14 @@+export function eventPriority(event = {}) {+ if (event.type === 'accept' || event.type === 'discard' || event.type === 'exit') return 0;+ if (event.type === 'manual_edit_apply' || event.type === 'steer' || event.type === 'carbonize_cleanup') return 1;+ if (event.type === 'generate') return 2;+ return 3;+}++export function selectAvailablePendingEvent(entries, { now = Date.now(), types = null } = {}) {+ const allowed = types instanceof Set ? types : (Array.isArray(types) ? new Set(types) : null);+ return entries+ .filter((entry) => !(entry.leaseUntil && entry.leaseUntil > now))+ .filter((entry) => !allowed || allowed.has(entry.event?.type))+ .sort((a, b) => eventPriority(a.event) - eventPriority(b.event) || a.seq - b.seq)[0] || null;+}diff --git a/.rovodev/skills/impeccable/scripts/live/session-store.mjs b/.rovodev/skills/impeccable/scripts/live/session-store.mjsindex affba67c9..9d20341dd 100644--- a/.rovodev/skills/impeccable/scripts/live/session-store.mjs+++ b/.rovodev/skills/impeccable/scripts/live/session-store.mjs@@ -1,24 +1,26 @@import fs from 'node:fs';import path from 'node:path';-import { getLegacyLiveSessionsDir, getLiveSessionsDir } from '../lib/impeccable-paths.mjs';+import { getLegacyLiveSessionsDir, getLiveSessionsDir, safeSessionId } from '../lib/impeccable-paths.mjs';const COMPLETED_PHASES = new Set(['completed', 'discarded']);+export const GENERATION_FENCED_PHASES = new Set([+ 'accept_requested',+ 'discard_requested',+ 'carbonize_required',+ 'completed',+ 'discarded',+]);export function createLiveSessionStore({ cwd = process.cwd(), sessionId } = {}) {const rootDir = getLiveSessionsDir(cwd);const legacyRootDir = getLegacyLiveSessionsDir(cwd);fs.mkdirSync(rootDir, { recursive: true });- const snapshotCache = new Map();-- function loadCachedOrRebuild(id) {- const cached = snapshotCache.get(id);- if (cached) return cached;- const journalPath = getReadableJournalPath(id);- const rebuilt = rebuildSnapshotFromJournal(journalPath, id);- snapshotCache.set(id, rebuilt);- return rebuilt;- }+ // No snapshot cache on purpose: appendEvent and getSnapshot both rebuild from+ // the journal so sequence numbers and phase fences never come from a stale+ // in-memory copy when the publisher/complete helpers append from another+ // process. A cache written but never read would grow per session for the+ // lifetime of the server without ever saving a rebuild.function getReadableJournalPath(id) {const primary = getJournalPath(rootDir, id);if (fs.existsSync(primary)) return primary;@@ -38,7 +40,10 @@ export function createLiveSessionStore({ cwd = process.cwd(), sessionId } = {})if (!fs.existsSync(journalPath) && fs.existsSync(legacyJournalPath)) {fs.copyFileSync(legacyJournalPath, journalPath);}- const prior = loadCachedOrRebuild(normalized.id);+ // Publisher/complete helpers can append from a separate process while+ // the server is alive. Rebuild here so sequence numbers and phase+ // fences never come from a stale in-memory cache.+ const prior = rebuildSnapshotFromJournal(getReadableJournalPath(normalized.id), normalized.id);const seq = prior.nextSeq;const entry = {seq,@@ -49,7 +54,6 @@ export function createLiveSessionStore({ cwd = process.cwd(), sessionId } = {})};fs.appendFileSync(journalPath, JSON.stringify(entry) + '\n');const next = applyEvent(prior.snapshot, entry, prior.diagnostics);- snapshotCache.set(normalized.id, { snapshot: next, diagnostics: next.diagnostics || [], nextSeq: seq + 1 });writeSnapshot(snapshotPath, next);return next;},@@ -58,7 +62,6 @@ export function createLiveSessionStore({ cwd = process.cwd(), sessionId } = {})const journalPath = getReadableJournalPath(id);const snapshotPath = getSnapshotPath(rootDir, id);const rebuilt = rebuildSnapshotFromJournal(journalPath, id);- snapshotCache.set(id, rebuilt);writeSnapshot(snapshotPath, rebuilt.snapshot);if (!opts.includeCompleted && COMPLETED_PHASES.has(rebuilt.snapshot.phase)) return null;return rebuilt.snapshot;@@ -95,11 +98,6 @@ function getSnapshotPath(rootDir, id) {return path.join(rootDir, safeSessionId(id) + '.snapshot.json');}-function safeSessionId(id) {- if (!/^[A-Za-z0-9_-]{1,128}$/.test(id)) throw new Error('invalid session id: ' + id);- return id;-}-function baseSnapshot(id) {return {id,@@ -116,9 +114,18 @@ function baseSnapshot(id) {pendingEvent: null,deliveryLease: null,checkpointRevision: 0,+ browserCheckpointRevision: 0,+ publicationCheckpointRevision: 0,activeOwner: null,sourceMarkers: {},fallbackMode: null,+ generationPhase: null,+ generationCompletedAt: null,+ generationTimings: {},+ variantPlan: null,+ generationCanceled: false,+ generationCanceledAt: null,+ cancelReason: null,annotationArtifacts: [],diagnostics: [],updatedAt: null,@@ -158,6 +165,8 @@ function applyEvent(snapshot, entry, inheritedDiagnostics = []) {...snapshot,paramValues: { ...(snapshot.paramValues || {}) },sourceMarkers: { ...(snapshot.sourceMarkers || {}) },+ generationTimings: { ...(snapshot.generationTimings || {}) },+ variantPlan: snapshot.variantPlan || null,annotationArtifacts: [...(snapshot.annotationArtifacts || [])],diagnostics: [...(snapshot.diagnostics || [])],updatedAt: entry.ts || new Date().toISOString(),@@ -174,11 +183,48 @@ function applyEvent(snapshot, entry, inheritedDiagnostics = []) {next.expectedVariants = event.count ?? next.expectedVariants;next.pendingEventSeq = entry.seq ?? next.pendingEventSeq;next.pendingEvent = toPendingEvent(event);+ next.variantPlan = null;if (event.screenshotPath) upsertArtifact(next.annotationArtifacts, { type: 'screenshot', path: event.screenshotPath });break;+ case 'variant_plan':+ if (!next.generationCanceled && !GENERATION_FENCED_PHASES.has(next.phase)) {+ next.variantPlan = event.plan ?? next.variantPlan;+ }+ break;+ case 'detector_waivers':+ if (!next.generationCanceled && !GENERATION_FENCED_PHASES.has(next.phase)) {+ next.detectorWaivers = [+ ...(next.detectorWaivers || []),+ ...(Array.isArray(event.waivers) ? event.waivers : []),+ ];+ }+ break;+ case 'agent_phase':+ next.generationPhase = event.phase ?? next.generationPhase;+ if (event.phase) {+ next.generationTimings[event.phase] = {+ at: event.at ?? (Date.parse(entry.ts || '') || null),+ durationMs: event.durationMs ?? null,+ };+ }+ break;case 'variants_ready':case 'agent_done':+ if ((next.generationCanceled || GENERATION_FENCED_PHASES.has(next.phase))+ && !(event.type === 'agent_done' && event.carbonize === true && next.phase === 'accept_requested')) {+ next.diagnostics.push({+ error: 'late_generation_event_ignored',+ type: event.type,+ phase: next.phase,+ });+ break;+ }next.phase = event.carbonize === true ? 'carbonize_required' : 'variants_ready';+ // Durable completion marker: later browser checkpoints (a resumed page+ // reporting phase "generating") regress `phase`, but generation staying+ // finished is monotone — the live server keys missed-`done` redelivery+ // on this field.+ next.generationCompletedAt = event.at ?? (Date.parse(entry.ts || '') || Date.now());next.sourceFile = event.sourceFile ?? event.file ?? next.sourceFile;next.previewFile = event.previewFile ?? next.previewFile;next.previewMode = event.previewMode ?? next.previewMode;@@ -194,27 +240,45 @@ function applyEvent(snapshot, entry, inheritedDiagnostics = []) {}break;case 'checkpoint':- if (COMPLETED_PHASES.has(next.phase)) {+ if (next.generationCanceled || GENERATION_FENCED_PHASES.has(next.phase)) {next.diagnostics.push({ error: 'checkpoint_after_terminal_ignored', phase: event.phase ?? null, revision: event.revision ?? null });break;}- if ((event.revision ?? 0) >= (next.checkpointRevision ?? 0)) {- next.phase = event.phase ?? next.phase;- next.checkpointRevision = event.revision ?? next.checkpointRevision;- next.activeOwner = event.owner ?? next.activeOwner;- next.arrivedVariants = event.arrivedVariants ?? next.arrivedVariants;- next.visibleVariant = event.visibleVariant ?? next.visibleVariant;- next.sourceFile = event.sourceFile ?? next.sourceFile;- next.previewFile = event.previewFile ?? next.previewFile;- next.previewMode = event.previewMode ?? next.previewMode;- if (event.paramValues) next.paramValues = { ...event.paramValues };- } else {- next.diagnostics.push({ error: 'stale_checkpoint_ignored', revision: event.revision });+ {+ const revisionDomain = event.revisionDomain === 'publication'+ || (event.reason === 'variants_progress' && !event.owner)+ ? 'publication'+ : 'browser';+ const revisionField = revisionDomain === 'publication'+ ? 'publicationCheckpointRevision'+ : 'browserCheckpointRevision';+ const currentRevision = next[revisionField]+ ?? (revisionDomain === 'browser' ? next.checkpointRevision : 0)+ ?? 0;+ if ((event.revision ?? 0) >= currentRevision) {+ next.phase = event.phase ?? next.phase;+ next[revisionField] = event.revision ?? currentRevision;+ if (revisionDomain === 'browser') {+ next.checkpointRevision = event.revision ?? next.checkpointRevision;+ next.activeOwner = event.owner ?? next.activeOwner;+ }+ next.arrivedVariants = event.arrivedVariants ?? next.arrivedVariants;+ if (revisionDomain === 'browser') next.visibleVariant = event.visibleVariant ?? next.visibleVariant;+ next.sourceFile = event.sourceFile ?? next.sourceFile;+ next.previewFile = event.previewFile ?? next.previewFile;+ next.previewMode = event.previewMode ?? next.previewMode;+ if (revisionDomain === 'browser' && event.paramValues) next.paramValues = { ...event.paramValues };+ } else {+ next.diagnostics.push({ error: 'stale_checkpoint_ignored', revision: event.revision, revisionDomain });+ }}break;case 'accept':case 'accept_intent':next.phase = 'accept_requested';+ next.generationCanceled = true;+ next.generationCanceledAt = event.at ?? (Date.parse(entry.ts || '') || Date.now());+ next.cancelReason = 'accept';next.visibleVariant = Number(event.variantId ?? next.visibleVariant);if (event.paramValues) next.paramValues = { ...event.paramValues };next.pendingEventSeq = entry.seq ?? next.pendingEventSeq;@@ -232,6 +296,12 @@ function applyEvent(snapshot, entry, inheritedDiagnostics = []) {next.pendingEventSeq = entry.seq ?? next.pendingEventSeq;next.pendingEvent = toPendingEvent(event);break;+ case 'carbonize_cleanup':+ next.phase = 'carbonize_cleanup_requested';+ next.sourceFile = event.file ?? next.sourceFile;+ next.pendingEventSeq = entry.seq ?? next.pendingEventSeq;+ next.pendingEvent = toPendingEvent(event);+ break;case 'steer_done':next.phase = 'steer_done';next.sourceFile = event.sourceFile ?? event.file ?? next.sourceFile;@@ -243,6 +313,9 @@ function applyEvent(snapshot, entry, inheritedDiagnostics = []) {break;case 'discard':next.phase = 'discard_requested';+ next.generationCanceled = true;+ next.generationCanceledAt = event.at ?? (Date.parse(entry.ts || '') || Date.now());+ next.cancelReason = 'discard';next.pendingEventSeq = entry.seq ?? next.pendingEventSeq;next.pendingEvent = toPendingEvent(event);break;@@ -260,6 +333,10 @@ function applyEvent(snapshot, entry, inheritedDiagnostics = []) {next.pendingEvent = null;break;case 'agent_error':+ if (next.generationCanceled && event.sourceEventType === 'generate') {+ next.diagnostics.push({ error: 'late_generation_event_ignored', type: event.type, phase: next.phase });+ break;+ }next.phase = 'agent_error';next.pendingEventSeq = null;next.pendingEvent = null;diff --git a/.rovodev/skills/impeccable/scripts/live/source-lock.mjs b/.rovodev/skills/impeccable/scripts/live/source-lock.mjsnew file mode 100644index 000000000..9ccc557be--- /dev/null+++ b/.rovodev/skills/impeccable/scripts/live/source-lock.mjs@@ -0,0 +1,105 @@+import fs from 'node:fs';+import path from 'node:path';+import { createHash, randomUUID } from 'node:crypto';+import { getLiveDir, isLiveServerPidReachable } from '../lib/impeccable-paths.mjs';++// Only used to retire a lock whose contents we cannot read (empty or truncated+// by a crash mid-write). A readable lock's fate is decided by its owner's+// liveness instead, so a slow critical section is never swept.+const UNREADABLE_LOCK_STALE_MS = 60_000;++export function sourceLockPath(file, cwd = process.cwd()) {+ const digest = createHash('sha256').update(path.resolve(cwd, file)).digest('hex').slice(0, 24);+ return path.join(getLiveDir(cwd), 'locks', digest + '.lock');+}++export function withSourceLockSync(file, owner, fn, {+ cwd = process.cwd(),+ waitMs = 0,+ retryMs = 5,+} = {}) {+ const lockPath = sourceLockPath(file, cwd);+ fs.mkdirSync(path.dirname(lockPath), { recursive: true });+ const deadline = Date.now() + Math.max(0, Number(waitMs) || 0);+ // Identifies this acquisition specifically, so release can tell our own lock+ // from a replacement that some other writer created.+ const token = randomUUID();+ let acquired = false;++ while (!acquired) {+ clearStaleLock(lockPath);+ let fd;+ try {+ fd = fs.openSync(lockPath, 'wx');+ fs.writeFileSync(fd, JSON.stringify({+ owner,+ token,+ pid: process.pid,+ at: Date.now(),+ file: path.resolve(cwd, file),+ }) + '\n');+ acquired = true;+ } catch (error) {+ if (error?.code !== 'EEXIST') throw error;+ if (Date.now() >= deadline) {+ const locked = new Error('source_locked');+ locked.code = 'SOURCE_LOCKED';+ locked.lockPath = lockPath;+ throw locked;+ }+ sleepSync(Math.max(1, Math.min(Number(retryMs) || 5, deadline - Date.now())));+ } finally {+ try { if (fd !== undefined) fs.closeSync(fd); } catch {}+ }+ }++ try {+ return fn();+ } finally {+ releaseOwnLock(lockPath, token);+ }+}++function sleepSync(ms) {+ Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, ms);+}++function readLock(lockPath) {+ try { return JSON.parse(fs.readFileSync(lockPath, 'utf-8')); } catch { return null; }+}++/**+ * Remove the lock only if it is still the one this call created. If a sweeper+ * judged our lock stale and another writer replaced it, unlinking here would+ * end *their* critical section and admit a third writer to the same file.+ */+function releaseOwnLock(lockPath, token) {+ const held = readLock(lockPath);+ if (held && held.token !== token) return;+ try { fs.unlinkSync(lockPath); } catch {}+}++/**+ * A lock is stale when its owner is gone, not when it is old.+ *+ * Age alone cuts both ways: it sweeps a live holder whose critical section+ * outran the timeout (a suspended laptop, a stopped process), letting two+ * writers into the same source file, while still making every accept on a+ * crashed holder's file wait out the full timeout. Asking the OS whether the+ * recorded pid is alive answers both correctly: a dead owner releases at once,+ * and a live owner keeps its lock however long it needs.+ */+function clearStaleLock(lockPath) {+ const held = readLock(lockPath);+ if (!held) {+ // Unreadable: either a crash truncated it, or we caught the brief window+ // between create and write in a live acquisition. mtime distinguishes them.+ try {+ const stat = fs.statSync(lockPath);+ if (Date.now() - stat.mtimeMs > UNREADABLE_LOCK_STALE_MS) fs.unlinkSync(lockPath);+ } catch { /* gone already */ }+ return;+ }+ if (typeof held.pid === 'number' && isLiveServerPidReachable(held.pid)) return;+ try { fs.unlinkSync(lockPath); } catch {}+}diff --git a/.trae-cn/skills/impeccable/reference/live.md b/.trae-cn/skills/impeccable/reference/live.mdindex ba78670e6..8099cf94f 100644--- a/.trae-cn/skills/impeccable/reference/live.md+++ b/.trae-cn/skills/impeccable/reference/live.md@@ -10,21 +10,24 @@ Execute in order. No step skipped, no step reordered.1. `live.mjs`: boot. If the request names or implies a file, route, or app inside a monorepo, infer the concrete path and run `node .trae-cn/skills/impeccable/scripts/live.mjs --target <path>` instead; then run the rest of this live session from the returned `projectRoot`.2. Open the app URL that serves `pageFile` (infer from `package.json`, docs, terminal output, or an open tab). Never use `serverPort`; it's the helper, not the app. **Cursor:** `browser_navigate` to that URL before polling; do not skip. **Other harnesses:** use the available browser tool; if the URL is uncertain, ask the user once.-3. Poll loop with the default long timeout (600000 ms). After every event or `--reply`, run `live-poll.mjs` again immediately. Never pass a short `--timeout=`.+3. Poll loop with the default long timeout (600000 ms). Run `live-poll.mjs` again immediately after every event or `--reply`; Codex runs this one-shot poll in the foreground. Never pass a short `--timeout=`.The global bar **Impeccable mark** dims and shows a pulsing amber dot when no agent is long-polling `/poll`. Hover the mark for the hint; restart `live-poll.mjs` to reconnect.-4. On `generate`: read screenshot if present; load the action's reference; plan three distinct directions; write all variants in one edit; `--reply done`; poll again.+4. On `generate`: reuse `event.scaffold` when present; read the screenshot if present; load the action's reference; deliver variants using the delivery policy below; `--reply done`; poll again. Generate in this thread. You already hold the project's tokens, conventions, and file layout; that context is the job, not overhead.5. On `steer`: read the message and `pageUrl`; do the work (page edits, navigation help, or a short reply in the `--reply` message); `--reply steer_done`; poll again. No pickup ack. The Steer bar unlocks when `steer_done` arrives over SSE.-6. On `accept` / `discard`: the poll script runs `live-accept.mjs`, acknowledges the delivered event, and prints `_completionAck`. Plain accepts/discards are terminal immediately; carbonize accepts remain recoverable until you finish cleanup, run `live-complete.mjs --id EVENT_ID`, and only then poll again.+6. On `accept` / `discard`: the poll script runs `live-accept.mjs`, acknowledges the delivered event, and prints `_completionAck`. Plain accepts/discards are terminal immediately. Carbonize accepts remain recoverable until the foreground task runs `live-complete.mjs --id EVENT_ID`; finish that cleanup before polling again.7. If interrupted, run `live-status.mjs` or `live-resume.mjs` before guessing. The durable journal replays unacknowledged work after helper restart.8. On `exit`: run the cleanup at the bottom.Harness policy:-- **Claude Code**: run the poll as a **background task** (no short timeout). The harness notifies you when it completes, so the main conversation stays free. Do not block the shell.+- **Claude Code**: run the poll as a **background task** (no short timeout). The harness notifies you when it completes, so the main conversation stays free while you generate and publish in it. Do not block the shell.- **Cursor**: run **one-shot** poll in a **background terminal** with notify on `"type":"(steer|generate|accept|discard|exit)"`. After each event the poll exits; handle it, `--reply`, then start `live-poll.mjs` again. Do **not** use `--stream` on Cursor: incremental stdout notify is slower in practice than exit-based notify (~5s vs sub-second in testing).-- **Codex**: run the poll in the **foreground** (blocking shell; not a background task, not a subagent). Codex background exec sessions do not reliably surface poll stdout back into the conversation at the moment events arrive, so a "fire-and-forget" background poll will stall live mode.+- **Codex**: run the default one-shot poll in a **yielded foreground exec session**. Do not suffix it with `&`, use `--stream`, or leave Live without an active foreground poll. Handle every event in the main task; after each handler/reply, restart the foreground poll.- **Other harnesses**: one-shot foreground unless you know stdout reliably returns to this session when a shell exits.+Generation delivery policy:+- **Default (Cursor and other harnesses):** keep the established atomic single-edit delivery. Do not switch a harness to progressive until its poll loop is known not to block on the extra publish calls. This avoids trading model latency for extra tool-call latency on harnesses with different streaming behavior.+Chat is overhead. No recap, no tutorial output, no pasting PRODUCT / DESIGN bodies. Spend tokens on tools and edits; on failure, one or two short sentences.## Start@@ -92,14 +95,14 @@ Server restart rule: start `live-server.mjs` again, then poll. Startup requeues**Insert mode** (`event.mode === "insert"`): `{id, mode: "insert", count, pageUrl, insert: { position, anchor }, placeholder: { width, height }, freeformPrompt?, screenshotPath?, comments?, strokes?}`. No `action`. Requires a non-empty `freeformPrompt` **or** annotations. Screenshot is sent only when annotations exist (same rule as replace). Use `placeholder` dimensions as a soft size hint for net-new content.-Speed matters; the user is watching a spinner. Minimize tool calls by using the wrap/insert helper and writing all variants in a single edit.+Speed matters; the user is watching the selected element. Reuse server preflight metadata when available, minimize discovery calls, and follow the harness-specific delivery policy above.### Insert mode branchWhen `event.mode === "insert"`:1. Read the screenshot if `event.screenshotPath` is present (annotations only).-2. Run the insert helper instead of wrap:+2. If `event.scaffold` is present, use it as the insert-helper result and do **not** run the helper again. Otherwise run the insert helper instead of wrap:```bashnode .trae-cn/skills/impeccable/scripts/live-insert.mjs --id EVENT_ID --count EVENT_COUNT --position after \@@ -109,7 +112,7 @@ node .trae-cn/skills/impeccable/scripts/live-insert.mjs --id EVENT_ID --count EV- `--position` ← `event.insert.position` (`before` | `after`)- Anchor flags ← `event.insert.anchor` (same mapping as wrap: id, classes, tag, text)-The scaffold has **no** `data-impeccable-variant="original"`. Variants are net-new HTML+CSS inserted at `insertLine`. Load `brand.md` or `product.md` (freeform only, no action sub-command). Write all variants in one edit, then `--reply done`.+The scaffold has **no** `data-impeccable-variant="original"`. Variants are net-new HTML+CSS inserted at `insertLine`. Load `brand.md` or `product.md` (freeform only, no action sub-command). Deliver using the harness policy, then `--reply done`.For Svelte/SvelteKit targets, `live-insert.mjs` returns `previewMode: "svelte-component"` with `mode: "insert"`, `file` pointing at a temporary `node_modules/.impeccable-live/<id>/manifest.json`, `componentDir` pointing at the variant component files, and `sourceFile` pointing at the real `.svelte` route. Write each inserted variant as a real Svelte component (`v1.svelte`, `v2.svelte`, …) under `componentDir`. Insert variants must be non-empty net-new content with a single top-level root, no `data-impeccable-*` attributes, and CSS in each component's `<style>` block. Do **not** edit the route source during generation; the browser mounts the temporary component before/after the live anchor while the user cycles variants. On Accept, `live-accept.mjs` inserts the selected component markup into `sourceFile` immediately and deletes the temp session after the source write succeeds.@@ -134,6 +137,8 @@ Reading annotations precisely:### 2. Wrap the element+When `event.scaffold` is present, the local helper already found and wrapped the source before the poll returned. Treat `event.scaffold` as the successful helper output and skip this command entirely. `event.scaffoldAttempted` with `scaffoldError` means local preflight could not finish; use the command/fallback path below. This optimization removes a deterministic tool round trip without changing the generated design.+```bashnode .trae-cn/skills/impeccable/scripts/live-wrap.mjs --id EVENT_ID --count EVENT_COUNT --element-id "ELEMENT_ID" --classes "class1,class2" --tag "div" --text "TEXT_SNIPPET"```@@ -153,7 +158,7 @@ Output on success: `{ file, insertLine, commentSyntax, styleMode, styleTag, cssSFor Svelte/SvelteKit targets, `live-wrap.mjs` returns `previewMode: "svelte-component"` with `file` pointing at a temporary `node_modules/.impeccable-live/<id>/manifest.json`, `componentDir` pointing at the variant component files, and `sourceFile` pointing at the real `.svelte` route. Write each variant as a real Svelte component (`v1.svelte`, `v2.svelte`, …) under `componentDir`; use the `propContract` prop names for dynamic text (`{propName}`), not literal snapshot strings. Put variant CSS in each component's `<style>` block with semantic class selectors (no `@scope`, no `data-impeccable-*`). Reply with `--file` set to the manifest path; the browser dynamically imports and mounts the compiled components so Svelte HMR does not reset page state while the user cycles variants. On Accept, `live-accept.mjs` inlines the accepted component back into `sourceFile` immediately after source promotion succeeds.-**Params on the Svelte component path go in a sidecar, never as an attribute.** Svelte parses `{` inside an attribute value as the start of an expression, so a `data-impeccable-params='[{…}]'` attribute on a component element fails to compile (`Expected token }`). Declare params for this path in `componentDir/params.json`, keyed by variant number, using the exact param schema from section 7:+**Params on component-preview paths go in a sidecar, never as an attribute.** Svelte parses `{` inside an attribute value as the start of an expression, and both Svelte/Vue previews mount without an HTML variant wrapper. Declare params in `componentDir/params.json`, keyed by variant number, using the exact param schema from section 7:```json{@@ -291,11 +296,13 @@ In **departure mode**, the prompt narrows the lanes you draw from, not the familWhen the prompt and PRODUCT.md anti-references conflict (the prompt asks for X, the anti-references ban X), the anti-references win; they describe the brand's standing position, the prompt is one moment.-### 6. Write all variants in a single edit+### 6. Deliver variantsComplete HTML replacement of the original element for each variant, not a CSS-only patch. Consider the element's context (computed styles, parent structure, CSS variables from `event.element`).-Write CSS + all variants in ONE edit at the `insertLine` reported by `wrap`. Colocate CSS as a `<style>` tag inside the variant wrapper; `<style>` works anywhere in modern browsers and this ensures CSS and HTML arrive atomically (no FOUC).+Colocate preview CSS as a `<style>` tag inside the variant wrapper; `<style>` works anywhere in modern browsers and keeps each delivered state internally complete (no FOUC).++**Atomic default:** write CSS + all variants + parameter manifests in one edit at `insertLine`, preserving the established behavior.Use the `cssAuthoring` object returned by `live-wrap.mjs` to author the temporary preview CSS. The style opening tag shown below is the common case; replace it with `cssAuthoring.styleTag` when the tool returns a different one. The variant markup shape is otherwise stable:@@ -319,7 +326,7 @@ Use the `cssAuthoring` object returned by `live-wrap.mjs` to author the temporarThe first variant has no `display: none` (visible by default). All others do. If variants use only inline styles and no preview CSS, omit the `<style>` tag entirely.-One edit, all variants; the browser's MutationObserver picks everything up in one pass.+The browser's MutationObserver accepts either delivery shape. On the transactional progressive path it shows arrived variants and pending dots immediately; Accept and Discard are available as soon as one variant exists. Accepting an arrived variant fences the worker before the browser releases the picker, so later publications are rejected.For `styleMode: "scoped"`, author every `:scope` rule with a descendant combinator. The `@scope` boundary is the **variant wrapper `<div data-impeccable-variant="N">`**, not the element you're designing. A bare `:scope { background: cream; }` styles the wrapper, not the inner replacement, so the cream lands on a `display: contents` shell while the actual element keeps page defaults. Always step in: `:scope > .card`, `:scope > section`, `:scope .hero-title`, etc. The fake test agent's CSS in `tests/live-e2e/agent.mjs` is a faithful template; every scoped rule starts `:scope > ...`.@@ -361,7 +368,7 @@ Each variant can expose **coarse** knobs alongside the full HTML/CSS replacement**Hard cap per variant**: at most **four** parameters so the panel stays legible; rare fifth only if the reference explicitly allows it.-**How to declare.** Put a JSON manifest on the variant wrapper (HTML/JSX path). **On the Svelte `svelte-component` path, do not use this attribute** (Svelte can't compile `{` inside an attribute value). Declare params in `componentDir/params.json` keyed by variant number instead (see the Svelte component paragraph in the wrap section). The param schema below is identical for both paths.+**How to declare.** Put a JSON manifest on the variant wrapper (HTML/JSX path). **On the `svelte-component` path, do not use this attribute.** Declare params in `componentDir/params.json` keyed by variant number instead (see the component-preview paragraphs in the wrap section). The param schema below is identical for every path.```html<div data-impeccable-variant="1" data-impeccable-params='[@@ -462,15 +469,19 @@ Event: `{id, variantId, _acceptResult, _completionAck}`. The poll script already- The accept event includes `pageUrl`; the poll script must forward it to `live-accept.mjs --page-url PAGE_URL` so accept-time cleanup only scrubs staged copy edits for the current page.- `_completionAck.ok !== true`: do not poll yet. Run `live-status.mjs` / `live-resume.mjs`, complete the cleanup manually if needed, then run `live-complete.mjs --id EVENT_ID`.- `_acceptResult.handled: true` and `carbonize: false`: nothing to do. Poll again.-- `_acceptResult.handled: true` and `carbonize: true`: **post-accept cleanup is required before the next poll.** See the "Required after accept (carbonize)" section below. The `event._acceptResult.todo` field, `_completionAck.requiresComplete`, and a stderr banner all point at this required follow-up; none are decorative. After cleanup, run `live-complete.mjs --id EVENT_ID`, then poll again.+- `_acceptResult.handled: true` and `carbonize: true`: post-accept cleanup is required, but it must not stall Codex's control lane. See "Required after accept (carbonize)" below. The `event._acceptResult.todo` field, `_completionAck.requiresComplete`, and stderr banner all point at this required follow-up; none are decorative.- `_acceptResult.handled: false, mode: "fallback"`: the session lived in a generated file and the script refused to persist there. You've already written the accepted variant into true source during Handle fallback Step 3; just clean up the temporary wrapper in the served file if any, and poll again.+- `_acceptResult.handled: false, mode: "error"`: the operation genuinely failed. **Do not hand-edit the file**; the source was not touched and editing it yourself would either double-apply or race whoever holds it.+ - `error: "source_locked"`: a generation publish holds the file. Run the same `live-accept.mjs` command again; it is idempotent and will succeed once the publisher releases. Do not poll past it.+ - `error: "accept_receipt_conflict"`: this session already resolved as `priorOperation` (on `priorVariantId` for an accept), so the request contradicts durable truth. Do not edit. Run `live-status.mjs` and tell the user what the session actually resolved to.+ - anything else: report the error briefly and run `live-status.mjs` before continuing.- `_acceptResult.handled: false` without `mode`: manual cleanup: read file, find markers, edit.### Required after accept (carbonize)When `_acceptResult.carbonize === true`, the accepted variant was stitched into source with helper markers and inline CSS so the browser can render it immediately with no visual gap. That stitch-in is **temporary**. The agent must rewrite it into permanent form before doing anything else. Skipping this leaves dead `@scope` rules for unaccepted variants, a pointless `data-impeccable-variant` wrapper, and `impeccable-carbonize-start/end` comment noise in the source file; all of which accumulate across sessions.-Do these five steps in the current thread, synchronously, before the next poll. Do not poll again until the file is clean.+Do these five steps synchronously before the next poll. The source lock, generation epoch, and expected-source hash remain the final safety gates against a generator finishing concurrently with Accept.1. **Locate the carbonize block** in the source file (`_acceptResult.file`). It's bracketed by `<!-- impeccable-carbonize-start SESSION_ID -->` and `<!-- impeccable-carbonize-end SESSION_ID -->` and contains a `<style data-impeccable-css="SESSION_ID">` element. If the variant declared parameters, an `<!-- impeccable-param-values SESSION_ID: {...} -->` comment sits alongside the style tag with the user's chosen values; read it first; it drives steps 3 and 4 below.2. **Move the CSS rules** into the project's real stylesheet. Which stylesheet depends on the project (e.g. `site/styles/workflow.css` for an Astro project, or the component's co-located CSS file for a Vite/Next project; pick whichever already owns styling for the surrounding element).@@ -478,9 +489,7 @@ Do these five steps in the current thread, synchronously, before the next poll.4. **Unwrap the accepted content.** Delete the inner `<div data-impeccable-variant="N" style="display: contents">` that wraps it. On JSX/TSX, also delete the outer `<div data-impeccable-carbonize="SESSION_ID" style={{ display: 'contents' }}>` wrapper if present (accept adds it so ternary/`return` slots keep a single root). Drop `data-impeccable-params` and any `data-p-*` attributes; those are live-mode plumbing, not source.5. **Delete the inline `<style>` block, the `<!-- impeccable-param-values -->` comment if present, and both `<!-- impeccable-carbonize-start/end -->` markers.** Also drop any `@scope` rules for variants other than the accepted one; those are dead code now.-After the file is clean, run `live-complete.mjs --id SESSION_ID`, verify it reports `phase: "completed"`, then poll again.--A background agent may be used for the rewrite, but the current thread is responsible for verifying the five steps are complete before issuing the next poll. In practice, inline is usually faster and less error-prone.+After the file is clean, the cleanup owner runs `live-complete.mjs --id SESSION_ID` and verifies `phase: "completed"`. Poll again only after that verification.## Handle `discard`diff --git a/.trae-cn/skills/impeccable/scripts/lib/impeccable-paths.mjs b/.trae-cn/skills/impeccable/scripts/lib/impeccable-paths.mjsindex 2ccbe7b74..99956c0f3 100644--- a/.trae-cn/skills/impeccable/scripts/lib/impeccable-paths.mjs+++ b/.trae-cn/skills/impeccable/scripts/lib/impeccable-paths.mjs@@ -104,6 +104,20 @@ export function removeLiveServerInfo(cwd = process.cwd(), options = {}) {}}+/**+ * Session IDs become path segments (journals, snapshots, accept receipts,+ * preview manifests, generated component dirs). They arrive from CLI `--id`+ * arguments and HTTP payloads, so anything containing a separator or `..` must+ * be rejected before it reaches path.join, which would happily escape+ * `.impeccable/live/`. Real IDs are 8 hex chars; the tests use short slugs.+ */+export function safeSessionId(id) {+ if (typeof id !== 'string' || !/^[A-Za-z0-9_-]{1,128}$/.test(id)) {+ throw new Error('invalid session id: ' + id);+ }+ return id;+}+export function getLiveSessionsDir(cwd = process.cwd(), options = {}) {return path.join(getLiveDir(cwd, options), 'sessions');}diff --git a/.trae-cn/skills/impeccable/scripts/live-accept.mjs b/.trae-cn/skills/impeccable/scripts/live-accept.mjsindex 278dfbb2e..453ddea35 100644--- a/.trae-cn/skills/impeccable/scripts/live-accept.mjs+++ b/.trae-cn/skills/impeccable/scripts/live-accept.mjs@@ -16,7 +16,9 @@import fs from 'node:fs';import path from 'node:path';import { isGeneratedFile } from './lib/is-generated.mjs';+import { IMPECCABLE_DIR, getLiveDir, safeSessionId } from './lib/impeccable-paths.mjs';import { readBuffer as readManualEditsBuffer, writeBuffer as writeManualEditsBuffer } from './live/manual-edits-buffer.mjs';+import { withSourceLockSync } from './live/source-lock.mjs';import {applyDeferredSvelteComponentAccepts,findSvelteComponentManifest,@@ -25,6 +27,46 @@ import {} from './live/svelte-component.mjs';const EXTENSIONS = ['.html', '.jsx', '.tsx', '.vue', '.svelte', '.astro'];+const ACCEPT_LOCK_WAIT_MS = 1_000;+// Mirrors VARIANT_ID_PATTERN in live/event-validation.mjs, which gates the same+// value arriving over HTTP.+const VARIANT_NUM_PATTERN = /^[0-9]{1,3}$/;++/**+ * A thrown accept/discard is a real failure, not a manual handoff.+ *+ * live/completion.mjs only classifies a result as `error` when it carries+ * `mode: 'error'`; anything else unhandled falls through to `agent_done` with a+ * successful ack, and reference/live.md then tells the agent to finish the edit+ * by hand. That is right for the documented fallback paths and wrong here: a+ * `source_locked` contention needs a retry (hand-editing races the publisher+ * holding the lock), and a crash needs surfacing, not a hand-applied guess.+ */+function operationFailure(err, extra = {}) {+ return { handled: false, mode: 'error', error: err.message, ...extra };+}++/**+ * Mark an unhandled preview-path result as a real failure.+ *+ * operationFailure only covers results built from a *thrown* error. The accept+ * implementations also return `{handled: false, error}` for their own checks+ * (variant missing, template empty, original text ambiguous), and those arrived+ * without `mode`, so completion.mjs classified them as agent_done and+ * reference/live.md routed the agent to "read file, find markers, edit".+ *+ * That handoff only makes sense for a plain wrapper session, which is the one+ * shape with markers in the user's source to edit. Component and isolated+ * artifact previews keep the source clean until Accept, so there is nothing to+ * hand-edit and an unhandled result is always a failure. `previewMode` is+ * exactly that discriminator: only the preview branches set it.+ */+function markPreviewFailure(result) {+ if (result?.handled === false && !result.mode && result.previewMode) {+ return { ...result, mode: 'error' };+ }+ return result;+}// ---------------------------------------------------------------------------// CLI@@ -63,7 +105,52 @@ Output (JSON):const isDiscard = args.includes('--discard');if (!id) { console.error('Missing --id'); process.exit(1); }+ // `id` becomes a path segment (accept receipts, preview manifests, generated+ // component dirs). Reject separators and traversal here so one check covers+ // every downstream sink.+ try { safeSessionId(id); } catch { console.error('Invalid --id'); process.exit(1); }if (!isDiscard && !variantNum) { console.error('Need --discard or --variant N'); process.exit(1); }+ // `variantNum` is interpolated into a RegExp and into the markup written back+ // to source. The browser and the /events schema both constrain it to digits;+ // enforce the same here, or `--variant '.*'` matches the `original` block+ // first and silently accepts the original while reporting success.+ if (!isDiscard && !VARIANT_NUM_PATTERN.test(variantNum)) {+ console.error('Invalid --variant');+ process.exit(1);+ }++ const requestedOperation = isDiscard ? 'discard' : 'accept';+ const priorReceipt = readAcceptReceipt(process.cwd(), id);+ if (priorReceipt) {+ const sameOperation = priorReceipt.operation === requestedOperation+ && (isDiscard || String(priorReceipt.variantId) === String(variantNum));+ console.log(JSON.stringify(sameOperation+ ? { ...priorReceipt.result, handled: true, alreadyApplied: true }+ : {+ // mode: 'error' is what marks this a real failure rather than a manual+ // handoff. Without it, live/completion.mjs classifies the reply as+ // agent_done and reference/live.md tells the agent to "read file, find+ // markers, edit" by hand — which would apply a second, conflicting+ // accept on top of the one the receipt already recorded.+ handled: false,+ mode: 'error',+ error: 'accept_receipt_conflict',+ priorOperation: priorReceipt.operation,+ priorVariantId: priorReceipt.variantId ?? null,+ }));+ return;+ }+ const emitResult = (rawResult) => {+ const result = markPreviewFailure(rawResult);+ if (result?.handled !== false) {+ writeAcceptReceipt(process.cwd(), id, {+ operation: requestedOperation,+ variantId: isDiscard ? null : String(variantNum),+ result,+ });+ }+ console.log(JSON.stringify(result));+ };let paramValues = null;if (paramValuesRaw) {@@ -82,39 +169,55 @@ Output (JSON):if (svelteComponentManifest) {if (isDiscard) {- removeSvelteComponentSession(id, process.cwd());- console.log(JSON.stringify({- handled: true,+ let result;+ try {+ result = withSourceLockSync(+ path.resolve(process.cwd(), svelteComponentManifest.sourceFile),+ 'discard:' + id,+ () => {+ removeSvelteComponentSession(id, process.cwd());+ return { handled: true };+ },+ { waitMs: ACCEPT_LOCK_WAIT_MS },+ );+ } catch (err) {+ result = operationFailure(err);+ }+ emitResult({+ ...result,file: svelteComponentManifest.sourceFile,carbonize: false,previewMode: 'svelte-component',componentDir: svelteComponentManifest.componentDir,- }));+ });return;}let result;try {- result = inlineSvelteComponentAccept(- svelteComponentManifest,- variantNum,- paramValues,- process.cwd(),+ result = withSourceLockSync(+ path.resolve(process.cwd(), svelteComponentManifest.sourceFile),+ 'accept:' + id,+ () => inlineSvelteComponentAccept(+ svelteComponentManifest,+ variantNum,+ paramValues,+ process.cwd(),+ ),+ { waitMs: ACCEPT_LOCK_WAIT_MS },);} catch (err) {- result = {- handled: false,- error: err.message,+ result = operationFailure(err, {file: svelteComponentManifest.sourceFile,sourceFile: svelteComponentManifest.sourceFile,previewMode: 'svelte-component',componentDir: svelteComponentManifest.componentDir,- };+ });}if (result.carbonize) {result.todo = 'REQUIRED before next poll: carbonize cleanup in ' + result.file + '. See reference/live.md "Required after accept".';}- console.log(JSON.stringify({ handled: result.handled !== false, ...result }));+ emitResult({ handled: result.handled !== false, ...result });return;}@@ -145,10 +248,25 @@ Output (JSON):}if (isDiscard) {- const result = handleDiscard(id, lines, targetFile);- console.log(JSON.stringify({ handled: true, file: relFile, carbonize: false, ...result }));+ let result;+ // handleDiscard takes the source lock, which throws SOURCE_LOCKED under+ // contention. Without this catch the CLI exits non-zero with empty stdout+ // and the agent gets no JSON to act on.+ try {+ result = handleDiscard(id, lines, targetFile);+ } catch (err) {+ emitResult(operationFailure(err, { file: relFile }));+ return;+ }+ emitResult({ handled: true, file: relFile, carbonize: false, ...result });} else {- const result = handleAccept(id, variantNum, lines, targetFile, paramValues);+ let result;+ try {+ result = handleAccept(id, variantNum, lines, targetFile, paramValues);+ } catch (err) {+ emitResult(operationFailure(err, { file: relFile }));+ return;+ }const acceptedOriginalText = result.acceptedOriginalText || '';delete result.acceptedOriginalText;// Single-line attention-grabber when cleanup is required. The full@@ -167,7 +285,7 @@ Output (JSON):// Non-fatal; the buffer stays as-is and the user can discard later.}}- console.log(JSON.stringify({ handled: true, file: relFile, ...result }));+ emitResult({ handled: true, file: relFile, ...result });}}@@ -235,7 +353,14 @@ function scrubManualEditsAgainstFile(_targetFile, cwd = process.cwd(), originalB// Discard// ----------------------------------------------------------------------------function handleDiscard(id, lines, targetFile) {+function handleDiscard(id, _lines, targetFile) {+ return withSourceLockSync(targetFile, 'discard:' + id, () => {+ const lines = fs.readFileSync(targetFile, 'utf-8').split('\n');+ return handleDiscardUnlocked(id, lines, targetFile);+ }, { waitMs: ACCEPT_LOCK_WAIT_MS });+}++function handleDiscardUnlocked(id, lines, targetFile) {const block = findMarkerBlock(id, lines);if (!block) return { handled: false, error: 'Markers not found' };@@ -330,7 +455,24 @@ function reindentContent(contentLines, fromIndent, toIndent) {});}-function handleAccept(id, variantNum, lines, targetFile, paramValues) {+function handleAccept(id, variantNum, _lines, targetFile, paramValues) {+ return withSourceLockSync(targetFile, 'accept:' + id, () => {+ const lines = fs.readFileSync(targetFile, 'utf-8').split('\n');+ return handleAcceptUnlocked(id, variantNum, lines, targetFile, paramValues);+ }, { waitMs: ACCEPT_LOCK_WAIT_MS });+}++function handleAcceptUnlocked(id, variantNum, lines, targetFile, paramValues) {+ const built = buildAcceptedWrappedSource(id, variantNum, lines, targetFile, paramValues);+ if (built.handled === false) return built;+ fs.writeFileSync(targetFile, built.content, 'utf-8');+ return {+ carbonize: built.carbonize,+ acceptedOriginalText: built.acceptedOriginalText,+ };+}++function buildAcceptedWrappedSource(id, variantNum, lines, targetFile, paramValues) {const block = findMarkerBlock(id, lines);if (!block) return { handled: false, error: 'Markers not found' };@@ -375,11 +517,14 @@ function handleAccept(id, variantNum, lines, targetFile, paramValues) {...replacement,...lines.slice(replaceRange.end + 1),];- fs.writeFileSync(targetFile, newLines.join('\n'), 'utf-8');-- return { carbonize: needsCarbonize, acceptedOriginalText: originalContent.join('\n') };+ return {+ content: newLines.join('\n'),+ carbonize: needsCarbonize,+ acceptedOriginalText: originalContent.join('\n'),+ };}+function readSourceShadowPreviewMeta(content, id) {const escaped = escapeRegExp(id);const wrapperRe = new RegExp('<[^>]+data-impeccable-variants=(["\'])' + escaped + '\\1[^>]*>');@@ -746,6 +891,21 @@ function detectCommentSyntax(filePath) {// File search (find the file containing session markers)// ---------------------------------------------------------------------------+/**+ * `.impeccable` is the critical entry, and it is not cosmetic.+ *+ * Progressive publication stages each revision as `.impeccable/live/artifacts/+ * <id>-r<n>.<source-ext>`, and those artifacts carry the very marker this search+ * looks for. The walk reaches `.` for any project whose source is not under one+ * of the privileged dirs above (this repo's own site lives in `site/pages/`), and+ * dot-directories sort before letters, so the artifact was found *before* the+ * real file. isGeneratedFile then declined the accept, and the agent fell back to+ * carbonizing several hundred lines of stylesheet by hand.+ *+ * Impeccable's own state directory is never project source. Never search it.+ */+const SEARCH_SKIP_DIRS = new Set(['node_modules', '.git', 'dist', 'build', IMPECCABLE_DIR]);+function findSessionFile(id, cwd) {const marker = 'impeccable-variants-start ' + id;const searchDirs = ['src', 'app', 'pages', 'components', 'public', 'views', 'templates', '.'];@@ -786,7 +946,7 @@ function searchDir(dir, query, seen, depth) {for (const entry of entries) {if (!entry.isDirectory()) continue;- if (['node_modules', '.git', 'dist', 'build'].includes(entry.name)) continue;+ if (SEARCH_SKIP_DIRS.has(entry.name)) continue;const result = searchDir(path.join(dir, entry.name), query, seen, depth + 1);if (result) return result;}@@ -798,6 +958,28 @@ function searchDir(dir, query, seen, depth) {// Utilities// ---------------------------------------------------------------------------+function acceptReceiptPath(cwd, id) {+ return path.join(getLiveDir(cwd), 'accept-receipts', `${safeSessionId(id)}.json`);+}++function readAcceptReceipt(cwd, id) {+ try { return JSON.parse(fs.readFileSync(acceptReceiptPath(cwd, id), 'utf-8')); } catch { return null; }+}++function writeAcceptReceipt(cwd, id, receipt) {+ const file = acceptReceiptPath(cwd, id);+ fs.mkdirSync(path.dirname(file), { recursive: true });+ const value = {+ id,+ ...receipt,+ completedAt: new Date().toISOString(),+ };+ const temporary = `${file}.${process.pid}.${Date.now()}.tmp`;+ fs.writeFileSync(temporary, JSON.stringify(value, null, 2) + '\n', 'utf-8');+ fs.renameSync(temporary, file);+ return value;+}+function argVal(args, flag) {const idx = args.indexOf(flag);return idx !== -1 && idx + 1 < args.length ? args[idx + 1] : null;diff --git a/.trae-cn/skills/impeccable/scripts/live-browser.js b/.trae-cn/skills/impeccable/scripts/live-browser.jsindex 616f1290a..20d875b93 100644--- a/.trae-cn/skills/impeccable/scripts/live-browser.js+++ b/.trae-cn/skills/impeccable/scripts/live-browser.js@@ -126,6 +126,9 @@let expectedVariants = 0;let arrivedVariants = 0;let visibleVariant = 0;+ let generationPhase = null;+ let parameterGenerationState = 'idle';+ let parameterReadyAnnouncedSession = null;let svelteComponentSession = null;let svelteRuntimePromise = null;let pendingSvelteComponentRetryObserver = null;@@ -134,6 +137,7 @@let currentPreviewMode = null;let recoveryWaitingForAnchor = false;let pickedAnchorSnapshot = null;+ let pickedAnchorViewportTop = null;let pendingVariantAnchorRetryObserver = null;let pendingAcceptedSession = null;let variantObserver = null;@@ -151,10 +155,12 @@// startScrollLock / stopScrollLock below.let scrollLockObserver = null;let scrollLockTargetY = null;+ let scrollLockAnchorTop = null;let scrollLockRaf = null;let scrollLockAbort = null;const SCROLL_ANCHOR_LOCK_ID = 'impeccable-scroll-anchor-lock';const VARIANT_STATE_STYLE_ID = 'impeccable-variant-state';+ const DISCARD_STATE_STYLE_ID = 'impeccable-discard-state';// Dedicated key for scroll position - SEPARATE from LS_KEY so that// saveSession's state updates don't clobber a carefully-captured scrollY.@@ -252,6 +258,13 @@barConnected: !!barEl?.isConnected,hasSvelteComponentSession: !!svelteComponentSession,mountedSvelteVariant: svelteComponentSession?.mountedVariant || 0,+ pickActive,+ pendingApplyInFlight,+ hoveredElement: hoveredElement ? {+ tag: hoveredElement.tagName,+ classes: hoveredElement.className,+ pickable: pickable(hoveredElement),+ } : null,pendingSvelteComponentRetry: !!pendingSvelteComponentRetryObserver,recoveryWaitingForAnchor,evtSourceReadyState: evtSource ? evtSource.readyState : null,@@ -1114,14 +1127,15 @@});}- function hideBar() {+ function hideBar(instant) {if (!barEl) return;const hideSeq = ++barHideSeq;stopVoice({ suppressSubmit: true });if (configureKind === 'insert') clearInsertPicking();barEl.style.opacity = '0';- barEl.style.transform = 'translateY(6px)';- setTimeout(() => { if (barEl && hideSeq === barHideSeq) barEl.style.display = 'none'; }, 250);+ barEl.style.transform = instant ? 'translateY(0)' : 'translateY(6px)';+ if (instant) barEl.style.display = 'none';+ else setTimeout(() => { if (barEl && hideSeq === barHideSeq) barEl.style.display = 'none'; }, 250);hideActionPicker();closeTunePopover();hideConfigureBarTooltip();@@ -1966,6 +1980,7 @@*/function setLiveState(next) {state = next;+ window.__IMPECCABLE_LIVE_STATE__ = next;syncPageInteractionCursor();}@@ -2516,18 +2531,27 @@fontSize: '11px', color: BP.textDim, whiteSpace: 'nowrap',marginLeft: 'auto',});- // Variants currently arrive atomically in a single file edit, so a- // per-variant counter would lie. Say what's true.status.textContent = recoveryWaitingForAnchor? 'Variants ready. Reveal the selected element to resume.'- : (arrivedVariants < expectedVariants- ? 'Generating ' + expectedVariants + ' variants...'- : 'Done');+ : generationStatusText();row.appendChild(status);return row;}+ function generationStatusText() {+ if (arrivedVariants >= expectedVariants && expectedVariants > 0) return 'Done';+ if (generationPhase === 'picked_up') return 'Agent picked up the request...';+ if (generationPhase === 'scaffolding') return 'Finding the source...';+ if (generationPhase === 'source_ready') return 'Source ready. Generating...';+ if (generationPhase === 'scaffold_fallback') return 'Agent is locating the source...';+ if (generationPhase === 'first_variant_generating') return 'Designing the first variant...';+ if (generationPhase === 'first_variant_validating') return 'Checking the first variant...';+ if (generationPhase === 'remaining_variants_generating') return 'Exploring two more directions...';+ if (generationPhase === 'remaining_variants_validating') return 'Checking the remaining variants...';+ return 'Generating ' + expectedVariants + ' variants...';+ }+// Cycling rowconst TUNE_ICON_SVG = '<svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" style="flex-shrink:0"><line x1="4" y1="8" x2="20" y2="8"/><circle cx="14" cy="8" r="2.4" fill="currentColor" stroke="none"/><line x1="4" y1="16" x2="20" y2="16"/><circle cx="10" cy="16" r="2.4" fill="currentColor" stroke="none"/></svg>';@@ -2557,7 +2581,7 @@color: BP.textDim, minWidth: '24px', textAlign: 'center',});counter.id = PREFIX + '-variant-counter';- counter.textContent = visibleVariant + '/' + arrivedVariants;+ counter.textContent = visibleVariant + '/' + expectedVariants;row.appendChild(counter);// Next@@ -2567,10 +2591,12 @@if (visibleVariant >= arrivedVariants) next.style.opacity = '0.3';row.appendChild(next);- // Tune chip - only when the visible variant exposes params+ // Tune chip stays visible while the deferred parameter phase is running,+ // then becomes interactive as soon as this variant exposes controls.const visParams = parseVariantParams(getVisibleVariantEl());const hasParams = visParams.length > 0;- if (hasParams) {+ const paramsPending = !hasParams && (parameterGenerationState === 'pending' || parameterGenerationState === 'loading');+ if (hasParams || paramsPending) {const tune = el('button', {display: 'inline-flex', alignItems: 'center', gap: '6px',padding: '4px 10px', borderRadius: '5px',@@ -2578,35 +2604,54 @@background: tuneOpen ? BP.accentSoft : 'transparent',color: tuneOpen ? BP.accent : BP.text,fontFamily: FONT, fontSize: '11px', fontWeight: '500',- cursor: 'pointer',+ cursor: paramsPending ? 'wait' : 'pointer',transition: 'color 0.12s ease, background 0.12s ease',whiteSpace: 'nowrap',});- tune.innerHTML = TUNE_ICON_SVG;+ if (paramsPending) {+ const spinner = el('span', {+ width: '11px', height: '11px', borderRadius: '50%',+ border: '1.5px solid ' + BP.hairline,+ borderTopColor: BP.accent,+ animation: 'impeccable-spin 0.6s linear infinite',+ boxSizing: 'border-box', flexShrink: '0',+ });+ spinner.setAttribute('aria-hidden', 'true');+ tune.appendChild(spinner);+ } else {+ tune.innerHTML = TUNE_ICON_SVG;+ }const tuneLabel = document.createElement('span');tuneLabel.textContent = 'Tune';tune.appendChild(tuneLabel);- const tuneBadge = document.createElement('span');- Object.assign(tuneBadge.style, {- display: 'inline-flex', alignItems: 'center', justifyContent: 'center',- minWidth: '16px', height: '16px', padding: '0 4px',- borderRadius: '999px',- background: tuneOpen ? C.brand : BP.hairline,- color: tuneOpen ? 'oklch(98% 0 0)' : 'inherit',- fontFamily: MONO, fontSize: '9.5px', fontWeight: '600',- lineHeight: '1',- boxSizing: 'border-box',- });- tuneBadge.textContent = String(visParams.length);- tune.appendChild(tuneBadge);- tune.title = 'Tune this variant (' + visParams.length + ' knob' + (visParams.length === 1 ? '' : 's') + ')';- tune.addEventListener('mouseenter', () => {- if (!tuneOpen) tune.style.background = BP.accentSoft;- });- tune.addEventListener('mouseleave', () => {- if (!tuneOpen) tune.style.background = 'transparent';- });- tune.addEventListener('click', (e) => { e.stopPropagation(); toggleTunePopover(); });+ if (hasParams) {+ const tuneBadge = document.createElement('span');+ Object.assign(tuneBadge.style, {+ display: 'inline-flex', alignItems: 'center', justifyContent: 'center',+ minWidth: '16px', height: '16px', padding: '0 4px',+ borderRadius: '999px',+ background: tuneOpen ? C.brand : BP.hairline,+ color: tuneOpen ? 'oklch(98% 0 0)' : 'inherit',+ fontFamily: MONO, fontSize: '9.5px', fontWeight: '600',+ lineHeight: '1',+ boxSizing: 'border-box',+ });+ tuneBadge.textContent = String(visParams.length);+ tune.appendChild(tuneBadge);+ tune.title = 'Tune this variant (' + visParams.length + ' knob' + (visParams.length === 1 ? '' : 's') + ')';+ tune.addEventListener('mouseenter', () => {+ if (!tuneOpen) tune.style.background = BP.accentSoft;+ });+ tune.addEventListener('mouseleave', () => {+ if (!tuneOpen) tune.style.background = 'transparent';+ });+ tune.addEventListener('click', (e) => { e.stopPropagation(); toggleTunePopover(); });+ } else {+ tune.disabled = true;+ tune.setAttribute('aria-label', 'Tune controls are still being prepared');+ tune.title = 'Tune controls are still being prepared';+ tune.style.opacity = '0.72';+ }tune.dataset.iceqTune = '1';row.appendChild(tune);}@@ -2614,6 +2659,15 @@// Spacerrow.appendChild(el('div', { flex: '1' }));+ if (arrivedVariants < expectedVariants) {+ const remaining = expectedVariants - arrivedVariants;+ const progress = el('span', {+ fontSize: '11px', color: BP.textDim, whiteSpace: 'nowrap',+ });+ progress.textContent = remaining + ' more arriving...';+ row.appendChild(progress);+ }+// Accept - primary action, kinpaku gold + lacquer-deep (matches demo .live-demo-ctx-accept)const accept = el('button', {padding: '5px 14px', borderRadius: '5px',@@ -2628,7 +2682,11 @@accept.addEventListener('mousedown', () => accept.style.transform = 'scale(0.97)');accept.addEventListener('mouseup', () => accept.style.transform = 'scale(1)');accept.addEventListener('click', (e) => { e.stopPropagation(); handleAccept(); });- if (arrivedVariants === 0) { accept.style.opacity = '0.3'; accept.style.pointerEvents = 'none'; }+ if (arrivedVariants === 0) {+ accept.style.opacity = '0.3';+ accept.style.pointerEvents = 'none';+ accept.title = 'Accept becomes available when the first variant arrives';+ }row.appendChild(accept);// Discard@@ -4743,6 +4801,32 @@}}+ function mountedParameterCount() {+ if (svelteComponentSession?.sessionId === currentSessionId) {+ return Object.values(svelteComponentSession.paramsByVariant || {})+ .reduce((total, params) => total + (Array.isArray(params) ? params.length : 0), 0);+ }+ const wrapper = document.querySelector('[data-impeccable-variants="' + currentSessionId + '"]');+ if (!wrapper) return 0;+ return [...wrapper.querySelectorAll('[data-impeccable-variant]:not([data-impeccable-variant="original"])')]+ .reduce((total, variant) => total + parseVariantParams(variant).length, 0);+ }++ function completeParameterPublication() {+ if (!currentSessionId) return;+ const ready = mountedParameterCount() > 0;+ parameterGenerationState = ready ? 'ready' : 'none';+ if (ready && parameterReadyAnnouncedSession !== currentSessionId) {+ parameterReadyAnnouncedSession = currentSessionId;+ showToast('Tune controls are ready.', 3000);+ }+ if (state === 'CYCLING') {+ refreshParamsPanel();+ showOrUpdateCyclingBar();+ }+ saveSession();+ }+function toggleTunePopover() {if (pendingApplyInFlight) { showManualApplyBusyToast(); return; }if (tuneOpen) { closeTunePopover(); return; }@@ -4835,6 +4919,10 @@return String(filePath || '').endsWith('manifest.json');}+ function isFrameworkComponentPreviewMode(mode) {+ return mode === 'svelte-component';+ }+function parseOriginalMarkupElement(originalMarkup) {const parser = new DOMParser();const doc = parser.parseFromString('<div id="impeccable-anchor">' + originalMarkup + '</div>', 'text/html');@@ -5029,9 +5117,13 @@}}- function loadSvelteRuntime(runtimeModule) {+ function resolveComponentModuleUrl(manifest, modulePath) {+ return new URL(String(modulePath || ''), location.origin).href;+ }++ function loadSvelteRuntime(runtimeModule, manifest) {const modulePath = runtimeModule || '/src/lib/impeccable/__runtime.js';- const url = new URL(modulePath, location.origin).href;+ const url = resolveComponentModuleUrl(manifest, modulePath);if (!svelteRuntimePromise) {svelteRuntimePromise = import(/* @vite-ignore */ url);}@@ -5065,7 +5157,8 @@async function loadSvelteComponentVariantSource(manifest, variantNum) {const dir = String(manifest?.componentDir || '').replace(/^\/+/, '');if (!dir || !variantNum) return '';- const sourcePath = dir + '/v' + variantNum + '.svelte';+ const extension = manifest.componentExtension || 'svelte';+ const sourcePath = dir + '/v' + variantNum + '.' + extension;const url = 'http://localhost:' + PORT + '/source?token=' + TOKEN + '&path=' + encodeURIComponent(sourcePath);try {const res = await fetch(url);@@ -5221,7 +5314,7 @@if (!sourceOriginal) return values;const map = buildSvelteExpressionTextMap(sourceOriginal, liveEl);for (const entry of contract) {- const token = '{' + entry.expr + '}';+ const token = entry.previewToken || ('{' + entry.expr + '}');values[entry.prop] = map.get(token) || '';}return values;@@ -5233,9 +5326,12 @@try {const previousAnchor = getMountedSvelteComponentAnchor(svelteComponentSession) || selectedElement;svelteComponentSession.swapAnchor = makeFrozenAnchor(previousAnchor) || svelteComponentSession.swapAnchor || null;- const runtime = await loadSvelteRuntime(manifest.runtimeModule);- const modulePath = '/' + String(manifest.componentDir || '').replace(/^\/+/, '') + '/v' + variantNum + '.svelte';- const moduleUrl = new URL(modulePath, location.origin).href + '?t=' + Date.now();+ const runtime = await loadSvelteRuntime(manifest.runtimeModule, manifest);+ const extension = manifest.componentExtension || 'svelte';+ const moduleBase = manifest.componentModuleBase+ || ('/' + String(manifest.componentDir || '').replace(/^\/+/, ''));+ const modulePath = String(moduleBase).replace(/\/+$/, '') + '/v' + variantNum + '.' + extension;+ const moduleUrl = resolveComponentModuleUrl(manifest, modulePath) + '?t=' + Date.now();const mod = await import(/* @vite-ignore */ moduleUrl);const Component = mod.default;if (svelteComponentSession.mountedInstance && runtime.unmount) {@@ -5275,7 +5371,7 @@if (svelteComponentSession?.sessionId === sessionId) {svelteComponentSession.swapAnchor = null;}- console.error('[impeccable] Failed to mount Svelte variant ' + variantNum + ' for ' + sessionId + ':', err);+ console.error('[impeccable] Failed to mount component variant ' + variantNum + ' for ' + sessionId + ':', err);return false;}}@@ -5340,40 +5436,46 @@if (manifest.id !== sessionId) return;const paramsByVariant = await loadSvelteComponentParams(manifest);+ const availableVariants = Number(manifest.arrivedVariants) || Number(manifest.count) || 1;+ const componentPreviewMode = isFrameworkComponentPreviewMode(manifest.previewMode)+ ? manifest.previewMode+ : 'svelte-component';currentSessionId = sessionId;expectedVariants = Number(manifest.count) || expectedVariants || 1;rememberSessionFileMeta({sourceFile: manifest.sourceFile,previewFile: manifestPath,- previewMode: 'svelte-component',+ previewMode: componentPreviewMode,});if (state !== 'CYCLING') setLiveState('GENERATING');const existingWrapper = document.querySelector('[data-impeccable-variants="' + sessionId + '"]');if (existingWrapper && svelteComponentSession?.sessionId === sessionId) {recoveryWaitingForAnchor = false;+ svelteComponentSession.manifest = manifest;svelteComponentSession.paramsByVariant = paramsByVariant;- arrivedVariants = Number(manifest.count) || expectedVariants || 1;- expectedVariants = arrivedVariants;+ arrivedVariants = availableVariants;+ expectedVariants = Number(manifest.count) || expectedVariants || arrivedVariants;visibleVariant = visibleVariant > 0 && visibleVariant <= arrivedVariants ? visibleVariant : 1;await mountSvelteComponentVariant(visibleVariant || 1);setLiveState('CYCLING');showOrUpdateCyclingBar();saveSession();+ if (parameterGenerationState === 'loading') completeParameterPublication();return;}const liveEl = findLiveElementForSvelteManifest(manifest);if (!liveEl?.parentElement) {console.warn('[impeccable] Could not find original element in live DOM.');- arrivedVariants = Number(manifest.count) || expectedVariants || 1;- expectedVariants = arrivedVariants;+ arrivedVariants = availableVariants;+ expectedVariants = Number(manifest.count) || expectedVariants || arrivedVariants;const saved = loadSession();const savedVisibleVariant = saved && saved.id === sessionId ? saved.visible : 0;visibleVariant = visibleVariant > 0 && visibleVariant <= arrivedVariants? visibleVariant: (savedVisibleVariant > 0 && savedVisibleVariant <= arrivedVariants ? savedVisibleVariant : 1);- enterRecoveryWaitingForAnchor({ checkpointReason: 'svelte_component_anchor_missing', trackScroll: true });+ enterRecoveryWaitingForAnchor({ checkpointReason: 'component_preview_anchor_missing', trackScroll: true });waitForSvelteComponentTargetAndRetry({ manifestPath, sessionId, manifest });return;}@@ -5381,7 +5483,7 @@const wrapper = document.createElement('div');wrapper.dataset.impeccableVariants = sessionId;wrapper.dataset.impeccableVariantCount = String(manifest.count || expectedVariants || 1);- wrapper.dataset.impeccablePreview = 'svelte-component';+ wrapper.dataset.impeccablePreview = componentPreviewMode;wrapper.style.display = 'contents';const mountTarget = document.createElement('div');@@ -5419,8 +5521,8 @@recoveryWaitingForAnchor = false;const previousVisibleVariant = currentSessionId === sessionId ? visibleVariant : 0;- arrivedVariants = Number(manifest.count) || expectedVariants || 1;- expectedVariants = arrivedVariants;+ arrivedVariants = availableVariants;+ expectedVariants = Number(manifest.count) || expectedVariants || arrivedVariants;const saved = loadSession();const savedVisibleVariant = saved && saved.id === sessionId ? saved.visible : 0;visibleVariant = previousVisibleVariant > 0 && previousVisibleVariant <= arrivedVariants@@ -5445,9 +5547,10 @@refreshParamsPanel();positionBar();saveSession();- console.log('[impeccable] Mounted ' + arrivedVariants + ' Svelte component variants.');+ if (parameterGenerationState === 'loading') completeParameterPublication();+ console.log('[impeccable] Mounted ' + arrivedVariants + ' ' + manifest.framework + ' component variants.');} catch (err) {- console.error('[impeccable] Failed to mount Svelte component variants:', err);+ console.error('[impeccable] Failed to mount component-preview variants:', err);abortSvelteComponentInjection(sessionId, 'Could not load variants. Fix the error and re-run.');}}@@ -5493,6 +5596,8 @@clearHandled();resetSessionFileMeta();currentSessionId = null;+ parameterGenerationState = 'idle';+ parameterReadyAnnouncedSession = null;expectedVariants = 0;arrivedVariants = 0;visibleVariant = 0;@@ -5502,12 +5607,24 @@if (message) showToast(message, 5000);}+ // How many delayed re-reads a completion-driven source fallback gets when+ // the fetched source still shows only the preflight scaffold, before the+ // failure is surfaced via recoverEmptyCycling.+ const COMPLETED_SOURCE_FALLBACK_RETRIES = 3;+ const COMPLETED_SOURCE_FALLBACK_RETRY_MS = 1200;+/*** No-HMR fallback: fetch the raw source file from the live server,* parse it, extract the variant wrapper, and inject it into the live DOM.* This works even when the dev server caches HTML (Bun, static servers).+ *+ * opts.generationCompleted marks callers that KNOW the agent finished (a+ * `done` arrived or the server reported a completed generation). For them an+ * empty read is a stale source view and no further event is coming, so the+ * read retries a few times and then surfaces recovery. Callers without the+ * flag may be mid-generation and wait indefinitely for the real completion.*/- function injectVariantsFromSource(filePath, sessionId) {+ function injectVariantsFromSource(filePath, sessionId, opts = {}) {if (isSvelteComponentManifestPath(filePath)) {injectSvelteComponentsFromManifest(filePath, sessionId);return;@@ -5573,6 +5690,32 @@arrivedVariants = variants.length;expectedVariants = parseInt(wrapper.dataset.impeccableVariantCount || arrivedVariants);if (arrivedVariants <= 0) {+ if (state === 'GENERATING') {+ // Mid-generation the source legitimately holds a scaffold wrapper+ // with no variants yet (the server-side preflight wraps before the+ // agent writes). Tearing the session down here would destroy an+ // in-flight generation; stay in GENERATING — the variant observer+ // is armed and the server re-delivers a missed `done`.+ if (!opts.generationCompleted) {+ console.log('[impeccable] Source has scaffold but no variants yet; still generating.');+ return;+ }+ // Generation finished, yet the read shows only the scaffold: the+ // source view is stale and no further event will fire. Re-read a+ // few times before surfacing recovery — a single silent return+ // here would strand the tab in GENERATING forever.+ const attempt = opts.attempt || 0;+ if (attempt < COMPLETED_SOURCE_FALLBACK_RETRIES) {+ console.log('[impeccable] Generation is done but source shows no variants yet; retrying read ('+ + (attempt + 1) + '/' + COMPLETED_SOURCE_FALLBACK_RETRIES + ').');+ setTimeout(() => {+ if (state !== 'GENERATING' || currentSessionId !== sessionId) return;+ if (arrivedVariants > 0) return;+ injectVariantsFromSource(filePath, sessionId, { ...opts, attempt: attempt + 1 });+ }, COMPLETED_SOURCE_FALLBACK_RETRY_MS);+ return;+ }+ }recoverEmptyCycling('source-fallback-empty');return;}@@ -5594,6 +5737,7 @@refreshParamsPanel();positionBar();saveSession();+ if (parameterGenerationState === 'loading') completeParameterPublication();console.log('[impeccable] Injected ' + arrivedVariants + ' variants from source file.');}).catch(err => {@@ -5865,13 +6009,36 @@document.getElementById(VARIANT_STATE_STYLE_ID)?.remove();}+ function showOriginalDuringDiscard(sessionId) {+ if (!sessionId) return;+ let styleEl = document.getElementById(DISCARD_STATE_STYLE_ID);+ if (!styleEl) {+ styleEl = document.createElement('style');+ styleEl.id = DISCARD_STATE_STYLE_ID;+ (document.head || document.documentElement).appendChild(styleEl);+ }+ const wrapper = '[data-impeccable-variants="' + sessionId + '"]';+ styleEl.textContent = wrapper + ' > [data-impeccable-variant]:not([data-impeccable-variant="original"]) { display:none !important; }\n'+ + wrapper + ' > [data-impeccable-variant="original"] { display:block !important; }';+ }++ function resolveScrollLockAnchorTop() {+ const anchor = resolveBarAnchor();+ if (!anchor?.isConnected) return null;+ const top = anchor.getBoundingClientRect().top;+ return Number.isFinite(top) ? top : null;+ }+// Hold window.scrollY at a fixed value across DOM mutations inside the// session's wrapper (HMR patches, variant inserts, cycle swaps).- function startScrollLock(sessionId, initialTargetY) {+ function startScrollLock(sessionId, initialTargetY, initialAnchorTop) {stopScrollLock();scrollLockTargetY = typeof initialTargetY === 'number' && isFinite(initialTargetY)? initialTargetY: window.scrollY;+ scrollLockAnchorTop = typeof initialAnchorTop === 'number' && isFinite(initialAnchorTop)+ ? initialAnchorTop+ : resolveScrollLockAnchorTop();try { history.scrollRestoration = 'manual'; } catch {}@@ -5895,6 +6062,17 @@const correct = (why) => {scrollLockRaf = null;if (scrollLockTargetY == null) return;+ const anchor = resolveBarAnchor();+ if (anchor?.isConnected && typeof scrollLockAnchorTop === 'number' && isFinite(scrollLockAnchorTop)) {+ const anchorTop = anchor.getBoundingClientRect().top;+ const anchorDelta = anchorTop - scrollLockAnchorTop;+ if (Math.abs(anchorDelta) >= 0.5) {+ window.scrollTo({ top: window.scrollY + anchorDelta, left: window.scrollX, behavior: 'instant' });+ scrollLockTargetY = window.scrollY;+ writeScrollY(scrollLockTargetY);+ return;+ }+ }const before = window.scrollY;const delta = before - scrollLockTargetY;if (Math.abs(delta) < 0.5) {@@ -5939,6 +6117,7 @@if (scrollLockRaf != null) { cancelAnimationFrame(scrollLockRaf); scrollLockRaf = null; }const prevTarget = scrollLockTargetY;scrollLockTargetY = window.scrollY;+ scrollLockAnchorTop = resolveScrollLockAnchorTop();writeScrollY(scrollLockTargetY);};const markGesture = (why) => {@@ -5976,6 +6155,7 @@if (scrollLockRaf != null) { cancelAnimationFrame(scrollLockRaf); scrollLockRaf = null; }if (scrollLockAbort) { scrollLockAbort.abort(); scrollLockAbort = null; }scrollLockTargetY = null;+ scrollLockAnchorTop = null;// NOTE: do NOT clear the persistent scroll key here. startScrollLock// calls us as a reset, and clearing the key would nuke the Go-time// scrollY that the next resume needs to read.@@ -6049,6 +6229,7 @@updating = true;arrivedVariants = count;+ generationPhase = arrivedVariants >= expectedVariants ? 'variants_ready' : 'variants_progress';if (visibleVariant === 0 && arrivedVariants > 0) {const saved = loadSession();const savedVisibleVariant = saved && saved.id === sessionId ? saved.visible : 0;@@ -6064,7 +6245,7 @@const expected = parseInt(wrapper.dataset.impeccableVariantCount || '0');if (expected > 0) expectedVariants = expected;- if (arrivedVariants >= expectedVariants && expectedVariants > 0) {+ if (arrivedVariants > 0) {setLiveState('CYCLING');recoveryWaitingForAnchor = false;hideShaderOverlay();@@ -6072,13 +6253,18 @@updateSelectedElement();showOrUpdateCyclingBar();disableInlineEdit();- refreshParamsPanel();+ if (arrivedVariants >= expectedVariants && expectedVariants > 0) refreshParamsPanel();+ else hideParamsPanel();positionBar();} else if (state === 'GENERATING') {updateBarContent('generating');}saveSession();- queueCheckpoint(state === 'CYCLING' ? 'variants_ready' : 'variants_progress');+ sendCheckpoint(+ arrivedVariants >= expectedVariants && expectedVariants > 0+ ? 'variants_ready'+ : 'variants_progress',+ );updating = false;});@@ -6151,6 +6337,7 @@syncAgentPollingUi(!!msg.agentPolling);startAgentStatusPoll();restoreFromActiveSessions(msg.activeSessions, 'sse_connected');+ recoverMissedGenerationCompletion(msg.activeSessions);if (state === 'IDLE' && (pickActive || insertActive)) setLiveState('PICKING');syncPageInteractionCursor();syncPageChatFocus('sse-connected');@@ -6158,6 +6345,42 @@case 'agent_polling':syncAgentPollingUi(!!msg.connected);break;+ case 'agent_phase':+ if (msg.id === currentSessionId && (state === 'GENERATING' || state === 'CYCLING')) {+ generationPhase = msg.phase || generationPhase;+ if (msg.phase === 'variant_parameters_generating' || msg.phase === 'variant_parameters_validating') {+ parameterGenerationState = 'loading';+ }+ if (msg.phase === 'parameters_ready' && parameterGenerationState !== 'ready') {+ parameterGenerationState = 'loading';+ }+ updateBarContent(state === 'CYCLING' ? 'cycling' : 'generating');+ saveSession();+ }+ break;+ case 'variant_progress':+ if (msg.id === currentSessionId) {+ if (msg.publicationKind === 'params') parameterGenerationState = 'loading';+ rememberSessionFileMeta(msg);+ if (isFrameworkComponentPreviewMode(msg.previewMode) && msg.previewFile) {+ injectSvelteComponentsFromManifest(msg.previewFile, msg.id);+ } else if ((msg.previewMode === 'source' || !msg.previewMode) && (msg.previewFile || msg.file)) {+ // Give normal framework HMR the first chance to reconcile its+ // own managed tree. Nuxt route-module HMR can skip intermediate+ // revisions, so fall back to source injection only when the+ // advertised progress still has not appeared after a short+ // settle. Immediate injection races React/Vue ownership and can+ // trigger removeChild errors on the next HMR commit.+ const targetArrived = Number(msg.arrivedVariants) || 1;+ setTimeout(() => {+ if (msg.id !== currentSessionId) return;+ if (state !== 'GENERATING' && state !== 'CYCLING') return;+ if (msg.publicationKind !== 'params' && arrivedVariants >= targetArrived) return;+ injectVariantsFromSource(msg.previewFile || msg.file, msg.id);+ }, 150);+ }+ }+ break;case 'steer_done':maybeCompleteSteer(msg);break;@@ -6175,6 +6398,10 @@case 'done':if (maybeCompleteSteer(msg)) break;rememberSessionFileMeta(msg);+ if (msg.id === currentSessionId && isFrameworkComponentPreviewMode(currentPreviewMode) && currentPreviewFile) {+ injectSvelteComponentsFromManifest(currentPreviewFile, msg.id);+ break;+ }// Variants already arrived via HMR → normal transition.if (arrivedVariants >= expectedVariants && expectedVariants > 0) {if (state === 'GENERATING') {@@ -6190,7 +6417,7 @@setTimeout(() => {if (arrivedVariants >= expectedVariants && expectedVariants > 0) return;if (state !== 'GENERATING' || msg.id !== currentSessionId) return;- injectVariantsFromSource(msg.file, msg.id);+ injectVariantsFromSource(msg.file, msg.id, { generationCompleted: true });}, 750);break;}@@ -6215,9 +6442,10 @@if (maybeCompleteAcceptedSession(msg)) break;break;case 'agent_done':- // Carbonize accepts are not terminal until live-complete.mjs sends- // the final complete event. Keep the browser in its recoverable- // saving state while the source cleanup is still in flight.+ // The deterministic accept has already committed the reviewed DOM+ // and fenced generation. Carbonize may continue in the background;+ // it must not hold the foreground picker hostage.+ if (msg.data?.carbonize === true && maybeCompleteAcceptedSession(msg)) break;break;case 'discarded':if (msg.id && msg.id === currentSessionId) {@@ -6306,6 +6534,7 @@type: 'checkpoint',id: currentSessionId,revision: sessionState.nextCheckpointRevision(),+ revisionDomain: 'browser',owner: browserOwner,phase: String(state || '').toLowerCase(),reason,@@ -6331,6 +6560,7 @@type: 'checkpoint',id,revision: sessionState.nextCheckpointRevision(),+ revisionDomain: 'browser',owner: browserOwner,phase: 'steer',reason,@@ -6684,6 +6914,9 @@expectedVariants = selectedCount;arrivedVariants = 0;visibleVariant = 0;+ generationPhase = 'queued';+ parameterGenerationState = 'pending';+ parameterReadyAnnouncedSession = null;resetSessionFileMeta();// Flip to GENERATING immediately so the bar morphs without waiting on@@ -6693,6 +6926,7 @@const elForCapture = selectedElement;pickedAnchorSnapshot = buildPickedAnchorSnapshot(elForCapture);const captureRect = elForCapture.getBoundingClientRect();+ pickedAnchorViewportTop = captureRect.top;const snapshot = {comments: annotState.comments.map(c => ({ x: c.x, y: c.y, text: c.text })),strokes: annotState.strokes.map(s => ({ points: s.points.map(p => [p[0], p[1]]) })),@@ -6724,7 +6958,7 @@writeScrollY(window.scrollY);if (variantObserver) variantObserver.disconnect();variantObserver = startVariantObserver(currentSessionId);- startScrollLock(currentSessionId);+ startScrollLock(currentSessionId, window.scrollY, pickedAnchorViewportTop);captureAndEmit(elForCapture, basePayload, snapshot, captureRect);}@@ -6759,12 +6993,16 @@expectedVariants = selectedCount;arrivedVariants = 0;visibleVariant = 0;+ generationPhase = 'queued';+ parameterGenerationState = 'pending';+ parameterReadyAnnouncedSession = null;resetSessionFileMeta();selectedElement = placeholderElement;insertPlaceholderSnapshot = buildInsertPlaceholderSnapshotFromDom(insertAnchorElement, placeholderElement);const elForCapture = placeholderElement;const captureRect = elForCapture.getBoundingClientRect();+ pickedAnchorViewportTop = captureRect.top;const basePayload = {type: 'generate',mode: 'insert',@@ -6795,7 +7033,7 @@writeScrollY(window.scrollY);if (variantObserver) variantObserver.disconnect();variantObserver = startVariantObserver(currentSessionId);- startScrollLock(currentSessionId);+ startScrollLock(currentSessionId, window.scrollY, pickedAnchorViewportTop);captureAndEmit(elForCapture, basePayload, snapshot, captureRect);}@@ -6975,9 +7213,9 @@// preview mounts are covered by the same shader regression checks.const adapter = String(window.__IMPECCABLE_LIVE_ADAPTER__ || '').toLowerCase();if (adapter === 'svelte' || adapter === 'sveltekit') return true;- if (currentPreviewMode === 'svelte-component' || svelteComponentSession) return true;+ if (isFrameworkComponentPreviewMode(currentPreviewMode) || svelteComponentSession) return true;const wrapper = el?.closest?.('[data-impeccable-variants]');- return wrapper?.dataset?.impeccablePreview === 'svelte-component';+ return isFrameworkComponentPreviewMode(wrapper?.dataset?.impeccablePreview);}function paintsShaderProxySurface(node) {@@ -7105,6 +7343,17 @@}async function captureAndEmit(el, basePayload, snapshot, rect) {+ const hasAnnotations = snapshot && (snapshot.comments.length > 0 || snapshot.strokes.length > 0);++ // Plain requests do not send a screenshot to the agent, so capture is+ // presentation-only. Wait only for the helper to accept the event before+ // starting CPU-heavy capture; this yields the browser task and prevents+ // rasterization from delaying the fetch itself.+ if (!hasAnnotations) {+ basePayload.clientSentAt = Date.now();+ await sendEvent(basePayload);+ }+let screenshotPath;let blob;let paper;@@ -7122,7 +7371,6 @@// are present. Without annotations the image is pure visual anchoring -// it biases the model toward the current rendering and works against the// three-distinct-directions brief.- const hasAnnotations = snapshot && (snapshot.comments.length > 0 || snapshot.strokes.length > 0);if (blob && hasAnnotations) {try {const uploadRes = await fetch(@@ -7140,7 +7388,12 @@console.warn('[impeccable] annotation upload failed:', err);}}- sendEvent(screenshotPath ? { ...basePayload, screenshotPath } : basePayload);+ // Annotated requests must wait for capture + upload because the screenshot+ // is semantic input. Plain requests were already dispatched above.+ if (hasAnnotations) {+ basePayload.clientSentAt = Date.now();+ sendEvent(screenshotPath ? { ...basePayload, screenshotPath } : basePayload);+ }}//@@ -7520,7 +7773,6 @@ void main() {if (variantSelectionPromise) {try { await variantSelectionPromise; } catch { /* failed selection falls back below */ }}- if (!currentSessionId || arrivedVariants === 0) return;const domVisibleVariant = readVisibleVariantFromDOM(currentSessionId);if (domVisibleVariant > 0) visibleVariant = domVisibleVariant;const acceptPayload = {@@ -7528,7 +7780,9 @@ void main() {id: currentSessionId,variantId: String(visibleVariant),pageUrl: location.pathname,+ clientSentAt: Date.now(),};+ if (!currentSessionId || arrivedVariants === 0) return;const acceptWrapper = document.querySelector('[data-impeccable-variants="' + currentSessionId + '"]');if (Object.keys(paramsCurrentValues).length > 0) {acceptPayload.paramValues = { ...paramsCurrentValues };@@ -7542,7 +7796,7 @@ void main() {const acceptedSessionId = currentSessionId;const acceptedVariant = visibleVariant;const acceptedIsSvelteComponent = svelteComponentSession?.sessionId === acceptedSessionId- || acceptWrapper?.dataset?.impeccablePreview === 'svelte-component';+ || isFrameworkComponentPreviewMode(acceptWrapper?.dataset?.impeccablePreview);const acceptedSnapshot = snapshotAcceptedVariantDom(acceptedSessionId, acceptedVariant);setLiveState('SAVING');@@ -7557,7 +7811,17 @@ void main() {saveSession();sendEvent(acceptPayload, { throwOnError: true })- .then(() => {})+ .then(() => {+ const pending = pendingAcceptedSession;+ if (!pending || pending.id !== acceptedSessionId) return;+ // POST /events returns only after the accept intent is durable and the+ // generation epoch is fenced. Source promotion/carbonize can finish in+ // the background; the foreground picker is free immediately.+ markSessionHandled();+ setLiveState('CONFIRMED');+ document.documentElement.dataset.impeccableAcceptToPickingMs = String(Date.now() - acceptPayload.clientSentAt);+ scheduleAcceptCleanup(pending);+ }).catch(() => {if (pendingAcceptedSession?.id === acceptedSessionId) pendingAcceptedSession = null;setLiveState('CYCLING');@@ -7586,17 +7850,26 @@ void main() {}function scheduleAcceptCleanup(accepted) {- setTimeout(function() {- if (!accepted?.isSvelteComponent && !acceptedDomAlreadyClean(accepted)) {- setTimeout(function() {- if (pendingAcceptedSession?.id !== accepted?.id) return;- if (!accepted?.isSvelteComponent) ensureAcceptedDomClean(accepted);- cleanupAcceptedSession();- }, 1800);- return;+ queueMicrotask(function() {+ if (pendingAcceptedSession?.id !== accepted?.id) return;+ // Svelte previews live in an adapter-owned mount rather than in source+ // wrapper markup. Promote the mounted variant before releasing the+ // session so the old adapter instance cannot linger behind the next+ // Pick → Go loop while carbonize finishes in the background.+ if (accepted?.isSvelteComponent) {+ commitAcceptedSvelteComponentToDom(accepted.id);}cleanupAcceptedSession();- }, 1200);+ });+ // Let React/Vue/Svelte own the HMR reconciliation. Mutating their DOM in+ // the same turn as the source update causes removeChild/NotFoundError+ // races. Static servers still need a fallback, but it must not keep Live+ // in SAVING or block the user's next pick.+ if (!accepted?.isSvelteComponent) {+ setTimeout(function() {+ if (!acceptedDomAlreadyClean(accepted)) ensureAcceptedDomClean(accepted);+ }, 1200);+ }}function snapshotAcceptedVariantDom(sessionId, variantId) {@@ -7700,7 +7973,11 @@ void main() {clearSession();resetSessionFileMeta();selectedElement = null;+ hoveredElement = null;+ pagePickSkipClick = false;currentSessionId = null;+ parameterGenerationState = 'idle';+ parameterReadyAnnouncedSession = null;selectedAction = 'impeccable';pendingAcceptedSession = null;renderEditBadge('hidden');@@ -7735,7 +8012,7 @@ void main() {sendEvent({ type: 'discard', id: currentSessionId }, { throwOnError: true }).then(() => {markSessionHandled();- cleanup();+ cleanup({ restoreOriginal: true, instantChrome: true });}).catch(() => showToast('Could not confirm discard with the live server. Session kept for recovery.', 5000));}@@ -7757,6 +8034,7 @@ void main() {currentPreviewMode = null;recoveryWaitingForAnchor = false;pickedAnchorSnapshot = null;+ pickedAnchorViewportTop = null;}function rememberSessionFileMeta(meta = {}) {@@ -7765,8 +8043,8 @@ void main() {const previewFile = normalizeSessionPath(meta.previewFile);const previewMode = meta.previewMode || (isSvelteComponentManifestPath(previewFile || file) ? 'svelte-component' : null);- if (previewMode === 'svelte-component' || isSvelteComponentManifestPath(file)) {- currentPreviewMode = 'svelte-component';+ if (isFrameworkComponentPreviewMode(previewMode) || isSvelteComponentManifestPath(file)) {+ currentPreviewMode = isFrameworkComponentPreviewMode(previewMode) ? previewMode : 'svelte-component';currentPreviewFile = previewFile || (isSvelteComponentManifestPath(file) ? file : currentPreviewFile);currentSourceFile = sourceFile || currentSourceFile;return;@@ -7782,12 +8060,15 @@ void main() {rememberSessionFileMeta(saved);if (saved.insertPlaceholder) insertPlaceholderSnapshot = saved.insertPlaceholder;if (saved.pickedAnchor) pickedAnchorSnapshot = saved.pickedAnchor;+ if (Number.isFinite(saved.pickedAnchorViewportTop)) pickedAnchorViewportTop = saved.pickedAnchorViewportTop;if (saved.action) selectedAction = saved.action;if (saved.count) selectedCount = saved.count;if (saved.previewMode) currentPreviewMode = saved.previewMode;if (saved.paramValues && typeof saved.paramValues === 'object') {paramsCurrentValues = { ...saved.paramValues };}+ if (saved.parameterState) parameterGenerationState = saved.parameterState;+ if (saved.generationPhase) generationPhase = saved.generationPhase;}function normalizePagePath(value) {@@ -7859,7 +8140,7 @@ void main() {saveSession();queueCheckpoint(reason || 'browser_restore_without_wrapper');- const restoreFile = currentPreviewMode === 'svelte-component'+ const restoreFile = isFrameworkComponentPreviewMode(currentPreviewMode)? currentPreviewFile: (currentSourceFile || currentPreviewFile);if (restoreFile) {@@ -7872,11 +8153,41 @@ void main() {function restoreFromActiveSessions(activeSessions, reason) {const wrapper = document.querySelector('[data-impeccable-variants]');- if (wrapper && wrapper.dataset.impeccablePreview !== 'svelte-component') return false;+ if (wrapper && !isFrameworkComponentPreviewMode(wrapper.dataset.impeccablePreview)) return false;if (svelteComponentSession?.sessionId === currentSessionId) return false;return restoreSessionWithoutWrapper(reason || 'sse_connected', activeSessions);}+ // Self-heal on SSE (re)connect. The preflight scaffold write triggers a+ // framework full-reload (Astro reloads pages for any .astro edit); if the+ // agent's variant write + `done` broadcast land while this page is+ // mid-reload, both the done SSE and the second HMR reload are missed and+ // the resumed page would wait in GENERATING at 0/N forever. The server's+ // session summary carries the durable generationCompletedAt marker, so on+ // every connect compare it against our own progress and pull the finished+ // variants from source when behind. Mirrors the `done` handler's source+ // fallback, including its give-HMR-the-first-chance settle delay.+ function recoverMissedGenerationCompletion(activeSessions) {+ if (!currentSessionId || state !== 'GENERATING') return;+ if (!Array.isArray(activeSessions)) return;+ const summary = activeSessions.find((session) => session?.id === currentSessionId);+ if (!summary?.generationCompletedAt || summary.generationCanceled) return;+ if (isTerminalSessionSummary(summary)) return;+ if (arrivedVariants > 0 && arrivedVariants >= expectedVariants) return;+ rememberSessionFileMeta(summary);+ const sessionId = currentSessionId;+ const file = isFrameworkComponentPreviewMode(currentPreviewMode)+ ? currentPreviewFile+ : (summary.sourceFile || summary.previewFile || currentSourceFile || currentPreviewFile);+ if (!file) return;+ console.log('[impeccable] Reconnected after generation completed; recovering variants from source.');+ setTimeout(() => {+ if (sessionId !== currentSessionId || state !== 'GENERATING') return;+ if (arrivedVariants > 0 && arrivedVariants >= expectedVariants) return;+ injectVariantsFromSource(file, sessionId, { generationCompleted: true });+ }, 750);+ }+function saveSession() {if (!currentSessionId) return;// NOTE: scrollY is stored under a separate key (writeScrollY). Storing@@ -7894,8 +8205,12 @@ void main() {previewMode: currentPreviewMode || undefined,pageUrl: location.pathname,paramValues: { ...paramsCurrentValues },+ parameterState: parameterGenerationState,insertPlaceholder: insertPlaceholderSnapshot || undefined,pickedAnchor: pickedAnchorSnapshot || undefined,+ pickedAnchorViewportTop: Number.isFinite(pickedAnchorViewportTop) ? pickedAnchorViewportTop : undefined,+ pageHash: location.hash || undefined,+ pageSearch: location.search || undefined,});}@@ -7923,20 +8238,26 @@ void main() {sessionState.clearHandled();}- function cleanup() {+ function cleanup(options) {+ const restoreOriginal = options?.restoreOriginal === true;+ const instantChrome = options?.instantChrome === true;const cleanupSessionId = currentSessionId;if (svelteComponentSession?.sessionId === cleanupSessionId) {teardownSvelteComponentSession(true);} else if (cleanupSessionId) {- // Hide the wrapper immediately so variants disappear. DON'T structurally- // mutate the DOM yet - HMR from the agent's source rewrite is on its way,+ // Switch visibility immediately without structurally mutating the DOM.+ // HMR from the agent's source rewrite may still be on its way,// and a manual replaceChild under React causes NotFoundError when the// reconciler later tries to remove a wrapper we already removed.// Schedule a 2s fallback that does the manual swap only if HMR hasn't// replaced the wrapper by then (keeps static-server / no-HMR flows alive).const wrapper = document.querySelector('[data-impeccable-variants="' + cleanupSessionId + '"]');- if (wrapper) wrapper.style.display = 'none';+ if (wrapper) {+ if (restoreOriginal) showOriginalDuringDiscard(cleanupSessionId);+ else wrapper.style.display = 'none';+ }setTimeout(function() {+ document.getElementById(DISCARD_STATE_STYLE_ID)?.remove();if (!cleanupSessionId) return;const lateWrapper = document.querySelector('[data-impeccable-variants="' + cleanupSessionId + '"]');if (!lateWrapper) return;@@ -7951,7 +8272,7 @@ void main() {lateWrapper.remove();}, 2000);}- hideBar();+ hideBar(instantChrome);hideHighlight();stopScrollTracking();if (variantObserver) { variantObserver.disconnect(); variantObserver = null; }@@ -7963,7 +8284,11 @@ void main() {clearSession();resetSessionFileMeta();selectedElement = null;+ hoveredElement = null;+ pagePickSkipClick = false;currentSessionId = null;+ parameterGenerationState = 'idle';+ parameterReadyAnnouncedSession = null;selectedAction = 'impeccable';renderEditBadge('hidden');setLiveState('PICKING');@@ -8047,7 +8372,7 @@ void main() {// would strand the bar in CYCLING at 0/0. If there's no live in-memory mount// for this wrapper, it's an orphan (reload / failed mount): drop it and let// the live-server's SSE re-inject the manifest if the session is still live.- if (wrapper.dataset.impeccablePreview === 'svelte-component'+ if (isFrameworkComponentPreviewMode(wrapper.dataset.impeccablePreview)&& svelteComponentSession?.sessionId !== sessionId) {wrapper.remove();if (restoreSessionWithoutWrapper('browser_resumed_svelte_orphan_wrapper')) return true;@@ -8056,7 +8381,7 @@ void main() {return false;}- if (wrapper.dataset.impeccablePreview === 'svelte-component') {+ if (isFrameworkComponentPreviewMode(wrapper.dataset.impeccablePreview)) {if (!svelteComponentSession?.mountedVariant) {return true;}@@ -8104,7 +8429,7 @@ void main() {insertPlaceholderSnapshot = saved.insertPlaceholder;}- const resumedState = arrivedVariants >= expectedVariants ? 'CYCLING' : 'GENERATING';+ const resumedState = arrivedVariants > 0 ? 'CYCLING' : 'GENERATING';// Find the visible variant's content element for highlight positioning.const isInsert = wrapper.dataset.impeccableMode === 'insert';@@ -8128,7 +8453,11 @@ void main() {// hid. Now that state is CYCLING, re-fire.if (state === 'CYCLING') refreshParamsPanel();saveSession();- queueCheckpoint('browser_resumed');+ if (arrivedVariants > 0 && arrivedVariants < expectedVariants) {+ sendCheckpoint('variants_progress');+ } else {+ queueCheckpoint('browser_resumed');+ }// Start observing for more variants AFTER initial setupif (variantObserver) variantObserver.disconnect();@@ -8136,7 +8465,7 @@ void main() {// Hold the target at its saved viewport top through any subsequent// HMR patches, variant inserts, or cycle swaps.- startScrollLock(currentSessionId, readScrollY());+ startScrollLock(currentSessionId, readScrollY(), pickedAnchorViewportTop);// If we reloaded mid-generation (Bun's HTML HMR destroys the shader// canvas), re-capture the original's content and restart the shader so@@ -8171,6 +8500,7 @@ void main() {let globalBarBrandEl = null;let agentPollTooltipEl = null;let agentPollingConnected = false;+ let agentStatusMessage = null;let agentStatusPollTimer = null;let steerFocusSuspended = false;let steerFocusPauseUntil = 0;@@ -8275,6 +8605,13 @@ void main() {const AGENT_STATUS_POLL_MS = 5000;const AGENT_DISCONNECTED_MARK = 'oklch(62% 0 0 / 0.78)';const AGENT_DISCONNECTED_TIP = 'Agent disconnected - run live-poll.mjs to connect';+ // The indicator tracks whether a poll is parked, which is what decides if+ // steering can reach the agent right now. That goes quiet two ways, and they+ // need different copy: nobody is polling at all, or the agent took the work+ // and is busy with it. Under one-shot foreground polling the second case is+ // every normal generation, and telling the user to start a poll loop then is+ // wrong advice about a healthy session.+ const AGENT_BUSY_TIP = 'Agent is working - steering resumes when it finishes';const GLOBAL_BAR_SECTION_GAP = 8;const GLOBAL_BAR_INNER_GAP = 2;const GLOBAL_BAR_INNER_PAD_LEFT = 2;@@ -9295,24 +9632,46 @@ void main() {</svg>`;}+ /**+ * True while the browser is waiting on work it already handed to the agent.+ * In these states a quiet poll indicator means "busy", not "absent".+ */+ function agentHasWorkInFlight() {+ return state === 'GENERATING' || state === 'SAVING';+ }++ /**+ * Derived at read time, not cached: which of the two reasons applies depends on+ * the live state, which moves between the 5s status polls. The truthiness is+ * the same either way, so the indicator's visuals can stay driven by the+ * cached value while the wording stays current.+ */+ function agentStatusText() {+ if (agentPollingConnected) return null;+ return agentHasWorkInFlight() ? AGENT_BUSY_TIP : AGENT_DISCONNECTED_TIP;+ }+function syncAgentPollingUi(connected) {agentPollingConnected = !!connected;if (!globalBarBrandEl) return;const P = barPaletteForTheme(globalBarEl?.dataset.theme || detectPageTheme());+ agentStatusMessage = agentStatusText();globalBarBrandEl.dataset.agentConnected = connected ? 'true' : 'false';- globalBarBrandEl.setAttribute('aria-label', connected- ? 'Impeccable live mode'- : 'Impeccable live mode - agent not polling');+ // The tooltip is mouse-only, so carry the same distinction in the label or+ // screen-reader users are left with the vaguer of the two readings.+ globalBarBrandEl.setAttribute('aria-label', agentStatusMessage+ ? 'Impeccable live mode - ' + (agentHasWorkInFlight() ? 'agent is working' : 'agent not polling')+ : 'Impeccable live mode');globalBarBrandEl.removeAttribute('title');- globalBarBrandEl.style.cursor = connected ? 'default' : 'help';+ globalBarBrandEl.style.cursor = agentStatusMessage ? 'help' : 'default';const mark = globalBarBrandEl.querySelector('[data-brand-mark]');if (mark) {mark.innerHTML = brandMarkSvg(connected ? P.accent : AGENT_DISCONNECTED_MARK, 18);mark.style.opacity = '1';}const dot = globalBarBrandEl.querySelector('[data-agent-dot]');- if (dot) dot.style.display = connected ? 'none' : 'block';- if (connected) hideAgentPollTooltip();+ if (dot) dot.style.display = agentStatusMessage ? 'block' : 'none';+ if (!agentStatusMessage) hideAgentPollTooltip();}function ensureAgentPollTooltip() {@@ -9339,14 +9698,17 @@ void main() {whiteSpace: 'normal',});agentPollTooltipEl.id = PREFIX + '-agent-poll-tooltip';- agentPollTooltipEl.textContent = AGENT_DISCONNECTED_TIP;+ agentPollTooltipEl.textContent = agentStatusText() || AGENT_DISCONNECTED_TIP;uiAppend(agentPollTooltipEl);return agentPollTooltipEl;}function showAgentPollTooltip(anchor) {- if (agentPollingConnected || !anchor) return;+ if (!agentStatusMessage || !anchor) return;const tip = ensureAgentPollTooltip();+ // Re-derive rather than reuse the cached copy: the live state may have moved+ // since the last status poll set it.+ tip.textContent = agentStatusText() || AGENT_DISCONNECTED_TIP;tip.style.transition = 'none';tip.style.display = 'block';tip.style.opacity = '1';@@ -9376,7 +9738,9 @@ void main() {fetch('http://localhost:' + PORT + '/status?token=' + TOKEN, { cache: 'no-store' }).then((res) => (res.ok ? res.json() : null)).then((data) => {- if (data && typeof data.agentPolling === 'boolean') syncAgentPollingUi(data.agentPolling);+ if (data && typeof data.agentPolling === 'boolean') {+ syncAgentPollingUi(data.agentPolling);+ }}).catch(() => { /* server loss handled elsewhere */ });}diff --git a/.trae-cn/skills/impeccable/scripts/live-inject.mjs b/.trae-cn/skills/impeccable/scripts/live-inject.mjsindex 7c8d91182..d99c37fd5 100644--- a/.trae-cn/skills/impeccable/scripts/live-inject.mjs+++ b/.trae-cn/skills/impeccable/scripts/live-inject.mjs@@ -27,6 +27,8 @@ const __dirname = path.dirname(fileURLToPath(import.meta.url));const CONFIG_PATH = resolveLiveConfigPath({ cwd: process.cwd(), scriptsDir: __dirname });const MARKER_OPEN_TEXT = 'impeccable-live-start';const MARKER_CLOSE_TEXT = 'impeccable-live-end';+const NUXT_PLUGIN_MARKER = 'impeccable-live-nuxt-plugin';+const NUXT_PLUGIN_NAME = 'impeccable-live.client.ts';const IGNORE_MARKER_OPEN = '# impeccable-live-ignore-start';const IGNORE_MARKER_CLOSE = '# impeccable-live-ignore-end';@@ -38,6 +40,9 @@ export const LIVE_IGNORE_PATTERNS = Object.freeze(['.impeccable/live/sessions/','.impeccable/live/previews/','.impeccable/live/annotations/',+ '.impeccable/live/artifacts/',+ '.impeccable/live/accept-receipts/',+ '.impeccable/live/locks/','.impeccable/live/cache/','.impeccable/live/manual-edit-apply-transaction.json','.impeccable/live/manual-edit-events.jsonl',@@ -46,10 +51,15 @@ export const LIVE_IGNORE_PATTERNS = Object.freeze(['.impeccable/live/deferred-svelte-component-accepts.json','.impeccable-live.json','.impeccable-live/',+ 'app/.impeccable-live/',+ 'src/.impeccable-live/','node_modules/.impeccable-live/','src/lib/impeccable/ImpeccableLiveRoot.svelte','src/lib/impeccable/__runtime.js','src/lib/impeccable/[0-9a-f]*/',+ 'plugins/impeccable-live.client.ts',+ 'app/plugins/impeccable-live.client.ts',+ 'src/plugins/impeccable-live.client.ts',]);/**@@ -113,6 +123,7 @@ Output (JSON):const resolvedFiles = resolveFiles(process.cwd(), config);const svelteKit = detectSvelteKitProject(process.cwd(), config);+ const nuxt = detectNuxtProject(process.cwd());if (args.includes('--remove')) {if (svelteKit) {@@ -120,6 +131,12 @@ Output (JSON):console.log(JSON.stringify({ ok: true, adapter: 'sveltekit', results: [adapterResult] }));return;}+ if (nuxt) {+ const adapterResult = removeNuxtLiveAdapter({ cwd: process.cwd(), project: nuxt });+ console.log(JSON.stringify({ ok: !adapterResult.error, adapter: 'nuxt', results: [adapterResult] }));+ if (adapterResult.error) process.exitCode = 1;+ return;+ }const results = resolvedFiles.map((relFile) => {const absFile = path.resolve(process.cwd(), relFile);if (!fs.existsSync(absFile)) return { file: relFile, error: 'file_not_found' };@@ -145,13 +162,28 @@ Output (JSON):console.error(JSON.stringify({ ok: false, error: 'missing_port' }));process.exit(1);}- const gitIgnore = ensureLiveGitIgnores(process.cwd());+ const gitIgnore = ensureLiveGitIgnores(+ process.cwd(),+ nuxt ? [nuxt.pluginFile] : [],+ );if (svelteKit) {const adapterResult = applySvelteKitLiveAdapter({ cwd: process.cwd(), port, config });console.log(JSON.stringify({ ok: true, port, adapter: 'sveltekit', gitIgnore, results: [adapterResult] }));return;}+ if (nuxt) {+ const adapterResult = applyNuxtLiveAdapter({ cwd: process.cwd(), port, project: nuxt });+ console.log(JSON.stringify({+ ok: !adapterResult.error,+ port,+ adapter: 'nuxt',+ gitIgnore,+ results: [adapterResult],+ }));+ if (adapterResult.error) process.exitCode = 1;+ return;+ }const results = resolvedFiles.map((relFile) => {const absFile = path.resolve(process.cwd(), relFile);@@ -175,12 +207,12 @@ Output (JSON):if (!anyInserted) process.exit(1);}-export function ensureLiveGitIgnores(cwd = process.cwd()) {+export function ensureLiveGitIgnores(cwd = process.cwd(), extraPatterns = []) {const target = resolveIgnoreTarget(cwd);const existing = fs.existsSync(target.path) ? fs.readFileSync(target.path, 'utf-8') : '';const block = [IGNORE_MARKER_OPEN,- ...LIVE_IGNORE_PATTERNS,+ ...new Set([...LIVE_IGNORE_PATTERNS, ...extraPatterns]),IGNORE_MARKER_CLOSE,].join('\n');const markerRe = new RegExp(`${escapeRegExp(IGNORE_MARKER_OPEN)}[\\s\\S]*?${escapeRegExp(IGNORE_MARKER_CLOSE)}`);@@ -202,10 +234,119 @@ export function ensureLiveGitIgnores(cwd = process.cwd()) {file: path.relative(cwd, target.path).split(path.sep).join('/'),mode: target.mode,changed: updated !== existing,- patterns: [...LIVE_IGNORE_PATTERNS],+ patterns: [...new Set([...LIVE_IGNORE_PATTERNS, ...extraPatterns])],};}+// ---------------------------------------------------------------------------+// Nuxt adapter+//+// A script element placed in app.vue is compiled as Vue-rendered DOM and is+// not executed. Nuxt instead auto-discovers client plugins. Keep the adapter+// generated, dev-only, and outside user-authored source: Live creates one+// marked .client.ts plugin on start and removes it on stop.+// ---------------------------------------------------------------------------++export function detectNuxtProject(cwd = process.cwd()) {+ const configFile = fs.readdirSync(cwd, { withFileTypes: true })+ .find((entry) => entry.isFile() && /^nuxt\.config\.(?:js|mjs|cjs|ts|mts|cts)$/.test(entry.name))+ ?.name;+ if (!configFile) return null;++ const config = fs.readFileSync(path.join(cwd, configFile), 'utf-8');+ const literalSrcDir = config.match(/\bsrcDir\s*:\s*(['"])([^'"]+)\1/);+ let appDir = '';+ if (literalSrcDir) {+ const candidate = literalSrcDir[2]+ .replace(/\\/g, '/')+ .replace(/^\.\//, '')+ .replace(/\/+$/, '');+ const normalized = path.posix.normalize(candidate);+ if (normalized !== '..' && !normalized.startsWith('../') && !path.isAbsolute(normalized)) {+ appDir = normalized === '.' ? '' : normalized;+ }+ } else if (+ fs.existsSync(path.join(cwd, 'app', 'app.vue'))+ || fs.existsSync(path.join(cwd, 'app', 'pages'))+ ) {+ appDir = 'app';+ }++ const pluginFile = [appDir, 'plugins', NUXT_PLUGIN_NAME].filter(Boolean).join('/');+ return { configFile, appDir, pluginFile };+}++export function buildNuxtPlugin(port) {+ return `/* ${NUXT_PLUGIN_MARKER} */+const liveSrc = 'http://localhost:${port}/live.js';+const liveSelector = 'script[data-impeccable-live-nuxt]';++export default defineNuxtPlugin(() => {+ if (!import.meta.dev || typeof document === 'undefined') return;++ const expectedSrc = new URL(liveSrc, window.location.href).href;+ let script = document.querySelector(liveSelector);+ if (script?.src === expectedSrc) return;+ script?.remove();++ script = document.createElement('script');+ script.src = liveSrc;+ script.async = true;+ script.dataset.impeccableLiveNuxt = '';+ document.head.appendChild(script);++ import.meta.hot?.dispose(() => {+ if (script?.isConnected) script.remove();+ });+});+/* /${NUXT_PLUGIN_MARKER} */+`;+}++export function applyNuxtLiveAdapter({ cwd = process.cwd(), port, project = detectNuxtProject(cwd) }) {+ if (!project) return { error: 'nuxt_not_detected' };+ const absFile = path.join(cwd, project.pluginFile);+ const existing = fs.existsSync(absFile) ? fs.readFileSync(absFile, 'utf-8') : null;+ if (existing !== null && !existing.includes(NUXT_PLUGIN_MARKER)) {+ return {+ file: project.pluginFile,+ error: 'nuxt_plugin_conflict',+ hint: `${project.pluginFile} already exists and is not managed by Impeccable Live`,+ };+ }++ const content = buildNuxtPlugin(port);+ fs.mkdirSync(path.dirname(absFile), { recursive: true });+ if (content !== existing) fs.writeFileSync(absFile, content, 'utf-8');+ return {+ file: project.pluginFile,+ inserted: true,+ changed: content !== existing,+ devOnly: true,+ };+}++export function removeNuxtLiveAdapter({ cwd = process.cwd(), project = detectNuxtProject(cwd) }) {+ if (!project) return { error: 'nuxt_not_detected' };+ const absFile = path.join(cwd, project.pluginFile);+ if (!fs.existsSync(absFile)) {+ return { file: project.pluginFile, removed: false, note: 'no adapter present' };+ }+ const content = fs.readFileSync(absFile, 'utf-8');+ if (!content.includes(NUXT_PLUGIN_MARKER)) {+ return {+ file: project.pluginFile,+ removed: false,+ error: 'nuxt_plugin_conflict',+ hint: `${project.pluginFile} is not managed by Impeccable Live`,+ };+ }+ fs.unlinkSync(absFile);+ const pluginDir = path.dirname(absFile);+ if (fs.readdirSync(pluginDir).length === 0) fs.rmdirSync(pluginDir);+ return { file: project.pluginFile, removed: true };+}+function resolveIgnoreTarget(cwd) {const gitExcludePath = resolveGitInfoExcludePath(cwd);if (gitExcludePath) {diff --git a/.trae-cn/skills/impeccable/scripts/live-poll.mjs b/.trae-cn/skills/impeccable/scripts/live-poll.mjsindex 740161e10..19a8b0f9b 100644--- a/.trae-cn/skills/impeccable/scripts/live-poll.mjs+++ b/.trae-cn/skills/impeccable/scripts/live-poll.mjs@@ -27,7 +27,7 @@ const scriptCmd = (name) => `node "${path.join(SELF_DIR, name)}"`;export const PER_REQUEST_TIMEOUT_MS = 270_000;export const DEFAULT_EVENT_LEASE_MS = 600_000;-const EVENT_TYPES_NEEDING_AGENT_REPLY = new Set(['generate', 'steer', 'manual_edit_apply']);+const EVENT_TYPES_NEEDING_AGENT_REPLY = new Set(['generate', 'steer', 'manual_edit_apply', 'carbonize_cleanup']);function readServerInfo() {const record = readLiveServerInfo(process.cwd());@@ -38,8 +38,8 @@ function readServerInfo() {return record.info;}-export function buildPollReplyPayload(token, { id, type, message, file, data }) {- return { token, id, type, message, file, data };+export function buildPollReplyPayload(token, { id, type, message, file, data, sourceEventType }) {+ return { token, id, type, message, file, data, sourceEventType };}export function manualApplyPollBanner(event = {}) {@@ -152,7 +152,14 @@ export async function waitForEventAck(base, token, eventId, {return false;}-export async function fetchNextEvent(base, token, { totalDeadline } = {}) {+export async function fetchNextEvent(base, token, {+ totalDeadline,+ types,+ resolveTypes,+ perRequestTimeoutMs = PER_REQUEST_TIMEOUT_MS,+ leaseMs = DEFAULT_EVENT_LEASE_MS,+ signal,+} = {}) {while (true) {if (totalDeadline && Date.now() >= totalDeadline) {return { type: 'timeout' };@@ -161,8 +168,15 @@ export async function fetchNextEvent(base, token, { totalDeadline } = {}) {const remaining = totalDeadline? totalDeadline - Date.now(): PER_REQUEST_TIMEOUT_MS;- const slice = Math.min(Math.max(remaining, 1000), PER_REQUEST_TIMEOUT_MS);- const res = await fetch(`${base}/poll?token=${token}&timeout=${slice}&leaseMs=${DEFAULT_EVENT_LEASE_MS}`);+ const slice = Math.min(Math.max(remaining, 1000), perRequestTimeoutMs);+ const query = new URLSearchParams({+ token,+ timeout: String(slice),+ leaseMs: String(leaseMs),+ });+ const normalizedTypes = normalizePollTypes(resolveTypes ? await resolveTypes() : types);+ if (normalizedTypes.length > 0) query.set('types', normalizedTypes.join(','));+ const res = await fetch(`${base}/poll?${query}`, { signal });if (res.status === 401) {const err = new Error('Authentication failed. The server token may have changed.');@@ -202,11 +216,17 @@ export async function augmentEventWithAcceptHandling(event, base, token) {event._acceptResult = { handled: false, mode: 'error', error: err.message };}+ await completeAcceptHandling(event, base, token);+ return event;+}++export async function completeAcceptHandling(event, base, token) {const completionType = completionTypeForAcceptResult(event.type, event._acceptResult);try {await postReply(base, token, {id: event.id,type: completionType,+ sourceEventType: event.type,message: event._acceptResult?.error,file: event._acceptResult?.file,data: event._acceptResult?.carbonize === true ? { carbonize: true } : undefined,@@ -217,7 +237,6 @@ export async function augmentEventWithAcceptHandling(event, base, token) {if (!event._completionAck) {event._completionAck = completionAckForAcceptResult(event.id, completionType, event._acceptResult);}-return event;}@@ -245,9 +264,9 @@ export function printPollEvent(event) {console.log(JSON.stringify(event));}-export async function runPollOnce(base, token, { totalTimeout = 600_000 } = {}) {+export async function runPollOnce(base, token, { totalTimeout = 600_000, types, resolveTypes, perRequestTimeoutMs } = {}) {const deadline = Date.now() + totalTimeout;- const event = await fetchNextEvent(base, token, { totalDeadline: deadline });+ const event = await fetchNextEvent(base, token, { totalDeadline: deadline, types, resolveTypes, perRequestTimeoutMs });await augmentEventWithAcceptHandling(event, base, token);writeCarbonizeBanner(event);printPollEvent(event);@@ -258,11 +277,14 @@ export async function runPollStream(base, token, {ackTimeoutMs = 600_000,ackPollIntervalMs = 400,shouldContinue = () => true,+ types,+ resolveTypes,+ perRequestTimeoutMs,} = {}) {process.stderr.write('[impeccable-poll] stream mode: one JSON object per line on stdout; use --reply while this process stays running\n');while (shouldContinue()) {- const event = await fetchNextEvent(base, token);+ const event = await fetchNextEvent(base, token, { types, resolveTypes, perRequestTimeoutMs });await augmentEventWithAcceptHandling(event, base, token);writeCarbonizeBanner(event);printPollEvent(event);@@ -322,14 +344,17 @@ Modes:Options:--timeout=MS One-shot poll timeout in ms (default: 600000). Ignored in --stream mode+ --types=A,B Lease only these event types--ack-timeout=MS Stream mode: max wait for --reply after generate/steer (default: 600000)--file PATH Attach a source file path to the reply (generate/steer flow)--data JSON Attach a JSON result object to the reply (manual_edit_apply flow). Must be valid JSON--help Show this help messageHarness note:- Default one-shot mode is the portable contract for Claude Code, Codex, and Cursor.- --stream is experimental for harnesses with fast incremental stdout; do not use on Cursor.`);+ Default one-shot mode is the primary contract, including Codex foreground polling.+ Claude Code may run it as a background task; Cursor uses a background terminal with exit notification.+ --stream is retained for harnesses with measured, reliable incremental stdout.+ Do not use --stream on Cursor.`);process.exit(0);}@@ -360,23 +385,30 @@ Harness note:}const streamMode = args.includes('--stream');+ const typesArg = args.find((a) => a.startsWith('--types='));+ const types = normalizePollTypes(typesArg ? typesArg.slice('--types='.length) : null);const ackTimeoutArg = args.find((a) => a.startsWith('--ack-timeout='));const ackTimeoutMs = ackTimeoutArg ? parseInt(ackTimeoutArg.split('=')[1], 10) : 600_000;try {if (streamMode) {- await runPollStream(base, info.token, { ackTimeoutMs });+ await runPollStream(base, info.token, { ackTimeoutMs, types });return;}const timeoutArg = args.find((a) => a.startsWith('--timeout='));const totalTimeout = timeoutArg ? parseInt(timeoutArg.split('=')[1], 10) : 600_000;- await runPollOnce(base, info.token, { totalTimeout });+ await runPollOnce(base, info.token, { totalTimeout, types });} catch (err) {handlePollError(err);}}+export function normalizePollTypes(value) {+ const values = Array.isArray(value) ? value : String(value || '').split(',');+ return [...new Set(values.map((type) => String(type).trim()).filter(Boolean))];+}+// Auto-execute when run directlyconst _running = process.argv[1];if (_running?.endsWith('live-poll.mjs') || _running?.endsWith('live-poll.mjs/')) {diff --git a/.trae-cn/skills/impeccable/scripts/live-server.mjs b/.trae-cn/skills/impeccable/scripts/live-server.mjsindex 5735f2aec..c6e951086 100644--- a/.trae-cn/skills/impeccable/scripts/live-server.mjs+++ b/.trae-cn/skills/impeccable/scripts/live-server.mjs@@ -28,8 +28,10 @@ import {readLiveBrowserScriptParts,resolveLiveBrowserScriptParts,} from './live/browser-script-parts.mjs';-import { createLiveSessionStore } from './live/session-store.mjs';+import { createLiveSessionStore, GENERATION_FENCED_PHASES } from './live/session-store.mjs';+import { runGenerationPreflight } from './live/generation-preflight.mjs';import { validateEvent } from './live/event-validation.mjs';+import { selectAvailablePendingEvent } from './live/poll-lanes.mjs';import { createManualEditRoutes } from './live/manual-edit-routes.mjs';import { LIVE_COMMANDS } from './live/vocabulary.mjs';import {@@ -63,6 +65,10 @@ const DESIGN_MD_PATH = PROJECT_CONTEXT.designPath: null;const DEFAULT_POLL_TIMEOUT = 600_000; // 10 min — agent re-polls on timeout anywayconst SSE_HEARTBEAT_INTERVAL = 30_000; // keepalive ping every 30s+// The browser checkpoints for several unrelated reasons (see checkpointPayload+// in live-browser.js). Only these two report that variant availability changed,+// and only they may drive variant_progress / the *_reviewable phases.+const VARIANT_PROGRESS_CHECKPOINT_REASONS = new Set(['variants_progress', 'variants_ready']);// ---------------------------------------------------------------------------// Port detection@@ -156,29 +162,206 @@ function restorePendingEventsFromStore() {}}-function findAvailablePendingEvent(now = Date.now()) {- for (const entry of state.pendingEvents) {- if (entry.leaseUntil && entry.leaseUntil > now) continue;- return entry;- }- return null;+function findAvailablePendingEvent(now = Date.now(), types = null) {+ return selectAvailablePendingEvent(state.pendingEvents, { now, types });}-function leaseEvent(entry, leaseMs) {+async function leaseEvent(entry, leaseMs) {+ // Claim the entry before awaiting anything. prepareGenerateEventForLease+ // yields to the event loop, and selectAvailablePendingEvent only skips+ // entries whose lease is in the future — an unclaimed entry would be handed+ // to a second poll in that window and generated twice.+ entry.leaseUntil = Date.now() + leaseMs;+ await prepareGenerateEventForLease(entry);if (!entry.event?.id) {const idx = state.pendingEvents.indexOf(entry);if (idx !== -1) state.pendingEvents.splice(idx, 1);return entry.event;}+ // Re-stamp so the lease window starts when the agent actually receives the+ // work, not when scaffolding began.entry.leaseUntil = Date.now() + leaseMs;+ recordGenerateDelivery(entry);scheduleLeaseFlush();broadcastAgentPollingIfChanged();return entry.event;}-function acknowledgePendingEvent(id) {+function recordGenerateDelivery(entry) {+ const event = entry?.event;+ if (!event || event.type !== 'generate' || event.generationReadyAt) return;+ const at = Date.now();+ entry.event = { ...event, generationReadyAt: at };+ state.sessionStore?.appendEvent(entry.event);+ recordAgentPhase(event.id, 'generation_ready', { at });+}++async function prepareGenerateEventForLease(entry) {+ const event = entry?.event;+ if (!event || event.type !== 'generate' || event.scaffoldAttempted) return;++ recordAgentPhase(event.id, 'picked_up');+ recordAgentPhase(event.id, 'scaffolding');+ const result = await runGenerationPreflight(event, {+ cwd: process.cwd(),+ scriptsDir: __dirname,+ });+ entry.event = {+ ...event,+ scaffoldAttempted: true,+ scaffoldDurationMs: result.durationMs ?? null,+ ...(result.ok ? { scaffold: result.scaffold } : { scaffoldError: result.error || result.reason }),+ };+ state.sessionStore?.appendEvent(entry.event);+ recordAgentPhase(event.id, result.ok ? 'source_ready' : 'scaffold_fallback', {+ durationMs: result.durationMs ?? null,+ previewMode: result.scaffold?.previewMode || 'source',+ });+}++function recordAgentPhase(id, phase, details = {}) {+ if (!id) return;+ const event = {+ type: 'agent_phase',+ id,+ phase,+ at: Date.now(),+ ...details,+ };+ state.sessionStore?.appendEvent(event);+ broadcast(event);+}++/**+ * Detect a browser that missed the generation `done` broadcast.+ *+ * The preflight scaffold write triggers a framework full-reload (Astro reloads+ * the page for any .astro edit). If the agent's variant write + `done` land+ * while the browser is mid-reload, the new page misses both the second HMR+ * reload and the SSE `done` — it resumes from the scaffold-only source and+ * sits in GENERATING at 0/N forever. That resumed page always checkpoints+ * (`browser_resumed`), so a checkpoint claiming "still generating, variants+ * missing" for a session whose generation already completed is direct+ * evidence of the miss. Rebuild the `done` payload from the snapshot so the+ * caller can re-broadcast it; the browser's done handler is idempotent and+ * falls back to injecting variants from source.+ *+ * Keys on the store's monotone `generationCompletedAt`, not `phase` — the+ * behind checkpoint itself regresses `phase` to `generating`, and a browser+ * that misses the redelivered `done` too (another reload) must still trigger+ * redelivery from its next checkpoint.+ */+function detectMissedGenerationCompletion(event) {+ if (!event?.id || event.type !== 'checkpoint') return null;+ if (event.phase !== 'generating') return null;+ if (!variantCountLooksBehind(event.arrivedVariants, event.expectedVariants)) return null;+ if (!state.sessionStore) return null;+ let snapshot = null;+ try {+ snapshot = state.sessionStore.getSnapshot(event.id);+ } catch {+ return null;+ }+ return missedCompletionFromSnapshot(snapshot);+}++function variantCountLooksBehind(arrivedValue, expectedValue) {+ const arrived = Number(arrivedValue) || 0;+ const expected = Number(expectedValue) || 0;+ return arrived <= 0 || (expected > 0 && arrived < expected);+}++function missedCompletionFromSnapshot(snapshot) {+ if (!snapshot?.id || !snapshot.generationCompletedAt) return null;+ if (snapshot.generationCanceled) return null;+ // Accept/discard already underway: the browser is no longer waiting on+ // generation, and a late `done` there would collide with teardown.+ if (GENERATION_FENCED_PHASES.has(snapshot.phase)) return null;+ const file = snapshot.sourceFile || snapshot.previewFile;+ if (!file) return null;+ return {+ type: 'done',+ id: snapshot.id,+ file,+ sourceFile: snapshot.sourceFile || undefined,+ previewFile: snapshot.previewFile || undefined,+ previewMode: snapshot.previewMode || undefined,+ redelivered: true,+ };+}++function recordGenerationCheckpoint(event) {+ if (!event?.id || event.type !== 'checkpoint') return;+ if (generationIsFenced(event.id)) return;+ // Only checkpoints that report a change in variant availability are+ // generation progress. The browser also checkpoints for durability on Tune+ // slider drags, resumes, and anchor recovery; treating those as progress+ // echoed `variant_progress` straight back to the browser that sent it, which+ // remounts the component preview mid-drag (reverting the user's live param+ // edit and detaching the popover's element), and permanently latched the+ // *_reviewable phases from the wrong trigger, corrupting generation timings.+ if (!VARIANT_PROGRESS_CHECKPOINT_REASONS.has(event.reason)) return;+ const arrived = Number(event.arrivedVariants) || 0;+ const expected = Number(event.expectedVariants) || 0;+ if (arrived <= 0 || expected <= 0) return;+ const previewMode = event.previewMode || 'source';+ const previewFile = event.previewFile || event.file;+ if (previewFile) {+ broadcast({+ type: 'variant_progress',+ id: event.id,+ file: previewFile,+ sourceFile: event.sourceFile || (previewMode === 'source' ? previewFile : undefined),+ previewFile,+ previewMode,+ arrivedVariants: arrived,+ expectedVariants: expected,+ publicationKind: event.publicationKind || 'variants',+ });+ }+ const details = {+ arrivedVariants: arrived,+ expectedVariants: expected,+ checkpointReason: event.reason || null,+ };+ const at = Date.now();+ if (!generationPhaseAlreadyRecorded(event.id, 'first_reviewable')) {+ recordAgentPhase(event.id, 'first_reviewable', { ...details, at });+ }+ if (arrived >= 2 && expected >= 3 && !generationPhaseAlreadyRecorded(event.id, 'second_reviewable')) {+ recordAgentPhase(event.id, 'second_reviewable', { ...details, at });+ }+ if (arrived >= expected && !generationPhaseAlreadyRecorded(event.id, 'all_variants_ready')) {+ recordAgentPhase(event.id, 'all_variants_ready', { ...details, at });+ }+}++function generationIsFenced(id) {+ if (!state.sessionStore || !id) return false;+ try {+ const snapshot = state.sessionStore.getSnapshot(id, { includeCompleted: true });+ return snapshot?.generationCanceled === true;+ } catch {+ return false;+ }+}++function generationPhaseAlreadyRecorded(id, phase) {+ if (!state.sessionStore) return false;+ try {+ const snapshot = state.sessionStore.getSnapshot(id, { includeCompleted: true });+ return !!snapshot?.generationTimings?.[phase];+ } catch {+ return false;+ }+}++function acknowledgePendingEvent(id, sourceEventType) {if (!id) return false;- const idx = state.pendingEvents.findIndex((entry) => entry.event?.id === id);+ const idx = state.pendingEvents.findIndex((entry) => (+ entry.event?.id === id+ && (!sourceEventType || entry.event?.type === sourceEventType)+ ));if (idx === -1) return false;const acknowledged = state.pendingEvents[idx].event;state.pendingEvents.splice(idx, 1);@@ -187,9 +370,39 @@ function acknowledgePendingEvent(id) {return acknowledged;}-function findPendingEventById(id) {+function releasePendingEvent(id, sourceEventType) {+ const entry = state.pendingEvents.find((item) => (+ item.event?.id === id+ && (!sourceEventType || item.event?.type === sourceEventType)+ ));+ if (!entry) return null;+ entry.leaseUntil = 0;+ scheduleLeaseFlush();+ return entry.event;+}++function retirePendingGeneration(id) {+ if (!id) return 0;+ let retired = 0;+ for (let index = state.pendingEvents.length - 1; index >= 0; index -= 1) {+ const event = state.pendingEvents[index]?.event;+ if (event?.id !== id || event.type !== 'generate') continue;+ state.pendingEvents.splice(index, 1);+ retired += 1;+ }+ if (retired > 0) {+ scheduleLeaseFlush();+ broadcastAgentPollingIfChanged();+ }+ return retired;+}++function findPendingEventById(id, sourceEventType) {if (!id) return null;- const entry = state.pendingEvents.find((item) => item.event?.id === id);+ const entry = state.pendingEvents.find((item) => (+ item.event?.id === id+ && (!sourceEventType || item.event?.type === sourceEventType)+ ));return entry?.event || null;}@@ -198,7 +411,7 @@ function summarizePendingEventForStatus(entry) {const summary = {id: event.id,type: event.type,- leased: !!(entry.leaseUntil && entry.leaseUntil > Date.now()),+ leased: isLeased(entry),leaseUntil: entry.leaseUntil || null,};if (event.type === 'manual_edit_apply') {@@ -224,7 +437,13 @@ function summarizeActiveSessionForClient(snapshot = {}) {arrivedVariants: snapshot.arrivedVariants ?? 0,visibleVariant: snapshot.visibleVariant ?? null,checkpointRevision: snapshot.checkpointRevision ?? 0,+ browserCheckpointRevision: snapshot.browserCheckpointRevision ?? snapshot.checkpointRevision ?? 0,+ publicationCheckpointRevision: snapshot.publicationCheckpointRevision ?? 0,paramValues: snapshot.paramValues || {},+ generationPhase: snapshot.generationPhase ?? null,+ generationCompletedAt: snapshot.generationCompletedAt ?? null,+ generationCanceled: snapshot.generationCanceled === true,+ cancelReason: snapshot.cancelReason ?? null,};}@@ -269,24 +488,46 @@ function scheduleLeaseFlush() {function flushPendingPolls() {let changed = false;while (state.pendingPolls.length > 0) {- const entry = findAvailablePendingEvent();+ let pollIndex = -1;+ let entry = null;+ for (let index = 0; index < state.pendingPolls.length; index += 1) {+ const candidate = findAvailablePendingEvent(Date.now(), state.pendingPolls[index].types);+ if (!candidate) continue;+ pollIndex = index;+ entry = candidate;+ break;+ }if (!entry) {scheduleLeaseFlush();broadcastAgentPollingIfChanged();return;}- const poll = state.pendingPolls.shift();- poll.resolve(leaseEvent(entry, poll.leaseMs));+ const [poll] = state.pendingPolls.splice(pollIndex, 1);+ // leaseEvent is async (it may scaffold source), but it claims the entry+ // synchronously, so the next loop iteration will not re-select it. Resolve+ // the poll when the lease settles rather than awaiting here, so one slow+ // scaffold never delays the other parked polls. On the exceptional failure+ // path, answer `timeout` so the agent re-polls; the claim stays until the+ // lease expires, which keeps a deterministic failure from hot-looping.+ leaseEvent(entry, poll.leaseMs).then(poll.resolve, (error) => {+ console.error('[live] lease failed for ' + (entry.event?.id || 'unknown') + ': ' + (error?.message || error));+ poll.resolve({ type: 'timeout' });+ });changed = true;}scheduleLeaseFlush();if (changed) broadcastAgentPollingIfChanged();}+function isLeased(entry) {+ return !!(entry?.leaseUntil && entry.leaseUntil > Date.now());+}+function agentPollingConnected() {- const now = Date.now();- return state.pendingPolls.length > 0- || state.pendingEvents.some((entry) => entry.leaseUntil && entry.leaseUntil > now);+ // A leased event only proves that a poll returned once. The foreground task+ // may have ended immediately afterward, so only an actively waiting poll is+ // evidence that steering can wake the task right now.+ return state.pendingPolls.length > 0;}function broadcastAgentPollingIfChanged() {@@ -689,6 +930,16 @@ function createRequestHandler({ detectScript, liveScriptParts }) {res.end(JSON.stringify({ error }));return;}+ if (msg.type === 'agent_phase') {+ recordAgentPhase(msg.id, msg.phase, {+ ...(Number.isFinite(msg.durationMs) ? { durationMs: msg.durationMs } : {}),+ owner: typeof msg.owner === 'string' ? msg.owner : undefined,+ });+ res.writeHead(200, { 'Content-Type': 'application/json' });+ res.end(JSON.stringify({ ok: true }));+ return;+ }+ const missedCompletion = detectMissedGenerationCompletion(msg);if (state.sessionStore && msg.id) {try {state.sessionStore.appendEvent(msg);@@ -698,6 +949,11 @@ function createRequestHandler({ detectScript, liveScriptParts }) {return;}}+ if (msg.type === 'accept' || msg.type === 'discard') {+ retirePendingGeneration(msg.id);+ }+ recordGenerationCheckpoint(msg);+ if (missedCompletion) broadcast(missedCompletion);if (msg.type === 'exit') {cleanupSvelteComponentSessionsBeforeExit();}@@ -738,6 +994,12 @@ function createRequestHandler({ detectScript, liveScriptParts }) {// Agent poll endpoints (unchanged from WS version)// ---------------------------------------------------------------------------+function parsePollTypes(value) {+ if (!value) return null;+ const types = String(value).split(',').map((type) => type.trim()).filter(Boolean);+ return types.length > 0 ? new Set(types) : null;+}+function handlePollGet(req, res, url) {const token = url.searchParams.get('token');if (token !== state.token) {@@ -748,13 +1010,25 @@ function handlePollGet(req, res, url) {state.lastPollAt = Date.now();const timeout = parseInt(url.searchParams.get('timeout') || DEFAULT_POLL_TIMEOUT, 10);const leaseMs = parseInt(url.searchParams.get('leaseMs') || '30000', 10);- const available = findAvailablePendingEvent();+ const types = parsePollTypes(url.searchParams.get('types'));+ const available = findAvailablePendingEvent(Date.now(), types);if (available) {- res.writeHead(200, { 'Content-Type': 'application/json' });- res.end(JSON.stringify(leaseEvent(available, leaseMs)));+ // Do not await inline: leaseEvent may scaffold source, and this handler runs+ // on the server's only thread. The client can disconnect during that window,+ // so check the socket before replying.+ leaseEvent(available, leaseMs).then((event) => {+ if (res.writableEnded || res.destroyed) return;+ res.writeHead(200, { 'Content-Type': 'application/json' });+ res.end(JSON.stringify(event));+ }, (error) => {+ console.error('[live] lease failed for ' + (available.event?.id || 'unknown') + ': ' + (error?.message || error));+ if (res.writableEnded || res.destroyed) return;+ res.writeHead(200, { 'Content-Type': 'application/json' });+ res.end(JSON.stringify({ type: 'timeout' }));+ });return;}- const poll = { resolve, leaseMs };+ const poll = { resolve, leaseMs, types };const timer = setTimeout(() => {const idx = state.pendingPolls.indexOf(poll);if (idx !== -1) state.pendingPolls.splice(idx, 1);@@ -783,12 +1057,15 @@ function sessionFileMetadataFromPollReply(file) {if (!file || typeof file !== 'string') return { file };const normalized = file.split(path.sep).join('/');const base = { file: normalized };- if (!normalized.endsWith('/manifest.json') && normalized !== 'manifest.json') return base;- if (!normalized.includes('node_modules/.impeccable-live/') && !normalized.includes('src/lib/impeccable/')) return base;+ const metadataFile = normalized;+ if (!metadataFile.endsWith('/manifest.json') && metadataFile !== 'manifest.json') return base;+ if (!metadataFile.includes('node_modules/.impeccable-live/')+ && !metadataFile.includes('src/lib/impeccable/')+ && !metadataFile.includes('/.impeccable-live/')) return base;let full;try {- full = path.resolve(process.cwd(), normalized);+ full = path.resolve(process.cwd(), metadataFile);const rel = path.relative(process.cwd(), full);if (!rel || rel.startsWith('..') || path.isAbsolute(rel)) return base;} catch {@@ -797,18 +1074,47 @@ function sessionFileMetadataFromPollReply(file) {try {const manifest = JSON.parse(fs.readFileSync(full, 'utf-8'));- if (manifest?.previewMode !== 'svelte-component' || !manifest.sourceFile) return base;+ if (manifest?.previewMode !== 'svelte-component'+ || !manifest.sourceFile) return base;return {file: String(manifest.sourceFile).split(path.sep).join('/'),sourceFile: String(manifest.sourceFile).split(path.sep).join('/'),previewFile: normalized,- previewMode: 'svelte-component',+ previewMode: manifest.previewMode,};} catch {return base;}}+function inferSourceEventType(msg = {}, pendingEvents = state.pendingEvents) {+ const entriesForId = pendingEvents.filter((entry) => entry.event?.id === msg.id);+ const pendingTypes = new Set(entriesForId.map((entry) => entry.event?.type));+ if (msg.type === 'discarded' || msg.type === 'discard') return 'discard';+ if (msg.type === 'complete') {+ if (pendingTypes.has('carbonize_cleanup')) return 'carbonize_cleanup';+ return pendingTypes.has('accept') ? 'accept' : (pendingTypes.has('generate') ? 'generate' : undefined);+ }+ if (msg.type === 'steer_done') return 'steer';+ // `agent_done` can be the automatic acknowledgement for a carbonize Accept.+ // New pollers send sourceEventType explicitly; default to generate only for+ // older callers so a late worker cannot acknowledge a queued Accept.+ if (msg.type === 'agent_done' || msg.type === 'done') return 'generate';+ // `error` is reference/live.md's documented failure reply, and parseReplyArgs+ // never sets sourceEventType on it (the poller is a fresh process that cannot+ // know what it leased). Returning undefined here makes acknowledgePendingEvent+ // match *any* event for this id: a stale generate worker's failure silently+ // consumed the user's queued Accept, which was then never delivered to any+ // agent and left the browser in SAVING forever. Attribute the failure to the+ // event this agent actually holds a lease on, and otherwise to `generate` —+ // never to a wildcard. If that generate was already retired by an Accept, the+ // ack simply finds no match, which is the correct outcome for a stale reply.+ if (msg.type === 'error') {+ return entriesForId.find(isLeased)?.event?.type || 'generate';+ }+ return undefined;+}+function handlePollPost(req, res) {let body = '';req.on('data', (c) => { body += c; });@@ -869,7 +1175,23 @@ function handlePollPost(req, res) {res.end(JSON.stringify({ error: 'stale_manual_edit_apply_reply', ...rollback }));return;}- const pendingEventBeforeAck = findPendingEventById(msg.id);+ const sourceEventType = msg.sourceEventType || inferSourceEventType(msg);+ if (msg.type === 'retry') {+ const releasedEvent = releasePendingEvent(msg.id, sourceEventType);+ if (!releasedEvent) {+ res.writeHead(msg.id ? 404 : 400, { 'Content-Type': 'application/json' });+ res.end(JSON.stringify({+ error: msg.id ? 'unknown_poll_retry_id' : 'missing_poll_retry_id',+ id: msg.id,+ }));+ return;+ }+ flushPendingPolls();+ res.writeHead(200, { 'Content-Type': 'application/json' });+ res.end(JSON.stringify({ ok: true, released: true }));+ return;+ }+ const pendingEventBeforeAck = findPendingEventById(msg.id, sourceEventType);if (pendingEventBeforeAck?.type === 'steer' && msg.type === 'steer_done'&& !msg.file && !(typeof msg.message === 'string' && msg.message.trim())) {res.writeHead(400, { 'Content-Type': 'application/json' });@@ -879,7 +1201,7 @@ function handlePollPost(req, res) {}));return;}- const acknowledgedEvent = acknowledgePendingEvent(msg.id);+ const acknowledgedEvent = acknowledgePendingEvent(msg.id, sourceEventType);let skipJournalReply = false;let existingSession = null;if (!acknowledgedEvent && state.sessionStore && msg.id) {@@ -1083,7 +1405,10 @@ if (args.includes('--background')) {process.exit(0);}} catch { /* not ready yet */ }- await new Promise(r => setTimeout(r, 200));+ // The detached child is typically listening in 35-45ms. A 200ms polling+ // floor dominated configured cold Live startup; poll cheaply and return+ // as soon as the child has written its ready record.+ await new Promise(r => setTimeout(r, 5));}console.error('Timed out waiting for live server to start.');process.exit(1);diff --git a/.trae-cn/skills/impeccable/scripts/live-status.mjs b/.trae-cn/skills/impeccable/scripts/live-status.mjsindex f7e464999..dc98b7386 100644--- a/.trae-cn/skills/impeccable/scripts/live-status.mjs+++ b/.trae-cn/skills/impeccable/scripts/live-status.mjs@@ -37,15 +37,19 @@ export async function statusCli() {pendingEvents: server.pendingEvents,} : null,activeSessions: server?.activeSessions || activeSessions,- recoveryHint: manualApply- ? manualApplyResumeHint(manualApply)- : server- ? 'Run live-poll.mjs to continue pending work, or live-complete.mjs --id <session> after manual cleanup.'- : 'Start live-server.mjs to requeue pending durable events, then run live-poll.mjs.',+ recoveryHint: recoveryHint({ server, manualApply }),};console.log(JSON.stringify(payload, null, 2));}+function recoveryHint({ server, manualApply }) {+ if (manualApply) return manualApplyResumeHint(manualApply);+ if (server) {+ return 'Run live-poll.mjs to continue pending work, or live-complete.mjs --id <session> after manual cleanup.';+ }+ return 'Start live-server.mjs to requeue pending durable events, then run live-poll.mjs.';+}+function findPendingManualApply(server, activeSessions) {const fromServer = server?.pendingEvents?.find((event) => event?.type === 'manual_edit_apply');if (fromServer) return fromServer;diff --git a/.trae-cn/skills/impeccable/scripts/live-wrap.mjs b/.trae-cn/skills/impeccable/scripts/live-wrap.mjsindex 438c01b68..48d7f7683 100644--- a/.trae-cn/skills/impeccable/scripts/live-wrap.mjs+++ b/.trae-cn/skills/impeccable/scripts/live-wrap.mjs@@ -160,11 +160,29 @@ The agent should insert variant HTML at insertLine.`);if (filtered.length === 1) {match = filtered[0];} else if (filtered.length === 0) {- // Source uses dynamic content (`<h1>{title}</h1>` etc.) so the- // browser-side textContent doesn't appear literally in source. Fall- // back to first-match rather than refusing — this is the same- // behavior unmodified callers see, just preserved.- match = candidates[0];+ const normalizedText = String(text).replace(/\s+/g, ' ').trim();+ if (normalizedText.length < 8) {+ // Very short labels cannot disambiguate siblings reliably. Preserve+ // the legacy behavior for these low-information picker events.+ match = candidates[0];+ } else {+ // Rendered text that is absent from every candidate usually means+ // the source uses expressions or component props. Picking the first+ // same-class sibling silently edits the wrong instance (observed on+ // Astro result cards), so stop and surface every candidate instead.+ console.error(JSON.stringify({+ error: 'element_ambiguous',+ fallback: 'agent-driven',+ reason: 'rendered_text_not_in_source',+ file: path.relative(process.cwd(), targetFile),+ candidates: candidates.map((c) => ({+ startLine: c.startLine + 1,+ endLine: c.endLine + 1,+ })),+ hint: 'Rendered text does not occur in any matching source branch. The element may use dynamic props or expressions; inspect the candidates and wrap the intended instance manually.',+ }));+ process.exit(1);+ }} else {// Multiple candidates ALSO match the text. Truly ambiguous — refuse// rather than pick wrong, and hand the agent the candidate locations@@ -269,6 +287,7 @@ The agent should insert variant HTML at insertLine.`);const originalIndented = reindentOriginal(' ');const relTargetFile = path.relative(process.cwd(), targetFile).split(path.sep).join('/');const useSvelteComponent = shouldUseSvelteComponentInjection(targetFile);+ const useFrameworkComponent = useSvelteComponent;// Wrapper attributes differ by syntax. HTML allows plain string attrs;// JSX requires object-literal style and parses string attrs as HTML (which@@ -288,7 +307,7 @@ The agent should insert variant HTML at insertLine.`);// replacement range to include the wrapper's `<div>` open / close lines// so the entire scaffold gets removed cleanly.const wrapperLines = isJsx ? [- indent + '<div data-impeccable-variants="' + id + '" data-impeccable-variant-count="' + count + '" ' + styleContents + '>',+ indent + '<div data-impeccable-variants="' + id + '" data-impeccable-variant-count="' + count + '"' + ' ' + styleContents + '>',indent + ' ' + commentSyntax.open + ' impeccable-variants-start ' + id + ' ' + commentSyntax.close,indent + ' ' + commentSyntax.open + ' Original ' + commentSyntax.close,indent + ' <div data-impeccable-variant="original">',@@ -299,7 +318,7 @@ The agent should insert variant HTML at insertLine.`);indent + '</div>',] : [indent + commentSyntax.open + ' impeccable-variants-start ' + id + ' ' + commentSyntax.close,- indent + '<div data-impeccable-variants="' + id + '" data-impeccable-variant-count="' + count + '" ' + styleContents + '>',+ indent + '<div data-impeccable-variants="' + id + '" data-impeccable-variant-count="' + count + '"' + ' ' + styleContents + '>',indent + ' ' + commentSyntax.open + ' Original ' + commentSyntax.close,indent + ' <div data-impeccable-variant="original">',originalIndented,@@ -356,15 +375,18 @@ The agent should insert variant HTML at insertLine.`);const outputRelFile = path.relative(process.cwd(), outputFile).split(path.sep).join('/');const svelteComponentAuthoring = useSvelteComponent ? buildSvelteComponentCssAuthoring(count) : null;+ const componentSession = svelteSession;+ const componentPreviewMode = useSvelteComponent ? 'svelte-component' : undefined;+ const previewMode = componentPreviewMode;console.log(JSON.stringify({file: outputRelFile,- sourceFile: useSvelteComponent ? relTargetFile : undefined,- previewMode: useSvelteComponent ? 'svelte-component' : undefined,- componentDir: svelteSession?.componentDir,- propContract: svelteSession?.propContract,- sourceStartLine: useSvelteComponent ? startLine + 1 : undefined,- sourceEndLine: useSvelteComponent ? endLine + 1 : undefined,+ sourceFile: useFrameworkComponent ? relTargetFile : undefined,+ previewMode,+ componentDir: componentSession?.componentDir,+ propContract: componentSession?.propContract,+ sourceStartLine: useFrameworkComponent ? startLine + 1 : undefined,+ sourceEndLine: useFrameworkComponent ? endLine + 1 : undefined,startLine: outputStartLine, // 1-indexed for the agent// wrapperLines is an array but one element (the original-content slot)// is a `\n`-joined multi-line string, so the actual file-row count is@@ -374,10 +396,10 @@ The agent should insert variant HTML at insertLine.`);endLine: outputEndLine, // 1-indexedinsertLine, // 1-indexed: where variants gocommentSyntax: commentSyntax,- styleMode: useSvelteComponent ? 'svelte-component' : styleMode.mode,- styleTag: useSvelteComponent ? null : styleMode.styleTag,- cssSelectorPrefixExamples: useSvelteComponent ? [] : buildCssSelectorPrefixExamples(styleMode.mode, count),- cssAuthoring: useSvelteComponent ? svelteComponentAuthoring : buildCssAuthoring(styleMode, count),+ styleMode: componentPreviewMode || styleMode.mode,+ styleTag: useFrameworkComponent ? null : styleMode.styleTag,+ cssSelectorPrefixExamples: useFrameworkComponent ? [] : buildCssSelectorPrefixExamples(styleMode.mode, count),+ cssAuthoring: svelteComponentAuthoring || buildCssAuthoring(styleMode, count),originalLineCount: originalLines.length,}));}diff --git a/.trae-cn/skills/impeccable/scripts/live.mjs b/.trae-cn/skills/impeccable/scripts/live.mjsindex e0bd1ad24..b21a71cc4 100644--- a/.trae-cn/skills/impeccable/scripts/live.mjs+++ b/.trae-cn/skills/impeccable/scripts/live.mjs@@ -10,7 +10,7 @@** After this, the agent's only remaining steps are:* - Open the project's live dev/preview URL in the browser (optional, if browser automation exists)—not `serverPort`; that port is the Impeccable helper for /live.js and /poll- * - Enter the poll loop: `node live-poll.mjs`+ * - Enter the harness-native poll loop: `node live-poll.mjs`** Usage:* node live.mjs # Prepare everything, print JSON, exit@@ -40,6 +40,7 @@ Prepare everything for live variant mode in a single command:- Starts (or reuses) the live server in the background- Injects the browser script tag- Reads PRODUCT.md / DESIGN.md for project context+ - Prepares the harness-native foreground/background poll loop- In monorepos, choose a child app first; --target <path> is the fallback/manual pathOn success, prints a JSON blob with:diff --git a/.trae-cn/skills/impeccable/scripts/live/completion.mjs b/.trae-cn/skills/impeccable/scripts/live/completion.mjsindex 986773066..6f539336d 100644--- a/.trae-cn/skills/impeccable/scripts/live/completion.mjs+++ b/.trae-cn/skills/impeccable/scripts/live/completion.mjs@@ -1,9 +1,18 @@+// A preview whose variants live in component modules rather than in the user's+// source. These leave no markers in the real file, so a failed accept gives the+// agent nothing to hand-edit and must be reported as a failure rather than+// reference/live.md's manual-cleanup handoff. Kept as a set: any future+// component-module preview mode belongs here the day it lands.+const PREVIEW_MODES_WITHOUT_SOURCE_MARKERS = new Set([+ 'svelte-component',+]);+export function completionTypeForAcceptResult(eventType, acceptResult) {if (eventType === 'discard') return acceptResult?.handled === true ? 'discarded' : 'error';if (acceptResult?.handled === true && acceptResult?.carbonize === true) return 'agent_done';if (acceptResult?.handled === true) return 'complete';if (acceptResult?.mode === 'error') return 'error';- if (eventType === 'accept' && acceptResult?.previewMode === 'svelte-component') return 'error';+ if (eventType === 'accept' && PREVIEW_MODES_WITHOUT_SOURCE_MARKERS.has(acceptResult?.previewMode)) return 'error';return 'agent_done';}diff --git a/.trae-cn/skills/impeccable/scripts/live/event-validation.mjs b/.trae-cn/skills/impeccable/scripts/live/event-validation.mjsindex 0897b1317..122c29836 100644--- a/.trae-cn/skills/impeccable/scripts/live/event-validation.mjs+++ b/.trae-cn/skills/impeccable/scripts/live/event-validation.mjs@@ -118,6 +118,15 @@ export function validateEvent(msg) {return 'checkpoint: paramValues must be an object';}return null;+ case 'agent_phase':+ if (!isValidId(msg.id)) return 'agent_phase: missing or malformed id';+ if (typeof msg.phase !== 'string' || !/^[a-z][a-z0-9_]{1,63}$/.test(msg.phase)) {+ return 'agent_phase: missing or malformed phase';+ }+ if (msg.durationMs !== undefined && (!Number.isFinite(msg.durationMs) || msg.durationMs < 0)) {+ return 'agent_phase: durationMs must be a non-negative number';+ }+ return null;case 'exit':return null;case 'prefetch':@@ -131,6 +140,12 @@ export function validateEvent(msg) {if (msg.message.length > 4000) return 'steer: message too long';if (msg.pageUrl !== undefined && typeof msg.pageUrl !== 'string') return 'steer: pageUrl must be string';return null;+ case 'carbonize_cleanup':+ if (!isValidId(msg.id)) return 'carbonize_cleanup: missing or malformed id';+ if (!isValidId(msg.sessionId)) return 'carbonize_cleanup: missing or malformed sessionId';+ if (!msg.file || typeof msg.file !== 'string') return 'carbonize_cleanup: missing file';+ if (!isValidVariantId(String(msg.variantId))) return 'carbonize_cleanup: missing or malformed variantId';+ return null;default:return 'Unknown event type: ' + msg.type;}diff --git a/.trae-cn/skills/impeccable/scripts/live/generation-preflight.mjs b/.trae-cn/skills/impeccable/scripts/live/generation-preflight.mjsnew file mode 100644index 000000000..07a5e957e--- /dev/null+++ b/.trae-cn/skills/impeccable/scripts/live/generation-preflight.mjs@@ -0,0 +1,102 @@+import { execFile } from 'node:child_process';+import path from 'node:path';+import { promisify } from 'node:util';++const execFileAsync = promisify(execFile);+const PREFLIGHT_TIMEOUT_MS = 15_000;++export function buildGenerationPreflight(event, scriptsDir) {+ if (!event || event.type !== 'generate' || !event.id) return null;++ const isInsert = event.mode === 'insert';+ const target = isInsert ? insertTarget(event) : replaceTarget(event);+ if (!target.elementId && !target.classes) return null;++ const script = path.join(scriptsDir, isInsert ? 'live-insert.mjs' : 'live-wrap.mjs');+ const args = [script, '--id', event.id, '--count', String(event.count || 3)];+ if (isInsert) args.push('--position', target.position);+ if (target.elementId) args.push('--element-id', target.elementId);+ if (target.classes) args.push('--classes', target.classes);+ if (target.tag) args.push('--tag', target.tag);+ if (target.text) args.push('--text', target.text);+ if (!isInsert && event.pageUrl) args.push('--page-url', event.pageUrl);+ return { script, args, mode: isInsert ? 'insert' : 'replace' };+}++/**+ * Scaffold the source for a generate event before handing it to an agent.+ *+ * Async on purpose. This spawns `live-wrap.mjs`, which walks the project's+ * source tree and can take seconds (measured at ~7.6s on a large repo when the+ * element is not found, with a 15s ceiling). The live server is single-threaded+ * and calls this while leasing a poll, so a synchronous spawn froze the whole+ * server for that entire window: Accept and Discard POSTs, SSE progress+ * broadcasts, and every other poll stalled behind it.+ */+export async function runGenerationPreflight(event, {+ cwd = process.cwd(),+ scriptsDir,+ execFileImpl = execFileAsync,+ timeoutMs = PREFLIGHT_TIMEOUT_MS,+} = {}) {+ const command = buildGenerationPreflight(event, scriptsDir);+ if (!command) {+ return { ok: false, skipped: true, reason: 'insufficient_locator' };+ }++ const startedAt = performance.now();+ try {+ const { stdout } = await execFileImpl(process.execPath, command.args, {+ cwd,+ encoding: 'utf-8',+ timeout: timeoutMs,+ });+ const line = String(stdout).trim().split('\n').filter(Boolean).pop();+ if (!line) throw new Error('preflight returned no scaffold metadata');+ return {+ ok: true,+ mode: command.mode,+ durationMs: performance.now() - startedAt,+ scaffold: JSON.parse(line),+ };+ } catch (error) {+ return {+ ok: false,+ mode: command.mode,+ durationMs: performance.now() - startedAt,+ error: compactError(error),+ };+ }+}++function replaceTarget(event) {+ return normalizeTarget(event.element || {});+}++function insertTarget(event) {+ return {+ ...normalizeTarget(event.insert?.anchor || {}),+ position: event.insert?.position === 'before' ? 'before' : 'after',+ };+}++function normalizeTarget(target) {+ const classes = Array.isArray(target.classes)+ ? target.classes.join(' ')+ : String(target.classes || '').trim();+ const text = typeof target.textContent === 'string'+ ? target.textContent.trim().slice(0, 80)+ : '';+ return {+ elementId: target.id || target.elementId || undefined,+ classes: classes || undefined,+ tag: target.tagName || target.tag || undefined,+ text: text || undefined,+ };+}++function compactError(error) {+ const stderr = error?.stderr ? String(error.stderr).trim() : '';+ const message = stderr.split('\n').filter(Boolean).pop() || error?.message || 'preflight failed';+ return String(message).slice(0, 500);+}diff --git a/.trae-cn/skills/impeccable/scripts/live/poll-lanes.mjs b/.trae-cn/skills/impeccable/scripts/live/poll-lanes.mjsnew file mode 100644index 000000000..65f20a87a--- /dev/null+++ b/.trae-cn/skills/impeccable/scripts/live/poll-lanes.mjs@@ -0,0 +1,14 @@+export function eventPriority(event = {}) {+ if (event.type === 'accept' || event.type === 'discard' || event.type === 'exit') return 0;+ if (event.type === 'manual_edit_apply' || event.type === 'steer' || event.type === 'carbonize_cleanup') return 1;+ if (event.type === 'generate') return 2;+ return 3;+}++export function selectAvailablePendingEvent(entries, { now = Date.now(), types = null } = {}) {+ const allowed = types instanceof Set ? types : (Array.isArray(types) ? new Set(types) : null);+ return entries+ .filter((entry) => !(entry.leaseUntil && entry.leaseUntil > now))+ .filter((entry) => !allowed || allowed.has(entry.event?.type))+ .sort((a, b) => eventPriority(a.event) - eventPriority(b.event) || a.seq - b.seq)[0] || null;+}diff --git a/.trae-cn/skills/impeccable/scripts/live/session-store.mjs b/.trae-cn/skills/impeccable/scripts/live/session-store.mjsindex affba67c9..9d20341dd 100644--- a/.trae-cn/skills/impeccable/scripts/live/session-store.mjs+++ b/.trae-cn/skills/impeccable/scripts/live/session-store.mjs@@ -1,24 +1,26 @@import fs from 'node:fs';import path from 'node:path';-import { getLegacyLiveSessionsDir, getLiveSessionsDir } from '../lib/impeccable-paths.mjs';+import { getLegacyLiveSessionsDir, getLiveSessionsDir, safeSessionId } from '../lib/impeccable-paths.mjs';const COMPLETED_PHASES = new Set(['completed', 'discarded']);+export const GENERATION_FENCED_PHASES = new Set([+ 'accept_requested',+ 'discard_requested',+ 'carbonize_required',+ 'completed',+ 'discarded',+]);export function createLiveSessionStore({ cwd = process.cwd(), sessionId } = {}) {const rootDir = getLiveSessionsDir(cwd);const legacyRootDir = getLegacyLiveSessionsDir(cwd);fs.mkdirSync(rootDir, { recursive: true });- const snapshotCache = new Map();-- function loadCachedOrRebuild(id) {- const cached = snapshotCache.get(id);- if (cached) return cached;- const journalPath = getReadableJournalPath(id);- const rebuilt = rebuildSnapshotFromJournal(journalPath, id);- snapshotCache.set(id, rebuilt);- return rebuilt;- }+ // No snapshot cache on purpose: appendEvent and getSnapshot both rebuild from+ // the journal so sequence numbers and phase fences never come from a stale+ // in-memory copy when the publisher/complete helpers append from another+ // process. A cache written but never read would grow per session for the+ // lifetime of the server without ever saving a rebuild.function getReadableJournalPath(id) {const primary = getJournalPath(rootDir, id);if (fs.existsSync(primary)) return primary;@@ -38,7 +40,10 @@ export function createLiveSessionStore({ cwd = process.cwd(), sessionId } = {})if (!fs.existsSync(journalPath) && fs.existsSync(legacyJournalPath)) {fs.copyFileSync(legacyJournalPath, journalPath);}- const prior = loadCachedOrRebuild(normalized.id);+ // Publisher/complete helpers can append from a separate process while+ // the server is alive. Rebuild here so sequence numbers and phase+ // fences never come from a stale in-memory cache.+ const prior = rebuildSnapshotFromJournal(getReadableJournalPath(normalized.id), normalized.id);const seq = prior.nextSeq;const entry = {seq,@@ -49,7 +54,6 @@ export function createLiveSessionStore({ cwd = process.cwd(), sessionId } = {})};fs.appendFileSync(journalPath, JSON.stringify(entry) + '\n');const next = applyEvent(prior.snapshot, entry, prior.diagnostics);- snapshotCache.set(normalized.id, { snapshot: next, diagnostics: next.diagnostics || [], nextSeq: seq + 1 });writeSnapshot(snapshotPath, next);return next;},@@ -58,7 +62,6 @@ export function createLiveSessionStore({ cwd = process.cwd(), sessionId } = {})const journalPath = getReadableJournalPath(id);const snapshotPath = getSnapshotPath(rootDir, id);const rebuilt = rebuildSnapshotFromJournal(journalPath, id);- snapshotCache.set(id, rebuilt);writeSnapshot(snapshotPath, rebuilt.snapshot);if (!opts.includeCompleted && COMPLETED_PHASES.has(rebuilt.snapshot.phase)) return null;return rebuilt.snapshot;@@ -95,11 +98,6 @@ function getSnapshotPath(rootDir, id) {return path.join(rootDir, safeSessionId(id) + '.snapshot.json');}-function safeSessionId(id) {- if (!/^[A-Za-z0-9_-]{1,128}$/.test(id)) throw new Error('invalid session id: ' + id);- return id;-}-function baseSnapshot(id) {return {id,@@ -116,9 +114,18 @@ function baseSnapshot(id) {pendingEvent: null,deliveryLease: null,checkpointRevision: 0,+ browserCheckpointRevision: 0,+ publicationCheckpointRevision: 0,activeOwner: null,sourceMarkers: {},fallbackMode: null,+ generationPhase: null,+ generationCompletedAt: null,+ generationTimings: {},+ variantPlan: null,+ generationCanceled: false,+ generationCanceledAt: null,+ cancelReason: null,annotationArtifacts: [],diagnostics: [],updatedAt: null,@@ -158,6 +165,8 @@ function applyEvent(snapshot, entry, inheritedDiagnostics = []) {...snapshot,paramValues: { ...(snapshot.paramValues || {}) },sourceMarkers: { ...(snapshot.sourceMarkers || {}) },+ generationTimings: { ...(snapshot.generationTimings || {}) },+ variantPlan: snapshot.variantPlan || null,annotationArtifacts: [...(snapshot.annotationArtifacts || [])],diagnostics: [...(snapshot.diagnostics || [])],updatedAt: entry.ts || new Date().toISOString(),@@ -174,11 +183,48 @@ function applyEvent(snapshot, entry, inheritedDiagnostics = []) {next.expectedVariants = event.count ?? next.expectedVariants;next.pendingEventSeq = entry.seq ?? next.pendingEventSeq;next.pendingEvent = toPendingEvent(event);+ next.variantPlan = null;if (event.screenshotPath) upsertArtifact(next.annotationArtifacts, { type: 'screenshot', path: event.screenshotPath });break;+ case 'variant_plan':+ if (!next.generationCanceled && !GENERATION_FENCED_PHASES.has(next.phase)) {+ next.variantPlan = event.plan ?? next.variantPlan;+ }+ break;+ case 'detector_waivers':+ if (!next.generationCanceled && !GENERATION_FENCED_PHASES.has(next.phase)) {+ next.detectorWaivers = [+ ...(next.detectorWaivers || []),+ ...(Array.isArray(event.waivers) ? event.waivers : []),+ ];+ }+ break;+ case 'agent_phase':+ next.generationPhase = event.phase ?? next.generationPhase;+ if (event.phase) {+ next.generationTimings[event.phase] = {+ at: event.at ?? (Date.parse(entry.ts || '') || null),+ durationMs: event.durationMs ?? null,+ };+ }+ break;case 'variants_ready':case 'agent_done':+ if ((next.generationCanceled || GENERATION_FENCED_PHASES.has(next.phase))+ && !(event.type === 'agent_done' && event.carbonize === true && next.phase === 'accept_requested')) {+ next.diagnostics.push({+ error: 'late_generation_event_ignored',+ type: event.type,+ phase: next.phase,+ });+ break;+ }next.phase = event.carbonize === true ? 'carbonize_required' : 'variants_ready';+ // Durable completion marker: later browser checkpoints (a resumed page+ // reporting phase "generating") regress `phase`, but generation staying+ // finished is monotone — the live server keys missed-`done` redelivery+ // on this field.+ next.generationCompletedAt = event.at ?? (Date.parse(entry.ts || '') || Date.now());next.sourceFile = event.sourceFile ?? event.file ?? next.sourceFile;next.previewFile = event.previewFile ?? next.previewFile;next.previewMode = event.previewMode ?? next.previewMode;@@ -194,27 +240,45 @@ function applyEvent(snapshot, entry, inheritedDiagnostics = []) {}break;case 'checkpoint':- if (COMPLETED_PHASES.has(next.phase)) {+ if (next.generationCanceled || GENERATION_FENCED_PHASES.has(next.phase)) {next.diagnostics.push({ error: 'checkpoint_after_terminal_ignored', phase: event.phase ?? null, revision: event.revision ?? null });break;}- if ((event.revision ?? 0) >= (next.checkpointRevision ?? 0)) {- next.phase = event.phase ?? next.phase;- next.checkpointRevision = event.revision ?? next.checkpointRevision;- next.activeOwner = event.owner ?? next.activeOwner;- next.arrivedVariants = event.arrivedVariants ?? next.arrivedVariants;- next.visibleVariant = event.visibleVariant ?? next.visibleVariant;- next.sourceFile = event.sourceFile ?? next.sourceFile;- next.previewFile = event.previewFile ?? next.previewFile;- next.previewMode = event.previewMode ?? next.previewMode;- if (event.paramValues) next.paramValues = { ...event.paramValues };- } else {- next.diagnostics.push({ error: 'stale_checkpoint_ignored', revision: event.revision });+ {+ const revisionDomain = event.revisionDomain === 'publication'+ || (event.reason === 'variants_progress' && !event.owner)+ ? 'publication'+ : 'browser';+ const revisionField = revisionDomain === 'publication'+ ? 'publicationCheckpointRevision'+ : 'browserCheckpointRevision';+ const currentRevision = next[revisionField]+ ?? (revisionDomain === 'browser' ? next.checkpointRevision : 0)+ ?? 0;+ if ((event.revision ?? 0) >= currentRevision) {+ next.phase = event.phase ?? next.phase;+ next[revisionField] = event.revision ?? currentRevision;+ if (revisionDomain === 'browser') {+ next.checkpointRevision = event.revision ?? next.checkpointRevision;+ next.activeOwner = event.owner ?? next.activeOwner;+ }+ next.arrivedVariants = event.arrivedVariants ?? next.arrivedVariants;+ if (revisionDomain === 'browser') next.visibleVariant = event.visibleVariant ?? next.visibleVariant;+ next.sourceFile = event.sourceFile ?? next.sourceFile;+ next.previewFile = event.previewFile ?? next.previewFile;+ next.previewMode = event.previewMode ?? next.previewMode;+ if (revisionDomain === 'browser' && event.paramValues) next.paramValues = { ...event.paramValues };+ } else {+ next.diagnostics.push({ error: 'stale_checkpoint_ignored', revision: event.revision, revisionDomain });+ }}break;case 'accept':case 'accept_intent':next.phase = 'accept_requested';+ next.generationCanceled = true;+ next.generationCanceledAt = event.at ?? (Date.parse(entry.ts || '') || Date.now());+ next.cancelReason = 'accept';next.visibleVariant = Number(event.variantId ?? next.visibleVariant);if (event.paramValues) next.paramValues = { ...event.paramValues };next.pendingEventSeq = entry.seq ?? next.pendingEventSeq;@@ -232,6 +296,12 @@ function applyEvent(snapshot, entry, inheritedDiagnostics = []) {next.pendingEventSeq = entry.seq ?? next.pendingEventSeq;next.pendingEvent = toPendingEvent(event);break;+ case 'carbonize_cleanup':+ next.phase = 'carbonize_cleanup_requested';+ next.sourceFile = event.file ?? next.sourceFile;+ next.pendingEventSeq = entry.seq ?? next.pendingEventSeq;+ next.pendingEvent = toPendingEvent(event);+ break;case 'steer_done':next.phase = 'steer_done';next.sourceFile = event.sourceFile ?? event.file ?? next.sourceFile;@@ -243,6 +313,9 @@ function applyEvent(snapshot, entry, inheritedDiagnostics = []) {break;case 'discard':next.phase = 'discard_requested';+ next.generationCanceled = true;+ next.generationCanceledAt = event.at ?? (Date.parse(entry.ts || '') || Date.now());+ next.cancelReason = 'discard';next.pendingEventSeq = entry.seq ?? next.pendingEventSeq;next.pendingEvent = toPendingEvent(event);break;@@ -260,6 +333,10 @@ function applyEvent(snapshot, entry, inheritedDiagnostics = []) {next.pendingEvent = null;break;case 'agent_error':+ if (next.generationCanceled && event.sourceEventType === 'generate') {+ next.diagnostics.push({ error: 'late_generation_event_ignored', type: event.type, phase: next.phase });+ break;+ }next.phase = 'agent_error';next.pendingEventSeq = null;next.pendingEvent = null;diff --git a/.trae-cn/skills/impeccable/scripts/live/source-lock.mjs b/.trae-cn/skills/impeccable/scripts/live/source-lock.mjsnew file mode 100644index 000000000..9ccc557be--- /dev/null+++ b/.trae-cn/skills/impeccable/scripts/live/source-lock.mjs@@ -0,0 +1,105 @@+import fs from 'node:fs';+import path from 'node:path';+import { createHash, randomUUID } from 'node:crypto';+import { getLiveDir, isLiveServerPidReachable } from '../lib/impeccable-paths.mjs';++// Only used to retire a lock whose contents we cannot read (empty or truncated+// by a crash mid-write). A readable lock's fate is decided by its owner's+// liveness instead, so a slow critical section is never swept.+const UNREADABLE_LOCK_STALE_MS = 60_000;++export function sourceLockPath(file, cwd = process.cwd()) {+ const digest = createHash('sha256').update(path.resolve(cwd, file)).digest('hex').slice(0, 24);+ return path.join(getLiveDir(cwd), 'locks', digest + '.lock');+}++export function withSourceLockSync(file, owner, fn, {+ cwd = process.cwd(),+ waitMs = 0,+ retryMs = 5,+} = {}) {+ const lockPath = sourceLockPath(file, cwd);+ fs.mkdirSync(path.dirname(lockPath), { recursive: true });+ const deadline = Date.now() + Math.max(0, Number(waitMs) || 0);+ // Identifies this acquisition specifically, so release can tell our own lock+ // from a replacement that some other writer created.+ const token = randomUUID();+ let acquired = false;++ while (!acquired) {+ clearStaleLock(lockPath);+ let fd;+ try {+ fd = fs.openSync(lockPath, 'wx');+ fs.writeFileSync(fd, JSON.stringify({+ owner,+ token,+ pid: process.pid,+ at: Date.now(),+ file: path.resolve(cwd, file),+ }) + '\n');+ acquired = true;+ } catch (error) {+ if (error?.code !== 'EEXIST') throw error;+ if (Date.now() >= deadline) {+ const locked = new Error('source_locked');+ locked.code = 'SOURCE_LOCKED';+ locked.lockPath = lockPath;+ throw locked;+ }+ sleepSync(Math.max(1, Math.min(Number(retryMs) || 5, deadline - Date.now())));+ } finally {+ try { if (fd !== undefined) fs.closeSync(fd); } catch {}+ }+ }++ try {+ return fn();+ } finally {+ releaseOwnLock(lockPath, token);+ }+}++function sleepSync(ms) {+ Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, ms);+}++function readLock(lockPath) {+ try { return JSON.parse(fs.readFileSync(lockPath, 'utf-8')); } catch { return null; }+}++/**+ * Remove the lock only if it is still the one this call created. If a sweeper+ * judged our lock stale and another writer replaced it, unlinking here would+ * end *their* critical section and admit a third writer to the same file.+ */+function releaseOwnLock(lockPath, token) {+ const held = readLock(lockPath);+ if (held && held.token !== token) return;+ try { fs.unlinkSync(lockPath); } catch {}+}++/**+ * A lock is stale when its owner is gone, not when it is old.+ *+ * Age alone cuts both ways: it sweeps a live holder whose critical section+ * outran the timeout (a suspended laptop, a stopped process), letting two+ * writers into the same source file, while still making every accept on a+ * crashed holder's file wait out the full timeout. Asking the OS whether the+ * recorded pid is alive answers both correctly: a dead owner releases at once,+ * and a live owner keeps its lock however long it needs.+ */+function clearStaleLock(lockPath) {+ const held = readLock(lockPath);+ if (!held) {+ // Unreadable: either a crash truncated it, or we caught the brief window+ // between create and write in a live acquisition. mtime distinguishes them.+ try {+ const stat = fs.statSync(lockPath);+ if (Date.now() - stat.mtimeMs > UNREADABLE_LOCK_STALE_MS) fs.unlinkSync(lockPath);+ } catch { /* gone already */ }+ return;+ }+ if (typeof held.pid === 'number' && isLiveServerPidReachable(held.pid)) return;+ try { fs.unlinkSync(lockPath); } catch {}+}diff --git a/.trae/skills/impeccable/reference/live.md b/.trae/skills/impeccable/reference/live.mdindex c8279f19c..29dd026f8 100644--- a/.trae/skills/impeccable/reference/live.md+++ b/.trae/skills/impeccable/reference/live.md@@ -10,21 +10,24 @@ Execute in order. No step skipped, no step reordered.1. `live.mjs`: boot. If the request names or implies a file, route, or app inside a monorepo, infer the concrete path and run `node .trae/skills/impeccable/scripts/live.mjs --target <path>` instead; then run the rest of this live session from the returned `projectRoot`.2. Open the app URL that serves `pageFile` (infer from `package.json`, docs, terminal output, or an open tab). Never use `serverPort`; it's the helper, not the app. **Cursor:** `browser_navigate` to that URL before polling; do not skip. **Other harnesses:** use the available browser tool; if the URL is uncertain, ask the user once.-3. Poll loop with the default long timeout (600000 ms). After every event or `--reply`, run `live-poll.mjs` again immediately. Never pass a short `--timeout=`.+3. Poll loop with the default long timeout (600000 ms). Run `live-poll.mjs` again immediately after every event or `--reply`; Codex runs this one-shot poll in the foreground. Never pass a short `--timeout=`.The global bar **Impeccable mark** dims and shows a pulsing amber dot when no agent is long-polling `/poll`. Hover the mark for the hint; restart `live-poll.mjs` to reconnect.-4. On `generate`: read screenshot if present; load the action's reference; plan three distinct directions; write all variants in one edit; `--reply done`; poll again.+4. On `generate`: reuse `event.scaffold` when present; read the screenshot if present; load the action's reference; deliver variants using the delivery policy below; `--reply done`; poll again. Generate in this thread. You already hold the project's tokens, conventions, and file layout; that context is the job, not overhead.5. On `steer`: read the message and `pageUrl`; do the work (page edits, navigation help, or a short reply in the `--reply` message); `--reply steer_done`; poll again. No pickup ack. The Steer bar unlocks when `steer_done` arrives over SSE.-6. On `accept` / `discard`: the poll script runs `live-accept.mjs`, acknowledges the delivered event, and prints `_completionAck`. Plain accepts/discards are terminal immediately; carbonize accepts remain recoverable until you finish cleanup, run `live-complete.mjs --id EVENT_ID`, and only then poll again.+6. On `accept` / `discard`: the poll script runs `live-accept.mjs`, acknowledges the delivered event, and prints `_completionAck`. Plain accepts/discards are terminal immediately. Carbonize accepts remain recoverable until the foreground task runs `live-complete.mjs --id EVENT_ID`; finish that cleanup before polling again.7. If interrupted, run `live-status.mjs` or `live-resume.mjs` before guessing. The durable journal replays unacknowledged work after helper restart.8. On `exit`: run the cleanup at the bottom.Harness policy:-- **Claude Code**: run the poll as a **background task** (no short timeout). The harness notifies you when it completes, so the main conversation stays free. Do not block the shell.+- **Claude Code**: run the poll as a **background task** (no short timeout). The harness notifies you when it completes, so the main conversation stays free while you generate and publish in it. Do not block the shell.- **Cursor**: run **one-shot** poll in a **background terminal** with notify on `"type":"(steer|generate|accept|discard|exit)"`. After each event the poll exits; handle it, `--reply`, then start `live-poll.mjs` again. Do **not** use `--stream` on Cursor: incremental stdout notify is slower in practice than exit-based notify (~5s vs sub-second in testing).-- **Codex**: run the poll in the **foreground** (blocking shell; not a background task, not a subagent). Codex background exec sessions do not reliably surface poll stdout back into the conversation at the moment events arrive, so a "fire-and-forget" background poll will stall live mode.+- **Codex**: run the default one-shot poll in a **yielded foreground exec session**. Do not suffix it with `&`, use `--stream`, or leave Live without an active foreground poll. Handle every event in the main task; after each handler/reply, restart the foreground poll.- **Other harnesses**: one-shot foreground unless you know stdout reliably returns to this session when a shell exits.+Generation delivery policy:+- **Default (Cursor and other harnesses):** keep the established atomic single-edit delivery. Do not switch a harness to progressive until its poll loop is known not to block on the extra publish calls. This avoids trading model latency for extra tool-call latency on harnesses with different streaming behavior.+Chat is overhead. No recap, no tutorial output, no pasting PRODUCT / DESIGN bodies. Spend tokens on tools and edits; on failure, one or two short sentences.## Start@@ -92,14 +95,14 @@ Server restart rule: start `live-server.mjs` again, then poll. Startup requeues**Insert mode** (`event.mode === "insert"`): `{id, mode: "insert", count, pageUrl, insert: { position, anchor }, placeholder: { width, height }, freeformPrompt?, screenshotPath?, comments?, strokes?}`. No `action`. Requires a non-empty `freeformPrompt` **or** annotations. Screenshot is sent only when annotations exist (same rule as replace). Use `placeholder` dimensions as a soft size hint for net-new content.-Speed matters; the user is watching a spinner. Minimize tool calls by using the wrap/insert helper and writing all variants in a single edit.+Speed matters; the user is watching the selected element. Reuse server preflight metadata when available, minimize discovery calls, and follow the harness-specific delivery policy above.### Insert mode branchWhen `event.mode === "insert"`:1. Read the screenshot if `event.screenshotPath` is present (annotations only).-2. Run the insert helper instead of wrap:+2. If `event.scaffold` is present, use it as the insert-helper result and do **not** run the helper again. Otherwise run the insert helper instead of wrap:```bashnode .trae/skills/impeccable/scripts/live-insert.mjs --id EVENT_ID --count EVENT_COUNT --position after \@@ -109,7 +112,7 @@ node .trae/skills/impeccable/scripts/live-insert.mjs --id EVENT_ID --count EVENT- `--position` ← `event.insert.position` (`before` | `after`)- Anchor flags ← `event.insert.anchor` (same mapping as wrap: id, classes, tag, text)-The scaffold has **no** `data-impeccable-variant="original"`. Variants are net-new HTML+CSS inserted at `insertLine`. Load `brand.md` or `product.md` (freeform only, no action sub-command). Write all variants in one edit, then `--reply done`.+The scaffold has **no** `data-impeccable-variant="original"`. Variants are net-new HTML+CSS inserted at `insertLine`. Load `brand.md` or `product.md` (freeform only, no action sub-command). Deliver using the harness policy, then `--reply done`.For Svelte/SvelteKit targets, `live-insert.mjs` returns `previewMode: "svelte-component"` with `mode: "insert"`, `file` pointing at a temporary `node_modules/.impeccable-live/<id>/manifest.json`, `componentDir` pointing at the variant component files, and `sourceFile` pointing at the real `.svelte` route. Write each inserted variant as a real Svelte component (`v1.svelte`, `v2.svelte`, …) under `componentDir`. Insert variants must be non-empty net-new content with a single top-level root, no `data-impeccable-*` attributes, and CSS in each component's `<style>` block. Do **not** edit the route source during generation; the browser mounts the temporary component before/after the live anchor while the user cycles variants. On Accept, `live-accept.mjs` inserts the selected component markup into `sourceFile` immediately and deletes the temp session after the source write succeeds.@@ -134,6 +137,8 @@ Reading annotations precisely:### 2. Wrap the element+When `event.scaffold` is present, the local helper already found and wrapped the source before the poll returned. Treat `event.scaffold` as the successful helper output and skip this command entirely. `event.scaffoldAttempted` with `scaffoldError` means local preflight could not finish; use the command/fallback path below. This optimization removes a deterministic tool round trip without changing the generated design.+```bashnode .trae/skills/impeccable/scripts/live-wrap.mjs --id EVENT_ID --count EVENT_COUNT --element-id "ELEMENT_ID" --classes "class1,class2" --tag "div" --text "TEXT_SNIPPET"```@@ -153,7 +158,7 @@ Output on success: `{ file, insertLine, commentSyntax, styleMode, styleTag, cssSFor Svelte/SvelteKit targets, `live-wrap.mjs` returns `previewMode: "svelte-component"` with `file` pointing at a temporary `node_modules/.impeccable-live/<id>/manifest.json`, `componentDir` pointing at the variant component files, and `sourceFile` pointing at the real `.svelte` route. Write each variant as a real Svelte component (`v1.svelte`, `v2.svelte`, …) under `componentDir`; use the `propContract` prop names for dynamic text (`{propName}`), not literal snapshot strings. Put variant CSS in each component's `<style>` block with semantic class selectors (no `@scope`, no `data-impeccable-*`). Reply with `--file` set to the manifest path; the browser dynamically imports and mounts the compiled components so Svelte HMR does not reset page state while the user cycles variants. On Accept, `live-accept.mjs` inlines the accepted component back into `sourceFile` immediately after source promotion succeeds.-**Params on the Svelte component path go in a sidecar, never as an attribute.** Svelte parses `{` inside an attribute value as the start of an expression, so a `data-impeccable-params='[{…}]'` attribute on a component element fails to compile (`Expected token }`). Declare params for this path in `componentDir/params.json`, keyed by variant number, using the exact param schema from section 7:+**Params on component-preview paths go in a sidecar, never as an attribute.** Svelte parses `{` inside an attribute value as the start of an expression, and both Svelte/Vue previews mount without an HTML variant wrapper. Declare params in `componentDir/params.json`, keyed by variant number, using the exact param schema from section 7:```json{@@ -291,11 +296,13 @@ In **departure mode**, the prompt narrows the lanes you draw from, not the familWhen the prompt and PRODUCT.md anti-references conflict (the prompt asks for X, the anti-references ban X), the anti-references win; they describe the brand's standing position, the prompt is one moment.-### 6. Write all variants in a single edit+### 6. Deliver variantsComplete HTML replacement of the original element for each variant, not a CSS-only patch. Consider the element's context (computed styles, parent structure, CSS variables from `event.element`).-Write CSS + all variants in ONE edit at the `insertLine` reported by `wrap`. Colocate CSS as a `<style>` tag inside the variant wrapper; `<style>` works anywhere in modern browsers and this ensures CSS and HTML arrive atomically (no FOUC).+Colocate preview CSS as a `<style>` tag inside the variant wrapper; `<style>` works anywhere in modern browsers and keeps each delivered state internally complete (no FOUC).++**Atomic default:** write CSS + all variants + parameter manifests in one edit at `insertLine`, preserving the established behavior.Use the `cssAuthoring` object returned by `live-wrap.mjs` to author the temporary preview CSS. The style opening tag shown below is the common case; replace it with `cssAuthoring.styleTag` when the tool returns a different one. The variant markup shape is otherwise stable:@@ -319,7 +326,7 @@ Use the `cssAuthoring` object returned by `live-wrap.mjs` to author the temporarThe first variant has no `display: none` (visible by default). All others do. If variants use only inline styles and no preview CSS, omit the `<style>` tag entirely.-One edit, all variants; the browser's MutationObserver picks everything up in one pass.+The browser's MutationObserver accepts either delivery shape. On the transactional progressive path it shows arrived variants and pending dots immediately; Accept and Discard are available as soon as one variant exists. Accepting an arrived variant fences the worker before the browser releases the picker, so later publications are rejected.For `styleMode: "scoped"`, author every `:scope` rule with a descendant combinator. The `@scope` boundary is the **variant wrapper `<div data-impeccable-variant="N">`**, not the element you're designing. A bare `:scope { background: cream; }` styles the wrapper, not the inner replacement, so the cream lands on a `display: contents` shell while the actual element keeps page defaults. Always step in: `:scope > .card`, `:scope > section`, `:scope .hero-title`, etc. The fake test agent's CSS in `tests/live-e2e/agent.mjs` is a faithful template; every scoped rule starts `:scope > ...`.@@ -361,7 +368,7 @@ Each variant can expose **coarse** knobs alongside the full HTML/CSS replacement**Hard cap per variant**: at most **four** parameters so the panel stays legible; rare fifth only if the reference explicitly allows it.-**How to declare.** Put a JSON manifest on the variant wrapper (HTML/JSX path). **On the Svelte `svelte-component` path, do not use this attribute** (Svelte can't compile `{` inside an attribute value). Declare params in `componentDir/params.json` keyed by variant number instead (see the Svelte component paragraph in the wrap section). The param schema below is identical for both paths.+**How to declare.** Put a JSON manifest on the variant wrapper (HTML/JSX path). **On the `svelte-component` path, do not use this attribute.** Declare params in `componentDir/params.json` keyed by variant number instead (see the component-preview paragraphs in the wrap section). The param schema below is identical for every path.```html<div data-impeccable-variant="1" data-impeccable-params='[@@ -462,15 +469,19 @@ Event: `{id, variantId, _acceptResult, _completionAck}`. The poll script already- The accept event includes `pageUrl`; the poll script must forward it to `live-accept.mjs --page-url PAGE_URL` so accept-time cleanup only scrubs staged copy edits for the current page.- `_completionAck.ok !== true`: do not poll yet. Run `live-status.mjs` / `live-resume.mjs`, complete the cleanup manually if needed, then run `live-complete.mjs --id EVENT_ID`.- `_acceptResult.handled: true` and `carbonize: false`: nothing to do. Poll again.-- `_acceptResult.handled: true` and `carbonize: true`: **post-accept cleanup is required before the next poll.** See the "Required after accept (carbonize)" section below. The `event._acceptResult.todo` field, `_completionAck.requiresComplete`, and a stderr banner all point at this required follow-up; none are decorative. After cleanup, run `live-complete.mjs --id EVENT_ID`, then poll again.+- `_acceptResult.handled: true` and `carbonize: true`: post-accept cleanup is required, but it must not stall Codex's control lane. See "Required after accept (carbonize)" below. The `event._acceptResult.todo` field, `_completionAck.requiresComplete`, and stderr banner all point at this required follow-up; none are decorative.- `_acceptResult.handled: false, mode: "fallback"`: the session lived in a generated file and the script refused to persist there. You've already written the accepted variant into true source during Handle fallback Step 3; just clean up the temporary wrapper in the served file if any, and poll again.+- `_acceptResult.handled: false, mode: "error"`: the operation genuinely failed. **Do not hand-edit the file**; the source was not touched and editing it yourself would either double-apply or race whoever holds it.+ - `error: "source_locked"`: a generation publish holds the file. Run the same `live-accept.mjs` command again; it is idempotent and will succeed once the publisher releases. Do not poll past it.+ - `error: "accept_receipt_conflict"`: this session already resolved as `priorOperation` (on `priorVariantId` for an accept), so the request contradicts durable truth. Do not edit. Run `live-status.mjs` and tell the user what the session actually resolved to.+ - anything else: report the error briefly and run `live-status.mjs` before continuing.- `_acceptResult.handled: false` without `mode`: manual cleanup: read file, find markers, edit.### Required after accept (carbonize)When `_acceptResult.carbonize === true`, the accepted variant was stitched into source with helper markers and inline CSS so the browser can render it immediately with no visual gap. That stitch-in is **temporary**. The agent must rewrite it into permanent form before doing anything else. Skipping this leaves dead `@scope` rules for unaccepted variants, a pointless `data-impeccable-variant` wrapper, and `impeccable-carbonize-start/end` comment noise in the source file; all of which accumulate across sessions.-Do these five steps in the current thread, synchronously, before the next poll. Do not poll again until the file is clean.+Do these five steps synchronously before the next poll. The source lock, generation epoch, and expected-source hash remain the final safety gates against a generator finishing concurrently with Accept.1. **Locate the carbonize block** in the source file (`_acceptResult.file`). It's bracketed by `<!-- impeccable-carbonize-start SESSION_ID -->` and `<!-- impeccable-carbonize-end SESSION_ID -->` and contains a `<style data-impeccable-css="SESSION_ID">` element. If the variant declared parameters, an `<!-- impeccable-param-values SESSION_ID: {...} -->` comment sits alongside the style tag with the user's chosen values; read it first; it drives steps 3 and 4 below.2. **Move the CSS rules** into the project's real stylesheet. Which stylesheet depends on the project (e.g. `site/styles/workflow.css` for an Astro project, or the component's co-located CSS file for a Vite/Next project; pick whichever already owns styling for the surrounding element).@@ -478,9 +489,7 @@ Do these five steps in the current thread, synchronously, before the next poll.4. **Unwrap the accepted content.** Delete the inner `<div data-impeccable-variant="N" style="display: contents">` that wraps it. On JSX/TSX, also delete the outer `<div data-impeccable-carbonize="SESSION_ID" style={{ display: 'contents' }}>` wrapper if present (accept adds it so ternary/`return` slots keep a single root). Drop `data-impeccable-params` and any `data-p-*` attributes; those are live-mode plumbing, not source.5. **Delete the inline `<style>` block, the `<!-- impeccable-param-values -->` comment if present, and both `<!-- impeccable-carbonize-start/end -->` markers.** Also drop any `@scope` rules for variants other than the accepted one; those are dead code now.-After the file is clean, run `live-complete.mjs --id SESSION_ID`, verify it reports `phase: "completed"`, then poll again.--A background agent may be used for the rewrite, but the current thread is responsible for verifying the five steps are complete before issuing the next poll. In practice, inline is usually faster and less error-prone.+After the file is clean, the cleanup owner runs `live-complete.mjs --id SESSION_ID` and verifies `phase: "completed"`. Poll again only after that verification.## Handle `discard`diff --git a/.trae/skills/impeccable/scripts/lib/impeccable-paths.mjs b/.trae/skills/impeccable/scripts/lib/impeccable-paths.mjsindex 2ccbe7b74..99956c0f3 100644--- a/.trae/skills/impeccable/scripts/lib/impeccable-paths.mjs+++ b/.trae/skills/impeccable/scripts/lib/impeccable-paths.mjs@@ -104,6 +104,20 @@ export function removeLiveServerInfo(cwd = process.cwd(), options = {}) {}}+/**+ * Session IDs become path segments (journals, snapshots, accept receipts,+ * preview manifests, generated component dirs). They arrive from CLI `--id`+ * arguments and HTTP payloads, so anything containing a separator or `..` must+ * be rejected before it reaches path.join, which would happily escape+ * `.impeccable/live/`. Real IDs are 8 hex chars; the tests use short slugs.+ */+export function safeSessionId(id) {+ if (typeof id !== 'string' || !/^[A-Za-z0-9_-]{1,128}$/.test(id)) {+ throw new Error('invalid session id: ' + id);+ }+ return id;+}+export function getLiveSessionsDir(cwd = process.cwd(), options = {}) {return path.join(getLiveDir(cwd, options), 'sessions');}diff --git a/.trae/skills/impeccable/scripts/live-accept.mjs b/.trae/skills/impeccable/scripts/live-accept.mjsindex 278dfbb2e..453ddea35 100644--- a/.trae/skills/impeccable/scripts/live-accept.mjs+++ b/.trae/skills/impeccable/scripts/live-accept.mjs@@ -16,7 +16,9 @@import fs from 'node:fs';import path from 'node:path';import { isGeneratedFile } from './lib/is-generated.mjs';+import { IMPECCABLE_DIR, getLiveDir, safeSessionId } from './lib/impeccable-paths.mjs';import { readBuffer as readManualEditsBuffer, writeBuffer as writeManualEditsBuffer } from './live/manual-edits-buffer.mjs';+import { withSourceLockSync } from './live/source-lock.mjs';import {applyDeferredSvelteComponentAccepts,findSvelteComponentManifest,@@ -25,6 +27,46 @@ import {} from './live/svelte-component.mjs';const EXTENSIONS = ['.html', '.jsx', '.tsx', '.vue', '.svelte', '.astro'];+const ACCEPT_LOCK_WAIT_MS = 1_000;+// Mirrors VARIANT_ID_PATTERN in live/event-validation.mjs, which gates the same+// value arriving over HTTP.+const VARIANT_NUM_PATTERN = /^[0-9]{1,3}$/;++/**+ * A thrown accept/discard is a real failure, not a manual handoff.+ *+ * live/completion.mjs only classifies a result as `error` when it carries+ * `mode: 'error'`; anything else unhandled falls through to `agent_done` with a+ * successful ack, and reference/live.md then tells the agent to finish the edit+ * by hand. That is right for the documented fallback paths and wrong here: a+ * `source_locked` contention needs a retry (hand-editing races the publisher+ * holding the lock), and a crash needs surfacing, not a hand-applied guess.+ */+function operationFailure(err, extra = {}) {+ return { handled: false, mode: 'error', error: err.message, ...extra };+}++/**+ * Mark an unhandled preview-path result as a real failure.+ *+ * operationFailure only covers results built from a *thrown* error. The accept+ * implementations also return `{handled: false, error}` for their own checks+ * (variant missing, template empty, original text ambiguous), and those arrived+ * without `mode`, so completion.mjs classified them as agent_done and+ * reference/live.md routed the agent to "read file, find markers, edit".+ *+ * That handoff only makes sense for a plain wrapper session, which is the one+ * shape with markers in the user's source to edit. Component and isolated+ * artifact previews keep the source clean until Accept, so there is nothing to+ * hand-edit and an unhandled result is always a failure. `previewMode` is+ * exactly that discriminator: only the preview branches set it.+ */+function markPreviewFailure(result) {+ if (result?.handled === false && !result.mode && result.previewMode) {+ return { ...result, mode: 'error' };+ }+ return result;+}// ---------------------------------------------------------------------------// CLI@@ -63,7 +105,52 @@ Output (JSON):const isDiscard = args.includes('--discard');if (!id) { console.error('Missing --id'); process.exit(1); }+ // `id` becomes a path segment (accept receipts, preview manifests, generated+ // component dirs). Reject separators and traversal here so one check covers+ // every downstream sink.+ try { safeSessionId(id); } catch { console.error('Invalid --id'); process.exit(1); }if (!isDiscard && !variantNum) { console.error('Need --discard or --variant N'); process.exit(1); }+ // `variantNum` is interpolated into a RegExp and into the markup written back+ // to source. The browser and the /events schema both constrain it to digits;+ // enforce the same here, or `--variant '.*'` matches the `original` block+ // first and silently accepts the original while reporting success.+ if (!isDiscard && !VARIANT_NUM_PATTERN.test(variantNum)) {+ console.error('Invalid --variant');+ process.exit(1);+ }++ const requestedOperation = isDiscard ? 'discard' : 'accept';+ const priorReceipt = readAcceptReceipt(process.cwd(), id);+ if (priorReceipt) {+ const sameOperation = priorReceipt.operation === requestedOperation+ && (isDiscard || String(priorReceipt.variantId) === String(variantNum));+ console.log(JSON.stringify(sameOperation+ ? { ...priorReceipt.result, handled: true, alreadyApplied: true }+ : {+ // mode: 'error' is what marks this a real failure rather than a manual+ // handoff. Without it, live/completion.mjs classifies the reply as+ // agent_done and reference/live.md tells the agent to "read file, find+ // markers, edit" by hand — which would apply a second, conflicting+ // accept on top of the one the receipt already recorded.+ handled: false,+ mode: 'error',+ error: 'accept_receipt_conflict',+ priorOperation: priorReceipt.operation,+ priorVariantId: priorReceipt.variantId ?? null,+ }));+ return;+ }+ const emitResult = (rawResult) => {+ const result = markPreviewFailure(rawResult);+ if (result?.handled !== false) {+ writeAcceptReceipt(process.cwd(), id, {+ operation: requestedOperation,+ variantId: isDiscard ? null : String(variantNum),+ result,+ });+ }+ console.log(JSON.stringify(result));+ };let paramValues = null;if (paramValuesRaw) {@@ -82,39 +169,55 @@ Output (JSON):if (svelteComponentManifest) {if (isDiscard) {- removeSvelteComponentSession(id, process.cwd());- console.log(JSON.stringify({- handled: true,+ let result;+ try {+ result = withSourceLockSync(+ path.resolve(process.cwd(), svelteComponentManifest.sourceFile),+ 'discard:' + id,+ () => {+ removeSvelteComponentSession(id, process.cwd());+ return { handled: true };+ },+ { waitMs: ACCEPT_LOCK_WAIT_MS },+ );+ } catch (err) {+ result = operationFailure(err);+ }+ emitResult({+ ...result,file: svelteComponentManifest.sourceFile,carbonize: false,previewMode: 'svelte-component',componentDir: svelteComponentManifest.componentDir,- }));+ });return;}let result;try {- result = inlineSvelteComponentAccept(- svelteComponentManifest,- variantNum,- paramValues,- process.cwd(),+ result = withSourceLockSync(+ path.resolve(process.cwd(), svelteComponentManifest.sourceFile),+ 'accept:' + id,+ () => inlineSvelteComponentAccept(+ svelteComponentManifest,+ variantNum,+ paramValues,+ process.cwd(),+ ),+ { waitMs: ACCEPT_LOCK_WAIT_MS },);} catch (err) {- result = {- handled: false,- error: err.message,+ result = operationFailure(err, {file: svelteComponentManifest.sourceFile,sourceFile: svelteComponentManifest.sourceFile,previewMode: 'svelte-component',componentDir: svelteComponentManifest.componentDir,- };+ });}if (result.carbonize) {result.todo = 'REQUIRED before next poll: carbonize cleanup in ' + result.file + '. See reference/live.md "Required after accept".';}- console.log(JSON.stringify({ handled: result.handled !== false, ...result }));+ emitResult({ handled: result.handled !== false, ...result });return;}@@ -145,10 +248,25 @@ Output (JSON):}if (isDiscard) {- const result = handleDiscard(id, lines, targetFile);- console.log(JSON.stringify({ handled: true, file: relFile, carbonize: false, ...result }));+ let result;+ // handleDiscard takes the source lock, which throws SOURCE_LOCKED under+ // contention. Without this catch the CLI exits non-zero with empty stdout+ // and the agent gets no JSON to act on.+ try {+ result = handleDiscard(id, lines, targetFile);+ } catch (err) {+ emitResult(operationFailure(err, { file: relFile }));+ return;+ }+ emitResult({ handled: true, file: relFile, carbonize: false, ...result });} else {- const result = handleAccept(id, variantNum, lines, targetFile, paramValues);+ let result;+ try {+ result = handleAccept(id, variantNum, lines, targetFile, paramValues);+ } catch (err) {+ emitResult(operationFailure(err, { file: relFile }));+ return;+ }const acceptedOriginalText = result.acceptedOriginalText || '';delete result.acceptedOriginalText;// Single-line attention-grabber when cleanup is required. The full@@ -167,7 +285,7 @@ Output (JSON):// Non-fatal; the buffer stays as-is and the user can discard later.}}- console.log(JSON.stringify({ handled: true, file: relFile, ...result }));+ emitResult({ handled: true, file: relFile, ...result });}}@@ -235,7 +353,14 @@ function scrubManualEditsAgainstFile(_targetFile, cwd = process.cwd(), originalB// Discard// ----------------------------------------------------------------------------function handleDiscard(id, lines, targetFile) {+function handleDiscard(id, _lines, targetFile) {+ return withSourceLockSync(targetFile, 'discard:' + id, () => {+ const lines = fs.readFileSync(targetFile, 'utf-8').split('\n');+ return handleDiscardUnlocked(id, lines, targetFile);+ }, { waitMs: ACCEPT_LOCK_WAIT_MS });+}++function handleDiscardUnlocked(id, lines, targetFile) {const block = findMarkerBlock(id, lines);if (!block) return { handled: false, error: 'Markers not found' };@@ -330,7 +455,24 @@ function reindentContent(contentLines, fromIndent, toIndent) {});}-function handleAccept(id, variantNum, lines, targetFile, paramValues) {+function handleAccept(id, variantNum, _lines, targetFile, paramValues) {+ return withSourceLockSync(targetFile, 'accept:' + id, () => {+ const lines = fs.readFileSync(targetFile, 'utf-8').split('\n');+ return handleAcceptUnlocked(id, variantNum, lines, targetFile, paramValues);+ }, { waitMs: ACCEPT_LOCK_WAIT_MS });+}++function handleAcceptUnlocked(id, variantNum, lines, targetFile, paramValues) {+ const built = buildAcceptedWrappedSource(id, variantNum, lines, targetFile, paramValues);+ if (built.handled === false) return built;+ fs.writeFileSync(targetFile, built.content, 'utf-8');+ return {+ carbonize: built.carbonize,+ acceptedOriginalText: built.acceptedOriginalText,+ };+}++function buildAcceptedWrappedSource(id, variantNum, lines, targetFile, paramValues) {const block = findMarkerBlock(id, lines);if (!block) return { handled: false, error: 'Markers not found' };@@ -375,11 +517,14 @@ function handleAccept(id, variantNum, lines, targetFile, paramValues) {...replacement,...lines.slice(replaceRange.end + 1),];- fs.writeFileSync(targetFile, newLines.join('\n'), 'utf-8');-- return { carbonize: needsCarbonize, acceptedOriginalText: originalContent.join('\n') };+ return {+ content: newLines.join('\n'),+ carbonize: needsCarbonize,+ acceptedOriginalText: originalContent.join('\n'),+ };}+function readSourceShadowPreviewMeta(content, id) {const escaped = escapeRegExp(id);const wrapperRe = new RegExp('<[^>]+data-impeccable-variants=(["\'])' + escaped + '\\1[^>]*>');@@ -746,6 +891,21 @@ function detectCommentSyntax(filePath) {// File search (find the file containing session markers)// ---------------------------------------------------------------------------+/**+ * `.impeccable` is the critical entry, and it is not cosmetic.+ *+ * Progressive publication stages each revision as `.impeccable/live/artifacts/+ * <id>-r<n>.<source-ext>`, and those artifacts carry the very marker this search+ * looks for. The walk reaches `.` for any project whose source is not under one+ * of the privileged dirs above (this repo's own site lives in `site/pages/`), and+ * dot-directories sort before letters, so the artifact was found *before* the+ * real file. isGeneratedFile then declined the accept, and the agent fell back to+ * carbonizing several hundred lines of stylesheet by hand.+ *+ * Impeccable's own state directory is never project source. Never search it.+ */+const SEARCH_SKIP_DIRS = new Set(['node_modules', '.git', 'dist', 'build', IMPECCABLE_DIR]);+function findSessionFile(id, cwd) {const marker = 'impeccable-variants-start ' + id;const searchDirs = ['src', 'app', 'pages', 'components', 'public', 'views', 'templates', '.'];@@ -786,7 +946,7 @@ function searchDir(dir, query, seen, depth) {for (const entry of entries) {if (!entry.isDirectory()) continue;- if (['node_modules', '.git', 'dist', 'build'].includes(entry.name)) continue;+ if (SEARCH_SKIP_DIRS.has(entry.name)) continue;const result = searchDir(path.join(dir, entry.name), query, seen, depth + 1);if (result) return result;}@@ -798,6 +958,28 @@ function searchDir(dir, query, seen, depth) {// Utilities// ---------------------------------------------------------------------------+function acceptReceiptPath(cwd, id) {+ return path.join(getLiveDir(cwd), 'accept-receipts', `${safeSessionId(id)}.json`);+}++function readAcceptReceipt(cwd, id) {+ try { return JSON.parse(fs.readFileSync(acceptReceiptPath(cwd, id), 'utf-8')); } catch { return null; }+}++function writeAcceptReceipt(cwd, id, receipt) {+ const file = acceptReceiptPath(cwd, id);+ fs.mkdirSync(path.dirname(file), { recursive: true });+ const value = {+ id,+ ...receipt,+ completedAt: new Date().toISOString(),+ };+ const temporary = `${file}.${process.pid}.${Date.now()}.tmp`;+ fs.writeFileSync(temporary, JSON.stringify(value, null, 2) + '\n', 'utf-8');+ fs.renameSync(temporary, file);+ return value;+}+function argVal(args, flag) {const idx = args.indexOf(flag);return idx !== -1 && idx + 1 < args.length ? args[idx + 1] : null;diff --git a/.trae/skills/impeccable/scripts/live-browser.js b/.trae/skills/impeccable/scripts/live-browser.jsindex 616f1290a..20d875b93 100644--- a/.trae/skills/impeccable/scripts/live-browser.js+++ b/.trae/skills/impeccable/scripts/live-browser.js@@ -126,6 +126,9 @@let expectedVariants = 0;let arrivedVariants = 0;let visibleVariant = 0;+ let generationPhase = null;+ let parameterGenerationState = 'idle';+ let parameterReadyAnnouncedSession = null;let svelteComponentSession = null;let svelteRuntimePromise = null;let pendingSvelteComponentRetryObserver = null;@@ -134,6 +137,7 @@let currentPreviewMode = null;let recoveryWaitingForAnchor = false;let pickedAnchorSnapshot = null;+ let pickedAnchorViewportTop = null;let pendingVariantAnchorRetryObserver = null;let pendingAcceptedSession = null;let variantObserver = null;@@ -151,10 +155,12 @@// startScrollLock / stopScrollLock below.let scrollLockObserver = null;let scrollLockTargetY = null;+ let scrollLockAnchorTop = null;let scrollLockRaf = null;let scrollLockAbort = null;const SCROLL_ANCHOR_LOCK_ID = 'impeccable-scroll-anchor-lock';const VARIANT_STATE_STYLE_ID = 'impeccable-variant-state';+ const DISCARD_STATE_STYLE_ID = 'impeccable-discard-state';// Dedicated key for scroll position - SEPARATE from LS_KEY so that// saveSession's state updates don't clobber a carefully-captured scrollY.@@ -252,6 +258,13 @@barConnected: !!barEl?.isConnected,hasSvelteComponentSession: !!svelteComponentSession,mountedSvelteVariant: svelteComponentSession?.mountedVariant || 0,+ pickActive,+ pendingApplyInFlight,+ hoveredElement: hoveredElement ? {+ tag: hoveredElement.tagName,+ classes: hoveredElement.className,+ pickable: pickable(hoveredElement),+ } : null,pendingSvelteComponentRetry: !!pendingSvelteComponentRetryObserver,recoveryWaitingForAnchor,evtSourceReadyState: evtSource ? evtSource.readyState : null,@@ -1114,14 +1127,15 @@});}- function hideBar() {+ function hideBar(instant) {if (!barEl) return;const hideSeq = ++barHideSeq;stopVoice({ suppressSubmit: true });if (configureKind === 'insert') clearInsertPicking();barEl.style.opacity = '0';- barEl.style.transform = 'translateY(6px)';- setTimeout(() => { if (barEl && hideSeq === barHideSeq) barEl.style.display = 'none'; }, 250);+ barEl.style.transform = instant ? 'translateY(0)' : 'translateY(6px)';+ if (instant) barEl.style.display = 'none';+ else setTimeout(() => { if (barEl && hideSeq === barHideSeq) barEl.style.display = 'none'; }, 250);hideActionPicker();closeTunePopover();hideConfigureBarTooltip();@@ -1966,6 +1980,7 @@*/function setLiveState(next) {state = next;+ window.__IMPECCABLE_LIVE_STATE__ = next;syncPageInteractionCursor();}@@ -2516,18 +2531,27 @@fontSize: '11px', color: BP.textDim, whiteSpace: 'nowrap',marginLeft: 'auto',});- // Variants currently arrive atomically in a single file edit, so a- // per-variant counter would lie. Say what's true.status.textContent = recoveryWaitingForAnchor? 'Variants ready. Reveal the selected element to resume.'- : (arrivedVariants < expectedVariants- ? 'Generating ' + expectedVariants + ' variants...'- : 'Done');+ : generationStatusText();row.appendChild(status);return row;}+ function generationStatusText() {+ if (arrivedVariants >= expectedVariants && expectedVariants > 0) return 'Done';+ if (generationPhase === 'picked_up') return 'Agent picked up the request...';+ if (generationPhase === 'scaffolding') return 'Finding the source...';+ if (generationPhase === 'source_ready') return 'Source ready. Generating...';+ if (generationPhase === 'scaffold_fallback') return 'Agent is locating the source...';+ if (generationPhase === 'first_variant_generating') return 'Designing the first variant...';+ if (generationPhase === 'first_variant_validating') return 'Checking the first variant...';+ if (generationPhase === 'remaining_variants_generating') return 'Exploring two more directions...';+ if (generationPhase === 'remaining_variants_validating') return 'Checking the remaining variants...';+ return 'Generating ' + expectedVariants + ' variants...';+ }+// Cycling rowconst TUNE_ICON_SVG = '<svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" style="flex-shrink:0"><line x1="4" y1="8" x2="20" y2="8"/><circle cx="14" cy="8" r="2.4" fill="currentColor" stroke="none"/><line x1="4" y1="16" x2="20" y2="16"/><circle cx="10" cy="16" r="2.4" fill="currentColor" stroke="none"/></svg>';@@ -2557,7 +2581,7 @@color: BP.textDim, minWidth: '24px', textAlign: 'center',});counter.id = PREFIX + '-variant-counter';- counter.textContent = visibleVariant + '/' + arrivedVariants;+ counter.textContent = visibleVariant + '/' + expectedVariants;row.appendChild(counter);// Next@@ -2567,10 +2591,12 @@if (visibleVariant >= arrivedVariants) next.style.opacity = '0.3';row.appendChild(next);- // Tune chip - only when the visible variant exposes params+ // Tune chip stays visible while the deferred parameter phase is running,+ // then becomes interactive as soon as this variant exposes controls.const visParams = parseVariantParams(getVisibleVariantEl());const hasParams = visParams.length > 0;- if (hasParams) {+ const paramsPending = !hasParams && (parameterGenerationState === 'pending' || parameterGenerationState === 'loading');+ if (hasParams || paramsPending) {const tune = el('button', {display: 'inline-flex', alignItems: 'center', gap: '6px',padding: '4px 10px', borderRadius: '5px',@@ -2578,35 +2604,54 @@background: tuneOpen ? BP.accentSoft : 'transparent',color: tuneOpen ? BP.accent : BP.text,fontFamily: FONT, fontSize: '11px', fontWeight: '500',- cursor: 'pointer',+ cursor: paramsPending ? 'wait' : 'pointer',transition: 'color 0.12s ease, background 0.12s ease',whiteSpace: 'nowrap',});- tune.innerHTML = TUNE_ICON_SVG;+ if (paramsPending) {+ const spinner = el('span', {+ width: '11px', height: '11px', borderRadius: '50%',+ border: '1.5px solid ' + BP.hairline,+ borderTopColor: BP.accent,+ animation: 'impeccable-spin 0.6s linear infinite',+ boxSizing: 'border-box', flexShrink: '0',+ });+ spinner.setAttribute('aria-hidden', 'true');+ tune.appendChild(spinner);+ } else {+ tune.innerHTML = TUNE_ICON_SVG;+ }const tuneLabel = document.createElement('span');tuneLabel.textContent = 'Tune';tune.appendChild(tuneLabel);- const tuneBadge = document.createElement('span');- Object.assign(tuneBadge.style, {- display: 'inline-flex', alignItems: 'center', justifyContent: 'center',- minWidth: '16px', height: '16px', padding: '0 4px',- borderRadius: '999px',- background: tuneOpen ? C.brand : BP.hairline,- color: tuneOpen ? 'oklch(98% 0 0)' : 'inherit',- fontFamily: MONO, fontSize: '9.5px', fontWeight: '600',- lineHeight: '1',- boxSizing: 'border-box',- });- tuneBadge.textContent = String(visParams.length);- tune.appendChild(tuneBadge);- tune.title = 'Tune this variant (' + visParams.length + ' knob' + (visParams.length === 1 ? '' : 's') + ')';- tune.addEventListener('mouseenter', () => {- if (!tuneOpen) tune.style.background = BP.accentSoft;- });- tune.addEventListener('mouseleave', () => {- if (!tuneOpen) tune.style.background = 'transparent';- });- tune.addEventListener('click', (e) => { e.stopPropagation(); toggleTunePopover(); });+ if (hasParams) {+ const tuneBadge = document.createElement('span');+ Object.assign(tuneBadge.style, {+ display: 'inline-flex', alignItems: 'center', justifyContent: 'center',+ minWidth: '16px', height: '16px', padding: '0 4px',+ borderRadius: '999px',+ background: tuneOpen ? C.brand : BP.hairline,+ color: tuneOpen ? 'oklch(98% 0 0)' : 'inherit',+ fontFamily: MONO, fontSize: '9.5px', fontWeight: '600',+ lineHeight: '1',+ boxSizing: 'border-box',+ });+ tuneBadge.textContent = String(visParams.length);+ tune.appendChild(tuneBadge);+ tune.title = 'Tune this variant (' + visParams.length + ' knob' + (visParams.length === 1 ? '' : 's') + ')';+ tune.addEventListener('mouseenter', () => {+ if (!tuneOpen) tune.style.background = BP.accentSoft;+ });+ tune.addEventListener('mouseleave', () => {+ if (!tuneOpen) tune.style.background = 'transparent';+ });+ tune.addEventListener('click', (e) => { e.stopPropagation(); toggleTunePopover(); });+ } else {+ tune.disabled = true;+ tune.setAttribute('aria-label', 'Tune controls are still being prepared');+ tune.title = 'Tune controls are still being prepared';+ tune.style.opacity = '0.72';+ }tune.dataset.iceqTune = '1';row.appendChild(tune);}@@ -2614,6 +2659,15 @@// Spacerrow.appendChild(el('div', { flex: '1' }));+ if (arrivedVariants < expectedVariants) {+ const remaining = expectedVariants - arrivedVariants;+ const progress = el('span', {+ fontSize: '11px', color: BP.textDim, whiteSpace: 'nowrap',+ });+ progress.textContent = remaining + ' more arriving...';+ row.appendChild(progress);+ }+// Accept - primary action, kinpaku gold + lacquer-deep (matches demo .live-demo-ctx-accept)const accept = el('button', {padding: '5px 14px', borderRadius: '5px',@@ -2628,7 +2682,11 @@accept.addEventListener('mousedown', () => accept.style.transform = 'scale(0.97)');accept.addEventListener('mouseup', () => accept.style.transform = 'scale(1)');accept.addEventListener('click', (e) => { e.stopPropagation(); handleAccept(); });- if (arrivedVariants === 0) { accept.style.opacity = '0.3'; accept.style.pointerEvents = 'none'; }+ if (arrivedVariants === 0) {+ accept.style.opacity = '0.3';+ accept.style.pointerEvents = 'none';+ accept.title = 'Accept becomes available when the first variant arrives';+ }row.appendChild(accept);// Discard@@ -4743,6 +4801,32 @@}}+ function mountedParameterCount() {+ if (svelteComponentSession?.sessionId === currentSessionId) {+ return Object.values(svelteComponentSession.paramsByVariant || {})+ .reduce((total, params) => total + (Array.isArray(params) ? params.length : 0), 0);+ }+ const wrapper = document.querySelector('[data-impeccable-variants="' + currentSessionId + '"]');+ if (!wrapper) return 0;+ return [...wrapper.querySelectorAll('[data-impeccable-variant]:not([data-impeccable-variant="original"])')]+ .reduce((total, variant) => total + parseVariantParams(variant).length, 0);+ }++ function completeParameterPublication() {+ if (!currentSessionId) return;+ const ready = mountedParameterCount() > 0;+ parameterGenerationState = ready ? 'ready' : 'none';+ if (ready && parameterReadyAnnouncedSession !== currentSessionId) {+ parameterReadyAnnouncedSession = currentSessionId;+ showToast('Tune controls are ready.', 3000);+ }+ if (state === 'CYCLING') {+ refreshParamsPanel();+ showOrUpdateCyclingBar();+ }+ saveSession();+ }+function toggleTunePopover() {if (pendingApplyInFlight) { showManualApplyBusyToast(); return; }if (tuneOpen) { closeTunePopover(); return; }@@ -4835,6 +4919,10 @@return String(filePath || '').endsWith('manifest.json');}+ function isFrameworkComponentPreviewMode(mode) {+ return mode === 'svelte-component';+ }+function parseOriginalMarkupElement(originalMarkup) {const parser = new DOMParser();const doc = parser.parseFromString('<div id="impeccable-anchor">' + originalMarkup + '</div>', 'text/html');@@ -5029,9 +5117,13 @@}}- function loadSvelteRuntime(runtimeModule) {+ function resolveComponentModuleUrl(manifest, modulePath) {+ return new URL(String(modulePath || ''), location.origin).href;+ }++ function loadSvelteRuntime(runtimeModule, manifest) {const modulePath = runtimeModule || '/src/lib/impeccable/__runtime.js';- const url = new URL(modulePath, location.origin).href;+ const url = resolveComponentModuleUrl(manifest, modulePath);if (!svelteRuntimePromise) {svelteRuntimePromise = import(/* @vite-ignore */ url);}@@ -5065,7 +5157,8 @@async function loadSvelteComponentVariantSource(manifest, variantNum) {const dir = String(manifest?.componentDir || '').replace(/^\/+/, '');if (!dir || !variantNum) return '';- const sourcePath = dir + '/v' + variantNum + '.svelte';+ const extension = manifest.componentExtension || 'svelte';+ const sourcePath = dir + '/v' + variantNum + '.' + extension;const url = 'http://localhost:' + PORT + '/source?token=' + TOKEN + '&path=' + encodeURIComponent(sourcePath);try {const res = await fetch(url);@@ -5221,7 +5314,7 @@if (!sourceOriginal) return values;const map = buildSvelteExpressionTextMap(sourceOriginal, liveEl);for (const entry of contract) {- const token = '{' + entry.expr + '}';+ const token = entry.previewToken || ('{' + entry.expr + '}');values[entry.prop] = map.get(token) || '';}return values;@@ -5233,9 +5326,12 @@try {const previousAnchor = getMountedSvelteComponentAnchor(svelteComponentSession) || selectedElement;svelteComponentSession.swapAnchor = makeFrozenAnchor(previousAnchor) || svelteComponentSession.swapAnchor || null;- const runtime = await loadSvelteRuntime(manifest.runtimeModule);- const modulePath = '/' + String(manifest.componentDir || '').replace(/^\/+/, '') + '/v' + variantNum + '.svelte';- const moduleUrl = new URL(modulePath, location.origin).href + '?t=' + Date.now();+ const runtime = await loadSvelteRuntime(manifest.runtimeModule, manifest);+ const extension = manifest.componentExtension || 'svelte';+ const moduleBase = manifest.componentModuleBase+ || ('/' + String(manifest.componentDir || '').replace(/^\/+/, ''));+ const modulePath = String(moduleBase).replace(/\/+$/, '') + '/v' + variantNum + '.' + extension;+ const moduleUrl = resolveComponentModuleUrl(manifest, modulePath) + '?t=' + Date.now();const mod = await import(/* @vite-ignore */ moduleUrl);const Component = mod.default;if (svelteComponentSession.mountedInstance && runtime.unmount) {@@ -5275,7 +5371,7 @@if (svelteComponentSession?.sessionId === sessionId) {svelteComponentSession.swapAnchor = null;}- console.error('[impeccable] Failed to mount Svelte variant ' + variantNum + ' for ' + sessionId + ':', err);+ console.error('[impeccable] Failed to mount component variant ' + variantNum + ' for ' + sessionId + ':', err);return false;}}@@ -5340,40 +5436,46 @@if (manifest.id !== sessionId) return;const paramsByVariant = await loadSvelteComponentParams(manifest);+ const availableVariants = Number(manifest.arrivedVariants) || Number(manifest.count) || 1;+ const componentPreviewMode = isFrameworkComponentPreviewMode(manifest.previewMode)+ ? manifest.previewMode+ : 'svelte-component';currentSessionId = sessionId;expectedVariants = Number(manifest.count) || expectedVariants || 1;rememberSessionFileMeta({sourceFile: manifest.sourceFile,previewFile: manifestPath,- previewMode: 'svelte-component',+ previewMode: componentPreviewMode,});if (state !== 'CYCLING') setLiveState('GENERATING');const existingWrapper = document.querySelector('[data-impeccable-variants="' + sessionId + '"]');if (existingWrapper && svelteComponentSession?.sessionId === sessionId) {recoveryWaitingForAnchor = false;+ svelteComponentSession.manifest = manifest;svelteComponentSession.paramsByVariant = paramsByVariant;- arrivedVariants = Number(manifest.count) || expectedVariants || 1;- expectedVariants = arrivedVariants;+ arrivedVariants = availableVariants;+ expectedVariants = Number(manifest.count) || expectedVariants || arrivedVariants;visibleVariant = visibleVariant > 0 && visibleVariant <= arrivedVariants ? visibleVariant : 1;await mountSvelteComponentVariant(visibleVariant || 1);setLiveState('CYCLING');showOrUpdateCyclingBar();saveSession();+ if (parameterGenerationState === 'loading') completeParameterPublication();return;}const liveEl = findLiveElementForSvelteManifest(manifest);if (!liveEl?.parentElement) {console.warn('[impeccable] Could not find original element in live DOM.');- arrivedVariants = Number(manifest.count) || expectedVariants || 1;- expectedVariants = arrivedVariants;+ arrivedVariants = availableVariants;+ expectedVariants = Number(manifest.count) || expectedVariants || arrivedVariants;const saved = loadSession();const savedVisibleVariant = saved && saved.id === sessionId ? saved.visible : 0;visibleVariant = visibleVariant > 0 && visibleVariant <= arrivedVariants? visibleVariant: (savedVisibleVariant > 0 && savedVisibleVariant <= arrivedVariants ? savedVisibleVariant : 1);- enterRecoveryWaitingForAnchor({ checkpointReason: 'svelte_component_anchor_missing', trackScroll: true });+ enterRecoveryWaitingForAnchor({ checkpointReason: 'component_preview_anchor_missing', trackScroll: true });waitForSvelteComponentTargetAndRetry({ manifestPath, sessionId, manifest });return;}@@ -5381,7 +5483,7 @@const wrapper = document.createElement('div');wrapper.dataset.impeccableVariants = sessionId;wrapper.dataset.impeccableVariantCount = String(manifest.count || expectedVariants || 1);- wrapper.dataset.impeccablePreview = 'svelte-component';+ wrapper.dataset.impeccablePreview = componentPreviewMode;wrapper.style.display = 'contents';const mountTarget = document.createElement('div');@@ -5419,8 +5521,8 @@recoveryWaitingForAnchor = false;const previousVisibleVariant = currentSessionId === sessionId ? visibleVariant : 0;- arrivedVariants = Number(manifest.count) || expectedVariants || 1;- expectedVariants = arrivedVariants;+ arrivedVariants = availableVariants;+ expectedVariants = Number(manifest.count) || expectedVariants || arrivedVariants;const saved = loadSession();const savedVisibleVariant = saved && saved.id === sessionId ? saved.visible : 0;visibleVariant = previousVisibleVariant > 0 && previousVisibleVariant <= arrivedVariants@@ -5445,9 +5547,10 @@refreshParamsPanel();positionBar();saveSession();- console.log('[impeccable] Mounted ' + arrivedVariants + ' Svelte component variants.');+ if (parameterGenerationState === 'loading') completeParameterPublication();+ console.log('[impeccable] Mounted ' + arrivedVariants + ' ' + manifest.framework + ' component variants.');} catch (err) {- console.error('[impeccable] Failed to mount Svelte component variants:', err);+ console.error('[impeccable] Failed to mount component-preview variants:', err);abortSvelteComponentInjection(sessionId, 'Could not load variants. Fix the error and re-run.');}}@@ -5493,6 +5596,8 @@clearHandled();resetSessionFileMeta();currentSessionId = null;+ parameterGenerationState = 'idle';+ parameterReadyAnnouncedSession = null;expectedVariants = 0;arrivedVariants = 0;visibleVariant = 0;@@ -5502,12 +5607,24 @@if (message) showToast(message, 5000);}+ // How many delayed re-reads a completion-driven source fallback gets when+ // the fetched source still shows only the preflight scaffold, before the+ // failure is surfaced via recoverEmptyCycling.+ const COMPLETED_SOURCE_FALLBACK_RETRIES = 3;+ const COMPLETED_SOURCE_FALLBACK_RETRY_MS = 1200;+/*** No-HMR fallback: fetch the raw source file from the live server,* parse it, extract the variant wrapper, and inject it into the live DOM.* This works even when the dev server caches HTML (Bun, static servers).+ *+ * opts.generationCompleted marks callers that KNOW the agent finished (a+ * `done` arrived or the server reported a completed generation). For them an+ * empty read is a stale source view and no further event is coming, so the+ * read retries a few times and then surfaces recovery. Callers without the+ * flag may be mid-generation and wait indefinitely for the real completion.*/- function injectVariantsFromSource(filePath, sessionId) {+ function injectVariantsFromSource(filePath, sessionId, opts = {}) {if (isSvelteComponentManifestPath(filePath)) {injectSvelteComponentsFromManifest(filePath, sessionId);return;@@ -5573,6 +5690,32 @@arrivedVariants = variants.length;expectedVariants = parseInt(wrapper.dataset.impeccableVariantCount || arrivedVariants);if (arrivedVariants <= 0) {+ if (state === 'GENERATING') {+ // Mid-generation the source legitimately holds a scaffold wrapper+ // with no variants yet (the server-side preflight wraps before the+ // agent writes). Tearing the session down here would destroy an+ // in-flight generation; stay in GENERATING — the variant observer+ // is armed and the server re-delivers a missed `done`.+ if (!opts.generationCompleted) {+ console.log('[impeccable] Source has scaffold but no variants yet; still generating.');+ return;+ }+ // Generation finished, yet the read shows only the scaffold: the+ // source view is stale and no further event will fire. Re-read a+ // few times before surfacing recovery — a single silent return+ // here would strand the tab in GENERATING forever.+ const attempt = opts.attempt || 0;+ if (attempt < COMPLETED_SOURCE_FALLBACK_RETRIES) {+ console.log('[impeccable] Generation is done but source shows no variants yet; retrying read ('+ + (attempt + 1) + '/' + COMPLETED_SOURCE_FALLBACK_RETRIES + ').');+ setTimeout(() => {+ if (state !== 'GENERATING' || currentSessionId !== sessionId) return;+ if (arrivedVariants > 0) return;+ injectVariantsFromSource(filePath, sessionId, { ...opts, attempt: attempt + 1 });+ }, COMPLETED_SOURCE_FALLBACK_RETRY_MS);+ return;+ }+ }recoverEmptyCycling('source-fallback-empty');return;}@@ -5594,6 +5737,7 @@refreshParamsPanel();positionBar();saveSession();+ if (parameterGenerationState === 'loading') completeParameterPublication();console.log('[impeccable] Injected ' + arrivedVariants + ' variants from source file.');}).catch(err => {@@ -5865,13 +6009,36 @@document.getElementById(VARIANT_STATE_STYLE_ID)?.remove();}+ function showOriginalDuringDiscard(sessionId) {+ if (!sessionId) return;+ let styleEl = document.getElementById(DISCARD_STATE_STYLE_ID);+ if (!styleEl) {+ styleEl = document.createElement('style');+ styleEl.id = DISCARD_STATE_STYLE_ID;+ (document.head || document.documentElement).appendChild(styleEl);+ }+ const wrapper = '[data-impeccable-variants="' + sessionId + '"]';+ styleEl.textContent = wrapper + ' > [data-impeccable-variant]:not([data-impeccable-variant="original"]) { display:none !important; }\n'+ + wrapper + ' > [data-impeccable-variant="original"] { display:block !important; }';+ }++ function resolveScrollLockAnchorTop() {+ const anchor = resolveBarAnchor();+ if (!anchor?.isConnected) return null;+ const top = anchor.getBoundingClientRect().top;+ return Number.isFinite(top) ? top : null;+ }+// Hold window.scrollY at a fixed value across DOM mutations inside the// session's wrapper (HMR patches, variant inserts, cycle swaps).- function startScrollLock(sessionId, initialTargetY) {+ function startScrollLock(sessionId, initialTargetY, initialAnchorTop) {stopScrollLock();scrollLockTargetY = typeof initialTargetY === 'number' && isFinite(initialTargetY)? initialTargetY: window.scrollY;+ scrollLockAnchorTop = typeof initialAnchorTop === 'number' && isFinite(initialAnchorTop)+ ? initialAnchorTop+ : resolveScrollLockAnchorTop();try { history.scrollRestoration = 'manual'; } catch {}@@ -5895,6 +6062,17 @@const correct = (why) => {scrollLockRaf = null;if (scrollLockTargetY == null) return;+ const anchor = resolveBarAnchor();+ if (anchor?.isConnected && typeof scrollLockAnchorTop === 'number' && isFinite(scrollLockAnchorTop)) {+ const anchorTop = anchor.getBoundingClientRect().top;+ const anchorDelta = anchorTop - scrollLockAnchorTop;+ if (Math.abs(anchorDelta) >= 0.5) {+ window.scrollTo({ top: window.scrollY + anchorDelta, left: window.scrollX, behavior: 'instant' });+ scrollLockTargetY = window.scrollY;+ writeScrollY(scrollLockTargetY);+ return;+ }+ }const before = window.scrollY;const delta = before - scrollLockTargetY;if (Math.abs(delta) < 0.5) {@@ -5939,6 +6117,7 @@if (scrollLockRaf != null) { cancelAnimationFrame(scrollLockRaf); scrollLockRaf = null; }const prevTarget = scrollLockTargetY;scrollLockTargetY = window.scrollY;+ scrollLockAnchorTop = resolveScrollLockAnchorTop();writeScrollY(scrollLockTargetY);};const markGesture = (why) => {@@ -5976,6 +6155,7 @@if (scrollLockRaf != null) { cancelAnimationFrame(scrollLockRaf); scrollLockRaf = null; }if (scrollLockAbort) { scrollLockAbort.abort(); scrollLockAbort = null; }scrollLockTargetY = null;+ scrollLockAnchorTop = null;// NOTE: do NOT clear the persistent scroll key here. startScrollLock// calls us as a reset, and clearing the key would nuke the Go-time// scrollY that the next resume needs to read.@@ -6049,6 +6229,7 @@updating = true;arrivedVariants = count;+ generationPhase = arrivedVariants >= expectedVariants ? 'variants_ready' : 'variants_progress';if (visibleVariant === 0 && arrivedVariants > 0) {const saved = loadSession();const savedVisibleVariant = saved && saved.id === sessionId ? saved.visible : 0;@@ -6064,7 +6245,7 @@const expected = parseInt(wrapper.dataset.impeccableVariantCount || '0');if (expected > 0) expectedVariants = expected;- if (arrivedVariants >= expectedVariants && expectedVariants > 0) {+ if (arrivedVariants > 0) {setLiveState('CYCLING');recoveryWaitingForAnchor = false;hideShaderOverlay();@@ -6072,13 +6253,18 @@updateSelectedElement();showOrUpdateCyclingBar();disableInlineEdit();- refreshParamsPanel();+ if (arrivedVariants >= expectedVariants && expectedVariants > 0) refreshParamsPanel();+ else hideParamsPanel();positionBar();} else if (state === 'GENERATING') {updateBarContent('generating');}saveSession();- queueCheckpoint(state === 'CYCLING' ? 'variants_ready' : 'variants_progress');+ sendCheckpoint(+ arrivedVariants >= expectedVariants && expectedVariants > 0+ ? 'variants_ready'+ : 'variants_progress',+ );updating = false;});@@ -6151,6 +6337,7 @@syncAgentPollingUi(!!msg.agentPolling);startAgentStatusPoll();restoreFromActiveSessions(msg.activeSessions, 'sse_connected');+ recoverMissedGenerationCompletion(msg.activeSessions);if (state === 'IDLE' && (pickActive || insertActive)) setLiveState('PICKING');syncPageInteractionCursor();syncPageChatFocus('sse-connected');@@ -6158,6 +6345,42 @@case 'agent_polling':syncAgentPollingUi(!!msg.connected);break;+ case 'agent_phase':+ if (msg.id === currentSessionId && (state === 'GENERATING' || state === 'CYCLING')) {+ generationPhase = msg.phase || generationPhase;+ if (msg.phase === 'variant_parameters_generating' || msg.phase === 'variant_parameters_validating') {+ parameterGenerationState = 'loading';+ }+ if (msg.phase === 'parameters_ready' && parameterGenerationState !== 'ready') {+ parameterGenerationState = 'loading';+ }+ updateBarContent(state === 'CYCLING' ? 'cycling' : 'generating');+ saveSession();+ }+ break;+ case 'variant_progress':+ if (msg.id === currentSessionId) {+ if (msg.publicationKind === 'params') parameterGenerationState = 'loading';+ rememberSessionFileMeta(msg);+ if (isFrameworkComponentPreviewMode(msg.previewMode) && msg.previewFile) {+ injectSvelteComponentsFromManifest(msg.previewFile, msg.id);+ } else if ((msg.previewMode === 'source' || !msg.previewMode) && (msg.previewFile || msg.file)) {+ // Give normal framework HMR the first chance to reconcile its+ // own managed tree. Nuxt route-module HMR can skip intermediate+ // revisions, so fall back to source injection only when the+ // advertised progress still has not appeared after a short+ // settle. Immediate injection races React/Vue ownership and can+ // trigger removeChild errors on the next HMR commit.+ const targetArrived = Number(msg.arrivedVariants) || 1;+ setTimeout(() => {+ if (msg.id !== currentSessionId) return;+ if (state !== 'GENERATING' && state !== 'CYCLING') return;+ if (msg.publicationKind !== 'params' && arrivedVariants >= targetArrived) return;+ injectVariantsFromSource(msg.previewFile || msg.file, msg.id);+ }, 150);+ }+ }+ break;case 'steer_done':maybeCompleteSteer(msg);break;@@ -6175,6 +6398,10 @@case 'done':if (maybeCompleteSteer(msg)) break;rememberSessionFileMeta(msg);+ if (msg.id === currentSessionId && isFrameworkComponentPreviewMode(currentPreviewMode) && currentPreviewFile) {+ injectSvelteComponentsFromManifest(currentPreviewFile, msg.id);+ break;+ }// Variants already arrived via HMR → normal transition.if (arrivedVariants >= expectedVariants && expectedVariants > 0) {if (state === 'GENERATING') {@@ -6190,7 +6417,7 @@setTimeout(() => {if (arrivedVariants >= expectedVariants && expectedVariants > 0) return;if (state !== 'GENERATING' || msg.id !== currentSessionId) return;- injectVariantsFromSource(msg.file, msg.id);+ injectVariantsFromSource(msg.file, msg.id, { generationCompleted: true });}, 750);break;}@@ -6215,9 +6442,10 @@if (maybeCompleteAcceptedSession(msg)) break;break;case 'agent_done':- // Carbonize accepts are not terminal until live-complete.mjs sends- // the final complete event. Keep the browser in its recoverable- // saving state while the source cleanup is still in flight.+ // The deterministic accept has already committed the reviewed DOM+ // and fenced generation. Carbonize may continue in the background;+ // it must not hold the foreground picker hostage.+ if (msg.data?.carbonize === true && maybeCompleteAcceptedSession(msg)) break;break;case 'discarded':if (msg.id && msg.id === currentSessionId) {@@ -6306,6 +6534,7 @@type: 'checkpoint',id: currentSessionId,revision: sessionState.nextCheckpointRevision(),+ revisionDomain: 'browser',owner: browserOwner,phase: String(state || '').toLowerCase(),reason,@@ -6331,6 +6560,7 @@type: 'checkpoint',id,revision: sessionState.nextCheckpointRevision(),+ revisionDomain: 'browser',owner: browserOwner,phase: 'steer',reason,@@ -6684,6 +6914,9 @@expectedVariants = selectedCount;arrivedVariants = 0;visibleVariant = 0;+ generationPhase = 'queued';+ parameterGenerationState = 'pending';+ parameterReadyAnnouncedSession = null;resetSessionFileMeta();// Flip to GENERATING immediately so the bar morphs without waiting on@@ -6693,6 +6926,7 @@const elForCapture = selectedElement;pickedAnchorSnapshot = buildPickedAnchorSnapshot(elForCapture);const captureRect = elForCapture.getBoundingClientRect();+ pickedAnchorViewportTop = captureRect.top;const snapshot = {comments: annotState.comments.map(c => ({ x: c.x, y: c.y, text: c.text })),strokes: annotState.strokes.map(s => ({ points: s.points.map(p => [p[0], p[1]]) })),@@ -6724,7 +6958,7 @@writeScrollY(window.scrollY);if (variantObserver) variantObserver.disconnect();variantObserver = startVariantObserver(currentSessionId);- startScrollLock(currentSessionId);+ startScrollLock(currentSessionId, window.scrollY, pickedAnchorViewportTop);captureAndEmit(elForCapture, basePayload, snapshot, captureRect);}@@ -6759,12 +6993,16 @@expectedVariants = selectedCount;arrivedVariants = 0;visibleVariant = 0;+ generationPhase = 'queued';+ parameterGenerationState = 'pending';+ parameterReadyAnnouncedSession = null;resetSessionFileMeta();selectedElement = placeholderElement;insertPlaceholderSnapshot = buildInsertPlaceholderSnapshotFromDom(insertAnchorElement, placeholderElement);const elForCapture = placeholderElement;const captureRect = elForCapture.getBoundingClientRect();+ pickedAnchorViewportTop = captureRect.top;const basePayload = {type: 'generate',mode: 'insert',@@ -6795,7 +7033,7 @@writeScrollY(window.scrollY);if (variantObserver) variantObserver.disconnect();variantObserver = startVariantObserver(currentSessionId);- startScrollLock(currentSessionId);+ startScrollLock(currentSessionId, window.scrollY, pickedAnchorViewportTop);captureAndEmit(elForCapture, basePayload, snapshot, captureRect);}@@ -6975,9 +7213,9 @@// preview mounts are covered by the same shader regression checks.const adapter = String(window.__IMPECCABLE_LIVE_ADAPTER__ || '').toLowerCase();if (adapter === 'svelte' || adapter === 'sveltekit') return true;- if (currentPreviewMode === 'svelte-component' || svelteComponentSession) return true;+ if (isFrameworkComponentPreviewMode(currentPreviewMode) || svelteComponentSession) return true;const wrapper = el?.closest?.('[data-impeccable-variants]');- return wrapper?.dataset?.impeccablePreview === 'svelte-component';+ return isFrameworkComponentPreviewMode(wrapper?.dataset?.impeccablePreview);}function paintsShaderProxySurface(node) {@@ -7105,6 +7343,17 @@}async function captureAndEmit(el, basePayload, snapshot, rect) {+ const hasAnnotations = snapshot && (snapshot.comments.length > 0 || snapshot.strokes.length > 0);++ // Plain requests do not send a screenshot to the agent, so capture is+ // presentation-only. Wait only for the helper to accept the event before+ // starting CPU-heavy capture; this yields the browser task and prevents+ // rasterization from delaying the fetch itself.+ if (!hasAnnotations) {+ basePayload.clientSentAt = Date.now();+ await sendEvent(basePayload);+ }+let screenshotPath;let blob;let paper;@@ -7122,7 +7371,6 @@// are present. Without annotations the image is pure visual anchoring -// it biases the model toward the current rendering and works against the// three-distinct-directions brief.- const hasAnnotations = snapshot && (snapshot.comments.length > 0 || snapshot.strokes.length > 0);if (blob && hasAnnotations) {try {const uploadRes = await fetch(@@ -7140,7 +7388,12 @@console.warn('[impeccable] annotation upload failed:', err);}}- sendEvent(screenshotPath ? { ...basePayload, screenshotPath } : basePayload);+ // Annotated requests must wait for capture + upload because the screenshot+ // is semantic input. Plain requests were already dispatched above.+ if (hasAnnotations) {+ basePayload.clientSentAt = Date.now();+ sendEvent(screenshotPath ? { ...basePayload, screenshotPath } : basePayload);+ }}//@@ -7520,7 +7773,6 @@ void main() {if (variantSelectionPromise) {try { await variantSelectionPromise; } catch { /* failed selection falls back below */ }}- if (!currentSessionId || arrivedVariants === 0) return;const domVisibleVariant = readVisibleVariantFromDOM(currentSessionId);if (domVisibleVariant > 0) visibleVariant = domVisibleVariant;const acceptPayload = {@@ -7528,7 +7780,9 @@ void main() {id: currentSessionId,variantId: String(visibleVariant),pageUrl: location.pathname,+ clientSentAt: Date.now(),};+ if (!currentSessionId || arrivedVariants === 0) return;const acceptWrapper = document.querySelector('[data-impeccable-variants="' + currentSessionId + '"]');if (Object.keys(paramsCurrentValues).length > 0) {acceptPayload.paramValues = { ...paramsCurrentValues };@@ -7542,7 +7796,7 @@ void main() {const acceptedSessionId = currentSessionId;const acceptedVariant = visibleVariant;const acceptedIsSvelteComponent = svelteComponentSession?.sessionId === acceptedSessionId- || acceptWrapper?.dataset?.impeccablePreview === 'svelte-component';+ || isFrameworkComponentPreviewMode(acceptWrapper?.dataset?.impeccablePreview);const acceptedSnapshot = snapshotAcceptedVariantDom(acceptedSessionId, acceptedVariant);setLiveState('SAVING');@@ -7557,7 +7811,17 @@ void main() {saveSession();sendEvent(acceptPayload, { throwOnError: true })- .then(() => {})+ .then(() => {+ const pending = pendingAcceptedSession;+ if (!pending || pending.id !== acceptedSessionId) return;+ // POST /events returns only after the accept intent is durable and the+ // generation epoch is fenced. Source promotion/carbonize can finish in+ // the background; the foreground picker is free immediately.+ markSessionHandled();+ setLiveState('CONFIRMED');+ document.documentElement.dataset.impeccableAcceptToPickingMs = String(Date.now() - acceptPayload.clientSentAt);+ scheduleAcceptCleanup(pending);+ }).catch(() => {if (pendingAcceptedSession?.id === acceptedSessionId) pendingAcceptedSession = null;setLiveState('CYCLING');@@ -7586,17 +7850,26 @@ void main() {}function scheduleAcceptCleanup(accepted) {- setTimeout(function() {- if (!accepted?.isSvelteComponent && !acceptedDomAlreadyClean(accepted)) {- setTimeout(function() {- if (pendingAcceptedSession?.id !== accepted?.id) return;- if (!accepted?.isSvelteComponent) ensureAcceptedDomClean(accepted);- cleanupAcceptedSession();- }, 1800);- return;+ queueMicrotask(function() {+ if (pendingAcceptedSession?.id !== accepted?.id) return;+ // Svelte previews live in an adapter-owned mount rather than in source+ // wrapper markup. Promote the mounted variant before releasing the+ // session so the old adapter instance cannot linger behind the next+ // Pick → Go loop while carbonize finishes in the background.+ if (accepted?.isSvelteComponent) {+ commitAcceptedSvelteComponentToDom(accepted.id);}cleanupAcceptedSession();- }, 1200);+ });+ // Let React/Vue/Svelte own the HMR reconciliation. Mutating their DOM in+ // the same turn as the source update causes removeChild/NotFoundError+ // races. Static servers still need a fallback, but it must not keep Live+ // in SAVING or block the user's next pick.+ if (!accepted?.isSvelteComponent) {+ setTimeout(function() {+ if (!acceptedDomAlreadyClean(accepted)) ensureAcceptedDomClean(accepted);+ }, 1200);+ }}function snapshotAcceptedVariantDom(sessionId, variantId) {@@ -7700,7 +7973,11 @@ void main() {clearSession();resetSessionFileMeta();selectedElement = null;+ hoveredElement = null;+ pagePickSkipClick = false;currentSessionId = null;+ parameterGenerationState = 'idle';+ parameterReadyAnnouncedSession = null;selectedAction = 'impeccable';pendingAcceptedSession = null;renderEditBadge('hidden');@@ -7735,7 +8012,7 @@ void main() {sendEvent({ type: 'discard', id: currentSessionId }, { throwOnError: true }).then(() => {markSessionHandled();- cleanup();+ cleanup({ restoreOriginal: true, instantChrome: true });}).catch(() => showToast('Could not confirm discard with the live server. Session kept for recovery.', 5000));}@@ -7757,6 +8034,7 @@ void main() {currentPreviewMode = null;recoveryWaitingForAnchor = false;pickedAnchorSnapshot = null;+ pickedAnchorViewportTop = null;}function rememberSessionFileMeta(meta = {}) {@@ -7765,8 +8043,8 @@ void main() {const previewFile = normalizeSessionPath(meta.previewFile);const previewMode = meta.previewMode || (isSvelteComponentManifestPath(previewFile || file) ? 'svelte-component' : null);- if (previewMode === 'svelte-component' || isSvelteComponentManifestPath(file)) {- currentPreviewMode = 'svelte-component';+ if (isFrameworkComponentPreviewMode(previewMode) || isSvelteComponentManifestPath(file)) {+ currentPreviewMode = isFrameworkComponentPreviewMode(previewMode) ? previewMode : 'svelte-component';currentPreviewFile = previewFile || (isSvelteComponentManifestPath(file) ? file : currentPreviewFile);currentSourceFile = sourceFile || currentSourceFile;return;@@ -7782,12 +8060,15 @@ void main() {rememberSessionFileMeta(saved);if (saved.insertPlaceholder) insertPlaceholderSnapshot = saved.insertPlaceholder;if (saved.pickedAnchor) pickedAnchorSnapshot = saved.pickedAnchor;+ if (Number.isFinite(saved.pickedAnchorViewportTop)) pickedAnchorViewportTop = saved.pickedAnchorViewportTop;if (saved.action) selectedAction = saved.action;if (saved.count) selectedCount = saved.count;if (saved.previewMode) currentPreviewMode = saved.previewMode;if (saved.paramValues && typeof saved.paramValues === 'object') {paramsCurrentValues = { ...saved.paramValues };}+ if (saved.parameterState) parameterGenerationState = saved.parameterState;+ if (saved.generationPhase) generationPhase = saved.generationPhase;}function normalizePagePath(value) {@@ -7859,7 +8140,7 @@ void main() {saveSession();queueCheckpoint(reason || 'browser_restore_without_wrapper');- const restoreFile = currentPreviewMode === 'svelte-component'+ const restoreFile = isFrameworkComponentPreviewMode(currentPreviewMode)? currentPreviewFile: (currentSourceFile || currentPreviewFile);if (restoreFile) {@@ -7872,11 +8153,41 @@ void main() {function restoreFromActiveSessions(activeSessions, reason) {const wrapper = document.querySelector('[data-impeccable-variants]');- if (wrapper && wrapper.dataset.impeccablePreview !== 'svelte-component') return false;+ if (wrapper && !isFrameworkComponentPreviewMode(wrapper.dataset.impeccablePreview)) return false;if (svelteComponentSession?.sessionId === currentSessionId) return false;return restoreSessionWithoutWrapper(reason || 'sse_connected', activeSessions);}+ // Self-heal on SSE (re)connect. The preflight scaffold write triggers a+ // framework full-reload (Astro reloads pages for any .astro edit); if the+ // agent's variant write + `done` broadcast land while this page is+ // mid-reload, both the done SSE and the second HMR reload are missed and+ // the resumed page would wait in GENERATING at 0/N forever. The server's+ // session summary carries the durable generationCompletedAt marker, so on+ // every connect compare it against our own progress and pull the finished+ // variants from source when behind. Mirrors the `done` handler's source+ // fallback, including its give-HMR-the-first-chance settle delay.+ function recoverMissedGenerationCompletion(activeSessions) {+ if (!currentSessionId || state !== 'GENERATING') return;+ if (!Array.isArray(activeSessions)) return;+ const summary = activeSessions.find((session) => session?.id === currentSessionId);+ if (!summary?.generationCompletedAt || summary.generationCanceled) return;+ if (isTerminalSessionSummary(summary)) return;+ if (arrivedVariants > 0 && arrivedVariants >= expectedVariants) return;+ rememberSessionFileMeta(summary);+ const sessionId = currentSessionId;+ const file = isFrameworkComponentPreviewMode(currentPreviewMode)+ ? currentPreviewFile+ : (summary.sourceFile || summary.previewFile || currentSourceFile || currentPreviewFile);+ if (!file) return;+ console.log('[impeccable] Reconnected after generation completed; recovering variants from source.');+ setTimeout(() => {+ if (sessionId !== currentSessionId || state !== 'GENERATING') return;+ if (arrivedVariants > 0 && arrivedVariants >= expectedVariants) return;+ injectVariantsFromSource(file, sessionId, { generationCompleted: true });+ }, 750);+ }+function saveSession() {if (!currentSessionId) return;// NOTE: scrollY is stored under a separate key (writeScrollY). Storing@@ -7894,8 +8205,12 @@ void main() {previewMode: currentPreviewMode || undefined,pageUrl: location.pathname,paramValues: { ...paramsCurrentValues },+ parameterState: parameterGenerationState,insertPlaceholder: insertPlaceholderSnapshot || undefined,pickedAnchor: pickedAnchorSnapshot || undefined,+ pickedAnchorViewportTop: Number.isFinite(pickedAnchorViewportTop) ? pickedAnchorViewportTop : undefined,+ pageHash: location.hash || undefined,+ pageSearch: location.search || undefined,});}@@ -7923,20 +8238,26 @@ void main() {sessionState.clearHandled();}- function cleanup() {+ function cleanup(options) {+ const restoreOriginal = options?.restoreOriginal === true;+ const instantChrome = options?.instantChrome === true;const cleanupSessionId = currentSessionId;if (svelteComponentSession?.sessionId === cleanupSessionId) {teardownSvelteComponentSession(true);} else if (cleanupSessionId) {- // Hide the wrapper immediately so variants disappear. DON'T structurally- // mutate the DOM yet - HMR from the agent's source rewrite is on its way,+ // Switch visibility immediately without structurally mutating the DOM.+ // HMR from the agent's source rewrite may still be on its way,// and a manual replaceChild under React causes NotFoundError when the// reconciler later tries to remove a wrapper we already removed.// Schedule a 2s fallback that does the manual swap only if HMR hasn't// replaced the wrapper by then (keeps static-server / no-HMR flows alive).const wrapper = document.querySelector('[data-impeccable-variants="' + cleanupSessionId + '"]');- if (wrapper) wrapper.style.display = 'none';+ if (wrapper) {+ if (restoreOriginal) showOriginalDuringDiscard(cleanupSessionId);+ else wrapper.style.display = 'none';+ }setTimeout(function() {+ document.getElementById(DISCARD_STATE_STYLE_ID)?.remove();if (!cleanupSessionId) return;const lateWrapper = document.querySelector('[data-impeccable-variants="' + cleanupSessionId + '"]');if (!lateWrapper) return;@@ -7951,7 +8272,7 @@ void main() {lateWrapper.remove();}, 2000);}- hideBar();+ hideBar(instantChrome);hideHighlight();stopScrollTracking();if (variantObserver) { variantObserver.disconnect(); variantObserver = null; }@@ -7963,7 +8284,11 @@ void main() {clearSession();resetSessionFileMeta();selectedElement = null;+ hoveredElement = null;+ pagePickSkipClick = false;currentSessionId = null;+ parameterGenerationState = 'idle';+ parameterReadyAnnouncedSession = null;selectedAction = 'impeccable';renderEditBadge('hidden');setLiveState('PICKING');@@ -8047,7 +8372,7 @@ void main() {// would strand the bar in CYCLING at 0/0. If there's no live in-memory mount// for this wrapper, it's an orphan (reload / failed mount): drop it and let// the live-server's SSE re-inject the manifest if the session is still live.- if (wrapper.dataset.impeccablePreview === 'svelte-component'+ if (isFrameworkComponentPreviewMode(wrapper.dataset.impeccablePreview)&& svelteComponentSession?.sessionId !== sessionId) {wrapper.remove();if (restoreSessionWithoutWrapper('browser_resumed_svelte_orphan_wrapper')) return true;@@ -8056,7 +8381,7 @@ void main() {return false;}- if (wrapper.dataset.impeccablePreview === 'svelte-component') {+ if (isFrameworkComponentPreviewMode(wrapper.dataset.impeccablePreview)) {if (!svelteComponentSession?.mountedVariant) {return true;}@@ -8104,7 +8429,7 @@ void main() {insertPlaceholderSnapshot = saved.insertPlaceholder;}- const resumedState = arrivedVariants >= expectedVariants ? 'CYCLING' : 'GENERATING';+ const resumedState = arrivedVariants > 0 ? 'CYCLING' : 'GENERATING';// Find the visible variant's content element for highlight positioning.const isInsert = wrapper.dataset.impeccableMode === 'insert';@@ -8128,7 +8453,11 @@ void main() {// hid. Now that state is CYCLING, re-fire.if (state === 'CYCLING') refreshParamsPanel();saveSession();- queueCheckpoint('browser_resumed');+ if (arrivedVariants > 0 && arrivedVariants < expectedVariants) {+ sendCheckpoint('variants_progress');+ } else {+ queueCheckpoint('browser_resumed');+ }// Start observing for more variants AFTER initial setupif (variantObserver) variantObserver.disconnect();@@ -8136,7 +8465,7 @@ void main() {// Hold the target at its saved viewport top through any subsequent// HMR patches, variant inserts, or cycle swaps.- startScrollLock(currentSessionId, readScrollY());+ startScrollLock(currentSessionId, readScrollY(), pickedAnchorViewportTop);// If we reloaded mid-generation (Bun's HTML HMR destroys the shader// canvas), re-capture the original's content and restart the shader so@@ -8171,6 +8500,7 @@ void main() {let globalBarBrandEl = null;let agentPollTooltipEl = null;let agentPollingConnected = false;+ let agentStatusMessage = null;let agentStatusPollTimer = null;let steerFocusSuspended = false;let steerFocusPauseUntil = 0;@@ -8275,6 +8605,13 @@ void main() {const AGENT_STATUS_POLL_MS = 5000;const AGENT_DISCONNECTED_MARK = 'oklch(62% 0 0 / 0.78)';const AGENT_DISCONNECTED_TIP = 'Agent disconnected - run live-poll.mjs to connect';+ // The indicator tracks whether a poll is parked, which is what decides if+ // steering can reach the agent right now. That goes quiet two ways, and they+ // need different copy: nobody is polling at all, or the agent took the work+ // and is busy with it. Under one-shot foreground polling the second case is+ // every normal generation, and telling the user to start a poll loop then is+ // wrong advice about a healthy session.+ const AGENT_BUSY_TIP = 'Agent is working - steering resumes when it finishes';const GLOBAL_BAR_SECTION_GAP = 8;const GLOBAL_BAR_INNER_GAP = 2;const GLOBAL_BAR_INNER_PAD_LEFT = 2;@@ -9295,24 +9632,46 @@ void main() {</svg>`;}+ /**+ * True while the browser is waiting on work it already handed to the agent.+ * In these states a quiet poll indicator means "busy", not "absent".+ */+ function agentHasWorkInFlight() {+ return state === 'GENERATING' || state === 'SAVING';+ }++ /**+ * Derived at read time, not cached: which of the two reasons applies depends on+ * the live state, which moves between the 5s status polls. The truthiness is+ * the same either way, so the indicator's visuals can stay driven by the+ * cached value while the wording stays current.+ */+ function agentStatusText() {+ if (agentPollingConnected) return null;+ return agentHasWorkInFlight() ? AGENT_BUSY_TIP : AGENT_DISCONNECTED_TIP;+ }+function syncAgentPollingUi(connected) {agentPollingConnected = !!connected;if (!globalBarBrandEl) return;const P = barPaletteForTheme(globalBarEl?.dataset.theme || detectPageTheme());+ agentStatusMessage = agentStatusText();globalBarBrandEl.dataset.agentConnected = connected ? 'true' : 'false';- globalBarBrandEl.setAttribute('aria-label', connected- ? 'Impeccable live mode'- : 'Impeccable live mode - agent not polling');+ // The tooltip is mouse-only, so carry the same distinction in the label or+ // screen-reader users are left with the vaguer of the two readings.+ globalBarBrandEl.setAttribute('aria-label', agentStatusMessage+ ? 'Impeccable live mode - ' + (agentHasWorkInFlight() ? 'agent is working' : 'agent not polling')+ : 'Impeccable live mode');globalBarBrandEl.removeAttribute('title');- globalBarBrandEl.style.cursor = connected ? 'default' : 'help';+ globalBarBrandEl.style.cursor = agentStatusMessage ? 'help' : 'default';const mark = globalBarBrandEl.querySelector('[data-brand-mark]');if (mark) {mark.innerHTML = brandMarkSvg(connected ? P.accent : AGENT_DISCONNECTED_MARK, 18);mark.style.opacity = '1';}const dot = globalBarBrandEl.querySelector('[data-agent-dot]');- if (dot) dot.style.display = connected ? 'none' : 'block';- if (connected) hideAgentPollTooltip();+ if (dot) dot.style.display = agentStatusMessage ? 'block' : 'none';+ if (!agentStatusMessage) hideAgentPollTooltip();}function ensureAgentPollTooltip() {@@ -9339,14 +9698,17 @@ void main() {whiteSpace: 'normal',});agentPollTooltipEl.id = PREFIX + '-agent-poll-tooltip';- agentPollTooltipEl.textContent = AGENT_DISCONNECTED_TIP;+ agentPollTooltipEl.textContent = agentStatusText() || AGENT_DISCONNECTED_TIP;uiAppend(agentPollTooltipEl);return agentPollTooltipEl;}function showAgentPollTooltip(anchor) {- if (agentPollingConnected || !anchor) return;+ if (!agentStatusMessage || !anchor) return;const tip = ensureAgentPollTooltip();+ // Re-derive rather than reuse the cached copy: the live state may have moved+ // since the last status poll set it.+ tip.textContent = agentStatusText() || AGENT_DISCONNECTED_TIP;tip.style.transition = 'none';tip.style.display = 'block';tip.style.opacity = '1';@@ -9376,7 +9738,9 @@ void main() {fetch('http://localhost:' + PORT + '/status?token=' + TOKEN, { cache: 'no-store' }).then((res) => (res.ok ? res.json() : null)).then((data) => {- if (data && typeof data.agentPolling === 'boolean') syncAgentPollingUi(data.agentPolling);+ if (data && typeof data.agentPolling === 'boolean') {+ syncAgentPollingUi(data.agentPolling);+ }}).catch(() => { /* server loss handled elsewhere */ });}diff --git a/.trae/skills/impeccable/scripts/live-inject.mjs b/.trae/skills/impeccable/scripts/live-inject.mjsindex 7c8d91182..d99c37fd5 100644--- a/.trae/skills/impeccable/scripts/live-inject.mjs+++ b/.trae/skills/impeccable/scripts/live-inject.mjs@@ -27,6 +27,8 @@ const __dirname = path.dirname(fileURLToPath(import.meta.url));const CONFIG_PATH = resolveLiveConfigPath({ cwd: process.cwd(), scriptsDir: __dirname });const MARKER_OPEN_TEXT = 'impeccable-live-start';const MARKER_CLOSE_TEXT = 'impeccable-live-end';+const NUXT_PLUGIN_MARKER = 'impeccable-live-nuxt-plugin';+const NUXT_PLUGIN_NAME = 'impeccable-live.client.ts';const IGNORE_MARKER_OPEN = '# impeccable-live-ignore-start';const IGNORE_MARKER_CLOSE = '# impeccable-live-ignore-end';@@ -38,6 +40,9 @@ export const LIVE_IGNORE_PATTERNS = Object.freeze(['.impeccable/live/sessions/','.impeccable/live/previews/','.impeccable/live/annotations/',+ '.impeccable/live/artifacts/',+ '.impeccable/live/accept-receipts/',+ '.impeccable/live/locks/','.impeccable/live/cache/','.impeccable/live/manual-edit-apply-transaction.json','.impeccable/live/manual-edit-events.jsonl',@@ -46,10 +51,15 @@ export const LIVE_IGNORE_PATTERNS = Object.freeze(['.impeccable/live/deferred-svelte-component-accepts.json','.impeccable-live.json','.impeccable-live/',+ 'app/.impeccable-live/',+ 'src/.impeccable-live/','node_modules/.impeccable-live/','src/lib/impeccable/ImpeccableLiveRoot.svelte','src/lib/impeccable/__runtime.js','src/lib/impeccable/[0-9a-f]*/',+ 'plugins/impeccable-live.client.ts',+ 'app/plugins/impeccable-live.client.ts',+ 'src/plugins/impeccable-live.client.ts',]);/**@@ -113,6 +123,7 @@ Output (JSON):const resolvedFiles = resolveFiles(process.cwd(), config);const svelteKit = detectSvelteKitProject(process.cwd(), config);+ const nuxt = detectNuxtProject(process.cwd());if (args.includes('--remove')) {if (svelteKit) {@@ -120,6 +131,12 @@ Output (JSON):console.log(JSON.stringify({ ok: true, adapter: 'sveltekit', results: [adapterResult] }));return;}+ if (nuxt) {+ const adapterResult = removeNuxtLiveAdapter({ cwd: process.cwd(), project: nuxt });+ console.log(JSON.stringify({ ok: !adapterResult.error, adapter: 'nuxt', results: [adapterResult] }));+ if (adapterResult.error) process.exitCode = 1;+ return;+ }const results = resolvedFiles.map((relFile) => {const absFile = path.resolve(process.cwd(), relFile);if (!fs.existsSync(absFile)) return { file: relFile, error: 'file_not_found' };@@ -145,13 +162,28 @@ Output (JSON):console.error(JSON.stringify({ ok: false, error: 'missing_port' }));process.exit(1);}- const gitIgnore = ensureLiveGitIgnores(process.cwd());+ const gitIgnore = ensureLiveGitIgnores(+ process.cwd(),+ nuxt ? [nuxt.pluginFile] : [],+ );if (svelteKit) {const adapterResult = applySvelteKitLiveAdapter({ cwd: process.cwd(), port, config });console.log(JSON.stringify({ ok: true, port, adapter: 'sveltekit', gitIgnore, results: [adapterResult] }));return;}+ if (nuxt) {+ const adapterResult = applyNuxtLiveAdapter({ cwd: process.cwd(), port, project: nuxt });+ console.log(JSON.stringify({+ ok: !adapterResult.error,+ port,+ adapter: 'nuxt',+ gitIgnore,+ results: [adapterResult],+ }));+ if (adapterResult.error) process.exitCode = 1;+ return;+ }const results = resolvedFiles.map((relFile) => {const absFile = path.resolve(process.cwd(), relFile);@@ -175,12 +207,12 @@ Output (JSON):if (!anyInserted) process.exit(1);}-export function ensureLiveGitIgnores(cwd = process.cwd()) {+export function ensureLiveGitIgnores(cwd = process.cwd(), extraPatterns = []) {const target = resolveIgnoreTarget(cwd);const existing = fs.existsSync(target.path) ? fs.readFileSync(target.path, 'utf-8') : '';const block = [IGNORE_MARKER_OPEN,- ...LIVE_IGNORE_PATTERNS,+ ...new Set([...LIVE_IGNORE_PATTERNS, ...extraPatterns]),IGNORE_MARKER_CLOSE,].join('\n');const markerRe = new RegExp(`${escapeRegExp(IGNORE_MARKER_OPEN)}[\\s\\S]*?${escapeRegExp(IGNORE_MARKER_CLOSE)}`);@@ -202,10 +234,119 @@ export function ensureLiveGitIgnores(cwd = process.cwd()) {file: path.relative(cwd, target.path).split(path.sep).join('/'),mode: target.mode,changed: updated !== existing,- patterns: [...LIVE_IGNORE_PATTERNS],+ patterns: [...new Set([...LIVE_IGNORE_PATTERNS, ...extraPatterns])],};}+// ---------------------------------------------------------------------------+// Nuxt adapter+//+// A script element placed in app.vue is compiled as Vue-rendered DOM and is+// not executed. Nuxt instead auto-discovers client plugins. Keep the adapter+// generated, dev-only, and outside user-authored source: Live creates one+// marked .client.ts plugin on start and removes it on stop.+// ---------------------------------------------------------------------------++export function detectNuxtProject(cwd = process.cwd()) {+ const configFile = fs.readdirSync(cwd, { withFileTypes: true })+ .find((entry) => entry.isFile() && /^nuxt\.config\.(?:js|mjs|cjs|ts|mts|cts)$/.test(entry.name))+ ?.name;+ if (!configFile) return null;++ const config = fs.readFileSync(path.join(cwd, configFile), 'utf-8');+ const literalSrcDir = config.match(/\bsrcDir\s*:\s*(['"])([^'"]+)\1/);+ let appDir = '';+ if (literalSrcDir) {+ const candidate = literalSrcDir[2]+ .replace(/\\/g, '/')+ .replace(/^\.\//, '')+ .replace(/\/+$/, '');+ const normalized = path.posix.normalize(candidate);+ if (normalized !== '..' && !normalized.startsWith('../') && !path.isAbsolute(normalized)) {+ appDir = normalized === '.' ? '' : normalized;+ }+ } else if (+ fs.existsSync(path.join(cwd, 'app', 'app.vue'))+ || fs.existsSync(path.join(cwd, 'app', 'pages'))+ ) {+ appDir = 'app';+ }++ const pluginFile = [appDir, 'plugins', NUXT_PLUGIN_NAME].filter(Boolean).join('/');+ return { configFile, appDir, pluginFile };+}++export function buildNuxtPlugin(port) {+ return `/* ${NUXT_PLUGIN_MARKER} */+const liveSrc = 'http://localhost:${port}/live.js';+const liveSelector = 'script[data-impeccable-live-nuxt]';++export default defineNuxtPlugin(() => {+ if (!import.meta.dev || typeof document === 'undefined') return;++ const expectedSrc = new URL(liveSrc, window.location.href).href;+ let script = document.querySelector(liveSelector);+ if (script?.src === expectedSrc) return;+ script?.remove();++ script = document.createElement('script');+ script.src = liveSrc;+ script.async = true;+ script.dataset.impeccableLiveNuxt = '';+ document.head.appendChild(script);++ import.meta.hot?.dispose(() => {+ if (script?.isConnected) script.remove();+ });+});+/* /${NUXT_PLUGIN_MARKER} */+`;+}++export function applyNuxtLiveAdapter({ cwd = process.cwd(), port, project = detectNuxtProject(cwd) }) {+ if (!project) return { error: 'nuxt_not_detected' };+ const absFile = path.join(cwd, project.pluginFile);+ const existing = fs.existsSync(absFile) ? fs.readFileSync(absFile, 'utf-8') : null;+ if (existing !== null && !existing.includes(NUXT_PLUGIN_MARKER)) {+ return {+ file: project.pluginFile,+ error: 'nuxt_plugin_conflict',+ hint: `${project.pluginFile} already exists and is not managed by Impeccable Live`,+ };+ }++ const content = buildNuxtPlugin(port);+ fs.mkdirSync(path.dirname(absFile), { recursive: true });+ if (content !== existing) fs.writeFileSync(absFile, content, 'utf-8');+ return {+ file: project.pluginFile,+ inserted: true,+ changed: content !== existing,+ devOnly: true,+ };+}++export function removeNuxtLiveAdapter({ cwd = process.cwd(), project = detectNuxtProject(cwd) }) {+ if (!project) return { error: 'nuxt_not_detected' };+ const absFile = path.join(cwd, project.pluginFile);+ if (!fs.existsSync(absFile)) {+ return { file: project.pluginFile, removed: false, note: 'no adapter present' };+ }+ const content = fs.readFileSync(absFile, 'utf-8');+ if (!content.includes(NUXT_PLUGIN_MARKER)) {+ return {+ file: project.pluginFile,+ removed: false,+ error: 'nuxt_plugin_conflict',+ hint: `${project.pluginFile} is not managed by Impeccable Live`,+ };+ }+ fs.unlinkSync(absFile);+ const pluginDir = path.dirname(absFile);+ if (fs.readdirSync(pluginDir).length === 0) fs.rmdirSync(pluginDir);+ return { file: project.pluginFile, removed: true };+}+function resolveIgnoreTarget(cwd) {const gitExcludePath = resolveGitInfoExcludePath(cwd);if (gitExcludePath) {diff --git a/.trae/skills/impeccable/scripts/live-poll.mjs b/.trae/skills/impeccable/scripts/live-poll.mjsindex 740161e10..19a8b0f9b 100644--- a/.trae/skills/impeccable/scripts/live-poll.mjs+++ b/.trae/skills/impeccable/scripts/live-poll.mjs@@ -27,7 +27,7 @@ const scriptCmd = (name) => `node "${path.join(SELF_DIR, name)}"`;export const PER_REQUEST_TIMEOUT_MS = 270_000;export const DEFAULT_EVENT_LEASE_MS = 600_000;-const EVENT_TYPES_NEEDING_AGENT_REPLY = new Set(['generate', 'steer', 'manual_edit_apply']);+const EVENT_TYPES_NEEDING_AGENT_REPLY = new Set(['generate', 'steer', 'manual_edit_apply', 'carbonize_cleanup']);function readServerInfo() {const record = readLiveServerInfo(process.cwd());@@ -38,8 +38,8 @@ function readServerInfo() {return record.info;}-export function buildPollReplyPayload(token, { id, type, message, file, data }) {- return { token, id, type, message, file, data };+export function buildPollReplyPayload(token, { id, type, message, file, data, sourceEventType }) {+ return { token, id, type, message, file, data, sourceEventType };}export function manualApplyPollBanner(event = {}) {@@ -152,7 +152,14 @@ export async function waitForEventAck(base, token, eventId, {return false;}-export async function fetchNextEvent(base, token, { totalDeadline } = {}) {+export async function fetchNextEvent(base, token, {+ totalDeadline,+ types,+ resolveTypes,+ perRequestTimeoutMs = PER_REQUEST_TIMEOUT_MS,+ leaseMs = DEFAULT_EVENT_LEASE_MS,+ signal,+} = {}) {while (true) {if (totalDeadline && Date.now() >= totalDeadline) {return { type: 'timeout' };@@ -161,8 +168,15 @@ export async function fetchNextEvent(base, token, { totalDeadline } = {}) {const remaining = totalDeadline? totalDeadline - Date.now(): PER_REQUEST_TIMEOUT_MS;- const slice = Math.min(Math.max(remaining, 1000), PER_REQUEST_TIMEOUT_MS);- const res = await fetch(`${base}/poll?token=${token}&timeout=${slice}&leaseMs=${DEFAULT_EVENT_LEASE_MS}`);+ const slice = Math.min(Math.max(remaining, 1000), perRequestTimeoutMs);+ const query = new URLSearchParams({+ token,+ timeout: String(slice),+ leaseMs: String(leaseMs),+ });+ const normalizedTypes = normalizePollTypes(resolveTypes ? await resolveTypes() : types);+ if (normalizedTypes.length > 0) query.set('types', normalizedTypes.join(','));+ const res = await fetch(`${base}/poll?${query}`, { signal });if (res.status === 401) {const err = new Error('Authentication failed. The server token may have changed.');@@ -202,11 +216,17 @@ export async function augmentEventWithAcceptHandling(event, base, token) {event._acceptResult = { handled: false, mode: 'error', error: err.message };}+ await completeAcceptHandling(event, base, token);+ return event;+}++export async function completeAcceptHandling(event, base, token) {const completionType = completionTypeForAcceptResult(event.type, event._acceptResult);try {await postReply(base, token, {id: event.id,type: completionType,+ sourceEventType: event.type,message: event._acceptResult?.error,file: event._acceptResult?.file,data: event._acceptResult?.carbonize === true ? { carbonize: true } : undefined,@@ -217,7 +237,6 @@ export async function augmentEventWithAcceptHandling(event, base, token) {if (!event._completionAck) {event._completionAck = completionAckForAcceptResult(event.id, completionType, event._acceptResult);}-return event;}@@ -245,9 +264,9 @@ export function printPollEvent(event) {console.log(JSON.stringify(event));}-export async function runPollOnce(base, token, { totalTimeout = 600_000 } = {}) {+export async function runPollOnce(base, token, { totalTimeout = 600_000, types, resolveTypes, perRequestTimeoutMs } = {}) {const deadline = Date.now() + totalTimeout;- const event = await fetchNextEvent(base, token, { totalDeadline: deadline });+ const event = await fetchNextEvent(base, token, { totalDeadline: deadline, types, resolveTypes, perRequestTimeoutMs });await augmentEventWithAcceptHandling(event, base, token);writeCarbonizeBanner(event);printPollEvent(event);@@ -258,11 +277,14 @@ export async function runPollStream(base, token, {ackTimeoutMs = 600_000,ackPollIntervalMs = 400,shouldContinue = () => true,+ types,+ resolveTypes,+ perRequestTimeoutMs,} = {}) {process.stderr.write('[impeccable-poll] stream mode: one JSON object per line on stdout; use --reply while this process stays running\n');while (shouldContinue()) {- const event = await fetchNextEvent(base, token);+ const event = await fetchNextEvent(base, token, { types, resolveTypes, perRequestTimeoutMs });await augmentEventWithAcceptHandling(event, base, token);writeCarbonizeBanner(event);printPollEvent(event);@@ -322,14 +344,17 @@ Modes:Options:--timeout=MS One-shot poll timeout in ms (default: 600000). Ignored in --stream mode+ --types=A,B Lease only these event types--ack-timeout=MS Stream mode: max wait for --reply after generate/steer (default: 600000)--file PATH Attach a source file path to the reply (generate/steer flow)--data JSON Attach a JSON result object to the reply (manual_edit_apply flow). Must be valid JSON--help Show this help messageHarness note:- Default one-shot mode is the portable contract for Claude Code, Codex, and Cursor.- --stream is experimental for harnesses with fast incremental stdout; do not use on Cursor.`);+ Default one-shot mode is the primary contract, including Codex foreground polling.+ Claude Code may run it as a background task; Cursor uses a background terminal with exit notification.+ --stream is retained for harnesses with measured, reliable incremental stdout.+ Do not use --stream on Cursor.`);process.exit(0);}@@ -360,23 +385,30 @@ Harness note:}const streamMode = args.includes('--stream');+ const typesArg = args.find((a) => a.startsWith('--types='));+ const types = normalizePollTypes(typesArg ? typesArg.slice('--types='.length) : null);const ackTimeoutArg = args.find((a) => a.startsWith('--ack-timeout='));const ackTimeoutMs = ackTimeoutArg ? parseInt(ackTimeoutArg.split('=')[1], 10) : 600_000;try {if (streamMode) {- await runPollStream(base, info.token, { ackTimeoutMs });+ await runPollStream(base, info.token, { ackTimeoutMs, types });return;}const timeoutArg = args.find((a) => a.startsWith('--timeout='));const totalTimeout = timeoutArg ? parseInt(timeoutArg.split('=')[1], 10) : 600_000;- await runPollOnce(base, info.token, { totalTimeout });+ await runPollOnce(base, info.token, { totalTimeout, types });} catch (err) {handlePollError(err);}}+export function normalizePollTypes(value) {+ const values = Array.isArray(value) ? value : String(value || '').split(',');+ return [...new Set(values.map((type) => String(type).trim()).filter(Boolean))];+}+// Auto-execute when run directlyconst _running = process.argv[1];if (_running?.endsWith('live-poll.mjs') || _running?.endsWith('live-poll.mjs/')) {diff --git a/.trae/skills/impeccable/scripts/live-server.mjs b/.trae/skills/impeccable/scripts/live-server.mjsindex 5735f2aec..c6e951086 100644--- a/.trae/skills/impeccable/scripts/live-server.mjs+++ b/.trae/skills/impeccable/scripts/live-server.mjs@@ -28,8 +28,10 @@ import {readLiveBrowserScriptParts,resolveLiveBrowserScriptParts,} from './live/browser-script-parts.mjs';-import { createLiveSessionStore } from './live/session-store.mjs';+import { createLiveSessionStore, GENERATION_FENCED_PHASES } from './live/session-store.mjs';+import { runGenerationPreflight } from './live/generation-preflight.mjs';import { validateEvent } from './live/event-validation.mjs';+import { selectAvailablePendingEvent } from './live/poll-lanes.mjs';import { createManualEditRoutes } from './live/manual-edit-routes.mjs';import { LIVE_COMMANDS } from './live/vocabulary.mjs';import {@@ -63,6 +65,10 @@ const DESIGN_MD_PATH = PROJECT_CONTEXT.designPath: null;const DEFAULT_POLL_TIMEOUT = 600_000; // 10 min — agent re-polls on timeout anywayconst SSE_HEARTBEAT_INTERVAL = 30_000; // keepalive ping every 30s+// The browser checkpoints for several unrelated reasons (see checkpointPayload+// in live-browser.js). Only these two report that variant availability changed,+// and only they may drive variant_progress / the *_reviewable phases.+const VARIANT_PROGRESS_CHECKPOINT_REASONS = new Set(['variants_progress', 'variants_ready']);// ---------------------------------------------------------------------------// Port detection@@ -156,29 +162,206 @@ function restorePendingEventsFromStore() {}}-function findAvailablePendingEvent(now = Date.now()) {- for (const entry of state.pendingEvents) {- if (entry.leaseUntil && entry.leaseUntil > now) continue;- return entry;- }- return null;+function findAvailablePendingEvent(now = Date.now(), types = null) {+ return selectAvailablePendingEvent(state.pendingEvents, { now, types });}-function leaseEvent(entry, leaseMs) {+async function leaseEvent(entry, leaseMs) {+ // Claim the entry before awaiting anything. prepareGenerateEventForLease+ // yields to the event loop, and selectAvailablePendingEvent only skips+ // entries whose lease is in the future — an unclaimed entry would be handed+ // to a second poll in that window and generated twice.+ entry.leaseUntil = Date.now() + leaseMs;+ await prepareGenerateEventForLease(entry);if (!entry.event?.id) {const idx = state.pendingEvents.indexOf(entry);if (idx !== -1) state.pendingEvents.splice(idx, 1);return entry.event;}+ // Re-stamp so the lease window starts when the agent actually receives the+ // work, not when scaffolding began.entry.leaseUntil = Date.now() + leaseMs;+ recordGenerateDelivery(entry);scheduleLeaseFlush();broadcastAgentPollingIfChanged();return entry.event;}-function acknowledgePendingEvent(id) {+function recordGenerateDelivery(entry) {+ const event = entry?.event;+ if (!event || event.type !== 'generate' || event.generationReadyAt) return;+ const at = Date.now();+ entry.event = { ...event, generationReadyAt: at };+ state.sessionStore?.appendEvent(entry.event);+ recordAgentPhase(event.id, 'generation_ready', { at });+}++async function prepareGenerateEventForLease(entry) {+ const event = entry?.event;+ if (!event || event.type !== 'generate' || event.scaffoldAttempted) return;++ recordAgentPhase(event.id, 'picked_up');+ recordAgentPhase(event.id, 'scaffolding');+ const result = await runGenerationPreflight(event, {+ cwd: process.cwd(),+ scriptsDir: __dirname,+ });+ entry.event = {+ ...event,+ scaffoldAttempted: true,+ scaffoldDurationMs: result.durationMs ?? null,+ ...(result.ok ? { scaffold: result.scaffold } : { scaffoldError: result.error || result.reason }),+ };+ state.sessionStore?.appendEvent(entry.event);+ recordAgentPhase(event.id, result.ok ? 'source_ready' : 'scaffold_fallback', {+ durationMs: result.durationMs ?? null,+ previewMode: result.scaffold?.previewMode || 'source',+ });+}++function recordAgentPhase(id, phase, details = {}) {+ if (!id) return;+ const event = {+ type: 'agent_phase',+ id,+ phase,+ at: Date.now(),+ ...details,+ };+ state.sessionStore?.appendEvent(event);+ broadcast(event);+}++/**+ * Detect a browser that missed the generation `done` broadcast.+ *+ * The preflight scaffold write triggers a framework full-reload (Astro reloads+ * the page for any .astro edit). If the agent's variant write + `done` land+ * while the browser is mid-reload, the new page misses both the second HMR+ * reload and the SSE `done` — it resumes from the scaffold-only source and+ * sits in GENERATING at 0/N forever. That resumed page always checkpoints+ * (`browser_resumed`), so a checkpoint claiming "still generating, variants+ * missing" for a session whose generation already completed is direct+ * evidence of the miss. Rebuild the `done` payload from the snapshot so the+ * caller can re-broadcast it; the browser's done handler is idempotent and+ * falls back to injecting variants from source.+ *+ * Keys on the store's monotone `generationCompletedAt`, not `phase` — the+ * behind checkpoint itself regresses `phase` to `generating`, and a browser+ * that misses the redelivered `done` too (another reload) must still trigger+ * redelivery from its next checkpoint.+ */+function detectMissedGenerationCompletion(event) {+ if (!event?.id || event.type !== 'checkpoint') return null;+ if (event.phase !== 'generating') return null;+ if (!variantCountLooksBehind(event.arrivedVariants, event.expectedVariants)) return null;+ if (!state.sessionStore) return null;+ let snapshot = null;+ try {+ snapshot = state.sessionStore.getSnapshot(event.id);+ } catch {+ return null;+ }+ return missedCompletionFromSnapshot(snapshot);+}++function variantCountLooksBehind(arrivedValue, expectedValue) {+ const arrived = Number(arrivedValue) || 0;+ const expected = Number(expectedValue) || 0;+ return arrived <= 0 || (expected > 0 && arrived < expected);+}++function missedCompletionFromSnapshot(snapshot) {+ if (!snapshot?.id || !snapshot.generationCompletedAt) return null;+ if (snapshot.generationCanceled) return null;+ // Accept/discard already underway: the browser is no longer waiting on+ // generation, and a late `done` there would collide with teardown.+ if (GENERATION_FENCED_PHASES.has(snapshot.phase)) return null;+ const file = snapshot.sourceFile || snapshot.previewFile;+ if (!file) return null;+ return {+ type: 'done',+ id: snapshot.id,+ file,+ sourceFile: snapshot.sourceFile || undefined,+ previewFile: snapshot.previewFile || undefined,+ previewMode: snapshot.previewMode || undefined,+ redelivered: true,+ };+}++function recordGenerationCheckpoint(event) {+ if (!event?.id || event.type !== 'checkpoint') return;+ if (generationIsFenced(event.id)) return;+ // Only checkpoints that report a change in variant availability are+ // generation progress. The browser also checkpoints for durability on Tune+ // slider drags, resumes, and anchor recovery; treating those as progress+ // echoed `variant_progress` straight back to the browser that sent it, which+ // remounts the component preview mid-drag (reverting the user's live param+ // edit and detaching the popover's element), and permanently latched the+ // *_reviewable phases from the wrong trigger, corrupting generation timings.+ if (!VARIANT_PROGRESS_CHECKPOINT_REASONS.has(event.reason)) return;+ const arrived = Number(event.arrivedVariants) || 0;+ const expected = Number(event.expectedVariants) || 0;+ if (arrived <= 0 || expected <= 0) return;+ const previewMode = event.previewMode || 'source';+ const previewFile = event.previewFile || event.file;+ if (previewFile) {+ broadcast({+ type: 'variant_progress',+ id: event.id,+ file: previewFile,+ sourceFile: event.sourceFile || (previewMode === 'source' ? previewFile : undefined),+ previewFile,+ previewMode,+ arrivedVariants: arrived,+ expectedVariants: expected,+ publicationKind: event.publicationKind || 'variants',+ });+ }+ const details = {+ arrivedVariants: arrived,+ expectedVariants: expected,+ checkpointReason: event.reason || null,+ };+ const at = Date.now();+ if (!generationPhaseAlreadyRecorded(event.id, 'first_reviewable')) {+ recordAgentPhase(event.id, 'first_reviewable', { ...details, at });+ }+ if (arrived >= 2 && expected >= 3 && !generationPhaseAlreadyRecorded(event.id, 'second_reviewable')) {+ recordAgentPhase(event.id, 'second_reviewable', { ...details, at });+ }+ if (arrived >= expected && !generationPhaseAlreadyRecorded(event.id, 'all_variants_ready')) {+ recordAgentPhase(event.id, 'all_variants_ready', { ...details, at });+ }+}++function generationIsFenced(id) {+ if (!state.sessionStore || !id) return false;+ try {+ const snapshot = state.sessionStore.getSnapshot(id, { includeCompleted: true });+ return snapshot?.generationCanceled === true;+ } catch {+ return false;+ }+}++function generationPhaseAlreadyRecorded(id, phase) {+ if (!state.sessionStore) return false;+ try {+ const snapshot = state.sessionStore.getSnapshot(id, { includeCompleted: true });+ return !!snapshot?.generationTimings?.[phase];+ } catch {+ return false;+ }+}++function acknowledgePendingEvent(id, sourceEventType) {if (!id) return false;- const idx = state.pendingEvents.findIndex((entry) => entry.event?.id === id);+ const idx = state.pendingEvents.findIndex((entry) => (+ entry.event?.id === id+ && (!sourceEventType || entry.event?.type === sourceEventType)+ ));if (idx === -1) return false;const acknowledged = state.pendingEvents[idx].event;state.pendingEvents.splice(idx, 1);@@ -187,9 +370,39 @@ function acknowledgePendingEvent(id) {return acknowledged;}-function findPendingEventById(id) {+function releasePendingEvent(id, sourceEventType) {+ const entry = state.pendingEvents.find((item) => (+ item.event?.id === id+ && (!sourceEventType || item.event?.type === sourceEventType)+ ));+ if (!entry) return null;+ entry.leaseUntil = 0;+ scheduleLeaseFlush();+ return entry.event;+}++function retirePendingGeneration(id) {+ if (!id) return 0;+ let retired = 0;+ for (let index = state.pendingEvents.length - 1; index >= 0; index -= 1) {+ const event = state.pendingEvents[index]?.event;+ if (event?.id !== id || event.type !== 'generate') continue;+ state.pendingEvents.splice(index, 1);+ retired += 1;+ }+ if (retired > 0) {+ scheduleLeaseFlush();+ broadcastAgentPollingIfChanged();+ }+ return retired;+}++function findPendingEventById(id, sourceEventType) {if (!id) return null;- const entry = state.pendingEvents.find((item) => item.event?.id === id);+ const entry = state.pendingEvents.find((item) => (+ item.event?.id === id+ && (!sourceEventType || item.event?.type === sourceEventType)+ ));return entry?.event || null;}@@ -198,7 +411,7 @@ function summarizePendingEventForStatus(entry) {const summary = {id: event.id,type: event.type,- leased: !!(entry.leaseUntil && entry.leaseUntil > Date.now()),+ leased: isLeased(entry),leaseUntil: entry.leaseUntil || null,};if (event.type === 'manual_edit_apply') {@@ -224,7 +437,13 @@ function summarizeActiveSessionForClient(snapshot = {}) {arrivedVariants: snapshot.arrivedVariants ?? 0,visibleVariant: snapshot.visibleVariant ?? null,checkpointRevision: snapshot.checkpointRevision ?? 0,+ browserCheckpointRevision: snapshot.browserCheckpointRevision ?? snapshot.checkpointRevision ?? 0,+ publicationCheckpointRevision: snapshot.publicationCheckpointRevision ?? 0,paramValues: snapshot.paramValues || {},+ generationPhase: snapshot.generationPhase ?? null,+ generationCompletedAt: snapshot.generationCompletedAt ?? null,+ generationCanceled: snapshot.generationCanceled === true,+ cancelReason: snapshot.cancelReason ?? null,};}@@ -269,24 +488,46 @@ function scheduleLeaseFlush() {function flushPendingPolls() {let changed = false;while (state.pendingPolls.length > 0) {- const entry = findAvailablePendingEvent();+ let pollIndex = -1;+ let entry = null;+ for (let index = 0; index < state.pendingPolls.length; index += 1) {+ const candidate = findAvailablePendingEvent(Date.now(), state.pendingPolls[index].types);+ if (!candidate) continue;+ pollIndex = index;+ entry = candidate;+ break;+ }if (!entry) {scheduleLeaseFlush();broadcastAgentPollingIfChanged();return;}- const poll = state.pendingPolls.shift();- poll.resolve(leaseEvent(entry, poll.leaseMs));+ const [poll] = state.pendingPolls.splice(pollIndex, 1);+ // leaseEvent is async (it may scaffold source), but it claims the entry+ // synchronously, so the next loop iteration will not re-select it. Resolve+ // the poll when the lease settles rather than awaiting here, so one slow+ // scaffold never delays the other parked polls. On the exceptional failure+ // path, answer `timeout` so the agent re-polls; the claim stays until the+ // lease expires, which keeps a deterministic failure from hot-looping.+ leaseEvent(entry, poll.leaseMs).then(poll.resolve, (error) => {+ console.error('[live] lease failed for ' + (entry.event?.id || 'unknown') + ': ' + (error?.message || error));+ poll.resolve({ type: 'timeout' });+ });changed = true;}scheduleLeaseFlush();if (changed) broadcastAgentPollingIfChanged();}+function isLeased(entry) {+ return !!(entry?.leaseUntil && entry.leaseUntil > Date.now());+}+function agentPollingConnected() {- const now = Date.now();- return state.pendingPolls.length > 0- || state.pendingEvents.some((entry) => entry.leaseUntil && entry.leaseUntil > now);+ // A leased event only proves that a poll returned once. The foreground task+ // may have ended immediately afterward, so only an actively waiting poll is+ // evidence that steering can wake the task right now.+ return state.pendingPolls.length > 0;}function broadcastAgentPollingIfChanged() {@@ -689,6 +930,16 @@ function createRequestHandler({ detectScript, liveScriptParts }) {res.end(JSON.stringify({ error }));return;}+ if (msg.type === 'agent_phase') {+ recordAgentPhase(msg.id, msg.phase, {+ ...(Number.isFinite(msg.durationMs) ? { durationMs: msg.durationMs } : {}),+ owner: typeof msg.owner === 'string' ? msg.owner : undefined,+ });+ res.writeHead(200, { 'Content-Type': 'application/json' });+ res.end(JSON.stringify({ ok: true }));+ return;+ }+ const missedCompletion = detectMissedGenerationCompletion(msg);if (state.sessionStore && msg.id) {try {state.sessionStore.appendEvent(msg);@@ -698,6 +949,11 @@ function createRequestHandler({ detectScript, liveScriptParts }) {return;}}+ if (msg.type === 'accept' || msg.type === 'discard') {+ retirePendingGeneration(msg.id);+ }+ recordGenerationCheckpoint(msg);+ if (missedCompletion) broadcast(missedCompletion);if (msg.type === 'exit') {cleanupSvelteComponentSessionsBeforeExit();}@@ -738,6 +994,12 @@ function createRequestHandler({ detectScript, liveScriptParts }) {// Agent poll endpoints (unchanged from WS version)// ---------------------------------------------------------------------------+function parsePollTypes(value) {+ if (!value) return null;+ const types = String(value).split(',').map((type) => type.trim()).filter(Boolean);+ return types.length > 0 ? new Set(types) : null;+}+function handlePollGet(req, res, url) {const token = url.searchParams.get('token');if (token !== state.token) {@@ -748,13 +1010,25 @@ function handlePollGet(req, res, url) {state.lastPollAt = Date.now();const timeout = parseInt(url.searchParams.get('timeout') || DEFAULT_POLL_TIMEOUT, 10);const leaseMs = parseInt(url.searchParams.get('leaseMs') || '30000', 10);- const available = findAvailablePendingEvent();+ const types = parsePollTypes(url.searchParams.get('types'));+ const available = findAvailablePendingEvent(Date.now(), types);if (available) {- res.writeHead(200, { 'Content-Type': 'application/json' });- res.end(JSON.stringify(leaseEvent(available, leaseMs)));+ // Do not await inline: leaseEvent may scaffold source, and this handler runs+ // on the server's only thread. The client can disconnect during that window,+ // so check the socket before replying.+ leaseEvent(available, leaseMs).then((event) => {+ if (res.writableEnded || res.destroyed) return;+ res.writeHead(200, { 'Content-Type': 'application/json' });+ res.end(JSON.stringify(event));+ }, (error) => {+ console.error('[live] lease failed for ' + (available.event?.id || 'unknown') + ': ' + (error?.message || error));+ if (res.writableEnded || res.destroyed) return;+ res.writeHead(200, { 'Content-Type': 'application/json' });+ res.end(JSON.stringify({ type: 'timeout' }));+ });return;}- const poll = { resolve, leaseMs };+ const poll = { resolve, leaseMs, types };const timer = setTimeout(() => {const idx = state.pendingPolls.indexOf(poll);if (idx !== -1) state.pendingPolls.splice(idx, 1);@@ -783,12 +1057,15 @@ function sessionFileMetadataFromPollReply(file) {if (!file || typeof file !== 'string') return { file };const normalized = file.split(path.sep).join('/');const base = { file: normalized };- if (!normalized.endsWith('/manifest.json') && normalized !== 'manifest.json') return base;- if (!normalized.includes('node_modules/.impeccable-live/') && !normalized.includes('src/lib/impeccable/')) return base;+ const metadataFile = normalized;+ if (!metadataFile.endsWith('/manifest.json') && metadataFile !== 'manifest.json') return base;+ if (!metadataFile.includes('node_modules/.impeccable-live/')+ && !metadataFile.includes('src/lib/impeccable/')+ && !metadataFile.includes('/.impeccable-live/')) return base;let full;try {- full = path.resolve(process.cwd(), normalized);+ full = path.resolve(process.cwd(), metadataFile);const rel = path.relative(process.cwd(), full);if (!rel || rel.startsWith('..') || path.isAbsolute(rel)) return base;} catch {@@ -797,18 +1074,47 @@ function sessionFileMetadataFromPollReply(file) {try {const manifest = JSON.parse(fs.readFileSync(full, 'utf-8'));- if (manifest?.previewMode !== 'svelte-component' || !manifest.sourceFile) return base;+ if (manifest?.previewMode !== 'svelte-component'+ || !manifest.sourceFile) return base;return {file: String(manifest.sourceFile).split(path.sep).join('/'),sourceFile: String(manifest.sourceFile).split(path.sep).join('/'),previewFile: normalized,- previewMode: 'svelte-component',+ previewMode: manifest.previewMode,};} catch {return base;}}+function inferSourceEventType(msg = {}, pendingEvents = state.pendingEvents) {+ const entriesForId = pendingEvents.filter((entry) => entry.event?.id === msg.id);+ const pendingTypes = new Set(entriesForId.map((entry) => entry.event?.type));+ if (msg.type === 'discarded' || msg.type === 'discard') return 'discard';+ if (msg.type === 'complete') {+ if (pendingTypes.has('carbonize_cleanup')) return 'carbonize_cleanup';+ return pendingTypes.has('accept') ? 'accept' : (pendingTypes.has('generate') ? 'generate' : undefined);+ }+ if (msg.type === 'steer_done') return 'steer';+ // `agent_done` can be the automatic acknowledgement for a carbonize Accept.+ // New pollers send sourceEventType explicitly; default to generate only for+ // older callers so a late worker cannot acknowledge a queued Accept.+ if (msg.type === 'agent_done' || msg.type === 'done') return 'generate';+ // `error` is reference/live.md's documented failure reply, and parseReplyArgs+ // never sets sourceEventType on it (the poller is a fresh process that cannot+ // know what it leased). Returning undefined here makes acknowledgePendingEvent+ // match *any* event for this id: a stale generate worker's failure silently+ // consumed the user's queued Accept, which was then never delivered to any+ // agent and left the browser in SAVING forever. Attribute the failure to the+ // event this agent actually holds a lease on, and otherwise to `generate` —+ // never to a wildcard. If that generate was already retired by an Accept, the+ // ack simply finds no match, which is the correct outcome for a stale reply.+ if (msg.type === 'error') {+ return entriesForId.find(isLeased)?.event?.type || 'generate';+ }+ return undefined;+}+function handlePollPost(req, res) {let body = '';req.on('data', (c) => { body += c; });@@ -869,7 +1175,23 @@ function handlePollPost(req, res) {res.end(JSON.stringify({ error: 'stale_manual_edit_apply_reply', ...rollback }));return;}- const pendingEventBeforeAck = findPendingEventById(msg.id);+ const sourceEventType = msg.sourceEventType || inferSourceEventType(msg);+ if (msg.type === 'retry') {+ const releasedEvent = releasePendingEvent(msg.id, sourceEventType);+ if (!releasedEvent) {+ res.writeHead(msg.id ? 404 : 400, { 'Content-Type': 'application/json' });+ res.end(JSON.stringify({+ error: msg.id ? 'unknown_poll_retry_id' : 'missing_poll_retry_id',+ id: msg.id,+ }));+ return;+ }+ flushPendingPolls();+ res.writeHead(200, { 'Content-Type': 'application/json' });+ res.end(JSON.stringify({ ok: true, released: true }));+ return;+ }+ const pendingEventBeforeAck = findPendingEventById(msg.id, sourceEventType);if (pendingEventBeforeAck?.type === 'steer' && msg.type === 'steer_done'&& !msg.file && !(typeof msg.message === 'string' && msg.message.trim())) {res.writeHead(400, { 'Content-Type': 'application/json' });@@ -879,7 +1201,7 @@ function handlePollPost(req, res) {}));return;}- const acknowledgedEvent = acknowledgePendingEvent(msg.id);+ const acknowledgedEvent = acknowledgePendingEvent(msg.id, sourceEventType);let skipJournalReply = false;let existingSession = null;if (!acknowledgedEvent && state.sessionStore && msg.id) {@@ -1083,7 +1405,10 @@ if (args.includes('--background')) {process.exit(0);}} catch { /* not ready yet */ }- await new Promise(r => setTimeout(r, 200));+ // The detached child is typically listening in 35-45ms. A 200ms polling+ // floor dominated configured cold Live startup; poll cheaply and return+ // as soon as the child has written its ready record.+ await new Promise(r => setTimeout(r, 5));}console.error('Timed out waiting for live server to start.');process.exit(1);diff --git a/.trae/skills/impeccable/scripts/live-status.mjs b/.trae/skills/impeccable/scripts/live-status.mjsindex f7e464999..dc98b7386 100644--- a/.trae/skills/impeccable/scripts/live-status.mjs+++ b/.trae/skills/impeccable/scripts/live-status.mjs@@ -37,15 +37,19 @@ export async function statusCli() {pendingEvents: server.pendingEvents,} : null,activeSessions: server?.activeSessions || activeSessions,- recoveryHint: manualApply- ? manualApplyResumeHint(manualApply)- : server- ? 'Run live-poll.mjs to continue pending work, or live-complete.mjs --id <session> after manual cleanup.'- : 'Start live-server.mjs to requeue pending durable events, then run live-poll.mjs.',+ recoveryHint: recoveryHint({ server, manualApply }),};console.log(JSON.stringify(payload, null, 2));}+function recoveryHint({ server, manualApply }) {+ if (manualApply) return manualApplyResumeHint(manualApply);+ if (server) {+ return 'Run live-poll.mjs to continue pending work, or live-complete.mjs --id <session> after manual cleanup.';+ }+ return 'Start live-server.mjs to requeue pending durable events, then run live-poll.mjs.';+}+function findPendingManualApply(server, activeSessions) {const fromServer = server?.pendingEvents?.find((event) => event?.type === 'manual_edit_apply');if (fromServer) return fromServer;diff --git a/.trae/skills/impeccable/scripts/live-wrap.mjs b/.trae/skills/impeccable/scripts/live-wrap.mjsindex 438c01b68..48d7f7683 100644--- a/.trae/skills/impeccable/scripts/live-wrap.mjs+++ b/.trae/skills/impeccable/scripts/live-wrap.mjs@@ -160,11 +160,29 @@ The agent should insert variant HTML at insertLine.`);if (filtered.length === 1) {match = filtered[0];} else if (filtered.length === 0) {- // Source uses dynamic content (`<h1>{title}</h1>` etc.) so the- // browser-side textContent doesn't appear literally in source. Fall- // back to first-match rather than refusing — this is the same- // behavior unmodified callers see, just preserved.- match = candidates[0];+ const normalizedText = String(text).replace(/\s+/g, ' ').trim();+ if (normalizedText.length < 8) {+ // Very short labels cannot disambiguate siblings reliably. Preserve+ // the legacy behavior for these low-information picker events.+ match = candidates[0];+ } else {+ // Rendered text that is absent from every candidate usually means+ // the source uses expressions or component props. Picking the first+ // same-class sibling silently edits the wrong instance (observed on+ // Astro result cards), so stop and surface every candidate instead.+ console.error(JSON.stringify({+ error: 'element_ambiguous',+ fallback: 'agent-driven',+ reason: 'rendered_text_not_in_source',+ file: path.relative(process.cwd(), targetFile),+ candidates: candidates.map((c) => ({+ startLine: c.startLine + 1,+ endLine: c.endLine + 1,+ })),+ hint: 'Rendered text does not occur in any matching source branch. The element may use dynamic props or expressions; inspect the candidates and wrap the intended instance manually.',+ }));+ process.exit(1);+ }} else {// Multiple candidates ALSO match the text. Truly ambiguous — refuse// rather than pick wrong, and hand the agent the candidate locations@@ -269,6 +287,7 @@ The agent should insert variant HTML at insertLine.`);const originalIndented = reindentOriginal(' ');const relTargetFile = path.relative(process.cwd(), targetFile).split(path.sep).join('/');const useSvelteComponent = shouldUseSvelteComponentInjection(targetFile);+ const useFrameworkComponent = useSvelteComponent;// Wrapper attributes differ by syntax. HTML allows plain string attrs;// JSX requires object-literal style and parses string attrs as HTML (which@@ -288,7 +307,7 @@ The agent should insert variant HTML at insertLine.`);// replacement range to include the wrapper's `<div>` open / close lines// so the entire scaffold gets removed cleanly.const wrapperLines = isJsx ? [- indent + '<div data-impeccable-variants="' + id + '" data-impeccable-variant-count="' + count + '" ' + styleContents + '>',+ indent + '<div data-impeccable-variants="' + id + '" data-impeccable-variant-count="' + count + '"' + ' ' + styleContents + '>',indent + ' ' + commentSyntax.open + ' impeccable-variants-start ' + id + ' ' + commentSyntax.close,indent + ' ' + commentSyntax.open + ' Original ' + commentSyntax.close,indent + ' <div data-impeccable-variant="original">',@@ -299,7 +318,7 @@ The agent should insert variant HTML at insertLine.`);indent + '</div>',] : [indent + commentSyntax.open + ' impeccable-variants-start ' + id + ' ' + commentSyntax.close,- indent + '<div data-impeccable-variants="' + id + '" data-impeccable-variant-count="' + count + '" ' + styleContents + '>',+ indent + '<div data-impeccable-variants="' + id + '" data-impeccable-variant-count="' + count + '"' + ' ' + styleContents + '>',indent + ' ' + commentSyntax.open + ' Original ' + commentSyntax.close,indent + ' <div data-impeccable-variant="original">',originalIndented,@@ -356,15 +375,18 @@ The agent should insert variant HTML at insertLine.`);const outputRelFile = path.relative(process.cwd(), outputFile).split(path.sep).join('/');const svelteComponentAuthoring = useSvelteComponent ? buildSvelteComponentCssAuthoring(count) : null;+ const componentSession = svelteSession;+ const componentPreviewMode = useSvelteComponent ? 'svelte-component' : undefined;+ const previewMode = componentPreviewMode;console.log(JSON.stringify({file: outputRelFile,- sourceFile: useSvelteComponent ? relTargetFile : undefined,- previewMode: useSvelteComponent ? 'svelte-component' : undefined,- componentDir: svelteSession?.componentDir,- propContract: svelteSession?.propContract,- sourceStartLine: useSvelteComponent ? startLine + 1 : undefined,- sourceEndLine: useSvelteComponent ? endLine + 1 : undefined,+ sourceFile: useFrameworkComponent ? relTargetFile : undefined,+ previewMode,+ componentDir: componentSession?.componentDir,+ propContract: componentSession?.propContract,+ sourceStartLine: useFrameworkComponent ? startLine + 1 : undefined,+ sourceEndLine: useFrameworkComponent ? endLine + 1 : undefined,startLine: outputStartLine, // 1-indexed for the agent// wrapperLines is an array but one element (the original-content slot)// is a `\n`-joined multi-line string, so the actual file-row count is@@ -374,10 +396,10 @@ The agent should insert variant HTML at insertLine.`);endLine: outputEndLine, // 1-indexedinsertLine, // 1-indexed: where variants gocommentSyntax: commentSyntax,- styleMode: useSvelteComponent ? 'svelte-component' : styleMode.mode,- styleTag: useSvelteComponent ? null : styleMode.styleTag,- cssSelectorPrefixExamples: useSvelteComponent ? [] : buildCssSelectorPrefixExamples(styleMode.mode, count),- cssAuthoring: useSvelteComponent ? svelteComponentAuthoring : buildCssAuthoring(styleMode, count),+ styleMode: componentPreviewMode || styleMode.mode,+ styleTag: useFrameworkComponent ? null : styleMode.styleTag,+ cssSelectorPrefixExamples: useFrameworkComponent ? [] : buildCssSelectorPrefixExamples(styleMode.mode, count),+ cssAuthoring: svelteComponentAuthoring || buildCssAuthoring(styleMode, count),originalLineCount: originalLines.length,}));}diff --git a/.trae/skills/impeccable/scripts/live.mjs b/.trae/skills/impeccable/scripts/live.mjsindex e0bd1ad24..b21a71cc4 100644--- a/.trae/skills/impeccable/scripts/live.mjs+++ b/.trae/skills/impeccable/scripts/live.mjs@@ -10,7 +10,7 @@** After this, the agent's only remaining steps are:* - Open the project's live dev/preview URL in the browser (optional, if browser automation exists)—not `serverPort`; that port is the Impeccable helper for /live.js and /poll- * - Enter the poll loop: `node live-poll.mjs`+ * - Enter the harness-native poll loop: `node live-poll.mjs`** Usage:* node live.mjs # Prepare everything, print JSON, exit@@ -40,6 +40,7 @@ Prepare everything for live variant mode in a single command:- Starts (or reuses) the live server in the background- Injects the browser script tag- Reads PRODUCT.md / DESIGN.md for project context+ - Prepares the harness-native foreground/background poll loop- In monorepos, choose a child app first; --target <path> is the fallback/manual pathOn success, prints a JSON blob with:diff --git a/.trae/skills/impeccable/scripts/live/completion.mjs b/.trae/skills/impeccable/scripts/live/completion.mjsindex 986773066..6f539336d 100644--- a/.trae/skills/impeccable/scripts/live/completion.mjs+++ b/.trae/skills/impeccable/scripts/live/completion.mjs@@ -1,9 +1,18 @@+// A preview whose variants live in component modules rather than in the user's+// source. These leave no markers in the real file, so a failed accept gives the+// agent nothing to hand-edit and must be reported as a failure rather than+// reference/live.md's manual-cleanup handoff. Kept as a set: any future+// component-module preview mode belongs here the day it lands.+const PREVIEW_MODES_WITHOUT_SOURCE_MARKERS = new Set([+ 'svelte-component',+]);+export function completionTypeForAcceptResult(eventType, acceptResult) {if (eventType === 'discard') return acceptResult?.handled === true ? 'discarded' : 'error';if (acceptResult?.handled === true && acceptResult?.carbonize === true) return 'agent_done';if (acceptResult?.handled === true) return 'complete';if (acceptResult?.mode === 'error') return 'error';- if (eventType === 'accept' && acceptResult?.previewMode === 'svelte-component') return 'error';+ if (eventType === 'accept' && PREVIEW_MODES_WITHOUT_SOURCE_MARKERS.has(acceptResult?.previewMode)) return 'error';return 'agent_done';}diff --git a/.trae/skills/impeccable/scripts/live/event-validation.mjs b/.trae/skills/impeccable/scripts/live/event-validation.mjsindex 0897b1317..122c29836 100644--- a/.trae/skills/impeccable/scripts/live/event-validation.mjs+++ b/.trae/skills/impeccable/scripts/live/event-validation.mjs@@ -118,6 +118,15 @@ export function validateEvent(msg) {return 'checkpoint: paramValues must be an object';}return null;+ case 'agent_phase':+ if (!isValidId(msg.id)) return 'agent_phase: missing or malformed id';+ if (typeof msg.phase !== 'string' || !/^[a-z][a-z0-9_]{1,63}$/.test(msg.phase)) {+ return 'agent_phase: missing or malformed phase';+ }+ if (msg.durationMs !== undefined && (!Number.isFinite(msg.durationMs) || msg.durationMs < 0)) {+ return 'agent_phase: durationMs must be a non-negative number';+ }+ return null;case 'exit':return null;case 'prefetch':@@ -131,6 +140,12 @@ export function validateEvent(msg) {if (msg.message.length > 4000) return 'steer: message too long';if (msg.pageUrl !== undefined && typeof msg.pageUrl !== 'string') return 'steer: pageUrl must be string';return null;+ case 'carbonize_cleanup':+ if (!isValidId(msg.id)) return 'carbonize_cleanup: missing or malformed id';+ if (!isValidId(msg.sessionId)) return 'carbonize_cleanup: missing or malformed sessionId';+ if (!msg.file || typeof msg.file !== 'string') return 'carbonize_cleanup: missing file';+ if (!isValidVariantId(String(msg.variantId))) return 'carbonize_cleanup: missing or malformed variantId';+ return null;default:return 'Unknown event type: ' + msg.type;}diff --git a/.trae/skills/impeccable/scripts/live/generation-preflight.mjs b/.trae/skills/impeccable/scripts/live/generation-preflight.mjsnew file mode 100644index 000000000..07a5e957e--- /dev/null+++ b/.trae/skills/impeccable/scripts/live/generation-preflight.mjs@@ -0,0 +1,102 @@+import { execFile } from 'node:child_process';+import path from 'node:path';+import { promisify } from 'node:util';++const execFileAsync = promisify(execFile);+const PREFLIGHT_TIMEOUT_MS = 15_000;++export function buildGenerationPreflight(event, scriptsDir) {+ if (!event || event.type !== 'generate' || !event.id) return null;++ const isInsert = event.mode === 'insert';+ const target = isInsert ? insertTarget(event) : replaceTarget(event);+ if (!target.elementId && !target.classes) return null;++ const script = path.join(scriptsDir, isInsert ? 'live-insert.mjs' : 'live-wrap.mjs');+ const args = [script, '--id', event.id, '--count', String(event.count || 3)];+ if (isInsert) args.push('--position', target.position);+ if (target.elementId) args.push('--element-id', target.elementId);+ if (target.classes) args.push('--classes', target.classes);+ if (target.tag) args.push('--tag', target.tag);+ if (target.text) args.push('--text', target.text);+ if (!isInsert && event.pageUrl) args.push('--page-url', event.pageUrl);+ return { script, args, mode: isInsert ? 'insert' : 'replace' };+}++/**+ * Scaffold the source for a generate event before handing it to an agent.+ *+ * Async on purpose. This spawns `live-wrap.mjs`, which walks the project's+ * source tree and can take seconds (measured at ~7.6s on a large repo when the+ * element is not found, with a 15s ceiling). The live server is single-threaded+ * and calls this while leasing a poll, so a synchronous spawn froze the whole+ * server for that entire window: Accept and Discard POSTs, SSE progress+ * broadcasts, and every other poll stalled behind it.+ */+export async function runGenerationPreflight(event, {+ cwd = process.cwd(),+ scriptsDir,+ execFileImpl = execFileAsync,+ timeoutMs = PREFLIGHT_TIMEOUT_MS,+} = {}) {+ const command = buildGenerationPreflight(event, scriptsDir);+ if (!command) {+ return { ok: false, skipped: true, reason: 'insufficient_locator' };+ }++ const startedAt = performance.now();+ try {+ const { stdout } = await execFileImpl(process.execPath, command.args, {+ cwd,+ encoding: 'utf-8',+ timeout: timeoutMs,+ });+ const line = String(stdout).trim().split('\n').filter(Boolean).pop();+ if (!line) throw new Error('preflight returned no scaffold metadata');+ return {+ ok: true,+ mode: command.mode,+ durationMs: performance.now() - startedAt,+ scaffold: JSON.parse(line),+ };+ } catch (error) {+ return {+ ok: false,+ mode: command.mode,+ durationMs: performance.now() - startedAt,+ error: compactError(error),+ };+ }+}++function replaceTarget(event) {+ return normalizeTarget(event.element || {});+}++function insertTarget(event) {+ return {+ ...normalizeTarget(event.insert?.anchor || {}),+ position: event.insert?.position === 'before' ? 'before' : 'after',+ };+}++function normalizeTarget(target) {+ const classes = Array.isArray(target.classes)+ ? target.classes.join(' ')+ : String(target.classes || '').trim();+ const text = typeof target.textContent === 'string'+ ? target.textContent.trim().slice(0, 80)+ : '';+ return {+ elementId: target.id || target.elementId || undefined,+ classes: classes || undefined,+ tag: target.tagName || target.tag || undefined,+ text: text || undefined,+ };+}++function compactError(error) {+ const stderr = error?.stderr ? String(error.stderr).trim() : '';+ const message = stderr.split('\n').filter(Boolean).pop() || error?.message || 'preflight failed';+ return String(message).slice(0, 500);+}diff --git a/.trae/skills/impeccable/scripts/live/poll-lanes.mjs b/.trae/skills/impeccable/scripts/live/poll-lanes.mjsnew file mode 100644index 000000000..65f20a87a--- /dev/null+++ b/.trae/skills/impeccable/scripts/live/poll-lanes.mjs@@ -0,0 +1,14 @@+export function eventPriority(event = {}) {+ if (event.type === 'accept' || event.type === 'discard' || event.type === 'exit') return 0;+ if (event.type === 'manual_edit_apply' || event.type === 'steer' || event.type === 'carbonize_cleanup') return 1;+ if (event.type === 'generate') return 2;+ return 3;+}++export function selectAvailablePendingEvent(entries, { now = Date.now(), types = null } = {}) {+ const allowed = types instanceof Set ? types : (Array.isArray(types) ? new Set(types) : null);+ return entries+ .filter((entry) => !(entry.leaseUntil && entry.leaseUntil > now))+ .filter((entry) => !allowed || allowed.has(entry.event?.type))+ .sort((a, b) => eventPriority(a.event) - eventPriority(b.event) || a.seq - b.seq)[0] || null;+}diff --git a/.trae/skills/impeccable/scripts/live/session-store.mjs b/.trae/skills/impeccable/scripts/live/session-store.mjsindex affba67c9..9d20341dd 100644--- a/.trae/skills/impeccable/scripts/live/session-store.mjs+++ b/.trae/skills/impeccable/scripts/live/session-store.mjs@@ -1,24 +1,26 @@import fs from 'node:fs';import path from 'node:path';-import { getLegacyLiveSessionsDir, getLiveSessionsDir } from '../lib/impeccable-paths.mjs';+import { getLegacyLiveSessionsDir, getLiveSessionsDir, safeSessionId } from '../lib/impeccable-paths.mjs';const COMPLETED_PHASES = new Set(['completed', 'discarded']);+export const GENERATION_FENCED_PHASES = new Set([+ 'accept_requested',+ 'discard_requested',+ 'carbonize_required',+ 'completed',+ 'discarded',+]);export function createLiveSessionStore({ cwd = process.cwd(), sessionId } = {}) {const rootDir = getLiveSessionsDir(cwd);const legacyRootDir = getLegacyLiveSessionsDir(cwd);fs.mkdirSync(rootDir, { recursive: true });- const snapshotCache = new Map();-- function loadCachedOrRebuild(id) {- const cached = snapshotCache.get(id);- if (cached) return cached;- const journalPath = getReadableJournalPath(id);- const rebuilt = rebuildSnapshotFromJournal(journalPath, id);- snapshotCache.set(id, rebuilt);- return rebuilt;- }+ // No snapshot cache on purpose: appendEvent and getSnapshot both rebuild from+ // the journal so sequence numbers and phase fences never come from a stale+ // in-memory copy when the publisher/complete helpers append from another+ // process. A cache written but never read would grow per session for the+ // lifetime of the server without ever saving a rebuild.function getReadableJournalPath(id) {const primary = getJournalPath(rootDir, id);if (fs.existsSync(primary)) return primary;@@ -38,7 +40,10 @@ export function createLiveSessionStore({ cwd = process.cwd(), sessionId } = {})if (!fs.existsSync(journalPath) && fs.existsSync(legacyJournalPath)) {fs.copyFileSync(legacyJournalPath, journalPath);}- const prior = loadCachedOrRebuild(normalized.id);+ // Publisher/complete helpers can append from a separate process while+ // the server is alive. Rebuild here so sequence numbers and phase+ // fences never come from a stale in-memory cache.+ const prior = rebuildSnapshotFromJournal(getReadableJournalPath(normalized.id), normalized.id);const seq = prior.nextSeq;const entry = {seq,@@ -49,7 +54,6 @@ export function createLiveSessionStore({ cwd = process.cwd(), sessionId } = {})};fs.appendFileSync(journalPath, JSON.stringify(entry) + '\n');const next = applyEvent(prior.snapshot, entry, prior.diagnostics);- snapshotCache.set(normalized.id, { snapshot: next, diagnostics: next.diagnostics || [], nextSeq: seq + 1 });writeSnapshot(snapshotPath, next);return next;},@@ -58,7 +62,6 @@ export function createLiveSessionStore({ cwd = process.cwd(), sessionId } = {})const journalPath = getReadableJournalPath(id);const snapshotPath = getSnapshotPath(rootDir, id);const rebuilt = rebuildSnapshotFromJournal(journalPath, id);- snapshotCache.set(id, rebuilt);writeSnapshot(snapshotPath, rebuilt.snapshot);if (!opts.includeCompleted && COMPLETED_PHASES.has(rebuilt.snapshot.phase)) return null;return rebuilt.snapshot;@@ -95,11 +98,6 @@ function getSnapshotPath(rootDir, id) {return path.join(rootDir, safeSessionId(id) + '.snapshot.json');}-function safeSessionId(id) {- if (!/^[A-Za-z0-9_-]{1,128}$/.test(id)) throw new Error('invalid session id: ' + id);- return id;-}-function baseSnapshot(id) {return {id,@@ -116,9 +114,18 @@ function baseSnapshot(id) {pendingEvent: null,deliveryLease: null,checkpointRevision: 0,+ browserCheckpointRevision: 0,+ publicationCheckpointRevision: 0,activeOwner: null,sourceMarkers: {},fallbackMode: null,+ generationPhase: null,+ generationCompletedAt: null,+ generationTimings: {},+ variantPlan: null,+ generationCanceled: false,+ generationCanceledAt: null,+ cancelReason: null,annotationArtifacts: [],diagnostics: [],updatedAt: null,@@ -158,6 +165,8 @@ function applyEvent(snapshot, entry, inheritedDiagnostics = []) {...snapshot,paramValues: { ...(snapshot.paramValues || {}) },sourceMarkers: { ...(snapshot.sourceMarkers || {}) },+ generationTimings: { ...(snapshot.generationTimings || {}) },+ variantPlan: snapshot.variantPlan || null,annotationArtifacts: [...(snapshot.annotationArtifacts || [])],diagnostics: [...(snapshot.diagnostics || [])],updatedAt: entry.ts || new Date().toISOString(),@@ -174,11 +183,48 @@ function applyEvent(snapshot, entry, inheritedDiagnostics = []) {next.expectedVariants = event.count ?? next.expectedVariants;next.pendingEventSeq = entry.seq ?? next.pendingEventSeq;next.pendingEvent = toPendingEvent(event);+ next.variantPlan = null;if (event.screenshotPath) upsertArtifact(next.annotationArtifacts, { type: 'screenshot', path: event.screenshotPath });break;+ case 'variant_plan':+ if (!next.generationCanceled && !GENERATION_FENCED_PHASES.has(next.phase)) {+ next.variantPlan = event.plan ?? next.variantPlan;+ }+ break;+ case 'detector_waivers':+ if (!next.generationCanceled && !GENERATION_FENCED_PHASES.has(next.phase)) {+ next.detectorWaivers = [+ ...(next.detectorWaivers || []),+ ...(Array.isArray(event.waivers) ? event.waivers : []),+ ];+ }+ break;+ case 'agent_phase':+ next.generationPhase = event.phase ?? next.generationPhase;+ if (event.phase) {+ next.generationTimings[event.phase] = {+ at: event.at ?? (Date.parse(entry.ts || '') || null),+ durationMs: event.durationMs ?? null,+ };+ }+ break;case 'variants_ready':case 'agent_done':+ if ((next.generationCanceled || GENERATION_FENCED_PHASES.has(next.phase))+ && !(event.type === 'agent_done' && event.carbonize === true && next.phase === 'accept_requested')) {+ next.diagnostics.push({+ error: 'late_generation_event_ignored',+ type: event.type,+ phase: next.phase,+ });+ break;+ }next.phase = event.carbonize === true ? 'carbonize_required' : 'variants_ready';+ // Durable completion marker: later browser checkpoints (a resumed page+ // reporting phase "generating") regress `phase`, but generation staying+ // finished is monotone — the live server keys missed-`done` redelivery+ // on this field.+ next.generationCompletedAt = event.at ?? (Date.parse(entry.ts || '') || Date.now());next.sourceFile = event.sourceFile ?? event.file ?? next.sourceFile;next.previewFile = event.previewFile ?? next.previewFile;next.previewMode = event.previewMode ?? next.previewMode;@@ -194,27 +240,45 @@ function applyEvent(snapshot, entry, inheritedDiagnostics = []) {}break;case 'checkpoint':- if (COMPLETED_PHASES.has(next.phase)) {+ if (next.generationCanceled || GENERATION_FENCED_PHASES.has(next.phase)) {next.diagnostics.push({ error: 'checkpoint_after_terminal_ignored', phase: event.phase ?? null, revision: event.revision ?? null });break;}- if ((event.revision ?? 0) >= (next.checkpointRevision ?? 0)) {- next.phase = event.phase ?? next.phase;- next.checkpointRevision = event.revision ?? next.checkpointRevision;- next.activeOwner = event.owner ?? next.activeOwner;- next.arrivedVariants = event.arrivedVariants ?? next.arrivedVariants;- next.visibleVariant = event.visibleVariant ?? next.visibleVariant;- next.sourceFile = event.sourceFile ?? next.sourceFile;- next.previewFile = event.previewFile ?? next.previewFile;- next.previewMode = event.previewMode ?? next.previewMode;- if (event.paramValues) next.paramValues = { ...event.paramValues };- } else {- next.diagnostics.push({ error: 'stale_checkpoint_ignored', revision: event.revision });+ {+ const revisionDomain = event.revisionDomain === 'publication'+ || (event.reason === 'variants_progress' && !event.owner)+ ? 'publication'+ : 'browser';+ const revisionField = revisionDomain === 'publication'+ ? 'publicationCheckpointRevision'+ : 'browserCheckpointRevision';+ const currentRevision = next[revisionField]+ ?? (revisionDomain === 'browser' ? next.checkpointRevision : 0)+ ?? 0;+ if ((event.revision ?? 0) >= currentRevision) {+ next.phase = event.phase ?? next.phase;+ next[revisionField] = event.revision ?? currentRevision;+ if (revisionDomain === 'browser') {+ next.checkpointRevision = event.revision ?? next.checkpointRevision;+ next.activeOwner = event.owner ?? next.activeOwner;+ }+ next.arrivedVariants = event.arrivedVariants ?? next.arrivedVariants;+ if (revisionDomain === 'browser') next.visibleVariant = event.visibleVariant ?? next.visibleVariant;+ next.sourceFile = event.sourceFile ?? next.sourceFile;+ next.previewFile = event.previewFile ?? next.previewFile;+ next.previewMode = event.previewMode ?? next.previewMode;+ if (revisionDomain === 'browser' && event.paramValues) next.paramValues = { ...event.paramValues };+ } else {+ next.diagnostics.push({ error: 'stale_checkpoint_ignored', revision: event.revision, revisionDomain });+ }}break;case 'accept':case 'accept_intent':next.phase = 'accept_requested';+ next.generationCanceled = true;+ next.generationCanceledAt = event.at ?? (Date.parse(entry.ts || '') || Date.now());+ next.cancelReason = 'accept';next.visibleVariant = Number(event.variantId ?? next.visibleVariant);if (event.paramValues) next.paramValues = { ...event.paramValues };next.pendingEventSeq = entry.seq ?? next.pendingEventSeq;@@ -232,6 +296,12 @@ function applyEvent(snapshot, entry, inheritedDiagnostics = []) {next.pendingEventSeq = entry.seq ?? next.pendingEventSeq;next.pendingEvent = toPendingEvent(event);break;+ case 'carbonize_cleanup':+ next.phase = 'carbonize_cleanup_requested';+ next.sourceFile = event.file ?? next.sourceFile;+ next.pendingEventSeq = entry.seq ?? next.pendingEventSeq;+ next.pendingEvent = toPendingEvent(event);+ break;case 'steer_done':next.phase = 'steer_done';next.sourceFile = event.sourceFile ?? event.file ?? next.sourceFile;@@ -243,6 +313,9 @@ function applyEvent(snapshot, entry, inheritedDiagnostics = []) {break;case 'discard':next.phase = 'discard_requested';+ next.generationCanceled = true;+ next.generationCanceledAt = event.at ?? (Date.parse(entry.ts || '') || Date.now());+ next.cancelReason = 'discard';next.pendingEventSeq = entry.seq ?? next.pendingEventSeq;next.pendingEvent = toPendingEvent(event);break;@@ -260,6 +333,10 @@ function applyEvent(snapshot, entry, inheritedDiagnostics = []) {next.pendingEvent = null;break;case 'agent_error':+ if (next.generationCanceled && event.sourceEventType === 'generate') {+ next.diagnostics.push({ error: 'late_generation_event_ignored', type: event.type, phase: next.phase });+ break;+ }next.phase = 'agent_error';next.pendingEventSeq = null;next.pendingEvent = null;diff --git a/.trae/skills/impeccable/scripts/live/source-lock.mjs b/.trae/skills/impeccable/scripts/live/source-lock.mjsnew file mode 100644index 000000000..9ccc557be--- /dev/null+++ b/.trae/skills/impeccable/scripts/live/source-lock.mjs@@ -0,0 +1,105 @@+import fs from 'node:fs';+import path from 'node:path';+import { createHash, randomUUID } from 'node:crypto';+import { getLiveDir, isLiveServerPidReachable } from '../lib/impeccable-paths.mjs';++// Only used to retire a lock whose contents we cannot read (empty or truncated+// by a crash mid-write). A readable lock's fate is decided by its owner's+// liveness instead, so a slow critical section is never swept.+const UNREADABLE_LOCK_STALE_MS = 60_000;++export function sourceLockPath(file, cwd = process.cwd()) {+ const digest = createHash('sha256').update(path.resolve(cwd, file)).digest('hex').slice(0, 24);+ return path.join(getLiveDir(cwd), 'locks', digest + '.lock');+}++export function withSourceLockSync(file, owner, fn, {+ cwd = process.cwd(),+ waitMs = 0,+ retryMs = 5,+} = {}) {+ const lockPath = sourceLockPath(file, cwd);+ fs.mkdirSync(path.dirname(lockPath), { recursive: true });+ const deadline = Date.now() + Math.max(0, Number(waitMs) || 0);+ // Identifies this acquisition specifically, so release can tell our own lock+ // from a replacement that some other writer created.+ const token = randomUUID();+ let acquired = false;++ while (!acquired) {+ clearStaleLock(lockPath);+ let fd;+ try {+ fd = fs.openSync(lockPath, 'wx');+ fs.writeFileSync(fd, JSON.stringify({+ owner,+ token,+ pid: process.pid,+ at: Date.now(),+ file: path.resolve(cwd, file),+ }) + '\n');+ acquired = true;+ } catch (error) {+ if (error?.code !== 'EEXIST') throw error;+ if (Date.now() >= deadline) {+ const locked = new Error('source_locked');+ locked.code = 'SOURCE_LOCKED';+ locked.lockPath = lockPath;+ throw locked;+ }+ sleepSync(Math.max(1, Math.min(Number(retryMs) || 5, deadline - Date.now())));+ } finally {+ try { if (fd !== undefined) fs.closeSync(fd); } catch {}+ }+ }++ try {+ return fn();+ } finally {+ releaseOwnLock(lockPath, token);+ }+}++function sleepSync(ms) {+ Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, ms);+}++function readLock(lockPath) {+ try { return JSON.parse(fs.readFileSync(lockPath, 'utf-8')); } catch { return null; }+}++/**+ * Remove the lock only if it is still the one this call created. If a sweeper+ * judged our lock stale and another writer replaced it, unlinking here would+ * end *their* critical section and admit a third writer to the same file.+ */+function releaseOwnLock(lockPath, token) {+ const held = readLock(lockPath);+ if (held && held.token !== token) return;+ try { fs.unlinkSync(lockPath); } catch {}+}++/**+ * A lock is stale when its owner is gone, not when it is old.+ *+ * Age alone cuts both ways: it sweeps a live holder whose critical section+ * outran the timeout (a suspended laptop, a stopped process), letting two+ * writers into the same source file, while still making every accept on a+ * crashed holder's file wait out the full timeout. Asking the OS whether the+ * recorded pid is alive answers both correctly: a dead owner releases at once,+ * and a live owner keeps its lock however long it needs.+ */+function clearStaleLock(lockPath) {+ const held = readLock(lockPath);+ if (!held) {+ // Unreadable: either a crash truncated it, or we caught the brief window+ // between create and write in a live acquisition. mtime distinguishes them.+ try {+ const stat = fs.statSync(lockPath);+ if (Date.now() - stat.mtimeMs > UNREADABLE_LOCK_STALE_MS) fs.unlinkSync(lockPath);+ } catch { /* gone already */ }+ return;+ }+ if (typeof held.pid === 'number' && isLiveServerPidReachable(held.pid)) return;+ try { fs.unlinkSync(lockPath); } catch {}+}diff --git a/plugin/skills/impeccable/reference/live.md b/plugin/skills/impeccable/reference/live.mdindex 8c2cccd0a..295ae28fc 100644--- a/plugin/skills/impeccable/reference/live.md+++ b/plugin/skills/impeccable/reference/live.md@@ -10,21 +10,24 @@ Execute in order. No step skipped, no step reordered.1. `live.mjs`: boot. If the request names or implies a file, route, or app inside a monorepo, infer the concrete path and run `node .claude/skills/impeccable/scripts/live.mjs --target <path>` instead; then run the rest of this live session from the returned `projectRoot`.2. Open the app URL that serves `pageFile` (infer from `package.json`, docs, terminal output, or an open tab). Never use `serverPort`; it's the helper, not the app. **Cursor:** `browser_navigate` to that URL before polling; do not skip. **Other harnesses:** use the available browser tool; if the URL is uncertain, ask the user once.-3. Poll loop with the default long timeout (600000 ms). After every event or `--reply`, run `live-poll.mjs` again immediately. Never pass a short `--timeout=`.+3. Poll loop with the default long timeout (600000 ms). Run `live-poll.mjs` again immediately after every event or `--reply`; Codex runs this one-shot poll in the foreground. Never pass a short `--timeout=`.The global bar **Impeccable mark** dims and shows a pulsing amber dot when no agent is long-polling `/poll`. Hover the mark for the hint; restart `live-poll.mjs` to reconnect.-4. On `generate`: read screenshot if present; load the action's reference; plan three distinct directions; write all variants in one edit; `--reply done`; poll again.+4. On `generate`: reuse `event.scaffold` when present; read the screenshot if present; load the action's reference; deliver variants using the delivery policy below; `--reply done`; poll again. Generate in this thread. You already hold the project's tokens, conventions, and file layout; that context is the job, not overhead.5. On `steer`: read the message and `pageUrl`; do the work (page edits, navigation help, or a short reply in the `--reply` message); `--reply steer_done`; poll again. No pickup ack. The Steer bar unlocks when `steer_done` arrives over SSE.-6. On `accept` / `discard`: the poll script runs `live-accept.mjs`, acknowledges the delivered event, and prints `_completionAck`. Plain accepts/discards are terminal immediately; carbonize accepts remain recoverable until you finish cleanup, run `live-complete.mjs --id EVENT_ID`, and only then poll again.+6. On `accept` / `discard`: the poll script runs `live-accept.mjs`, acknowledges the delivered event, and prints `_completionAck`. Plain accepts/discards are terminal immediately. Carbonize accepts remain recoverable until the foreground task runs `live-complete.mjs --id EVENT_ID`; finish that cleanup before polling again.7. If interrupted, run `live-status.mjs` or `live-resume.mjs` before guessing. The durable journal replays unacknowledged work after helper restart.8. On `exit`: run the cleanup at the bottom.Harness policy:-- **Claude Code**: run the poll as a **background task** (no short timeout). The harness notifies you when it completes, so the main conversation stays free. Do not block the shell.+- **Claude Code**: run the poll as a **background task** (no short timeout). The harness notifies you when it completes, so the main conversation stays free while you generate and publish in it. Do not block the shell.- **Cursor**: run **one-shot** poll in a **background terminal** with notify on `"type":"(steer|generate|accept|discard|exit)"`. After each event the poll exits; handle it, `--reply`, then start `live-poll.mjs` again. Do **not** use `--stream` on Cursor: incremental stdout notify is slower in practice than exit-based notify (~5s vs sub-second in testing).-- **Codex**: run the poll in the **foreground** (blocking shell; not a background task, not a subagent). Codex background exec sessions do not reliably surface poll stdout back into the conversation at the moment events arrive, so a "fire-and-forget" background poll will stall live mode.+- **Codex**: run the default one-shot poll in a **yielded foreground exec session**. Do not suffix it with `&`, use `--stream`, or leave Live without an active foreground poll. Handle every event in the main task; after each handler/reply, restart the foreground poll.- **Other harnesses**: one-shot foreground unless you know stdout reliably returns to this session when a shell exits.+Generation delivery policy:+- **Default (Cursor and other harnesses):** keep the established atomic single-edit delivery. Do not switch a harness to progressive until its poll loop is known not to block on the extra publish calls. This avoids trading model latency for extra tool-call latency on harnesses with different streaming behavior.+Chat is overhead. No recap, no tutorial output, no pasting PRODUCT / DESIGN bodies. Spend tokens on tools and edits; on failure, one or two short sentences.## Start@@ -92,14 +95,14 @@ Server restart rule: start `live-server.mjs` again, then poll. Startup requeues**Insert mode** (`event.mode === "insert"`): `{id, mode: "insert", count, pageUrl, insert: { position, anchor }, placeholder: { width, height }, freeformPrompt?, screenshotPath?, comments?, strokes?}`. No `action`. Requires a non-empty `freeformPrompt` **or** annotations. Screenshot is sent only when annotations exist (same rule as replace). Use `placeholder` dimensions as a soft size hint for net-new content.-Speed matters; the user is watching a spinner. Minimize tool calls by using the wrap/insert helper and writing all variants in a single edit.+Speed matters; the user is watching the selected element. Reuse server preflight metadata when available, minimize discovery calls, and follow the harness-specific delivery policy above.### Insert mode branchWhen `event.mode === "insert"`:1. Read the screenshot if `event.screenshotPath` is present (annotations only).-2. Run the insert helper instead of wrap:+2. If `event.scaffold` is present, use it as the insert-helper result and do **not** run the helper again. Otherwise run the insert helper instead of wrap:```bashnode .claude/skills/impeccable/scripts/live-insert.mjs --id EVENT_ID --count EVENT_COUNT --position after \@@ -109,7 +112,7 @@ node .claude/skills/impeccable/scripts/live-insert.mjs --id EVENT_ID --count EVE- `--position` ← `event.insert.position` (`before` | `after`)- Anchor flags ← `event.insert.anchor` (same mapping as wrap: id, classes, tag, text)-The scaffold has **no** `data-impeccable-variant="original"`. Variants are net-new HTML+CSS inserted at `insertLine`. Load `brand.md` or `product.md` (freeform only, no action sub-command). Write all variants in one edit, then `--reply done`.+The scaffold has **no** `data-impeccable-variant="original"`. Variants are net-new HTML+CSS inserted at `insertLine`. Load `brand.md` or `product.md` (freeform only, no action sub-command). Deliver using the harness policy, then `--reply done`.For Svelte/SvelteKit targets, `live-insert.mjs` returns `previewMode: "svelte-component"` with `mode: "insert"`, `file` pointing at a temporary `node_modules/.impeccable-live/<id>/manifest.json`, `componentDir` pointing at the variant component files, and `sourceFile` pointing at the real `.svelte` route. Write each inserted variant as a real Svelte component (`v1.svelte`, `v2.svelte`, …) under `componentDir`. Insert variants must be non-empty net-new content with a single top-level root, no `data-impeccable-*` attributes, and CSS in each component's `<style>` block. Do **not** edit the route source during generation; the browser mounts the temporary component before/after the live anchor while the user cycles variants. On Accept, `live-accept.mjs` inserts the selected component markup into `sourceFile` immediately and deletes the temp session after the source write succeeds.@@ -134,6 +137,8 @@ Reading annotations precisely:### 2. Wrap the element+When `event.scaffold` is present, the local helper already found and wrapped the source before the poll returned. Treat `event.scaffold` as the successful helper output and skip this command entirely. `event.scaffoldAttempted` with `scaffoldError` means local preflight could not finish; use the command/fallback path below. This optimization removes a deterministic tool round trip without changing the generated design.+```bashnode .claude/skills/impeccable/scripts/live-wrap.mjs --id EVENT_ID --count EVENT_COUNT --element-id "ELEMENT_ID" --classes "class1,class2" --tag "div" --text "TEXT_SNIPPET"```@@ -153,7 +158,7 @@ Output on success: `{ file, insertLine, commentSyntax, styleMode, styleTag, cssSFor Svelte/SvelteKit targets, `live-wrap.mjs` returns `previewMode: "svelte-component"` with `file` pointing at a temporary `node_modules/.impeccable-live/<id>/manifest.json`, `componentDir` pointing at the variant component files, and `sourceFile` pointing at the real `.svelte` route. Write each variant as a real Svelte component (`v1.svelte`, `v2.svelte`, …) under `componentDir`; use the `propContract` prop names for dynamic text (`{propName}`), not literal snapshot strings. Put variant CSS in each component's `<style>` block with semantic class selectors (no `@scope`, no `data-impeccable-*`). Reply with `--file` set to the manifest path; the browser dynamically imports and mounts the compiled components so Svelte HMR does not reset page state while the user cycles variants. On Accept, `live-accept.mjs` inlines the accepted component back into `sourceFile` immediately after source promotion succeeds.-**Params on the Svelte component path go in a sidecar, never as an attribute.** Svelte parses `{` inside an attribute value as the start of an expression, so a `data-impeccable-params='[{…}]'` attribute on a component element fails to compile (`Expected token }`). Declare params for this path in `componentDir/params.json`, keyed by variant number, using the exact param schema from section 7:+**Params on component-preview paths go in a sidecar, never as an attribute.** Svelte parses `{` inside an attribute value as the start of an expression, and both Svelte/Vue previews mount without an HTML variant wrapper. Declare params in `componentDir/params.json`, keyed by variant number, using the exact param schema from section 7:```json{@@ -291,11 +296,13 @@ In **departure mode**, the prompt narrows the lanes you draw from, not the familWhen the prompt and PRODUCT.md anti-references conflict (the prompt asks for X, the anti-references ban X), the anti-references win; they describe the brand's standing position, the prompt is one moment.-### 6. Write all variants in a single edit+### 6. Deliver variantsComplete HTML replacement of the original element for each variant, not a CSS-only patch. Consider the element's context (computed styles, parent structure, CSS variables from `event.element`).-Write CSS + all variants in ONE edit at the `insertLine` reported by `wrap`. Colocate CSS as a `<style>` tag inside the variant wrapper; `<style>` works anywhere in modern browsers and this ensures CSS and HTML arrive atomically (no FOUC).+Colocate preview CSS as a `<style>` tag inside the variant wrapper; `<style>` works anywhere in modern browsers and keeps each delivered state internally complete (no FOUC).++**Atomic default:** write CSS + all variants + parameter manifests in one edit at `insertLine`, preserving the established behavior.Use the `cssAuthoring` object returned by `live-wrap.mjs` to author the temporary preview CSS. The style opening tag shown below is the common case; replace it with `cssAuthoring.styleTag` when the tool returns a different one. The variant markup shape is otherwise stable:@@ -319,7 +326,7 @@ Use the `cssAuthoring` object returned by `live-wrap.mjs` to author the temporarThe first variant has no `display: none` (visible by default). All others do. If variants use only inline styles and no preview CSS, omit the `<style>` tag entirely.-One edit, all variants; the browser's MutationObserver picks everything up in one pass.+The browser's MutationObserver accepts either delivery shape. On the transactional progressive path it shows arrived variants and pending dots immediately; Accept and Discard are available as soon as one variant exists. Accepting an arrived variant fences the worker before the browser releases the picker, so later publications are rejected.For `styleMode: "scoped"`, author every `:scope` rule with a descendant combinator. The `@scope` boundary is the **variant wrapper `<div data-impeccable-variant="N">`**, not the element you're designing. A bare `:scope { background: cream; }` styles the wrapper, not the inner replacement, so the cream lands on a `display: contents` shell while the actual element keeps page defaults. Always step in: `:scope > .card`, `:scope > section`, `:scope .hero-title`, etc. The fake test agent's CSS in `tests/live-e2e/agent.mjs` is a faithful template; every scoped rule starts `:scope > ...`.@@ -361,7 +368,7 @@ Each variant can expose **coarse** knobs alongside the full HTML/CSS replacement**Hard cap per variant**: at most **four** parameters so the panel stays legible; rare fifth only if the reference explicitly allows it.-**How to declare.** Put a JSON manifest on the variant wrapper (HTML/JSX path). **On the Svelte `svelte-component` path, do not use this attribute** (Svelte can't compile `{` inside an attribute value). Declare params in `componentDir/params.json` keyed by variant number instead (see the Svelte component paragraph in the wrap section). The param schema below is identical for both paths.+**How to declare.** Put a JSON manifest on the variant wrapper (HTML/JSX path). **On the `svelte-component` path, do not use this attribute.** Declare params in `componentDir/params.json` keyed by variant number instead (see the component-preview paragraphs in the wrap section). The param schema below is identical for every path.```html<div data-impeccable-variant="1" data-impeccable-params='[@@ -462,15 +469,19 @@ Event: `{id, variantId, _acceptResult, _completionAck}`. The poll script already- The accept event includes `pageUrl`; the poll script must forward it to `live-accept.mjs --page-url PAGE_URL` so accept-time cleanup only scrubs staged copy edits for the current page.- `_completionAck.ok !== true`: do not poll yet. Run `live-status.mjs` / `live-resume.mjs`, complete the cleanup manually if needed, then run `live-complete.mjs --id EVENT_ID`.- `_acceptResult.handled: true` and `carbonize: false`: nothing to do. Poll again.-- `_acceptResult.handled: true` and `carbonize: true`: **post-accept cleanup is required before the next poll.** See the "Required after accept (carbonize)" section below. The `event._acceptResult.todo` field, `_completionAck.requiresComplete`, and a stderr banner all point at this required follow-up; none are decorative. After cleanup, run `live-complete.mjs --id EVENT_ID`, then poll again.+- `_acceptResult.handled: true` and `carbonize: true`: post-accept cleanup is required, but it must not stall Codex's control lane. See "Required after accept (carbonize)" below. The `event._acceptResult.todo` field, `_completionAck.requiresComplete`, and stderr banner all point at this required follow-up; none are decorative.- `_acceptResult.handled: false, mode: "fallback"`: the session lived in a generated file and the script refused to persist there. You've already written the accepted variant into true source during Handle fallback Step 3; just clean up the temporary wrapper in the served file if any, and poll again.+- `_acceptResult.handled: false, mode: "error"`: the operation genuinely failed. **Do not hand-edit the file**; the source was not touched and editing it yourself would either double-apply or race whoever holds it.+ - `error: "source_locked"`: a generation publish holds the file. Run the same `live-accept.mjs` command again; it is idempotent and will succeed once the publisher releases. Do not poll past it.+ - `error: "accept_receipt_conflict"`: this session already resolved as `priorOperation` (on `priorVariantId` for an accept), so the request contradicts durable truth. Do not edit. Run `live-status.mjs` and tell the user what the session actually resolved to.+ - anything else: report the error briefly and run `live-status.mjs` before continuing.- `_acceptResult.handled: false` without `mode`: manual cleanup: read file, find markers, edit.### Required after accept (carbonize)When `_acceptResult.carbonize === true`, the accepted variant was stitched into source with helper markers and inline CSS so the browser can render it immediately with no visual gap. That stitch-in is **temporary**. The agent must rewrite it into permanent form before doing anything else. Skipping this leaves dead `@scope` rules for unaccepted variants, a pointless `data-impeccable-variant` wrapper, and `impeccable-carbonize-start/end` comment noise in the source file; all of which accumulate across sessions.-Do these five steps in the current thread, synchronously, before the next poll. Do not poll again until the file is clean.+Do these five steps synchronously before the next poll. The source lock, generation epoch, and expected-source hash remain the final safety gates against a generator finishing concurrently with Accept.1. **Locate the carbonize block** in the source file (`_acceptResult.file`). It's bracketed by `<!-- impeccable-carbonize-start SESSION_ID -->` and `<!-- impeccable-carbonize-end SESSION_ID -->` and contains a `<style data-impeccable-css="SESSION_ID">` element. If the variant declared parameters, an `<!-- impeccable-param-values SESSION_ID: {...} -->` comment sits alongside the style tag with the user's chosen values; read it first; it drives steps 3 and 4 below.2. **Move the CSS rules** into the project's real stylesheet. Which stylesheet depends on the project (e.g. `site/styles/workflow.css` for an Astro project, or the component's co-located CSS file for a Vite/Next project; pick whichever already owns styling for the surrounding element).@@ -478,9 +489,7 @@ Do these five steps in the current thread, synchronously, before the next poll.4. **Unwrap the accepted content.** Delete the inner `<div data-impeccable-variant="N" style="display: contents">` that wraps it. On JSX/TSX, also delete the outer `<div data-impeccable-carbonize="SESSION_ID" style={{ display: 'contents' }}>` wrapper if present (accept adds it so ternary/`return` slots keep a single root). Drop `data-impeccable-params` and any `data-p-*` attributes; those are live-mode plumbing, not source.5. **Delete the inline `<style>` block, the `<!-- impeccable-param-values -->` comment if present, and both `<!-- impeccable-carbonize-start/end -->` markers.** Also drop any `@scope` rules for variants other than the accepted one; those are dead code now.-After the file is clean, run `live-complete.mjs --id SESSION_ID`, verify it reports `phase: "completed"`, then poll again.--A background agent may be used for the rewrite, but the current thread is responsible for verifying the five steps are complete before issuing the next poll. In practice, inline is usually faster and less error-prone.+After the file is clean, the cleanup owner runs `live-complete.mjs --id SESSION_ID` and verifies `phase: "completed"`. Poll again only after that verification.## Handle `discard`diff --git a/plugin/skills/impeccable/scripts/lib/impeccable-paths.mjs b/plugin/skills/impeccable/scripts/lib/impeccable-paths.mjsindex 2ccbe7b74..99956c0f3 100644--- a/plugin/skills/impeccable/scripts/lib/impeccable-paths.mjs+++ b/plugin/skills/impeccable/scripts/lib/impeccable-paths.mjs@@ -104,6 +104,20 @@ export function removeLiveServerInfo(cwd = process.cwd(), options = {}) {}}+/**+ * Session IDs become path segments (journals, snapshots, accept receipts,+ * preview manifests, generated component dirs). They arrive from CLI `--id`+ * arguments and HTTP payloads, so anything containing a separator or `..` must+ * be rejected before it reaches path.join, which would happily escape+ * `.impeccable/live/`. Real IDs are 8 hex chars; the tests use short slugs.+ */+export function safeSessionId(id) {+ if (typeof id !== 'string' || !/^[A-Za-z0-9_-]{1,128}$/.test(id)) {+ throw new Error('invalid session id: ' + id);+ }+ return id;+}+export function getLiveSessionsDir(cwd = process.cwd(), options = {}) {return path.join(getLiveDir(cwd, options), 'sessions');}diff --git a/plugin/skills/impeccable/scripts/live-accept.mjs b/plugin/skills/impeccable/scripts/live-accept.mjsindex 278dfbb2e..453ddea35 100644--- a/plugin/skills/impeccable/scripts/live-accept.mjs+++ b/plugin/skills/impeccable/scripts/live-accept.mjs@@ -16,7 +16,9 @@import fs from 'node:fs';import path from 'node:path';import { isGeneratedFile } from './lib/is-generated.mjs';+import { IMPECCABLE_DIR, getLiveDir, safeSessionId } from './lib/impeccable-paths.mjs';import { readBuffer as readManualEditsBuffer, writeBuffer as writeManualEditsBuffer } from './live/manual-edits-buffer.mjs';+import { withSourceLockSync } from './live/source-lock.mjs';import {applyDeferredSvelteComponentAccepts,findSvelteComponentManifest,@@ -25,6 +27,46 @@ import {} from './live/svelte-component.mjs';const EXTENSIONS = ['.html', '.jsx', '.tsx', '.vue', '.svelte', '.astro'];+const ACCEPT_LOCK_WAIT_MS = 1_000;+// Mirrors VARIANT_ID_PATTERN in live/event-validation.mjs, which gates the same+// value arriving over HTTP.+const VARIANT_NUM_PATTERN = /^[0-9]{1,3}$/;++/**+ * A thrown accept/discard is a real failure, not a manual handoff.+ *+ * live/completion.mjs only classifies a result as `error` when it carries+ * `mode: 'error'`; anything else unhandled falls through to `agent_done` with a+ * successful ack, and reference/live.md then tells the agent to finish the edit+ * by hand. That is right for the documented fallback paths and wrong here: a+ * `source_locked` contention needs a retry (hand-editing races the publisher+ * holding the lock), and a crash needs surfacing, not a hand-applied guess.+ */+function operationFailure(err, extra = {}) {+ return { handled: false, mode: 'error', error: err.message, ...extra };+}++/**+ * Mark an unhandled preview-path result as a real failure.+ *+ * operationFailure only covers results built from a *thrown* error. The accept+ * implementations also return `{handled: false, error}` for their own checks+ * (variant missing, template empty, original text ambiguous), and those arrived+ * without `mode`, so completion.mjs classified them as agent_done and+ * reference/live.md routed the agent to "read file, find markers, edit".+ *+ * That handoff only makes sense for a plain wrapper session, which is the one+ * shape with markers in the user's source to edit. Component and isolated+ * artifact previews keep the source clean until Accept, so there is nothing to+ * hand-edit and an unhandled result is always a failure. `previewMode` is+ * exactly that discriminator: only the preview branches set it.+ */+function markPreviewFailure(result) {+ if (result?.handled === false && !result.mode && result.previewMode) {+ return { ...result, mode: 'error' };+ }+ return result;+}// ---------------------------------------------------------------------------// CLI@@ -63,7 +105,52 @@ Output (JSON):const isDiscard = args.includes('--discard');if (!id) { console.error('Missing --id'); process.exit(1); }+ // `id` becomes a path segment (accept receipts, preview manifests, generated+ // component dirs). Reject separators and traversal here so one check covers+ // every downstream sink.+ try { safeSessionId(id); } catch { console.error('Invalid --id'); process.exit(1); }if (!isDiscard && !variantNum) { console.error('Need --discard or --variant N'); process.exit(1); }+ // `variantNum` is interpolated into a RegExp and into the markup written back+ // to source. The browser and the /events schema both constrain it to digits;+ // enforce the same here, or `--variant '.*'` matches the `original` block+ // first and silently accepts the original while reporting success.+ if (!isDiscard && !VARIANT_NUM_PATTERN.test(variantNum)) {+ console.error('Invalid --variant');+ process.exit(1);+ }++ const requestedOperation = isDiscard ? 'discard' : 'accept';+ const priorReceipt = readAcceptReceipt(process.cwd(), id);+ if (priorReceipt) {+ const sameOperation = priorReceipt.operation === requestedOperation+ && (isDiscard || String(priorReceipt.variantId) === String(variantNum));+ console.log(JSON.stringify(sameOperation+ ? { ...priorReceipt.result, handled: true, alreadyApplied: true }+ : {+ // mode: 'error' is what marks this a real failure rather than a manual+ // handoff. Without it, live/completion.mjs classifies the reply as+ // agent_done and reference/live.md tells the agent to "read file, find+ // markers, edit" by hand — which would apply a second, conflicting+ // accept on top of the one the receipt already recorded.+ handled: false,+ mode: 'error',+ error: 'accept_receipt_conflict',+ priorOperation: priorReceipt.operation,+ priorVariantId: priorReceipt.variantId ?? null,+ }));+ return;+ }+ const emitResult = (rawResult) => {+ const result = markPreviewFailure(rawResult);+ if (result?.handled !== false) {+ writeAcceptReceipt(process.cwd(), id, {+ operation: requestedOperation,+ variantId: isDiscard ? null : String(variantNum),+ result,+ });+ }+ console.log(JSON.stringify(result));+ };let paramValues = null;if (paramValuesRaw) {@@ -82,39 +169,55 @@ Output (JSON):if (svelteComponentManifest) {if (isDiscard) {- removeSvelteComponentSession(id, process.cwd());- console.log(JSON.stringify({- handled: true,+ let result;+ try {+ result = withSourceLockSync(+ path.resolve(process.cwd(), svelteComponentManifest.sourceFile),+ 'discard:' + id,+ () => {+ removeSvelteComponentSession(id, process.cwd());+ return { handled: true };+ },+ { waitMs: ACCEPT_LOCK_WAIT_MS },+ );+ } catch (err) {+ result = operationFailure(err);+ }+ emitResult({+ ...result,file: svelteComponentManifest.sourceFile,carbonize: false,previewMode: 'svelte-component',componentDir: svelteComponentManifest.componentDir,- }));+ });return;}let result;try {- result = inlineSvelteComponentAccept(- svelteComponentManifest,- variantNum,- paramValues,- process.cwd(),+ result = withSourceLockSync(+ path.resolve(process.cwd(), svelteComponentManifest.sourceFile),+ 'accept:' + id,+ () => inlineSvelteComponentAccept(+ svelteComponentManifest,+ variantNum,+ paramValues,+ process.cwd(),+ ),+ { waitMs: ACCEPT_LOCK_WAIT_MS },);} catch (err) {- result = {- handled: false,- error: err.message,+ result = operationFailure(err, {file: svelteComponentManifest.sourceFile,sourceFile: svelteComponentManifest.sourceFile,previewMode: 'svelte-component',componentDir: svelteComponentManifest.componentDir,- };+ });}if (result.carbonize) {result.todo = 'REQUIRED before next poll: carbonize cleanup in ' + result.file + '. See reference/live.md "Required after accept".';}- console.log(JSON.stringify({ handled: result.handled !== false, ...result }));+ emitResult({ handled: result.handled !== false, ...result });return;}@@ -145,10 +248,25 @@ Output (JSON):}if (isDiscard) {- const result = handleDiscard(id, lines, targetFile);- console.log(JSON.stringify({ handled: true, file: relFile, carbonize: false, ...result }));+ let result;+ // handleDiscard takes the source lock, which throws SOURCE_LOCKED under+ // contention. Without this catch the CLI exits non-zero with empty stdout+ // and the agent gets no JSON to act on.+ try {+ result = handleDiscard(id, lines, targetFile);+ } catch (err) {+ emitResult(operationFailure(err, { file: relFile }));+ return;+ }+ emitResult({ handled: true, file: relFile, carbonize: false, ...result });} else {- const result = handleAccept(id, variantNum, lines, targetFile, paramValues);+ let result;+ try {+ result = handleAccept(id, variantNum, lines, targetFile, paramValues);+ } catch (err) {+ emitResult(operationFailure(err, { file: relFile }));+ return;+ }const acceptedOriginalText = result.acceptedOriginalText || '';delete result.acceptedOriginalText;// Single-line attention-grabber when cleanup is required. The full@@ -167,7 +285,7 @@ Output (JSON):// Non-fatal; the buffer stays as-is and the user can discard later.}}- console.log(JSON.stringify({ handled: true, file: relFile, ...result }));+ emitResult({ handled: true, file: relFile, ...result });}}@@ -235,7 +353,14 @@ function scrubManualEditsAgainstFile(_targetFile, cwd = process.cwd(), originalB// Discard// ----------------------------------------------------------------------------function handleDiscard(id, lines, targetFile) {+function handleDiscard(id, _lines, targetFile) {+ return withSourceLockSync(targetFile, 'discard:' + id, () => {+ const lines = fs.readFileSync(targetFile, 'utf-8').split('\n');+ return handleDiscardUnlocked(id, lines, targetFile);+ }, { waitMs: ACCEPT_LOCK_WAIT_MS });+}++function handleDiscardUnlocked(id, lines, targetFile) {const block = findMarkerBlock(id, lines);if (!block) return { handled: false, error: 'Markers not found' };@@ -330,7 +455,24 @@ function reindentContent(contentLines, fromIndent, toIndent) {});}-function handleAccept(id, variantNum, lines, targetFile, paramValues) {+function handleAccept(id, variantNum, _lines, targetFile, paramValues) {+ return withSourceLockSync(targetFile, 'accept:' + id, () => {+ const lines = fs.readFileSync(targetFile, 'utf-8').split('\n');+ return handleAcceptUnlocked(id, variantNum, lines, targetFile, paramValues);+ }, { waitMs: ACCEPT_LOCK_WAIT_MS });+}++function handleAcceptUnlocked(id, variantNum, lines, targetFile, paramValues) {+ const built = buildAcceptedWrappedSource(id, variantNum, lines, targetFile, paramValues);+ if (built.handled === false) return built;+ fs.writeFileSync(targetFile, built.content, 'utf-8');+ return {+ carbonize: built.carbonize,+ acceptedOriginalText: built.acceptedOriginalText,+ };+}++function buildAcceptedWrappedSource(id, variantNum, lines, targetFile, paramValues) {const block = findMarkerBlock(id, lines);if (!block) return { handled: false, error: 'Markers not found' };@@ -375,11 +517,14 @@ function handleAccept(id, variantNum, lines, targetFile, paramValues) {...replacement,...lines.slice(replaceRange.end + 1),];- fs.writeFileSync(targetFile, newLines.join('\n'), 'utf-8');-- return { carbonize: needsCarbonize, acceptedOriginalText: originalContent.join('\n') };+ return {+ content: newLines.join('\n'),+ carbonize: needsCarbonize,+ acceptedOriginalText: originalContent.join('\n'),+ };}+function readSourceShadowPreviewMeta(content, id) {const escaped = escapeRegExp(id);const wrapperRe = new RegExp('<[^>]+data-impeccable-variants=(["\'])' + escaped + '\\1[^>]*>');@@ -746,6 +891,21 @@ function detectCommentSyntax(filePath) {// File search (find the file containing session markers)// ---------------------------------------------------------------------------+/**+ * `.impeccable` is the critical entry, and it is not cosmetic.+ *+ * Progressive publication stages each revision as `.impeccable/live/artifacts/+ * <id>-r<n>.<source-ext>`, and those artifacts carry the very marker this search+ * looks for. The walk reaches `.` for any project whose source is not under one+ * of the privileged dirs above (this repo's own site lives in `site/pages/`), and+ * dot-directories sort before letters, so the artifact was found *before* the+ * real file. isGeneratedFile then declined the accept, and the agent fell back to+ * carbonizing several hundred lines of stylesheet by hand.+ *+ * Impeccable's own state directory is never project source. Never search it.+ */+const SEARCH_SKIP_DIRS = new Set(['node_modules', '.git', 'dist', 'build', IMPECCABLE_DIR]);+function findSessionFile(id, cwd) {const marker = 'impeccable-variants-start ' + id;const searchDirs = ['src', 'app', 'pages', 'components', 'public', 'views', 'templates', '.'];@@ -786,7 +946,7 @@ function searchDir(dir, query, seen, depth) {for (const entry of entries) {if (!entry.isDirectory()) continue;- if (['node_modules', '.git', 'dist', 'build'].includes(entry.name)) continue;+ if (SEARCH_SKIP_DIRS.has(entry.name)) continue;const result = searchDir(path.join(dir, entry.name), query, seen, depth + 1);if (result) return result;}@@ -798,6 +958,28 @@ function searchDir(dir, query, seen, depth) {// Utilities// ---------------------------------------------------------------------------+function acceptReceiptPath(cwd, id) {+ return path.join(getLiveDir(cwd), 'accept-receipts', `${safeSessionId(id)}.json`);+}++function readAcceptReceipt(cwd, id) {+ try { return JSON.parse(fs.readFileSync(acceptReceiptPath(cwd, id), 'utf-8')); } catch { return null; }+}++function writeAcceptReceipt(cwd, id, receipt) {+ const file = acceptReceiptPath(cwd, id);+ fs.mkdirSync(path.dirname(file), { recursive: true });+ const value = {+ id,+ ...receipt,+ completedAt: new Date().toISOString(),+ };+ const temporary = `${file}.${process.pid}.${Date.now()}.tmp`;+ fs.writeFileSync(temporary, JSON.stringify(value, null, 2) + '\n', 'utf-8');+ fs.renameSync(temporary, file);+ return value;+}+function argVal(args, flag) {const idx = args.indexOf(flag);return idx !== -1 && idx + 1 < args.length ? args[idx + 1] : null;diff --git a/plugin/skills/impeccable/scripts/live-browser.js b/plugin/skills/impeccable/scripts/live-browser.jsindex 616f1290a..20d875b93 100644--- a/plugin/skills/impeccable/scripts/live-browser.js+++ b/plugin/skills/impeccable/scripts/live-browser.js@@ -126,6 +126,9 @@let expectedVariants = 0;let arrivedVariants = 0;let visibleVariant = 0;+ let generationPhase = null;+ let parameterGenerationState = 'idle';+ let parameterReadyAnnouncedSession = null;let svelteComponentSession = null;let svelteRuntimePromise = null;let pendingSvelteComponentRetryObserver = null;@@ -134,6 +137,7 @@let currentPreviewMode = null;let recoveryWaitingForAnchor = false;let pickedAnchorSnapshot = null;+ let pickedAnchorViewportTop = null;let pendingVariantAnchorRetryObserver = null;let pendingAcceptedSession = null;let variantObserver = null;@@ -151,10 +155,12 @@// startScrollLock / stopScrollLock below.let scrollLockObserver = null;let scrollLockTargetY = null;+ let scrollLockAnchorTop = null;let scrollLockRaf = null;let scrollLockAbort = null;const SCROLL_ANCHOR_LOCK_ID = 'impeccable-scroll-anchor-lock';const VARIANT_STATE_STYLE_ID = 'impeccable-variant-state';+ const DISCARD_STATE_STYLE_ID = 'impeccable-discard-state';// Dedicated key for scroll position - SEPARATE from LS_KEY so that// saveSession's state updates don't clobber a carefully-captured scrollY.@@ -252,6 +258,13 @@barConnected: !!barEl?.isConnected,hasSvelteComponentSession: !!svelteComponentSession,mountedSvelteVariant: svelteComponentSession?.mountedVariant || 0,+ pickActive,+ pendingApplyInFlight,+ hoveredElement: hoveredElement ? {+ tag: hoveredElement.tagName,+ classes: hoveredElement.className,+ pickable: pickable(hoveredElement),+ } : null,pendingSvelteComponentRetry: !!pendingSvelteComponentRetryObserver,recoveryWaitingForAnchor,evtSourceReadyState: evtSource ? evtSource.readyState : null,@@ -1114,14 +1127,15 @@});}- function hideBar() {+ function hideBar(instant) {if (!barEl) return;const hideSeq = ++barHideSeq;stopVoice({ suppressSubmit: true });if (configureKind === 'insert') clearInsertPicking();barEl.style.opacity = '0';- barEl.style.transform = 'translateY(6px)';- setTimeout(() => { if (barEl && hideSeq === barHideSeq) barEl.style.display = 'none'; }, 250);+ barEl.style.transform = instant ? 'translateY(0)' : 'translateY(6px)';+ if (instant) barEl.style.display = 'none';+ else setTimeout(() => { if (barEl && hideSeq === barHideSeq) barEl.style.display = 'none'; }, 250);hideActionPicker();closeTunePopover();hideConfigureBarTooltip();@@ -1966,6 +1980,7 @@*/function setLiveState(next) {state = next;+ window.__IMPECCABLE_LIVE_STATE__ = next;syncPageInteractionCursor();}@@ -2516,18 +2531,27 @@fontSize: '11px', color: BP.textDim, whiteSpace: 'nowrap',marginLeft: 'auto',});- // Variants currently arrive atomically in a single file edit, so a- // per-variant counter would lie. Say what's true.status.textContent = recoveryWaitingForAnchor? 'Variants ready. Reveal the selected element to resume.'- : (arrivedVariants < expectedVariants- ? 'Generating ' + expectedVariants + ' variants...'- : 'Done');+ : generationStatusText();row.appendChild(status);return row;}+ function generationStatusText() {+ if (arrivedVariants >= expectedVariants && expectedVariants > 0) return 'Done';+ if (generationPhase === 'picked_up') return 'Agent picked up the request...';+ if (generationPhase === 'scaffolding') return 'Finding the source...';+ if (generationPhase === 'source_ready') return 'Source ready. Generating...';+ if (generationPhase === 'scaffold_fallback') return 'Agent is locating the source...';+ if (generationPhase === 'first_variant_generating') return 'Designing the first variant...';+ if (generationPhase === 'first_variant_validating') return 'Checking the first variant...';+ if (generationPhase === 'remaining_variants_generating') return 'Exploring two more directions...';+ if (generationPhase === 'remaining_variants_validating') return 'Checking the remaining variants...';+ return 'Generating ' + expectedVariants + ' variants...';+ }+// Cycling rowconst TUNE_ICON_SVG = '<svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" style="flex-shrink:0"><line x1="4" y1="8" x2="20" y2="8"/><circle cx="14" cy="8" r="2.4" fill="currentColor" stroke="none"/><line x1="4" y1="16" x2="20" y2="16"/><circle cx="10" cy="16" r="2.4" fill="currentColor" stroke="none"/></svg>';@@ -2557,7 +2581,7 @@color: BP.textDim, minWidth: '24px', textAlign: 'center',});counter.id = PREFIX + '-variant-counter';- counter.textContent = visibleVariant + '/' + arrivedVariants;+ counter.textContent = visibleVariant + '/' + expectedVariants;row.appendChild(counter);// Next@@ -2567,10 +2591,12 @@if (visibleVariant >= arrivedVariants) next.style.opacity = '0.3';row.appendChild(next);- // Tune chip - only when the visible variant exposes params+ // Tune chip stays visible while the deferred parameter phase is running,+ // then becomes interactive as soon as this variant exposes controls.const visParams = parseVariantParams(getVisibleVariantEl());const hasParams = visParams.length > 0;- if (hasParams) {+ const paramsPending = !hasParams && (parameterGenerationState === 'pending' || parameterGenerationState === 'loading');+ if (hasParams || paramsPending) {const tune = el('button', {display: 'inline-flex', alignItems: 'center', gap: '6px',padding: '4px 10px', borderRadius: '5px',@@ -2578,35 +2604,54 @@background: tuneOpen ? BP.accentSoft : 'transparent',color: tuneOpen ? BP.accent : BP.text,fontFamily: FONT, fontSize: '11px', fontWeight: '500',- cursor: 'pointer',+ cursor: paramsPending ? 'wait' : 'pointer',transition: 'color 0.12s ease, background 0.12s ease',whiteSpace: 'nowrap',});- tune.innerHTML = TUNE_ICON_SVG;+ if (paramsPending) {+ const spinner = el('span', {+ width: '11px', height: '11px', borderRadius: '50%',+ border: '1.5px solid ' + BP.hairline,+ borderTopColor: BP.accent,+ animation: 'impeccable-spin 0.6s linear infinite',+ boxSizing: 'border-box', flexShrink: '0',+ });+ spinner.setAttribute('aria-hidden', 'true');+ tune.appendChild(spinner);+ } else {+ tune.innerHTML = TUNE_ICON_SVG;+ }const tuneLabel = document.createElement('span');tuneLabel.textContent = 'Tune';tune.appendChild(tuneLabel);- const tuneBadge = document.createElement('span');- Object.assign(tuneBadge.style, {- display: 'inline-flex', alignItems: 'center', justifyContent: 'center',- minWidth: '16px', height: '16px', padding: '0 4px',- borderRadius: '999px',- background: tuneOpen ? C.brand : BP.hairline,- color: tuneOpen ? 'oklch(98% 0 0)' : 'inherit',- fontFamily: MONO, fontSize: '9.5px', fontWeight: '600',- lineHeight: '1',- boxSizing: 'border-box',- });- tuneBadge.textContent = String(visParams.length);- tune.appendChild(tuneBadge);- tune.title = 'Tune this variant (' + visParams.length + ' knob' + (visParams.length === 1 ? '' : 's') + ')';- tune.addEventListener('mouseenter', () => {- if (!tuneOpen) tune.style.background = BP.accentSoft;- });- tune.addEventListener('mouseleave', () => {- if (!tuneOpen) tune.style.background = 'transparent';- });- tune.addEventListener('click', (e) => { e.stopPropagation(); toggleTunePopover(); });+ if (hasParams) {+ const tuneBadge = document.createElement('span');+ Object.assign(tuneBadge.style, {+ display: 'inline-flex', alignItems: 'center', justifyContent: 'center',+ minWidth: '16px', height: '16px', padding: '0 4px',+ borderRadius: '999px',+ background: tuneOpen ? C.brand : BP.hairline,+ color: tuneOpen ? 'oklch(98% 0 0)' : 'inherit',+ fontFamily: MONO, fontSize: '9.5px', fontWeight: '600',+ lineHeight: '1',+ boxSizing: 'border-box',+ });+ tuneBadge.textContent = String(visParams.length);+ tune.appendChild(tuneBadge);+ tune.title = 'Tune this variant (' + visParams.length + ' knob' + (visParams.length === 1 ? '' : 's') + ')';+ tune.addEventListener('mouseenter', () => {+ if (!tuneOpen) tune.style.background = BP.accentSoft;+ });+ tune.addEventListener('mouseleave', () => {+ if (!tuneOpen) tune.style.background = 'transparent';+ });+ tune.addEventListener('click', (e) => { e.stopPropagation(); toggleTunePopover(); });+ } else {+ tune.disabled = true;+ tune.setAttribute('aria-label', 'Tune controls are still being prepared');+ tune.title = 'Tune controls are still being prepared';+ tune.style.opacity = '0.72';+ }tune.dataset.iceqTune = '1';row.appendChild(tune);}@@ -2614,6 +2659,15 @@// Spacerrow.appendChild(el('div', { flex: '1' }));+ if (arrivedVariants < expectedVariants) {+ const remaining = expectedVariants - arrivedVariants;+ const progress = el('span', {+ fontSize: '11px', color: BP.textDim, whiteSpace: 'nowrap',+ });+ progress.textContent = remaining + ' more arriving...';+ row.appendChild(progress);+ }+// Accept - primary action, kinpaku gold + lacquer-deep (matches demo .live-demo-ctx-accept)const accept = el('button', {padding: '5px 14px', borderRadius: '5px',@@ -2628,7 +2682,11 @@accept.addEventListener('mousedown', () => accept.style.transform = 'scale(0.97)');accept.addEventListener('mouseup', () => accept.style.transform = 'scale(1)');accept.addEventListener('click', (e) => { e.stopPropagation(); handleAccept(); });- if (arrivedVariants === 0) { accept.style.opacity = '0.3'; accept.style.pointerEvents = 'none'; }+ if (arrivedVariants === 0) {+ accept.style.opacity = '0.3';+ accept.style.pointerEvents = 'none';+ accept.title = 'Accept becomes available when the first variant arrives';+ }row.appendChild(accept);// Discard@@ -4743,6 +4801,32 @@}}+ function mountedParameterCount() {+ if (svelteComponentSession?.sessionId === currentSessionId) {+ return Object.values(svelteComponentSession.paramsByVariant || {})+ .reduce((total, params) => total + (Array.isArray(params) ? params.length : 0), 0);+ }+ const wrapper = document.querySelector('[data-impeccable-variants="' + currentSessionId + '"]');+ if (!wrapper) return 0;+ return [...wrapper.querySelectorAll('[data-impeccable-variant]:not([data-impeccable-variant="original"])')]+ .reduce((total, variant) => total + parseVariantParams(variant).length, 0);+ }++ function completeParameterPublication() {+ if (!currentSessionId) return;+ const ready = mountedParameterCount() > 0;+ parameterGenerationState = ready ? 'ready' : 'none';+ if (ready && parameterReadyAnnouncedSession !== currentSessionId) {+ parameterReadyAnnouncedSession = currentSessionId;+ showToast('Tune controls are ready.', 3000);+ }+ if (state === 'CYCLING') {+ refreshParamsPanel();+ showOrUpdateCyclingBar();+ }+ saveSession();+ }+function toggleTunePopover() {if (pendingApplyInFlight) { showManualApplyBusyToast(); return; }if (tuneOpen) { closeTunePopover(); return; }@@ -4835,6 +4919,10 @@return String(filePath || '').endsWith('manifest.json');}+ function isFrameworkComponentPreviewMode(mode) {+ return mode === 'svelte-component';+ }+function parseOriginalMarkupElement(originalMarkup) {const parser = new DOMParser();const doc = parser.parseFromString('<div id="impeccable-anchor">' + originalMarkup + '</div>', 'text/html');@@ -5029,9 +5117,13 @@}}- function loadSvelteRuntime(runtimeModule) {+ function resolveComponentModuleUrl(manifest, modulePath) {+ return new URL(String(modulePath || ''), location.origin).href;+ }++ function loadSvelteRuntime(runtimeModule, manifest) {const modulePath = runtimeModule || '/src/lib/impeccable/__runtime.js';- const url = new URL(modulePath, location.origin).href;+ const url = resolveComponentModuleUrl(manifest, modulePath);if (!svelteRuntimePromise) {svelteRuntimePromise = import(/* @vite-ignore */ url);}@@ -5065,7 +5157,8 @@async function loadSvelteComponentVariantSource(manifest, variantNum) {const dir = String(manifest?.componentDir || '').replace(/^\/+/, '');if (!dir || !variantNum) return '';- const sourcePath = dir + '/v' + variantNum + '.svelte';+ const extension = manifest.componentExtension || 'svelte';+ const sourcePath = dir + '/v' + variantNum + '.' + extension;const url = 'http://localhost:' + PORT + '/source?token=' + TOKEN + '&path=' + encodeURIComponent(sourcePath);try {const res = await fetch(url);@@ -5221,7 +5314,7 @@if (!sourceOriginal) return values;const map = buildSvelteExpressionTextMap(sourceOriginal, liveEl);for (const entry of contract) {- const token = '{' + entry.expr + '}';+ const token = entry.previewToken || ('{' + entry.expr + '}');values[entry.prop] = map.get(token) || '';}return values;@@ -5233,9 +5326,12 @@try {const previousAnchor = getMountedSvelteComponentAnchor(svelteComponentSession) || selectedElement;svelteComponentSession.swapAnchor = makeFrozenAnchor(previousAnchor) || svelteComponentSession.swapAnchor || null;- const runtime = await loadSvelteRuntime(manifest.runtimeModule);- const modulePath = '/' + String(manifest.componentDir || '').replace(/^\/+/, '') + '/v' + variantNum + '.svelte';- const moduleUrl = new URL(modulePath, location.origin).href + '?t=' + Date.now();+ const runtime = await loadSvelteRuntime(manifest.runtimeModule, manifest);+ const extension = manifest.componentExtension || 'svelte';+ const moduleBase = manifest.componentModuleBase+ || ('/' + String(manifest.componentDir || '').replace(/^\/+/, ''));+ const modulePath = String(moduleBase).replace(/\/+$/, '') + '/v' + variantNum + '.' + extension;+ const moduleUrl = resolveComponentModuleUrl(manifest, modulePath) + '?t=' + Date.now();const mod = await import(/* @vite-ignore */ moduleUrl);const Component = mod.default;if (svelteComponentSession.mountedInstance && runtime.unmount) {@@ -5275,7 +5371,7 @@if (svelteComponentSession?.sessionId === sessionId) {svelteComponentSession.swapAnchor = null;}- console.error('[impeccable] Failed to mount Svelte variant ' + variantNum + ' for ' + sessionId + ':', err);+ console.error('[impeccable] Failed to mount component variant ' + variantNum + ' for ' + sessionId + ':', err);return false;}}@@ -5340,40 +5436,46 @@if (manifest.id !== sessionId) return;const paramsByVariant = await loadSvelteComponentParams(manifest);+ const availableVariants = Number(manifest.arrivedVariants) || Number(manifest.count) || 1;+ const componentPreviewMode = isFrameworkComponentPreviewMode(manifest.previewMode)+ ? manifest.previewMode+ : 'svelte-component';currentSessionId = sessionId;expectedVariants = Number(manifest.count) || expectedVariants || 1;rememberSessionFileMeta({sourceFile: manifest.sourceFile,previewFile: manifestPath,- previewMode: 'svelte-component',+ previewMode: componentPreviewMode,});if (state !== 'CYCLING') setLiveState('GENERATING');const existingWrapper = document.querySelector('[data-impeccable-variants="' + sessionId + '"]');if (existingWrapper && svelteComponentSession?.sessionId === sessionId) {recoveryWaitingForAnchor = false;+ svelteComponentSession.manifest = manifest;svelteComponentSession.paramsByVariant = paramsByVariant;- arrivedVariants = Number(manifest.count) || expectedVariants || 1;- expectedVariants = arrivedVariants;+ arrivedVariants = availableVariants;+ expectedVariants = Number(manifest.count) || expectedVariants || arrivedVariants;visibleVariant = visibleVariant > 0 && visibleVariant <= arrivedVariants ? visibleVariant : 1;await mountSvelteComponentVariant(visibleVariant || 1);setLiveState('CYCLING');showOrUpdateCyclingBar();saveSession();+ if (parameterGenerationState === 'loading') completeParameterPublication();return;}const liveEl = findLiveElementForSvelteManifest(manifest);if (!liveEl?.parentElement) {console.warn('[impeccable] Could not find original element in live DOM.');- arrivedVariants = Number(manifest.count) || expectedVariants || 1;- expectedVariants = arrivedVariants;+ arrivedVariants = availableVariants;+ expectedVariants = Number(manifest.count) || expectedVariants || arrivedVariants;const saved = loadSession();const savedVisibleVariant = saved && saved.id === sessionId ? saved.visible : 0;visibleVariant = visibleVariant > 0 && visibleVariant <= arrivedVariants? visibleVariant: (savedVisibleVariant > 0 && savedVisibleVariant <= arrivedVariants ? savedVisibleVariant : 1);- enterRecoveryWaitingForAnchor({ checkpointReason: 'svelte_component_anchor_missing', trackScroll: true });+ enterRecoveryWaitingForAnchor({ checkpointReason: 'component_preview_anchor_missing', trackScroll: true });waitForSvelteComponentTargetAndRetry({ manifestPath, sessionId, manifest });return;}@@ -5381,7 +5483,7 @@const wrapper = document.createElement('div');wrapper.dataset.impeccableVariants = sessionId;wrapper.dataset.impeccableVariantCount = String(manifest.count || expectedVariants || 1);- wrapper.dataset.impeccablePreview = 'svelte-component';+ wrapper.dataset.impeccablePreview = componentPreviewMode;wrapper.style.display = 'contents';const mountTarget = document.createElement('div');@@ -5419,8 +5521,8 @@recoveryWaitingForAnchor = false;const previousVisibleVariant = currentSessionId === sessionId ? visibleVariant : 0;- arrivedVariants = Number(manifest.count) || expectedVariants || 1;- expectedVariants = arrivedVariants;+ arrivedVariants = availableVariants;+ expectedVariants = Number(manifest.count) || expectedVariants || arrivedVariants;const saved = loadSession();const savedVisibleVariant = saved && saved.id === sessionId ? saved.visible : 0;visibleVariant = previousVisibleVariant > 0 && previousVisibleVariant <= arrivedVariants@@ -5445,9 +5547,10 @@refreshParamsPanel();positionBar();saveSession();- console.log('[impeccable] Mounted ' + arrivedVariants + ' Svelte component variants.');+ if (parameterGenerationState === 'loading') completeParameterPublication();+ console.log('[impeccable] Mounted ' + arrivedVariants + ' ' + manifest.framework + ' component variants.');} catch (err) {- console.error('[impeccable] Failed to mount Svelte component variants:', err);+ console.error('[impeccable] Failed to mount component-preview variants:', err);abortSvelteComponentInjection(sessionId, 'Could not load variants. Fix the error and re-run.');}}@@ -5493,6 +5596,8 @@clearHandled();resetSessionFileMeta();currentSessionId = null;+ parameterGenerationState = 'idle';+ parameterReadyAnnouncedSession = null;expectedVariants = 0;arrivedVariants = 0;visibleVariant = 0;@@ -5502,12 +5607,24 @@if (message) showToast(message, 5000);}+ // How many delayed re-reads a completion-driven source fallback gets when+ // the fetched source still shows only the preflight scaffold, before the+ // failure is surfaced via recoverEmptyCycling.+ const COMPLETED_SOURCE_FALLBACK_RETRIES = 3;+ const COMPLETED_SOURCE_FALLBACK_RETRY_MS = 1200;+/*** No-HMR fallback: fetch the raw source file from the live server,* parse it, extract the variant wrapper, and inject it into the live DOM.* This works even when the dev server caches HTML (Bun, static servers).+ *+ * opts.generationCompleted marks callers that KNOW the agent finished (a+ * `done` arrived or the server reported a completed generation). For them an+ * empty read is a stale source view and no further event is coming, so the+ * read retries a few times and then surfaces recovery. Callers without the+ * flag may be mid-generation and wait indefinitely for the real completion.*/- function injectVariantsFromSource(filePath, sessionId) {+ function injectVariantsFromSource(filePath, sessionId, opts = {}) {if (isSvelteComponentManifestPath(filePath)) {injectSvelteComponentsFromManifest(filePath, sessionId);return;@@ -5573,6 +5690,32 @@arrivedVariants = variants.length;expectedVariants = parseInt(wrapper.dataset.impeccableVariantCount || arrivedVariants);if (arrivedVariants <= 0) {+ if (state === 'GENERATING') {+ // Mid-generation the source legitimately holds a scaffold wrapper+ // with no variants yet (the server-side preflight wraps before the+ // agent writes). Tearing the session down here would destroy an+ // in-flight generation; stay in GENERATING — the variant observer+ // is armed and the server re-delivers a missed `done`.+ if (!opts.generationCompleted) {+ console.log('[impeccable] Source has scaffold but no variants yet; still generating.');+ return;+ }+ // Generation finished, yet the read shows only the scaffold: the+ // source view is stale and no further event will fire. Re-read a+ // few times before surfacing recovery — a single silent return+ // here would strand the tab in GENERATING forever.+ const attempt = opts.attempt || 0;+ if (attempt < COMPLETED_SOURCE_FALLBACK_RETRIES) {+ console.log('[impeccable] Generation is done but source shows no variants yet; retrying read ('+ + (attempt + 1) + '/' + COMPLETED_SOURCE_FALLBACK_RETRIES + ').');+ setTimeout(() => {+ if (state !== 'GENERATING' || currentSessionId !== sessionId) return;+ if (arrivedVariants > 0) return;+ injectVariantsFromSource(filePath, sessionId, { ...opts, attempt: attempt + 1 });+ }, COMPLETED_SOURCE_FALLBACK_RETRY_MS);+ return;+ }+ }recoverEmptyCycling('source-fallback-empty');return;}@@ -5594,6 +5737,7 @@refreshParamsPanel();positionBar();saveSession();+ if (parameterGenerationState === 'loading') completeParameterPublication();console.log('[impeccable] Injected ' + arrivedVariants + ' variants from source file.');}).catch(err => {@@ -5865,13 +6009,36 @@document.getElementById(VARIANT_STATE_STYLE_ID)?.remove();}+ function showOriginalDuringDiscard(sessionId) {+ if (!sessionId) return;+ let styleEl = document.getElementById(DISCARD_STATE_STYLE_ID);+ if (!styleEl) {+ styleEl = document.createElement('style');+ styleEl.id = DISCARD_STATE_STYLE_ID;+ (document.head || document.documentElement).appendChild(styleEl);+ }+ const wrapper = '[data-impeccable-variants="' + sessionId + '"]';+ styleEl.textContent = wrapper + ' > [data-impeccable-variant]:not([data-impeccable-variant="original"]) { display:none !important; }\n'+ + wrapper + ' > [data-impeccable-variant="original"] { display:block !important; }';+ }++ function resolveScrollLockAnchorTop() {+ const anchor = resolveBarAnchor();+ if (!anchor?.isConnected) return null;+ const top = anchor.getBoundingClientRect().top;+ return Number.isFinite(top) ? top : null;+ }+// Hold window.scrollY at a fixed value across DOM mutations inside the// session's wrapper (HMR patches, variant inserts, cycle swaps).- function startScrollLock(sessionId, initialTargetY) {+ function startScrollLock(sessionId, initialTargetY, initialAnchorTop) {stopScrollLock();scrollLockTargetY = typeof initialTargetY === 'number' && isFinite(initialTargetY)? initialTargetY: window.scrollY;+ scrollLockAnchorTop = typeof initialAnchorTop === 'number' && isFinite(initialAnchorTop)+ ? initialAnchorTop+ : resolveScrollLockAnchorTop();try { history.scrollRestoration = 'manual'; } catch {}@@ -5895,6 +6062,17 @@const correct = (why) => {scrollLockRaf = null;if (scrollLockTargetY == null) return;+ const anchor = resolveBarAnchor();+ if (anchor?.isConnected && typeof scrollLockAnchorTop === 'number' && isFinite(scrollLockAnchorTop)) {+ const anchorTop = anchor.getBoundingClientRect().top;+ const anchorDelta = anchorTop - scrollLockAnchorTop;+ if (Math.abs(anchorDelta) >= 0.5) {+ window.scrollTo({ top: window.scrollY + anchorDelta, left: window.scrollX, behavior: 'instant' });+ scrollLockTargetY = window.scrollY;+ writeScrollY(scrollLockTargetY);+ return;+ }+ }const before = window.scrollY;const delta = before - scrollLockTargetY;if (Math.abs(delta) < 0.5) {@@ -5939,6 +6117,7 @@if (scrollLockRaf != null) { cancelAnimationFrame(scrollLockRaf); scrollLockRaf = null; }const prevTarget = scrollLockTargetY;scrollLockTargetY = window.scrollY;+ scrollLockAnchorTop = resolveScrollLockAnchorTop();writeScrollY(scrollLockTargetY);};const markGesture = (why) => {@@ -5976,6 +6155,7 @@if (scrollLockRaf != null) { cancelAnimationFrame(scrollLockRaf); scrollLockRaf = null; }if (scrollLockAbort) { scrollLockAbort.abort(); scrollLockAbort = null; }scrollLockTargetY = null;+ scrollLockAnchorTop = null;// NOTE: do NOT clear the persistent scroll key here. startScrollLock// calls us as a reset, and clearing the key would nuke the Go-time// scrollY that the next resume needs to read.@@ -6049,6 +6229,7 @@updating = true;arrivedVariants = count;+ generationPhase = arrivedVariants >= expectedVariants ? 'variants_ready' : 'variants_progress';if (visibleVariant === 0 && arrivedVariants > 0) {const saved = loadSession();const savedVisibleVariant = saved && saved.id === sessionId ? saved.visible : 0;@@ -6064,7 +6245,7 @@const expected = parseInt(wrapper.dataset.impeccableVariantCount || '0');if (expected > 0) expectedVariants = expected;- if (arrivedVariants >= expectedVariants && expectedVariants > 0) {+ if (arrivedVariants > 0) {setLiveState('CYCLING');recoveryWaitingForAnchor = false;hideShaderOverlay();@@ -6072,13 +6253,18 @@updateSelectedElement();showOrUpdateCyclingBar();disableInlineEdit();- refreshParamsPanel();+ if (arrivedVariants >= expectedVariants && expectedVariants > 0) refreshParamsPanel();+ else hideParamsPanel();positionBar();} else if (state === 'GENERATING') {updateBarContent('generating');}saveSession();- queueCheckpoint(state === 'CYCLING' ? 'variants_ready' : 'variants_progress');+ sendCheckpoint(+ arrivedVariants >= expectedVariants && expectedVariants > 0+ ? 'variants_ready'+ : 'variants_progress',+ );updating = false;});@@ -6151,6 +6337,7 @@syncAgentPollingUi(!!msg.agentPolling);startAgentStatusPoll();restoreFromActiveSessions(msg.activeSessions, 'sse_connected');+ recoverMissedGenerationCompletion(msg.activeSessions);if (state === 'IDLE' && (pickActive || insertActive)) setLiveState('PICKING');syncPageInteractionCursor();syncPageChatFocus('sse-connected');@@ -6158,6 +6345,42 @@case 'agent_polling':syncAgentPollingUi(!!msg.connected);break;+ case 'agent_phase':+ if (msg.id === currentSessionId && (state === 'GENERATING' || state === 'CYCLING')) {+ generationPhase = msg.phase || generationPhase;+ if (msg.phase === 'variant_parameters_generating' || msg.phase === 'variant_parameters_validating') {+ parameterGenerationState = 'loading';+ }+ if (msg.phase === 'parameters_ready' && parameterGenerationState !== 'ready') {+ parameterGenerationState = 'loading';+ }+ updateBarContent(state === 'CYCLING' ? 'cycling' : 'generating');+ saveSession();+ }+ break;+ case 'variant_progress':+ if (msg.id === currentSessionId) {+ if (msg.publicationKind === 'params') parameterGenerationState = 'loading';+ rememberSessionFileMeta(msg);+ if (isFrameworkComponentPreviewMode(msg.previewMode) && msg.previewFile) {+ injectSvelteComponentsFromManifest(msg.previewFile, msg.id);+ } else if ((msg.previewMode === 'source' || !msg.previewMode) && (msg.previewFile || msg.file)) {+ // Give normal framework HMR the first chance to reconcile its+ // own managed tree. Nuxt route-module HMR can skip intermediate+ // revisions, so fall back to source injection only when the+ // advertised progress still has not appeared after a short+ // settle. Immediate injection races React/Vue ownership and can+ // trigger removeChild errors on the next HMR commit.+ const targetArrived = Number(msg.arrivedVariants) || 1;+ setTimeout(() => {+ if (msg.id !== currentSessionId) return;+ if (state !== 'GENERATING' && state !== 'CYCLING') return;+ if (msg.publicationKind !== 'params' && arrivedVariants >= targetArrived) return;+ injectVariantsFromSource(msg.previewFile || msg.file, msg.id);+ }, 150);+ }+ }+ break;case 'steer_done':maybeCompleteSteer(msg);break;@@ -6175,6 +6398,10 @@case 'done':if (maybeCompleteSteer(msg)) break;rememberSessionFileMeta(msg);+ if (msg.id === currentSessionId && isFrameworkComponentPreviewMode(currentPreviewMode) && currentPreviewFile) {+ injectSvelteComponentsFromManifest(currentPreviewFile, msg.id);+ break;+ }// Variants already arrived via HMR → normal transition.if (arrivedVariants >= expectedVariants && expectedVariants > 0) {if (state === 'GENERATING') {@@ -6190,7 +6417,7 @@setTimeout(() => {if (arrivedVariants >= expectedVariants && expectedVariants > 0) return;if (state !== 'GENERATING' || msg.id !== currentSessionId) return;- injectVariantsFromSource(msg.file, msg.id);+ injectVariantsFromSource(msg.file, msg.id, { generationCompleted: true });}, 750);break;}@@ -6215,9 +6442,10 @@if (maybeCompleteAcceptedSession(msg)) break;break;case 'agent_done':- // Carbonize accepts are not terminal until live-complete.mjs sends- // the final complete event. Keep the browser in its recoverable- // saving state while the source cleanup is still in flight.+ // The deterministic accept has already committed the reviewed DOM+ // and fenced generation. Carbonize may continue in the background;+ // it must not hold the foreground picker hostage.+ if (msg.data?.carbonize === true && maybeCompleteAcceptedSession(msg)) break;break;case 'discarded':if (msg.id && msg.id === currentSessionId) {@@ -6306,6 +6534,7 @@type: 'checkpoint',id: currentSessionId,revision: sessionState.nextCheckpointRevision(),+ revisionDomain: 'browser',owner: browserOwner,phase: String(state || '').toLowerCase(),reason,@@ -6331,6 +6560,7 @@type: 'checkpoint',id,revision: sessionState.nextCheckpointRevision(),+ revisionDomain: 'browser',owner: browserOwner,phase: 'steer',reason,@@ -6684,6 +6914,9 @@expectedVariants = selectedCount;arrivedVariants = 0;visibleVariant = 0;+ generationPhase = 'queued';+ parameterGenerationState = 'pending';+ parameterReadyAnnouncedSession = null;resetSessionFileMeta();// Flip to GENERATING immediately so the bar morphs without waiting on@@ -6693,6 +6926,7 @@const elForCapture = selectedElement;pickedAnchorSnapshot = buildPickedAnchorSnapshot(elForCapture);const captureRect = elForCapture.getBoundingClientRect();+ pickedAnchorViewportTop = captureRect.top;const snapshot = {comments: annotState.comments.map(c => ({ x: c.x, y: c.y, text: c.text })),strokes: annotState.strokes.map(s => ({ points: s.points.map(p => [p[0], p[1]]) })),@@ -6724,7 +6958,7 @@writeScrollY(window.scrollY);if (variantObserver) variantObserver.disconnect();variantObserver = startVariantObserver(currentSessionId);- startScrollLock(currentSessionId);+ startScrollLock(currentSessionId, window.scrollY, pickedAnchorViewportTop);captureAndEmit(elForCapture, basePayload, snapshot, captureRect);}@@ -6759,12 +6993,16 @@expectedVariants = selectedCount;arrivedVariants = 0;visibleVariant = 0;+ generationPhase = 'queued';+ parameterGenerationState = 'pending';+ parameterReadyAnnouncedSession = null;resetSessionFileMeta();selectedElement = placeholderElement;insertPlaceholderSnapshot = buildInsertPlaceholderSnapshotFromDom(insertAnchorElement, placeholderElement);const elForCapture = placeholderElement;const captureRect = elForCapture.getBoundingClientRect();+ pickedAnchorViewportTop = captureRect.top;const basePayload = {type: 'generate',mode: 'insert',@@ -6795,7 +7033,7 @@writeScrollY(window.scrollY);if (variantObserver) variantObserver.disconnect();variantObserver = startVariantObserver(currentSessionId);- startScrollLock(currentSessionId);+ startScrollLock(currentSessionId, window.scrollY, pickedAnchorViewportTop);captureAndEmit(elForCapture, basePayload, snapshot, captureRect);}@@ -6975,9 +7213,9 @@// preview mounts are covered by the same shader regression checks.const adapter = String(window.__IMPECCABLE_LIVE_ADAPTER__ || '').toLowerCase();if (adapter === 'svelte' || adapter === 'sveltekit') return true;- if (currentPreviewMode === 'svelte-component' || svelteComponentSession) return true;+ if (isFrameworkComponentPreviewMode(currentPreviewMode) || svelteComponentSession) return true;const wrapper = el?.closest?.('[data-impeccable-variants]');- return wrapper?.dataset?.impeccablePreview === 'svelte-component';+ return isFrameworkComponentPreviewMode(wrapper?.dataset?.impeccablePreview);}function paintsShaderProxySurface(node) {@@ -7105,6 +7343,17 @@}async function captureAndEmit(el, basePayload, snapshot, rect) {+ const hasAnnotations = snapshot && (snapshot.comments.length > 0 || snapshot.strokes.length > 0);++ // Plain requests do not send a screenshot to the agent, so capture is+ // presentation-only. Wait only for the helper to accept the event before+ // starting CPU-heavy capture; this yields the browser task and prevents+ // rasterization from delaying the fetch itself.+ if (!hasAnnotations) {+ basePayload.clientSentAt = Date.now();+ await sendEvent(basePayload);+ }+let screenshotPath;let blob;let paper;@@ -7122,7 +7371,6 @@// are present. Without annotations the image is pure visual anchoring -// it biases the model toward the current rendering and works against the// three-distinct-directions brief.- const hasAnnotations = snapshot && (snapshot.comments.length > 0 || snapshot.strokes.length > 0);if (blob && hasAnnotations) {try {const uploadRes = await fetch(@@ -7140,7 +7388,12 @@console.warn('[impeccable] annotation upload failed:', err);}}- sendEvent(screenshotPath ? { ...basePayload, screenshotPath } : basePayload);+ // Annotated requests must wait for capture + upload because the screenshot+ // is semantic input. Plain requests were already dispatched above.+ if (hasAnnotations) {+ basePayload.clientSentAt = Date.now();+ sendEvent(screenshotPath ? { ...basePayload, screenshotPath } : basePayload);+ }}//@@ -7520,7 +7773,6 @@ void main() {if (variantSelectionPromise) {try { await variantSelectionPromise; } catch { /* failed selection falls back below */ }}- if (!currentSessionId || arrivedVariants === 0) return;const domVisibleVariant = readVisibleVariantFromDOM(currentSessionId);if (domVisibleVariant > 0) visibleVariant = domVisibleVariant;const acceptPayload = {@@ -7528,7 +7780,9 @@ void main() {id: currentSessionId,variantId: String(visibleVariant),pageUrl: location.pathname,+ clientSentAt: Date.now(),};+ if (!currentSessionId || arrivedVariants === 0) return;const acceptWrapper = document.querySelector('[data-impeccable-variants="' + currentSessionId + '"]');if (Object.keys(paramsCurrentValues).length > 0) {acceptPayload.paramValues = { ...paramsCurrentValues };@@ -7542,7 +7796,7 @@ void main() {const acceptedSessionId = currentSessionId;const acceptedVariant = visibleVariant;const acceptedIsSvelteComponent = svelteComponentSession?.sessionId === acceptedSessionId- || acceptWrapper?.dataset?.impeccablePreview === 'svelte-component';+ || isFrameworkComponentPreviewMode(acceptWrapper?.dataset?.impeccablePreview);const acceptedSnapshot = snapshotAcceptedVariantDom(acceptedSessionId, acceptedVariant);setLiveState('SAVING');@@ -7557,7 +7811,17 @@ void main() {saveSession();sendEvent(acceptPayload, { throwOnError: true })- .then(() => {})+ .then(() => {+ const pending = pendingAcceptedSession;+ if (!pending || pending.id !== acceptedSessionId) return;+ // POST /events returns only after the accept intent is durable and the+ // generation epoch is fenced. Source promotion/carbonize can finish in+ // the background; the foreground picker is free immediately.+ markSessionHandled();+ setLiveState('CONFIRMED');+ document.documentElement.dataset.impeccableAcceptToPickingMs = String(Date.now() - acceptPayload.clientSentAt);+ scheduleAcceptCleanup(pending);+ }).catch(() => {if (pendingAcceptedSession?.id === acceptedSessionId) pendingAcceptedSession = null;setLiveState('CYCLING');@@ -7586,17 +7850,26 @@ void main() {}function scheduleAcceptCleanup(accepted) {- setTimeout(function() {- if (!accepted?.isSvelteComponent && !acceptedDomAlreadyClean(accepted)) {- setTimeout(function() {- if (pendingAcceptedSession?.id !== accepted?.id) return;- if (!accepted?.isSvelteComponent) ensureAcceptedDomClean(accepted);- cleanupAcceptedSession();- }, 1800);- return;+ queueMicrotask(function() {+ if (pendingAcceptedSession?.id !== accepted?.id) return;+ // Svelte previews live in an adapter-owned mount rather than in source+ // wrapper markup. Promote the mounted variant before releasing the+ // session so the old adapter instance cannot linger behind the next+ // Pick → Go loop while carbonize finishes in the background.+ if (accepted?.isSvelteComponent) {+ commitAcceptedSvelteComponentToDom(accepted.id);}cleanupAcceptedSession();- }, 1200);+ });+ // Let React/Vue/Svelte own the HMR reconciliation. Mutating their DOM in+ // the same turn as the source update causes removeChild/NotFoundError+ // races. Static servers still need a fallback, but it must not keep Live+ // in SAVING or block the user's next pick.+ if (!accepted?.isSvelteComponent) {+ setTimeout(function() {+ if (!acceptedDomAlreadyClean(accepted)) ensureAcceptedDomClean(accepted);+ }, 1200);+ }}function snapshotAcceptedVariantDom(sessionId, variantId) {@@ -7700,7 +7973,11 @@ void main() {clearSession();resetSessionFileMeta();selectedElement = null;+ hoveredElement = null;+ pagePickSkipClick = false;currentSessionId = null;+ parameterGenerationState = 'idle';+ parameterReadyAnnouncedSession = null;selectedAction = 'impeccable';pendingAcceptedSession = null;renderEditBadge('hidden');@@ -7735,7 +8012,7 @@ void main() {sendEvent({ type: 'discard', id: currentSessionId }, { throwOnError: true }).then(() => {markSessionHandled();- cleanup();+ cleanup({ restoreOriginal: true, instantChrome: true });}).catch(() => showToast('Could not confirm discard with the live server. Session kept for recovery.', 5000));}@@ -7757,6 +8034,7 @@ void main() {currentPreviewMode = null;recoveryWaitingForAnchor = false;pickedAnchorSnapshot = null;+ pickedAnchorViewportTop = null;}function rememberSessionFileMeta(meta = {}) {@@ -7765,8 +8043,8 @@ void main() {const previewFile = normalizeSessionPath(meta.previewFile);const previewMode = meta.previewMode || (isSvelteComponentManifestPath(previewFile || file) ? 'svelte-component' : null);- if (previewMode === 'svelte-component' || isSvelteComponentManifestPath(file)) {- currentPreviewMode = 'svelte-component';+ if (isFrameworkComponentPreviewMode(previewMode) || isSvelteComponentManifestPath(file)) {+ currentPreviewMode = isFrameworkComponentPreviewMode(previewMode) ? previewMode : 'svelte-component';currentPreviewFile = previewFile || (isSvelteComponentManifestPath(file) ? file : currentPreviewFile);currentSourceFile = sourceFile || currentSourceFile;return;@@ -7782,12 +8060,15 @@ void main() {rememberSessionFileMeta(saved);if (saved.insertPlaceholder) insertPlaceholderSnapshot = saved.insertPlaceholder;if (saved.pickedAnchor) pickedAnchorSnapshot = saved.pickedAnchor;+ if (Number.isFinite(saved.pickedAnchorViewportTop)) pickedAnchorViewportTop = saved.pickedAnchorViewportTop;if (saved.action) selectedAction = saved.action;if (saved.count) selectedCount = saved.count;if (saved.previewMode) currentPreviewMode = saved.previewMode;if (saved.paramValues && typeof saved.paramValues === 'object') {paramsCurrentValues = { ...saved.paramValues };}+ if (saved.parameterState) parameterGenerationState = saved.parameterState;+ if (saved.generationPhase) generationPhase = saved.generationPhase;}function normalizePagePath(value) {@@ -7859,7 +8140,7 @@ void main() {saveSession();queueCheckpoint(reason || 'browser_restore_without_wrapper');- const restoreFile = currentPreviewMode === 'svelte-component'+ const restoreFile = isFrameworkComponentPreviewMode(currentPreviewMode)? currentPreviewFile: (currentSourceFile || currentPreviewFile);if (restoreFile) {@@ -7872,11 +8153,41 @@ void main() {function restoreFromActiveSessions(activeSessions, reason) {const wrapper = document.querySelector('[data-impeccable-variants]');- if (wrapper && wrapper.dataset.impeccablePreview !== 'svelte-component') return false;+ if (wrapper && !isFrameworkComponentPreviewMode(wrapper.dataset.impeccablePreview)) return false;if (svelteComponentSession?.sessionId === currentSessionId) return false;return restoreSessionWithoutWrapper(reason || 'sse_connected', activeSessions);}+ // Self-heal on SSE (re)connect. The preflight scaffold write triggers a+ // framework full-reload (Astro reloads pages for any .astro edit); if the+ // agent's variant write + `done` broadcast land while this page is+ // mid-reload, both the done SSE and the second HMR reload are missed and+ // the resumed page would wait in GENERATING at 0/N forever. The server's+ // session summary carries the durable generationCompletedAt marker, so on+ // every connect compare it against our own progress and pull the finished+ // variants from source when behind. Mirrors the `done` handler's source+ // fallback, including its give-HMR-the-first-chance settle delay.+ function recoverMissedGenerationCompletion(activeSessions) {+ if (!currentSessionId || state !== 'GENERATING') return;+ if (!Array.isArray(activeSessions)) return;+ const summary = activeSessions.find((session) => session?.id === currentSessionId);+ if (!summary?.generationCompletedAt || summary.generationCanceled) return;+ if (isTerminalSessionSummary(summary)) return;+ if (arrivedVariants > 0 && arrivedVariants >= expectedVariants) return;+ rememberSessionFileMeta(summary);+ const sessionId = currentSessionId;+ const file = isFrameworkComponentPreviewMode(currentPreviewMode)+ ? currentPreviewFile+ : (summary.sourceFile || summary.previewFile || currentSourceFile || currentPreviewFile);+ if (!file) return;+ console.log('[impeccable] Reconnected after generation completed; recovering variants from source.');+ setTimeout(() => {+ if (sessionId !== currentSessionId || state !== 'GENERATING') return;+ if (arrivedVariants > 0 && arrivedVariants >= expectedVariants) return;+ injectVariantsFromSource(file, sessionId, { generationCompleted: true });+ }, 750);+ }+function saveSession() {if (!currentSessionId) return;// NOTE: scrollY is stored under a separate key (writeScrollY). Storing@@ -7894,8 +8205,12 @@ void main() {previewMode: currentPreviewMode || undefined,pageUrl: location.pathname,paramValues: { ...paramsCurrentValues },+ parameterState: parameterGenerationState,insertPlaceholder: insertPlaceholderSnapshot || undefined,pickedAnchor: pickedAnchorSnapshot || undefined,+ pickedAnchorViewportTop: Number.isFinite(pickedAnchorViewportTop) ? pickedAnchorViewportTop : undefined,+ pageHash: location.hash || undefined,+ pageSearch: location.search || undefined,});}@@ -7923,20 +8238,26 @@ void main() {sessionState.clearHandled();}- function cleanup() {+ function cleanup(options) {+ const restoreOriginal = options?.restoreOriginal === true;+ const instantChrome = options?.instantChrome === true;const cleanupSessionId = currentSessionId;if (svelteComponentSession?.sessionId === cleanupSessionId) {teardownSvelteComponentSession(true);} else if (cleanupSessionId) {- // Hide the wrapper immediately so variants disappear. DON'T structurally- // mutate the DOM yet - HMR from the agent's source rewrite is on its way,+ // Switch visibility immediately without structurally mutating the DOM.+ // HMR from the agent's source rewrite may still be on its way,// and a manual replaceChild under React causes NotFoundError when the// reconciler later tries to remove a wrapper we already removed.// Schedule a 2s fallback that does the manual swap only if HMR hasn't// replaced the wrapper by then (keeps static-server / no-HMR flows alive).const wrapper = document.querySelector('[data-impeccable-variants="' + cleanupSessionId + '"]');- if (wrapper) wrapper.style.display = 'none';+ if (wrapper) {+ if (restoreOriginal) showOriginalDuringDiscard(cleanupSessionId);+ else wrapper.style.display = 'none';+ }setTimeout(function() {+ document.getElementById(DISCARD_STATE_STYLE_ID)?.remove();if (!cleanupSessionId) return;const lateWrapper = document.querySelector('[data-impeccable-variants="' + cleanupSessionId + '"]');if (!lateWrapper) return;@@ -7951,7 +8272,7 @@ void main() {lateWrapper.remove();}, 2000);}- hideBar();+ hideBar(instantChrome);hideHighlight();stopScrollTracking();if (variantObserver) { variantObserver.disconnect(); variantObserver = null; }@@ -7963,7 +8284,11 @@ void main() {clearSession();resetSessionFileMeta();selectedElement = null;+ hoveredElement = null;+ pagePickSkipClick = false;currentSessionId = null;+ parameterGenerationState = 'idle';+ parameterReadyAnnouncedSession = null;selectedAction = 'impeccable';renderEditBadge('hidden');setLiveState('PICKING');@@ -8047,7 +8372,7 @@ void main() {// would strand the bar in CYCLING at 0/0. If there's no live in-memory mount// for this wrapper, it's an orphan (reload / failed mount): drop it and let// the live-server's SSE re-inject the manifest if the session is still live.- if (wrapper.dataset.impeccablePreview === 'svelte-component'+ if (isFrameworkComponentPreviewMode(wrapper.dataset.impeccablePreview)&& svelteComponentSession?.sessionId !== sessionId) {wrapper.remove();if (restoreSessionWithoutWrapper('browser_resumed_svelte_orphan_wrapper')) return true;@@ -8056,7 +8381,7 @@ void main() {return false;}- if (wrapper.dataset.impeccablePreview === 'svelte-component') {+ if (isFrameworkComponentPreviewMode(wrapper.dataset.impeccablePreview)) {if (!svelteComponentSession?.mountedVariant) {return true;}@@ -8104,7 +8429,7 @@ void main() {insertPlaceholderSnapshot = saved.insertPlaceholder;}- const resumedState = arrivedVariants >= expectedVariants ? 'CYCLING' : 'GENERATING';+ const resumedState = arrivedVariants > 0 ? 'CYCLING' : 'GENERATING';// Find the visible variant's content element for highlight positioning.const isInsert = wrapper.dataset.impeccableMode === 'insert';@@ -8128,7 +8453,11 @@ void main() {// hid. Now that state is CYCLING, re-fire.if (state === 'CYCLING') refreshParamsPanel();saveSession();- queueCheckpoint('browser_resumed');+ if (arrivedVariants > 0 && arrivedVariants < expectedVariants) {+ sendCheckpoint('variants_progress');+ } else {+ queueCheckpoint('browser_resumed');+ }// Start observing for more variants AFTER initial setupif (variantObserver) variantObserver.disconnect();@@ -8136,7 +8465,7 @@ void main() {// Hold the target at its saved viewport top through any subsequent// HMR patches, variant inserts, or cycle swaps.- startScrollLock(currentSessionId, readScrollY());+ startScrollLock(currentSessionId, readScrollY(), pickedAnchorViewportTop);// If we reloaded mid-generation (Bun's HTML HMR destroys the shader// canvas), re-capture the original's content and restart the shader so@@ -8171,6 +8500,7 @@ void main() {let globalBarBrandEl = null;let agentPollTooltipEl = null;let agentPollingConnected = false;+ let agentStatusMessage = null;let agentStatusPollTimer = null;let steerFocusSuspended = false;let steerFocusPauseUntil = 0;@@ -8275,6 +8605,13 @@ void main() {const AGENT_STATUS_POLL_MS = 5000;const AGENT_DISCONNECTED_MARK = 'oklch(62% 0 0 / 0.78)';const AGENT_DISCONNECTED_TIP = 'Agent disconnected - run live-poll.mjs to connect';+ // The indicator tracks whether a poll is parked, which is what decides if+ // steering can reach the agent right now. That goes quiet two ways, and they+ // need different copy: nobody is polling at all, or the agent took the work+ // and is busy with it. Under one-shot foreground polling the second case is+ // every normal generation, and telling the user to start a poll loop then is+ // wrong advice about a healthy session.+ const AGENT_BUSY_TIP = 'Agent is working - steering resumes when it finishes';const GLOBAL_BAR_SECTION_GAP = 8;const GLOBAL_BAR_INNER_GAP = 2;const GLOBAL_BAR_INNER_PAD_LEFT = 2;@@ -9295,24 +9632,46 @@ void main() {</svg>`;}+ /**+ * True while the browser is waiting on work it already handed to the agent.+ * In these states a quiet poll indicator means "busy", not "absent".+ */+ function agentHasWorkInFlight() {+ return state === 'GENERATING' || state === 'SAVING';+ }++ /**+ * Derived at read time, not cached: which of the two reasons applies depends on+ * the live state, which moves between the 5s status polls. The truthiness is+ * the same either way, so the indicator's visuals can stay driven by the+ * cached value while the wording stays current.+ */+ function agentStatusText() {+ if (agentPollingConnected) return null;+ return agentHasWorkInFlight() ? AGENT_BUSY_TIP : AGENT_DISCONNECTED_TIP;+ }+function syncAgentPollingUi(connected) {agentPollingConnected = !!connected;if (!globalBarBrandEl) return;const P = barPaletteForTheme(globalBarEl?.dataset.theme || detectPageTheme());+ agentStatusMessage = agentStatusText();globalBarBrandEl.dataset.agentConnected = connected ? 'true' : 'false';- globalBarBrandEl.setAttribute('aria-label', connected- ? 'Impeccable live mode'- : 'Impeccable live mode - agent not polling');+ // The tooltip is mouse-only, so carry the same distinction in the label or+ // screen-reader users are left with the vaguer of the two readings.+ globalBarBrandEl.setAttribute('aria-label', agentStatusMessage+ ? 'Impeccable live mode - ' + (agentHasWorkInFlight() ? 'agent is working' : 'agent not polling')+ : 'Impeccable live mode');globalBarBrandEl.removeAttribute('title');- globalBarBrandEl.style.cursor = connected ? 'default' : 'help';+ globalBarBrandEl.style.cursor = agentStatusMessage ? 'help' : 'default';const mark = globalBarBrandEl.querySelector('[data-brand-mark]');if (mark) {mark.innerHTML = brandMarkSvg(connected ? P.accent : AGENT_DISCONNECTED_MARK, 18);mark.style.opacity = '1';}const dot = globalBarBrandEl.querySelector('[data-agent-dot]');- if (dot) dot.style.display = connected ? 'none' : 'block';- if (connected) hideAgentPollTooltip();+ if (dot) dot.style.display = agentStatusMessage ? 'block' : 'none';+ if (!agentStatusMessage) hideAgentPollTooltip();}function ensureAgentPollTooltip() {@@ -9339,14 +9698,17 @@ void main() {whiteSpace: 'normal',});agentPollTooltipEl.id = PREFIX + '-agent-poll-tooltip';- agentPollTooltipEl.textContent = AGENT_DISCONNECTED_TIP;+ agentPollTooltipEl.textContent = agentStatusText() || AGENT_DISCONNECTED_TIP;uiAppend(agentPollTooltipEl);return agentPollTooltipEl;}function showAgentPollTooltip(anchor) {- if (agentPollingConnected || !anchor) return;+ if (!agentStatusMessage || !anchor) return;const tip = ensureAgentPollTooltip();+ // Re-derive rather than reuse the cached copy: the live state may have moved+ // since the last status poll set it.+ tip.textContent = agentStatusText() || AGENT_DISCONNECTED_TIP;tip.style.transition = 'none';tip.style.display = 'block';tip.style.opacity = '1';@@ -9376,7 +9738,9 @@ void main() {fetch('http://localhost:' + PORT + '/status?token=' + TOKEN, { cache: 'no-store' }).then((res) => (res.ok ? res.json() : null)).then((data) => {- if (data && typeof data.agentPolling === 'boolean') syncAgentPollingUi(data.agentPolling);+ if (data && typeof data.agentPolling === 'boolean') {+ syncAgentPollingUi(data.agentPolling);+ }}).catch(() => { /* server loss handled elsewhere */ });}diff --git a/plugin/skills/impeccable/scripts/live-inject.mjs b/plugin/skills/impeccable/scripts/live-inject.mjsindex 7c8d91182..d99c37fd5 100644--- a/plugin/skills/impeccable/scripts/live-inject.mjs+++ b/plugin/skills/impeccable/scripts/live-inject.mjs@@ -27,6 +27,8 @@ const __dirname = path.dirname(fileURLToPath(import.meta.url));const CONFIG_PATH = resolveLiveConfigPath({ cwd: process.cwd(), scriptsDir: __dirname });const MARKER_OPEN_TEXT = 'impeccable-live-start';const MARKER_CLOSE_TEXT = 'impeccable-live-end';+const NUXT_PLUGIN_MARKER = 'impeccable-live-nuxt-plugin';+const NUXT_PLUGIN_NAME = 'impeccable-live.client.ts';const IGNORE_MARKER_OPEN = '# impeccable-live-ignore-start';const IGNORE_MARKER_CLOSE = '# impeccable-live-ignore-end';@@ -38,6 +40,9 @@ export const LIVE_IGNORE_PATTERNS = Object.freeze(['.impeccable/live/sessions/','.impeccable/live/previews/','.impeccable/live/annotations/',+ '.impeccable/live/artifacts/',+ '.impeccable/live/accept-receipts/',+ '.impeccable/live/locks/','.impeccable/live/cache/','.impeccable/live/manual-edit-apply-transaction.json','.impeccable/live/manual-edit-events.jsonl',@@ -46,10 +51,15 @@ export const LIVE_IGNORE_PATTERNS = Object.freeze(['.impeccable/live/deferred-svelte-component-accepts.json','.impeccable-live.json','.impeccable-live/',+ 'app/.impeccable-live/',+ 'src/.impeccable-live/','node_modules/.impeccable-live/','src/lib/impeccable/ImpeccableLiveRoot.svelte','src/lib/impeccable/__runtime.js','src/lib/impeccable/[0-9a-f]*/',+ 'plugins/impeccable-live.client.ts',+ 'app/plugins/impeccable-live.client.ts',+ 'src/plugins/impeccable-live.client.ts',]);/**@@ -113,6 +123,7 @@ Output (JSON):const resolvedFiles = resolveFiles(process.cwd(), config);const svelteKit = detectSvelteKitProject(process.cwd(), config);+ const nuxt = detectNuxtProject(process.cwd());if (args.includes('--remove')) {if (svelteKit) {@@ -120,6 +131,12 @@ Output (JSON):console.log(JSON.stringify({ ok: true, adapter: 'sveltekit', results: [adapterResult] }));return;}+ if (nuxt) {+ const adapterResult = removeNuxtLiveAdapter({ cwd: process.cwd(), project: nuxt });+ console.log(JSON.stringify({ ok: !adapterResult.error, adapter: 'nuxt', results: [adapterResult] }));+ if (adapterResult.error) process.exitCode = 1;+ return;+ }const results = resolvedFiles.map((relFile) => {const absFile = path.resolve(process.cwd(), relFile);if (!fs.existsSync(absFile)) return { file: relFile, error: 'file_not_found' };@@ -145,13 +162,28 @@ Output (JSON):console.error(JSON.stringify({ ok: false, error: 'missing_port' }));process.exit(1);}- const gitIgnore = ensureLiveGitIgnores(process.cwd());+ const gitIgnore = ensureLiveGitIgnores(+ process.cwd(),+ nuxt ? [nuxt.pluginFile] : [],+ );if (svelteKit) {const adapterResult = applySvelteKitLiveAdapter({ cwd: process.cwd(), port, config });console.log(JSON.stringify({ ok: true, port, adapter: 'sveltekit', gitIgnore, results: [adapterResult] }));return;}+ if (nuxt) {+ const adapterResult = applyNuxtLiveAdapter({ cwd: process.cwd(), port, project: nuxt });+ console.log(JSON.stringify({+ ok: !adapterResult.error,+ port,+ adapter: 'nuxt',+ gitIgnore,+ results: [adapterResult],+ }));+ if (adapterResult.error) process.exitCode = 1;+ return;+ }const results = resolvedFiles.map((relFile) => {const absFile = path.resolve(process.cwd(), relFile);@@ -175,12 +207,12 @@ Output (JSON):if (!anyInserted) process.exit(1);}-export function ensureLiveGitIgnores(cwd = process.cwd()) {+export function ensureLiveGitIgnores(cwd = process.cwd(), extraPatterns = []) {const target = resolveIgnoreTarget(cwd);const existing = fs.existsSync(target.path) ? fs.readFileSync(target.path, 'utf-8') : '';const block = [IGNORE_MARKER_OPEN,- ...LIVE_IGNORE_PATTERNS,+ ...new Set([...LIVE_IGNORE_PATTERNS, ...extraPatterns]),IGNORE_MARKER_CLOSE,].join('\n');const markerRe = new RegExp(`${escapeRegExp(IGNORE_MARKER_OPEN)}[\\s\\S]*?${escapeRegExp(IGNORE_MARKER_CLOSE)}`);@@ -202,10 +234,119 @@ export function ensureLiveGitIgnores(cwd = process.cwd()) {file: path.relative(cwd, target.path).split(path.sep).join('/'),mode: target.mode,changed: updated !== existing,- patterns: [...LIVE_IGNORE_PATTERNS],+ patterns: [...new Set([...LIVE_IGNORE_PATTERNS, ...extraPatterns])],};}+// ---------------------------------------------------------------------------+// Nuxt adapter+//+// A script element placed in app.vue is compiled as Vue-rendered DOM and is+// not executed. Nuxt instead auto-discovers client plugins. Keep the adapter+// generated, dev-only, and outside user-authored source: Live creates one+// marked .client.ts plugin on start and removes it on stop.+// ---------------------------------------------------------------------------++export function detectNuxtProject(cwd = process.cwd()) {+ const configFile = fs.readdirSync(cwd, { withFileTypes: true })+ .find((entry) => entry.isFile() && /^nuxt\.config\.(?:js|mjs|cjs|ts|mts|cts)$/.test(entry.name))+ ?.name;+ if (!configFile) return null;++ const config = fs.readFileSync(path.join(cwd, configFile), 'utf-8');+ const literalSrcDir = config.match(/\bsrcDir\s*:\s*(['"])([^'"]+)\1/);+ let appDir = '';+ if (literalSrcDir) {+ const candidate = literalSrcDir[2]+ .replace(/\\/g, '/')+ .replace(/^\.\//, '')+ .replace(/\/+$/, '');+ const normalized = path.posix.normalize(candidate);+ if (normalized !== '..' && !normalized.startsWith('../') && !path.isAbsolute(normalized)) {+ appDir = normalized === '.' ? '' : normalized;+ }+ } else if (+ fs.existsSync(path.join(cwd, 'app', 'app.vue'))+ || fs.existsSync(path.join(cwd, 'app', 'pages'))+ ) {+ appDir = 'app';+ }++ const pluginFile = [appDir, 'plugins', NUXT_PLUGIN_NAME].filter(Boolean).join('/');+ return { configFile, appDir, pluginFile };+}++export function buildNuxtPlugin(port) {+ return `/* ${NUXT_PLUGIN_MARKER} */+const liveSrc = 'http://localhost:${port}/live.js';+const liveSelector = 'script[data-impeccable-live-nuxt]';++export default defineNuxtPlugin(() => {+ if (!import.meta.dev || typeof document === 'undefined') return;++ const expectedSrc = new URL(liveSrc, window.location.href).href;+ let script = document.querySelector(liveSelector);+ if (script?.src === expectedSrc) return;+ script?.remove();++ script = document.createElement('script');+ script.src = liveSrc;+ script.async = true;+ script.dataset.impeccableLiveNuxt = '';+ document.head.appendChild(script);++ import.meta.hot?.dispose(() => {+ if (script?.isConnected) script.remove();+ });+});+/* /${NUXT_PLUGIN_MARKER} */+`;+}++export function applyNuxtLiveAdapter({ cwd = process.cwd(), port, project = detectNuxtProject(cwd) }) {+ if (!project) return { error: 'nuxt_not_detected' };+ const absFile = path.join(cwd, project.pluginFile);+ const existing = fs.existsSync(absFile) ? fs.readFileSync(absFile, 'utf-8') : null;+ if (existing !== null && !existing.includes(NUXT_PLUGIN_MARKER)) {+ return {+ file: project.pluginFile,+ error: 'nuxt_plugin_conflict',+ hint: `${project.pluginFile} already exists and is not managed by Impeccable Live`,+ };+ }++ const content = buildNuxtPlugin(port);+ fs.mkdirSync(path.dirname(absFile), { recursive: true });+ if (content !== existing) fs.writeFileSync(absFile, content, 'utf-8');+ return {+ file: project.pluginFile,+ inserted: true,+ changed: content !== existing,+ devOnly: true,+ };+}++export function removeNuxtLiveAdapter({ cwd = process.cwd(), project = detectNuxtProject(cwd) }) {+ if (!project) return { error: 'nuxt_not_detected' };+ const absFile = path.join(cwd, project.pluginFile);+ if (!fs.existsSync(absFile)) {+ return { file: project.pluginFile, removed: false, note: 'no adapter present' };+ }+ const content = fs.readFileSync(absFile, 'utf-8');+ if (!content.includes(NUXT_PLUGIN_MARKER)) {+ return {+ file: project.pluginFile,+ removed: false,+ error: 'nuxt_plugin_conflict',+ hint: `${project.pluginFile} is not managed by Impeccable Live`,+ };+ }+ fs.unlinkSync(absFile);+ const pluginDir = path.dirname(absFile);+ if (fs.readdirSync(pluginDir).length === 0) fs.rmdirSync(pluginDir);+ return { file: project.pluginFile, removed: true };+}+function resolveIgnoreTarget(cwd) {const gitExcludePath = resolveGitInfoExcludePath(cwd);if (gitExcludePath) {diff --git a/plugin/skills/impeccable/scripts/live-poll.mjs b/plugin/skills/impeccable/scripts/live-poll.mjsindex 740161e10..19a8b0f9b 100644--- a/plugin/skills/impeccable/scripts/live-poll.mjs+++ b/plugin/skills/impeccable/scripts/live-poll.mjs@@ -27,7 +27,7 @@ const scriptCmd = (name) => `node "${path.join(SELF_DIR, name)}"`;export const PER_REQUEST_TIMEOUT_MS = 270_000;export const DEFAULT_EVENT_LEASE_MS = 600_000;-const EVENT_TYPES_NEEDING_AGENT_REPLY = new Set(['generate', 'steer', 'manual_edit_apply']);+const EVENT_TYPES_NEEDING_AGENT_REPLY = new Set(['generate', 'steer', 'manual_edit_apply', 'carbonize_cleanup']);function readServerInfo() {const record = readLiveServerInfo(process.cwd());@@ -38,8 +38,8 @@ function readServerInfo() {return record.info;}-export function buildPollReplyPayload(token, { id, type, message, file, data }) {- return { token, id, type, message, file, data };+export function buildPollReplyPayload(token, { id, type, message, file, data, sourceEventType }) {+ return { token, id, type, message, file, data, sourceEventType };}export function manualApplyPollBanner(event = {}) {@@ -152,7 +152,14 @@ export async function waitForEventAck(base, token, eventId, {return false;}-export async function fetchNextEvent(base, token, { totalDeadline } = {}) {+export async function fetchNextEvent(base, token, {+ totalDeadline,+ types,+ resolveTypes,+ perRequestTimeoutMs = PER_REQUEST_TIMEOUT_MS,+ leaseMs = DEFAULT_EVENT_LEASE_MS,+ signal,+} = {}) {while (true) {if (totalDeadline && Date.now() >= totalDeadline) {return { type: 'timeout' };@@ -161,8 +168,15 @@ export async function fetchNextEvent(base, token, { totalDeadline } = {}) {const remaining = totalDeadline? totalDeadline - Date.now(): PER_REQUEST_TIMEOUT_MS;- const slice = Math.min(Math.max(remaining, 1000), PER_REQUEST_TIMEOUT_MS);- const res = await fetch(`${base}/poll?token=${token}&timeout=${slice}&leaseMs=${DEFAULT_EVENT_LEASE_MS}`);+ const slice = Math.min(Math.max(remaining, 1000), perRequestTimeoutMs);+ const query = new URLSearchParams({+ token,+ timeout: String(slice),+ leaseMs: String(leaseMs),+ });+ const normalizedTypes = normalizePollTypes(resolveTypes ? await resolveTypes() : types);+ if (normalizedTypes.length > 0) query.set('types', normalizedTypes.join(','));+ const res = await fetch(`${base}/poll?${query}`, { signal });if (res.status === 401) {const err = new Error('Authentication failed. The server token may have changed.');@@ -202,11 +216,17 @@ export async function augmentEventWithAcceptHandling(event, base, token) {event._acceptResult = { handled: false, mode: 'error', error: err.message };}+ await completeAcceptHandling(event, base, token);+ return event;+}++export async function completeAcceptHandling(event, base, token) {const completionType = completionTypeForAcceptResult(event.type, event._acceptResult);try {await postReply(base, token, {id: event.id,type: completionType,+ sourceEventType: event.type,message: event._acceptResult?.error,file: event._acceptResult?.file,data: event._acceptResult?.carbonize === true ? { carbonize: true } : undefined,@@ -217,7 +237,6 @@ export async function augmentEventWithAcceptHandling(event, base, token) {if (!event._completionAck) {event._completionAck = completionAckForAcceptResult(event.id, completionType, event._acceptResult);}-return event;}@@ -245,9 +264,9 @@ export function printPollEvent(event) {console.log(JSON.stringify(event));}-export async function runPollOnce(base, token, { totalTimeout = 600_000 } = {}) {+export async function runPollOnce(base, token, { totalTimeout = 600_000, types, resolveTypes, perRequestTimeoutMs } = {}) {const deadline = Date.now() + totalTimeout;- const event = await fetchNextEvent(base, token, { totalDeadline: deadline });+ const event = await fetchNextEvent(base, token, { totalDeadline: deadline, types, resolveTypes, perRequestTimeoutMs });await augmentEventWithAcceptHandling(event, base, token);writeCarbonizeBanner(event);printPollEvent(event);@@ -258,11 +277,14 @@ export async function runPollStream(base, token, {ackTimeoutMs = 600_000,ackPollIntervalMs = 400,shouldContinue = () => true,+ types,+ resolveTypes,+ perRequestTimeoutMs,} = {}) {process.stderr.write('[impeccable-poll] stream mode: one JSON object per line on stdout; use --reply while this process stays running\n');while (shouldContinue()) {- const event = await fetchNextEvent(base, token);+ const event = await fetchNextEvent(base, token, { types, resolveTypes, perRequestTimeoutMs });await augmentEventWithAcceptHandling(event, base, token);writeCarbonizeBanner(event);printPollEvent(event);@@ -322,14 +344,17 @@ Modes:Options:--timeout=MS One-shot poll timeout in ms (default: 600000). Ignored in --stream mode+ --types=A,B Lease only these event types--ack-timeout=MS Stream mode: max wait for --reply after generate/steer (default: 600000)--file PATH Attach a source file path to the reply (generate/steer flow)--data JSON Attach a JSON result object to the reply (manual_edit_apply flow). Must be valid JSON--help Show this help messageHarness note:- Default one-shot mode is the portable contract for Claude Code, Codex, and Cursor.- --stream is experimental for harnesses with fast incremental stdout; do not use on Cursor.`);+ Default one-shot mode is the primary contract, including Codex foreground polling.+ Claude Code may run it as a background task; Cursor uses a background terminal with exit notification.+ --stream is retained for harnesses with measured, reliable incremental stdout.+ Do not use --stream on Cursor.`);process.exit(0);}@@ -360,23 +385,30 @@ Harness note:}const streamMode = args.includes('--stream');+ const typesArg = args.find((a) => a.startsWith('--types='));+ const types = normalizePollTypes(typesArg ? typesArg.slice('--types='.length) : null);const ackTimeoutArg = args.find((a) => a.startsWith('--ack-timeout='));const ackTimeoutMs = ackTimeoutArg ? parseInt(ackTimeoutArg.split('=')[1], 10) : 600_000;try {if (streamMode) {- await runPollStream(base, info.token, { ackTimeoutMs });+ await runPollStream(base, info.token, { ackTimeoutMs, types });return;}const timeoutArg = args.find((a) => a.startsWith('--timeout='));const totalTimeout = timeoutArg ? parseInt(timeoutArg.split('=')[1], 10) : 600_000;- await runPollOnce(base, info.token, { totalTimeout });+ await runPollOnce(base, info.token, { totalTimeout, types });} catch (err) {handlePollError(err);}}+export function normalizePollTypes(value) {+ const values = Array.isArray(value) ? value : String(value || '').split(',');+ return [...new Set(values.map((type) => String(type).trim()).filter(Boolean))];+}+// Auto-execute when run directlyconst _running = process.argv[1];if (_running?.endsWith('live-poll.mjs') || _running?.endsWith('live-poll.mjs/')) {diff --git a/plugin/skills/impeccable/scripts/live-server.mjs b/plugin/skills/impeccable/scripts/live-server.mjsindex 5735f2aec..c6e951086 100644--- a/plugin/skills/impeccable/scripts/live-server.mjs+++ b/plugin/skills/impeccable/scripts/live-server.mjs@@ -28,8 +28,10 @@ import {readLiveBrowserScriptParts,resolveLiveBrowserScriptParts,} from './live/browser-script-parts.mjs';-import { createLiveSessionStore } from './live/session-store.mjs';+import { createLiveSessionStore, GENERATION_FENCED_PHASES } from './live/session-store.mjs';+import { runGenerationPreflight } from './live/generation-preflight.mjs';import { validateEvent } from './live/event-validation.mjs';+import { selectAvailablePendingEvent } from './live/poll-lanes.mjs';import { createManualEditRoutes } from './live/manual-edit-routes.mjs';import { LIVE_COMMANDS } from './live/vocabulary.mjs';import {@@ -63,6 +65,10 @@ const DESIGN_MD_PATH = PROJECT_CONTEXT.designPath: null;const DEFAULT_POLL_TIMEOUT = 600_000; // 10 min — agent re-polls on timeout anywayconst SSE_HEARTBEAT_INTERVAL = 30_000; // keepalive ping every 30s+// The browser checkpoints for several unrelated reasons (see checkpointPayload+// in live-browser.js). Only these two report that variant availability changed,+// and only they may drive variant_progress / the *_reviewable phases.+const VARIANT_PROGRESS_CHECKPOINT_REASONS = new Set(['variants_progress', 'variants_ready']);// ---------------------------------------------------------------------------// Port detection@@ -156,29 +162,206 @@ function restorePendingEventsFromStore() {}}-function findAvailablePendingEvent(now = Date.now()) {- for (const entry of state.pendingEvents) {- if (entry.leaseUntil && entry.leaseUntil > now) continue;- return entry;- }- return null;+function findAvailablePendingEvent(now = Date.now(), types = null) {+ return selectAvailablePendingEvent(state.pendingEvents, { now, types });}-function leaseEvent(entry, leaseMs) {+async function leaseEvent(entry, leaseMs) {+ // Claim the entry before awaiting anything. prepareGenerateEventForLease+ // yields to the event loop, and selectAvailablePendingEvent only skips+ // entries whose lease is in the future — an unclaimed entry would be handed+ // to a second poll in that window and generated twice.+ entry.leaseUntil = Date.now() + leaseMs;+ await prepareGenerateEventForLease(entry);if (!entry.event?.id) {const idx = state.pendingEvents.indexOf(entry);if (idx !== -1) state.pendingEvents.splice(idx, 1);return entry.event;}+ // Re-stamp so the lease window starts when the agent actually receives the+ // work, not when scaffolding began.entry.leaseUntil = Date.now() + leaseMs;+ recordGenerateDelivery(entry);scheduleLeaseFlush();broadcastAgentPollingIfChanged();return entry.event;}-function acknowledgePendingEvent(id) {+function recordGenerateDelivery(entry) {+ const event = entry?.event;+ if (!event || event.type !== 'generate' || event.generationReadyAt) return;+ const at = Date.now();+ entry.event = { ...event, generationReadyAt: at };+ state.sessionStore?.appendEvent(entry.event);+ recordAgentPhase(event.id, 'generation_ready', { at });+}++async function prepareGenerateEventForLease(entry) {+ const event = entry?.event;+ if (!event || event.type !== 'generate' || event.scaffoldAttempted) return;++ recordAgentPhase(event.id, 'picked_up');+ recordAgentPhase(event.id, 'scaffolding');+ const result = await runGenerationPreflight(event, {+ cwd: process.cwd(),+ scriptsDir: __dirname,+ });+ entry.event = {+ ...event,+ scaffoldAttempted: true,+ scaffoldDurationMs: result.durationMs ?? null,+ ...(result.ok ? { scaffold: result.scaffold } : { scaffoldError: result.error || result.reason }),+ };+ state.sessionStore?.appendEvent(entry.event);+ recordAgentPhase(event.id, result.ok ? 'source_ready' : 'scaffold_fallback', {+ durationMs: result.durationMs ?? null,+ previewMode: result.scaffold?.previewMode || 'source',+ });+}++function recordAgentPhase(id, phase, details = {}) {+ if (!id) return;+ const event = {+ type: 'agent_phase',+ id,+ phase,+ at: Date.now(),+ ...details,+ };+ state.sessionStore?.appendEvent(event);+ broadcast(event);+}++/**+ * Detect a browser that missed the generation `done` broadcast.+ *+ * The preflight scaffold write triggers a framework full-reload (Astro reloads+ * the page for any .astro edit). If the agent's variant write + `done` land+ * while the browser is mid-reload, the new page misses both the second HMR+ * reload and the SSE `done` — it resumes from the scaffold-only source and+ * sits in GENERATING at 0/N forever. That resumed page always checkpoints+ * (`browser_resumed`), so a checkpoint claiming "still generating, variants+ * missing" for a session whose generation already completed is direct+ * evidence of the miss. Rebuild the `done` payload from the snapshot so the+ * caller can re-broadcast it; the browser's done handler is idempotent and+ * falls back to injecting variants from source.+ *+ * Keys on the store's monotone `generationCompletedAt`, not `phase` — the+ * behind checkpoint itself regresses `phase` to `generating`, and a browser+ * that misses the redelivered `done` too (another reload) must still trigger+ * redelivery from its next checkpoint.+ */+function detectMissedGenerationCompletion(event) {+ if (!event?.id || event.type !== 'checkpoint') return null;+ if (event.phase !== 'generating') return null;+ if (!variantCountLooksBehind(event.arrivedVariants, event.expectedVariants)) return null;+ if (!state.sessionStore) return null;+ let snapshot = null;+ try {+ snapshot = state.sessionStore.getSnapshot(event.id);+ } catch {+ return null;+ }+ return missedCompletionFromSnapshot(snapshot);+}++function variantCountLooksBehind(arrivedValue, expectedValue) {+ const arrived = Number(arrivedValue) || 0;+ const expected = Number(expectedValue) || 0;+ return arrived <= 0 || (expected > 0 && arrived < expected);+}++function missedCompletionFromSnapshot(snapshot) {+ if (!snapshot?.id || !snapshot.generationCompletedAt) return null;+ if (snapshot.generationCanceled) return null;+ // Accept/discard already underway: the browser is no longer waiting on+ // generation, and a late `done` there would collide with teardown.+ if (GENERATION_FENCED_PHASES.has(snapshot.phase)) return null;+ const file = snapshot.sourceFile || snapshot.previewFile;+ if (!file) return null;+ return {+ type: 'done',+ id: snapshot.id,+ file,+ sourceFile: snapshot.sourceFile || undefined,+ previewFile: snapshot.previewFile || undefined,+ previewMode: snapshot.previewMode || undefined,+ redelivered: true,+ };+}++function recordGenerationCheckpoint(event) {+ if (!event?.id || event.type !== 'checkpoint') return;+ if (generationIsFenced(event.id)) return;+ // Only checkpoints that report a change in variant availability are+ // generation progress. The browser also checkpoints for durability on Tune+ // slider drags, resumes, and anchor recovery; treating those as progress+ // echoed `variant_progress` straight back to the browser that sent it, which+ // remounts the component preview mid-drag (reverting the user's live param+ // edit and detaching the popover's element), and permanently latched the+ // *_reviewable phases from the wrong trigger, corrupting generation timings.+ if (!VARIANT_PROGRESS_CHECKPOINT_REASONS.has(event.reason)) return;+ const arrived = Number(event.arrivedVariants) || 0;+ const expected = Number(event.expectedVariants) || 0;+ if (arrived <= 0 || expected <= 0) return;+ const previewMode = event.previewMode || 'source';+ const previewFile = event.previewFile || event.file;+ if (previewFile) {+ broadcast({+ type: 'variant_progress',+ id: event.id,+ file: previewFile,+ sourceFile: event.sourceFile || (previewMode === 'source' ? previewFile : undefined),+ previewFile,+ previewMode,+ arrivedVariants: arrived,+ expectedVariants: expected,+ publicationKind: event.publicationKind || 'variants',+ });+ }+ const details = {+ arrivedVariants: arrived,+ expectedVariants: expected,+ checkpointReason: event.reason || null,+ };+ const at = Date.now();+ if (!generationPhaseAlreadyRecorded(event.id, 'first_reviewable')) {+ recordAgentPhase(event.id, 'first_reviewable', { ...details, at });+ }+ if (arrived >= 2 && expected >= 3 && !generationPhaseAlreadyRecorded(event.id, 'second_reviewable')) {+ recordAgentPhase(event.id, 'second_reviewable', { ...details, at });+ }+ if (arrived >= expected && !generationPhaseAlreadyRecorded(event.id, 'all_variants_ready')) {+ recordAgentPhase(event.id, 'all_variants_ready', { ...details, at });+ }+}++function generationIsFenced(id) {+ if (!state.sessionStore || !id) return false;+ try {+ const snapshot = state.sessionStore.getSnapshot(id, { includeCompleted: true });+ return snapshot?.generationCanceled === true;+ } catch {+ return false;+ }+}++function generationPhaseAlreadyRecorded(id, phase) {+ if (!state.sessionStore) return false;+ try {+ const snapshot = state.sessionStore.getSnapshot(id, { includeCompleted: true });+ return !!snapshot?.generationTimings?.[phase];+ } catch {+ return false;+ }+}++function acknowledgePendingEvent(id, sourceEventType) {if (!id) return false;- const idx = state.pendingEvents.findIndex((entry) => entry.event?.id === id);+ const idx = state.pendingEvents.findIndex((entry) => (+ entry.event?.id === id+ && (!sourceEventType || entry.event?.type === sourceEventType)+ ));if (idx === -1) return false;const acknowledged = state.pendingEvents[idx].event;state.pendingEvents.splice(idx, 1);@@ -187,9 +370,39 @@ function acknowledgePendingEvent(id) {return acknowledged;}-function findPendingEventById(id) {+function releasePendingEvent(id, sourceEventType) {+ const entry = state.pendingEvents.find((item) => (+ item.event?.id === id+ && (!sourceEventType || item.event?.type === sourceEventType)+ ));+ if (!entry) return null;+ entry.leaseUntil = 0;+ scheduleLeaseFlush();+ return entry.event;+}++function retirePendingGeneration(id) {+ if (!id) return 0;+ let retired = 0;+ for (let index = state.pendingEvents.length - 1; index >= 0; index -= 1) {+ const event = state.pendingEvents[index]?.event;+ if (event?.id !== id || event.type !== 'generate') continue;+ state.pendingEvents.splice(index, 1);+ retired += 1;+ }+ if (retired > 0) {+ scheduleLeaseFlush();+ broadcastAgentPollingIfChanged();+ }+ return retired;+}++function findPendingEventById(id, sourceEventType) {if (!id) return null;- const entry = state.pendingEvents.find((item) => item.event?.id === id);+ const entry = state.pendingEvents.find((item) => (+ item.event?.id === id+ && (!sourceEventType || item.event?.type === sourceEventType)+ ));return entry?.event || null;}@@ -198,7 +411,7 @@ function summarizePendingEventForStatus(entry) {const summary = {id: event.id,type: event.type,- leased: !!(entry.leaseUntil && entry.leaseUntil > Date.now()),+ leased: isLeased(entry),leaseUntil: entry.leaseUntil || null,};if (event.type === 'manual_edit_apply') {@@ -224,7 +437,13 @@ function summarizeActiveSessionForClient(snapshot = {}) {arrivedVariants: snapshot.arrivedVariants ?? 0,visibleVariant: snapshot.visibleVariant ?? null,checkpointRevision: snapshot.checkpointRevision ?? 0,+ browserCheckpointRevision: snapshot.browserCheckpointRevision ?? snapshot.checkpointRevision ?? 0,+ publicationCheckpointRevision: snapshot.publicationCheckpointRevision ?? 0,paramValues: snapshot.paramValues || {},+ generationPhase: snapshot.generationPhase ?? null,+ generationCompletedAt: snapshot.generationCompletedAt ?? null,+ generationCanceled: snapshot.generationCanceled === true,+ cancelReason: snapshot.cancelReason ?? null,};}@@ -269,24 +488,46 @@ function scheduleLeaseFlush() {function flushPendingPolls() {let changed = false;while (state.pendingPolls.length > 0) {- const entry = findAvailablePendingEvent();+ let pollIndex = -1;+ let entry = null;+ for (let index = 0; index < state.pendingPolls.length; index += 1) {+ const candidate = findAvailablePendingEvent(Date.now(), state.pendingPolls[index].types);+ if (!candidate) continue;+ pollIndex = index;+ entry = candidate;+ break;+ }if (!entry) {scheduleLeaseFlush();broadcastAgentPollingIfChanged();return;}- const poll = state.pendingPolls.shift();- poll.resolve(leaseEvent(entry, poll.leaseMs));+ const [poll] = state.pendingPolls.splice(pollIndex, 1);+ // leaseEvent is async (it may scaffold source), but it claims the entry+ // synchronously, so the next loop iteration will not re-select it. Resolve+ // the poll when the lease settles rather than awaiting here, so one slow+ // scaffold never delays the other parked polls. On the exceptional failure+ // path, answer `timeout` so the agent re-polls; the claim stays until the+ // lease expires, which keeps a deterministic failure from hot-looping.+ leaseEvent(entry, poll.leaseMs).then(poll.resolve, (error) => {+ console.error('[live] lease failed for ' + (entry.event?.id || 'unknown') + ': ' + (error?.message || error));+ poll.resolve({ type: 'timeout' });+ });changed = true;}scheduleLeaseFlush();if (changed) broadcastAgentPollingIfChanged();}+function isLeased(entry) {+ return !!(entry?.leaseUntil && entry.leaseUntil > Date.now());+}+function agentPollingConnected() {- const now = Date.now();- return state.pendingPolls.length > 0- || state.pendingEvents.some((entry) => entry.leaseUntil && entry.leaseUntil > now);+ // A leased event only proves that a poll returned once. The foreground task+ // may have ended immediately afterward, so only an actively waiting poll is+ // evidence that steering can wake the task right now.+ return state.pendingPolls.length > 0;}function broadcastAgentPollingIfChanged() {@@ -689,6 +930,16 @@ function createRequestHandler({ detectScript, liveScriptParts }) {res.end(JSON.stringify({ error }));return;}+ if (msg.type === 'agent_phase') {+ recordAgentPhase(msg.id, msg.phase, {+ ...(Number.isFinite(msg.durationMs) ? { durationMs: msg.durationMs } : {}),+ owner: typeof msg.owner === 'string' ? msg.owner : undefined,+ });+ res.writeHead(200, { 'Content-Type': 'application/json' });+ res.end(JSON.stringify({ ok: true }));+ return;+ }+ const missedCompletion = detectMissedGenerationCompletion(msg);if (state.sessionStore && msg.id) {try {state.sessionStore.appendEvent(msg);@@ -698,6 +949,11 @@ function createRequestHandler({ detectScript, liveScriptParts }) {return;}}+ if (msg.type === 'accept' || msg.type === 'discard') {+ retirePendingGeneration(msg.id);+ }+ recordGenerationCheckpoint(msg);+ if (missedCompletion) broadcast(missedCompletion);if (msg.type === 'exit') {cleanupSvelteComponentSessionsBeforeExit();}@@ -738,6 +994,12 @@ function createRequestHandler({ detectScript, liveScriptParts }) {// Agent poll endpoints (unchanged from WS version)// ---------------------------------------------------------------------------+function parsePollTypes(value) {+ if (!value) return null;+ const types = String(value).split(',').map((type) => type.trim()).filter(Boolean);+ return types.length > 0 ? new Set(types) : null;+}+function handlePollGet(req, res, url) {const token = url.searchParams.get('token');if (token !== state.token) {@@ -748,13 +1010,25 @@ function handlePollGet(req, res, url) {state.lastPollAt = Date.now();const timeout = parseInt(url.searchParams.get('timeout') || DEFAULT_POLL_TIMEOUT, 10);const leaseMs = parseInt(url.searchParams.get('leaseMs') || '30000', 10);- const available = findAvailablePendingEvent();+ const types = parsePollTypes(url.searchParams.get('types'));+ const available = findAvailablePendingEvent(Date.now(), types);if (available) {- res.writeHead(200, { 'Content-Type': 'application/json' });- res.end(JSON.stringify(leaseEvent(available, leaseMs)));+ // Do not await inline: leaseEvent may scaffold source, and this handler runs+ // on the server's only thread. The client can disconnect during that window,+ // so check the socket before replying.+ leaseEvent(available, leaseMs).then((event) => {+ if (res.writableEnded || res.destroyed) return;+ res.writeHead(200, { 'Content-Type': 'application/json' });+ res.end(JSON.stringify(event));+ }, (error) => {+ console.error('[live] lease failed for ' + (available.event?.id || 'unknown') + ': ' + (error?.message || error));+ if (res.writableEnded || res.destroyed) return;+ res.writeHead(200, { 'Content-Type': 'application/json' });+ res.end(JSON.stringify({ type: 'timeout' }));+ });return;}- const poll = { resolve, leaseMs };+ const poll = { resolve, leaseMs, types };const timer = setTimeout(() => {const idx = state.pendingPolls.indexOf(poll);if (idx !== -1) state.pendingPolls.splice(idx, 1);@@ -783,12 +1057,15 @@ function sessionFileMetadataFromPollReply(file) {if (!file || typeof file !== 'string') return { file };const normalized = file.split(path.sep).join('/');const base = { file: normalized };- if (!normalized.endsWith('/manifest.json') && normalized !== 'manifest.json') return base;- if (!normalized.includes('node_modules/.impeccable-live/') && !normalized.includes('src/lib/impeccable/')) return base;+ const metadataFile = normalized;+ if (!metadataFile.endsWith('/manifest.json') && metadataFile !== 'manifest.json') return base;+ if (!metadataFile.includes('node_modules/.impeccable-live/')+ && !metadataFile.includes('src/lib/impeccable/')+ && !metadataFile.includes('/.impeccable-live/')) return base;let full;try {- full = path.resolve(process.cwd(), normalized);+ full = path.resolve(process.cwd(), metadataFile);const rel = path.relative(process.cwd(), full);if (!rel || rel.startsWith('..') || path.isAbsolute(rel)) return base;} catch {@@ -797,18 +1074,47 @@ function sessionFileMetadataFromPollReply(file) {try {const manifest = JSON.parse(fs.readFileSync(full, 'utf-8'));- if (manifest?.previewMode !== 'svelte-component' || !manifest.sourceFile) return base;+ if (manifest?.previewMode !== 'svelte-component'+ || !manifest.sourceFile) return base;return {file: String(manifest.sourceFile).split(path.sep).join('/'),sourceFile: String(manifest.sourceFile).split(path.sep).join('/'),previewFile: normalized,- previewMode: 'svelte-component',+ previewMode: manifest.previewMode,};} catch {return base;}}+function inferSourceEventType(msg = {}, pendingEvents = state.pendingEvents) {+ const entriesForId = pendingEvents.filter((entry) => entry.event?.id === msg.id);+ const pendingTypes = new Set(entriesForId.map((entry) => entry.event?.type));+ if (msg.type === 'discarded' || msg.type === 'discard') return 'discard';+ if (msg.type === 'complete') {+ if (pendingTypes.has('carbonize_cleanup')) return 'carbonize_cleanup';+ return pendingTypes.has('accept') ? 'accept' : (pendingTypes.has('generate') ? 'generate' : undefined);+ }+ if (msg.type === 'steer_done') return 'steer';+ // `agent_done` can be the automatic acknowledgement for a carbonize Accept.+ // New pollers send sourceEventType explicitly; default to generate only for+ // older callers so a late worker cannot acknowledge a queued Accept.+ if (msg.type === 'agent_done' || msg.type === 'done') return 'generate';+ // `error` is reference/live.md's documented failure reply, and parseReplyArgs+ // never sets sourceEventType on it (the poller is a fresh process that cannot+ // know what it leased). Returning undefined here makes acknowledgePendingEvent+ // match *any* event for this id: a stale generate worker's failure silently+ // consumed the user's queued Accept, which was then never delivered to any+ // agent and left the browser in SAVING forever. Attribute the failure to the+ // event this agent actually holds a lease on, and otherwise to `generate` —+ // never to a wildcard. If that generate was already retired by an Accept, the+ // ack simply finds no match, which is the correct outcome for a stale reply.+ if (msg.type === 'error') {+ return entriesForId.find(isLeased)?.event?.type || 'generate';+ }+ return undefined;+}+function handlePollPost(req, res) {let body = '';req.on('data', (c) => { body += c; });@@ -869,7 +1175,23 @@ function handlePollPost(req, res) {res.end(JSON.stringify({ error: 'stale_manual_edit_apply_reply', ...rollback }));return;}- const pendingEventBeforeAck = findPendingEventById(msg.id);+ const sourceEventType = msg.sourceEventType || inferSourceEventType(msg);+ if (msg.type === 'retry') {+ const releasedEvent = releasePendingEvent(msg.id, sourceEventType);+ if (!releasedEvent) {+ res.writeHead(msg.id ? 404 : 400, { 'Content-Type': 'application/json' });+ res.end(JSON.stringify({+ error: msg.id ? 'unknown_poll_retry_id' : 'missing_poll_retry_id',+ id: msg.id,+ }));+ return;+ }+ flushPendingPolls();+ res.writeHead(200, { 'Content-Type': 'application/json' });+ res.end(JSON.stringify({ ok: true, released: true }));+ return;+ }+ const pendingEventBeforeAck = findPendingEventById(msg.id, sourceEventType);if (pendingEventBeforeAck?.type === 'steer' && msg.type === 'steer_done'&& !msg.file && !(typeof msg.message === 'string' && msg.message.trim())) {res.writeHead(400, { 'Content-Type': 'application/json' });@@ -879,7 +1201,7 @@ function handlePollPost(req, res) {}));return;}- const acknowledgedEvent = acknowledgePendingEvent(msg.id);+ const acknowledgedEvent = acknowledgePendingEvent(msg.id, sourceEventType);let skipJournalReply = false;let existingSession = null;if (!acknowledgedEvent && state.sessionStore && msg.id) {@@ -1083,7 +1405,10 @@ if (args.includes('--background')) {process.exit(0);}} catch { /* not ready yet */ }- await new Promise(r => setTimeout(r, 200));+ // The detached child is typically listening in 35-45ms. A 200ms polling+ // floor dominated configured cold Live startup; poll cheaply and return+ // as soon as the child has written its ready record.+ await new Promise(r => setTimeout(r, 5));}console.error('Timed out waiting for live server to start.');process.exit(1);diff --git a/plugin/skills/impeccable/scripts/live-status.mjs b/plugin/skills/impeccable/scripts/live-status.mjsindex f7e464999..dc98b7386 100644--- a/plugin/skills/impeccable/scripts/live-status.mjs+++ b/plugin/skills/impeccable/scripts/live-status.mjs@@ -37,15 +37,19 @@ export async function statusCli() {pendingEvents: server.pendingEvents,} : null,activeSessions: server?.activeSessions || activeSessions,- recoveryHint: manualApply- ? manualApplyResumeHint(manualApply)- : server- ? 'Run live-poll.mjs to continue pending work, or live-complete.mjs --id <session> after manual cleanup.'- : 'Start live-server.mjs to requeue pending durable events, then run live-poll.mjs.',+ recoveryHint: recoveryHint({ server, manualApply }),};console.log(JSON.stringify(payload, null, 2));}+function recoveryHint({ server, manualApply }) {+ if (manualApply) return manualApplyResumeHint(manualApply);+ if (server) {+ return 'Run live-poll.mjs to continue pending work, or live-complete.mjs --id <session> after manual cleanup.';+ }+ return 'Start live-server.mjs to requeue pending durable events, then run live-poll.mjs.';+}+function findPendingManualApply(server, activeSessions) {const fromServer = server?.pendingEvents?.find((event) => event?.type === 'manual_edit_apply');if (fromServer) return fromServer;diff --git a/plugin/skills/impeccable/scripts/live-wrap.mjs b/plugin/skills/impeccable/scripts/live-wrap.mjsindex 438c01b68..48d7f7683 100644--- a/plugin/skills/impeccable/scripts/live-wrap.mjs+++ b/plugin/skills/impeccable/scripts/live-wrap.mjs@@ -160,11 +160,29 @@ The agent should insert variant HTML at insertLine.`);if (filtered.length === 1) {match = filtered[0];} else if (filtered.length === 0) {- // Source uses dynamic content (`<h1>{title}</h1>` etc.) so the- // browser-side textContent doesn't appear literally in source. Fall- // back to first-match rather than refusing — this is the same- // behavior unmodified callers see, just preserved.- match = candidates[0];+ const normalizedText = String(text).replace(/\s+/g, ' ').trim();+ if (normalizedText.length < 8) {+ // Very short labels cannot disambiguate siblings reliably. Preserve+ // the legacy behavior for these low-information picker events.+ match = candidates[0];+ } else {+ // Rendered text that is absent from every candidate usually means+ // the source uses expressions or component props. Picking the first+ // same-class sibling silently edits the wrong instance (observed on+ // Astro result cards), so stop and surface every candidate instead.+ console.error(JSON.stringify({+ error: 'element_ambiguous',+ fallback: 'agent-driven',+ reason: 'rendered_text_not_in_source',+ file: path.relative(process.cwd(), targetFile),+ candidates: candidates.map((c) => ({+ startLine: c.startLine + 1,+ endLine: c.endLine + 1,+ })),+ hint: 'Rendered text does not occur in any matching source branch. The element may use dynamic props or expressions; inspect the candidates and wrap the intended instance manually.',+ }));+ process.exit(1);+ }} else {// Multiple candidates ALSO match the text. Truly ambiguous — refuse// rather than pick wrong, and hand the agent the candidate locations@@ -269,6 +287,7 @@ The agent should insert variant HTML at insertLine.`);const originalIndented = reindentOriginal(' ');const relTargetFile = path.relative(process.cwd(), targetFile).split(path.sep).join('/');const useSvelteComponent = shouldUseSvelteComponentInjection(targetFile);+ const useFrameworkComponent = useSvelteComponent;// Wrapper attributes differ by syntax. HTML allows plain string attrs;// JSX requires object-literal style and parses string attrs as HTML (which@@ -288,7 +307,7 @@ The agent should insert variant HTML at insertLine.`);// replacement range to include the wrapper's `<div>` open / close lines// so the entire scaffold gets removed cleanly.const wrapperLines = isJsx ? [- indent + '<div data-impeccable-variants="' + id + '" data-impeccable-variant-count="' + count + '" ' + styleContents + '>',+ indent + '<div data-impeccable-variants="' + id + '" data-impeccable-variant-count="' + count + '"' + ' ' + styleContents + '>',indent + ' ' + commentSyntax.open + ' impeccable-variants-start ' + id + ' ' + commentSyntax.close,indent + ' ' + commentSyntax.open + ' Original ' + commentSyntax.close,indent + ' <div data-impeccable-variant="original">',@@ -299,7 +318,7 @@ The agent should insert variant HTML at insertLine.`);indent + '</div>',] : [indent + commentSyntax.open + ' impeccable-variants-start ' + id + ' ' + commentSyntax.close,- indent + '<div data-impeccable-variants="' + id + '" data-impeccable-variant-count="' + count + '" ' + styleContents + '>',+ indent + '<div data-impeccable-variants="' + id + '" data-impeccable-variant-count="' + count + '"' + ' ' + styleContents + '>',indent + ' ' + commentSyntax.open + ' Original ' + commentSyntax.close,indent + ' <div data-impeccable-variant="original">',originalIndented,@@ -356,15 +375,18 @@ The agent should insert variant HTML at insertLine.`);const outputRelFile = path.relative(process.cwd(), outputFile).split(path.sep).join('/');const svelteComponentAuthoring = useSvelteComponent ? buildSvelteComponentCssAuthoring(count) : null;+ const componentSession = svelteSession;+ const componentPreviewMode = useSvelteComponent ? 'svelte-component' : undefined;+ const previewMode = componentPreviewMode;console.log(JSON.stringify({file: outputRelFile,- sourceFile: useSvelteComponent ? relTargetFile : undefined,- previewMode: useSvelteComponent ? 'svelte-component' : undefined,- componentDir: svelteSession?.componentDir,- propContract: svelteSession?.propContract,- sourceStartLine: useSvelteComponent ? startLine + 1 : undefined,- sourceEndLine: useSvelteComponent ? endLine + 1 : undefined,+ sourceFile: useFrameworkComponent ? relTargetFile : undefined,+ previewMode,+ componentDir: componentSession?.componentDir,+ propContract: componentSession?.propContract,+ sourceStartLine: useFrameworkComponent ? startLine + 1 : undefined,+ sourceEndLine: useFrameworkComponent ? endLine + 1 : undefined,startLine: outputStartLine, // 1-indexed for the agent// wrapperLines is an array but one element (the original-content slot)// is a `\n`-joined multi-line string, so the actual file-row count is@@ -374,10 +396,10 @@ The agent should insert variant HTML at insertLine.`);endLine: outputEndLine, // 1-indexedinsertLine, // 1-indexed: where variants gocommentSyntax: commentSyntax,- styleMode: useSvelteComponent ? 'svelte-component' : styleMode.mode,- styleTag: useSvelteComponent ? null : styleMode.styleTag,- cssSelectorPrefixExamples: useSvelteComponent ? [] : buildCssSelectorPrefixExamples(styleMode.mode, count),- cssAuthoring: useSvelteComponent ? svelteComponentAuthoring : buildCssAuthoring(styleMode, count),+ styleMode: componentPreviewMode || styleMode.mode,+ styleTag: useFrameworkComponent ? null : styleMode.styleTag,+ cssSelectorPrefixExamples: useFrameworkComponent ? [] : buildCssSelectorPrefixExamples(styleMode.mode, count),+ cssAuthoring: svelteComponentAuthoring || buildCssAuthoring(styleMode, count),originalLineCount: originalLines.length,}));}diff --git a/plugin/skills/impeccable/scripts/live.mjs b/plugin/skills/impeccable/scripts/live.mjsindex e0bd1ad24..b21a71cc4 100644--- a/plugin/skills/impeccable/scripts/live.mjs+++ b/plugin/skills/impeccable/scripts/live.mjs@@ -10,7 +10,7 @@** After this, the agent's only remaining steps are:* - Open the project's live dev/preview URL in the browser (optional, if browser automation exists)—not `serverPort`; that port is the Impeccable helper for /live.js and /poll- * - Enter the poll loop: `node live-poll.mjs`+ * - Enter the harness-native poll loop: `node live-poll.mjs`** Usage:* node live.mjs # Prepare everything, print JSON, exit@@ -40,6 +40,7 @@ Prepare everything for live variant mode in a single command:- Starts (or reuses) the live server in the background- Injects the browser script tag- Reads PRODUCT.md / DESIGN.md for project context+ - Prepares the harness-native foreground/background poll loop- In monorepos, choose a child app first; --target <path> is the fallback/manual pathOn success, prints a JSON blob with:diff --git a/plugin/skills/impeccable/scripts/live/completion.mjs b/plugin/skills/impeccable/scripts/live/completion.mjsindex 986773066..6f539336d 100644--- a/plugin/skills/impeccable/scripts/live/completion.mjs+++ b/plugin/skills/impeccable/scripts/live/completion.mjs@@ -1,9 +1,18 @@+// A preview whose variants live in component modules rather than in the user's+// source. These leave no markers in the real file, so a failed accept gives the+// agent nothing to hand-edit and must be reported as a failure rather than+// reference/live.md's manual-cleanup handoff. Kept as a set: any future+// component-module preview mode belongs here the day it lands.+const PREVIEW_MODES_WITHOUT_SOURCE_MARKERS = new Set([+ 'svelte-component',+]);+export function completionTypeForAcceptResult(eventType, acceptResult) {if (eventType === 'discard') return acceptResult?.handled === true ? 'discarded' : 'error';if (acceptResult?.handled === true && acceptResult?.carbonize === true) return 'agent_done';if (acceptResult?.handled === true) return 'complete';if (acceptResult?.mode === 'error') return 'error';- if (eventType === 'accept' && acceptResult?.previewMode === 'svelte-component') return 'error';+ if (eventType === 'accept' && PREVIEW_MODES_WITHOUT_SOURCE_MARKERS.has(acceptResult?.previewMode)) return 'error';return 'agent_done';}diff --git a/plugin/skills/impeccable/scripts/live/event-validation.mjs b/plugin/skills/impeccable/scripts/live/event-validation.mjsindex 0897b1317..122c29836 100644--- a/plugin/skills/impeccable/scripts/live/event-validation.mjs+++ b/plugin/skills/impeccable/scripts/live/event-validation.mjs@@ -118,6 +118,15 @@ export function validateEvent(msg) {return 'checkpoint: paramValues must be an object';}return null;+ case 'agent_phase':+ if (!isValidId(msg.id)) return 'agent_phase: missing or malformed id';+ if (typeof msg.phase !== 'string' || !/^[a-z][a-z0-9_]{1,63}$/.test(msg.phase)) {+ return 'agent_phase: missing or malformed phase';+ }+ if (msg.durationMs !== undefined && (!Number.isFinite(msg.durationMs) || msg.durationMs < 0)) {+ return 'agent_phase: durationMs must be a non-negative number';+ }+ return null;case 'exit':return null;case 'prefetch':@@ -131,6 +140,12 @@ export function validateEvent(msg) {if (msg.message.length > 4000) return 'steer: message too long';if (msg.pageUrl !== undefined && typeof msg.pageUrl !== 'string') return 'steer: pageUrl must be string';return null;+ case 'carbonize_cleanup':+ if (!isValidId(msg.id)) return 'carbonize_cleanup: missing or malformed id';+ if (!isValidId(msg.sessionId)) return 'carbonize_cleanup: missing or malformed sessionId';+ if (!msg.file || typeof msg.file !== 'string') return 'carbonize_cleanup: missing file';+ if (!isValidVariantId(String(msg.variantId))) return 'carbonize_cleanup: missing or malformed variantId';+ return null;default:return 'Unknown event type: ' + msg.type;}diff --git a/plugin/skills/impeccable/scripts/live/generation-preflight.mjs b/plugin/skills/impeccable/scripts/live/generation-preflight.mjsnew file mode 100644index 000000000..07a5e957e--- /dev/null+++ b/plugin/skills/impeccable/scripts/live/generation-preflight.mjs@@ -0,0 +1,102 @@+import { execFile } from 'node:child_process';+import path from 'node:path';+import { promisify } from 'node:util';++const execFileAsync = promisify(execFile);+const PREFLIGHT_TIMEOUT_MS = 15_000;++export function buildGenerationPreflight(event, scriptsDir) {+ if (!event || event.type !== 'generate' || !event.id) return null;++ const isInsert = event.mode === 'insert';+ const target = isInsert ? insertTarget(event) : replaceTarget(event);+ if (!target.elementId && !target.classes) return null;++ const script = path.join(scriptsDir, isInsert ? 'live-insert.mjs' : 'live-wrap.mjs');+ const args = [script, '--id', event.id, '--count', String(event.count || 3)];+ if (isInsert) args.push('--position', target.position);+ if (target.elementId) args.push('--element-id', target.elementId);+ if (target.classes) args.push('--classes', target.classes);+ if (target.tag) args.push('--tag', target.tag);+ if (target.text) args.push('--text', target.text);+ if (!isInsert && event.pageUrl) args.push('--page-url', event.pageUrl);+ return { script, args, mode: isInsert ? 'insert' : 'replace' };+}++/**+ * Scaffold the source for a generate event before handing it to an agent.+ *+ * Async on purpose. This spawns `live-wrap.mjs`, which walks the project's+ * source tree and can take seconds (measured at ~7.6s on a large repo when the+ * element is not found, with a 15s ceiling). The live server is single-threaded+ * and calls this while leasing a poll, so a synchronous spawn froze the whole+ * server for that entire window: Accept and Discard POSTs, SSE progress+ * broadcasts, and every other poll stalled behind it.+ */+export async function runGenerationPreflight(event, {+ cwd = process.cwd(),+ scriptsDir,+ execFileImpl = execFileAsync,+ timeoutMs = PREFLIGHT_TIMEOUT_MS,+} = {}) {+ const command = buildGenerationPreflight(event, scriptsDir);+ if (!command) {+ return { ok: false, skipped: true, reason: 'insufficient_locator' };+ }++ const startedAt = performance.now();+ try {+ const { stdout } = await execFileImpl(process.execPath, command.args, {+ cwd,+ encoding: 'utf-8',+ timeout: timeoutMs,+ });+ const line = String(stdout).trim().split('\n').filter(Boolean).pop();+ if (!line) throw new Error('preflight returned no scaffold metadata');+ return {+ ok: true,+ mode: command.mode,+ durationMs: performance.now() - startedAt,+ scaffold: JSON.parse(line),+ };+ } catch (error) {+ return {+ ok: false,+ mode: command.mode,+ durationMs: performance.now() - startedAt,+ error: compactError(error),+ };+ }+}++function replaceTarget(event) {+ return normalizeTarget(event.element || {});+}++function insertTarget(event) {+ return {+ ...normalizeTarget(event.insert?.anchor || {}),+ position: event.insert?.position === 'before' ? 'before' : 'after',+ };+}++function normalizeTarget(target) {+ const classes = Array.isArray(target.classes)+ ? target.classes.join(' ')+ : String(target.classes || '').trim();+ const text = typeof target.textContent === 'string'+ ? target.textContent.trim().slice(0, 80)+ : '';+ return {+ elementId: target.id || target.elementId || undefined,+ classes: classes || undefined,+ tag: target.tagName || target.tag || undefined,+ text: text || undefined,+ };+}++function compactError(error) {+ const stderr = error?.stderr ? String(error.stderr).trim() : '';+ const message = stderr.split('\n').filter(Boolean).pop() || error?.message || 'preflight failed';+ return String(message).slice(0, 500);+}diff --git a/plugin/skills/impeccable/scripts/live/poll-lanes.mjs b/plugin/skills/impeccable/scripts/live/poll-lanes.mjsnew file mode 100644index 000000000..65f20a87a--- /dev/null+++ b/plugin/skills/impeccable/scripts/live/poll-lanes.mjs@@ -0,0 +1,14 @@+export function eventPriority(event = {}) {+ if (event.type === 'accept' || event.type === 'discard' || event.type === 'exit') return 0;+ if (event.type === 'manual_edit_apply' || event.type === 'steer' || event.type === 'carbonize_cleanup') return 1;+ if (event.type === 'generate') return 2;+ return 3;+}++export function selectAvailablePendingEvent(entries, { now = Date.now(), types = null } = {}) {+ const allowed = types instanceof Set ? types : (Array.isArray(types) ? new Set(types) : null);+ return entries+ .filter((entry) => !(entry.leaseUntil && entry.leaseUntil > now))+ .filter((entry) => !allowed || allowed.has(entry.event?.type))+ .sort((a, b) => eventPriority(a.event) - eventPriority(b.event) || a.seq - b.seq)[0] || null;+}diff --git a/plugin/skills/impeccable/scripts/live/session-store.mjs b/plugin/skills/impeccable/scripts/live/session-store.mjsindex affba67c9..9d20341dd 100644--- a/plugin/skills/impeccable/scripts/live/session-store.mjs+++ b/plugin/skills/impeccable/scripts/live/session-store.mjs@@ -1,24 +1,26 @@import fs from 'node:fs';import path from 'node:path';-import { getLegacyLiveSessionsDir, getLiveSessionsDir } from '../lib/impeccable-paths.mjs';+import { getLegacyLiveSessionsDir, getLiveSessionsDir, safeSessionId } from '../lib/impeccable-paths.mjs';const COMPLETED_PHASES = new Set(['completed', 'discarded']);+export const GENERATION_FENCED_PHASES = new Set([+ 'accept_requested',+ 'discard_requested',+ 'carbonize_required',+ 'completed',+ 'discarded',+]);export function createLiveSessionStore({ cwd = process.cwd(), sessionId } = {}) {const rootDir = getLiveSessionsDir(cwd);const legacyRootDir = getLegacyLiveSessionsDir(cwd);fs.mkdirSync(rootDir, { recursive: true });- const snapshotCache = new Map();-- function loadCachedOrRebuild(id) {- const cached = snapshotCache.get(id);- if (cached) return cached;- const journalPath = getReadableJournalPath(id);- const rebuilt = rebuildSnapshotFromJournal(journalPath, id);- snapshotCache.set(id, rebuilt);- return rebuilt;- }+ // No snapshot cache on purpose: appendEvent and getSnapshot both rebuild from+ // the journal so sequence numbers and phase fences never come from a stale+ // in-memory copy when the publisher/complete helpers append from another+ // process. A cache written but never read would grow per session for the+ // lifetime of the server without ever saving a rebuild.function getReadableJournalPath(id) {const primary = getJournalPath(rootDir, id);if (fs.existsSync(primary)) return primary;@@ -38,7 +40,10 @@ export function createLiveSessionStore({ cwd = process.cwd(), sessionId } = {})if (!fs.existsSync(journalPath) && fs.existsSync(legacyJournalPath)) {fs.copyFileSync(legacyJournalPath, journalPath);}- const prior = loadCachedOrRebuild(normalized.id);+ // Publisher/complete helpers can append from a separate process while+ // the server is alive. Rebuild here so sequence numbers and phase+ // fences never come from a stale in-memory cache.+ const prior = rebuildSnapshotFromJournal(getReadableJournalPath(normalized.id), normalized.id);const seq = prior.nextSeq;const entry = {seq,@@ -49,7 +54,6 @@ export function createLiveSessionStore({ cwd = process.cwd(), sessionId } = {})};fs.appendFileSync(journalPath, JSON.stringify(entry) + '\n');const next = applyEvent(prior.snapshot, entry, prior.diagnostics);- snapshotCache.set(normalized.id, { snapshot: next, diagnostics: next.diagnostics || [], nextSeq: seq + 1 });writeSnapshot(snapshotPath, next);return next;},@@ -58,7 +62,6 @@ export function createLiveSessionStore({ cwd = process.cwd(), sessionId } = {})const journalPath = getReadableJournalPath(id);const snapshotPath = getSnapshotPath(rootDir, id);const rebuilt = rebuildSnapshotFromJournal(journalPath, id);- snapshotCache.set(id, rebuilt);writeSnapshot(snapshotPath, rebuilt.snapshot);if (!opts.includeCompleted && COMPLETED_PHASES.has(rebuilt.snapshot.phase)) return null;return rebuilt.snapshot;@@ -95,11 +98,6 @@ function getSnapshotPath(rootDir, id) {return path.join(rootDir, safeSessionId(id) + '.snapshot.json');}-function safeSessionId(id) {- if (!/^[A-Za-z0-9_-]{1,128}$/.test(id)) throw new Error('invalid session id: ' + id);- return id;-}-function baseSnapshot(id) {return {id,@@ -116,9 +114,18 @@ function baseSnapshot(id) {pendingEvent: null,deliveryLease: null,checkpointRevision: 0,+ browserCheckpointRevision: 0,+ publicationCheckpointRevision: 0,activeOwner: null,sourceMarkers: {},fallbackMode: null,+ generationPhase: null,+ generationCompletedAt: null,+ generationTimings: {},+ variantPlan: null,+ generationCanceled: false,+ generationCanceledAt: null,+ cancelReason: null,annotationArtifacts: [],diagnostics: [],updatedAt: null,@@ -158,6 +165,8 @@ function applyEvent(snapshot, entry, inheritedDiagnostics = []) {...snapshot,paramValues: { ...(snapshot.paramValues || {}) },sourceMarkers: { ...(snapshot.sourceMarkers || {}) },+ generationTimings: { ...(snapshot.generationTimings || {}) },+ variantPlan: snapshot.variantPlan || null,annotationArtifacts: [...(snapshot.annotationArtifacts || [])],diagnostics: [...(snapshot.diagnostics || [])],updatedAt: entry.ts || new Date().toISOString(),@@ -174,11 +183,48 @@ function applyEvent(snapshot, entry, inheritedDiagnostics = []) {next.expectedVariants = event.count ?? next.expectedVariants;next.pendingEventSeq = entry.seq ?? next.pendingEventSeq;next.pendingEvent = toPendingEvent(event);+ next.variantPlan = null;if (event.screenshotPath) upsertArtifact(next.annotationArtifacts, { type: 'screenshot', path: event.screenshotPath });break;+ case 'variant_plan':+ if (!next.generationCanceled && !GENERATION_FENCED_PHASES.has(next.phase)) {+ next.variantPlan = event.plan ?? next.variantPlan;+ }+ break;+ case 'detector_waivers':+ if (!next.generationCanceled && !GENERATION_FENCED_PHASES.has(next.phase)) {+ next.detectorWaivers = [+ ...(next.detectorWaivers || []),+ ...(Array.isArray(event.waivers) ? event.waivers : []),+ ];+ }+ break;+ case 'agent_phase':+ next.generationPhase = event.phase ?? next.generationPhase;+ if (event.phase) {+ next.generationTimings[event.phase] = {+ at: event.at ?? (Date.parse(entry.ts || '') || null),+ durationMs: event.durationMs ?? null,+ };+ }+ break;case 'variants_ready':case 'agent_done':+ if ((next.generationCanceled || GENERATION_FENCED_PHASES.has(next.phase))+ && !(event.type === 'agent_done' && event.carbonize === true && next.phase === 'accept_requested')) {+ next.diagnostics.push({+ error: 'late_generation_event_ignored',+ type: event.type,+ phase: next.phase,+ });+ break;+ }next.phase = event.carbonize === true ? 'carbonize_required' : 'variants_ready';+ // Durable completion marker: later browser checkpoints (a resumed page+ // reporting phase "generating") regress `phase`, but generation staying+ // finished is monotone — the live server keys missed-`done` redelivery+ // on this field.+ next.generationCompletedAt = event.at ?? (Date.parse(entry.ts || '') || Date.now());next.sourceFile = event.sourceFile ?? event.file ?? next.sourceFile;next.previewFile = event.previewFile ?? next.previewFile;next.previewMode = event.previewMode ?? next.previewMode;@@ -194,27 +240,45 @@ function applyEvent(snapshot, entry, inheritedDiagnostics = []) {}break;case 'checkpoint':- if (COMPLETED_PHASES.has(next.phase)) {+ if (next.generationCanceled || GENERATION_FENCED_PHASES.has(next.phase)) {next.diagnostics.push({ error: 'checkpoint_after_terminal_ignored', phase: event.phase ?? null, revision: event.revision ?? null });break;}- if ((event.revision ?? 0) >= (next.checkpointRevision ?? 0)) {- next.phase = event.phase ?? next.phase;- next.checkpointRevision = event.revision ?? next.checkpointRevision;- next.activeOwner = event.owner ?? next.activeOwner;- next.arrivedVariants = event.arrivedVariants ?? next.arrivedVariants;- next.visibleVariant = event.visibleVariant ?? next.visibleVariant;- next.sourceFile = event.sourceFile ?? next.sourceFile;- next.previewFile = event.previewFile ?? next.previewFile;- next.previewMode = event.previewMode ?? next.previewMode;- if (event.paramValues) next.paramValues = { ...event.paramValues };- } else {- next.diagnostics.push({ error: 'stale_checkpoint_ignored', revision: event.revision });+ {+ const revisionDomain = event.revisionDomain === 'publication'+ || (event.reason === 'variants_progress' && !event.owner)+ ? 'publication'+ : 'browser';+ const revisionField = revisionDomain === 'publication'+ ? 'publicationCheckpointRevision'+ : 'browserCheckpointRevision';+ const currentRevision = next[revisionField]+ ?? (revisionDomain === 'browser' ? next.checkpointRevision : 0)+ ?? 0;+ if ((event.revision ?? 0) >= currentRevision) {+ next.phase = event.phase ?? next.phase;+ next[revisionField] = event.revision ?? currentRevision;+ if (revisionDomain === 'browser') {+ next.checkpointRevision = event.revision ?? next.checkpointRevision;+ next.activeOwner = event.owner ?? next.activeOwner;+ }+ next.arrivedVariants = event.arrivedVariants ?? next.arrivedVariants;+ if (revisionDomain === 'browser') next.visibleVariant = event.visibleVariant ?? next.visibleVariant;+ next.sourceFile = event.sourceFile ?? next.sourceFile;+ next.previewFile = event.previewFile ?? next.previewFile;+ next.previewMode = event.previewMode ?? next.previewMode;+ if (revisionDomain === 'browser' && event.paramValues) next.paramValues = { ...event.paramValues };+ } else {+ next.diagnostics.push({ error: 'stale_checkpoint_ignored', revision: event.revision, revisionDomain });+ }}break;case 'accept':case 'accept_intent':next.phase = 'accept_requested';+ next.generationCanceled = true;+ next.generationCanceledAt = event.at ?? (Date.parse(entry.ts || '') || Date.now());+ next.cancelReason = 'accept';next.visibleVariant = Number(event.variantId ?? next.visibleVariant);if (event.paramValues) next.paramValues = { ...event.paramValues };next.pendingEventSeq = entry.seq ?? next.pendingEventSeq;@@ -232,6 +296,12 @@ function applyEvent(snapshot, entry, inheritedDiagnostics = []) {next.pendingEventSeq = entry.seq ?? next.pendingEventSeq;next.pendingEvent = toPendingEvent(event);break;+ case 'carbonize_cleanup':+ next.phase = 'carbonize_cleanup_requested';+ next.sourceFile = event.file ?? next.sourceFile;+ next.pendingEventSeq = entry.seq ?? next.pendingEventSeq;+ next.pendingEvent = toPendingEvent(event);+ break;case 'steer_done':next.phase = 'steer_done';next.sourceFile = event.sourceFile ?? event.file ?? next.sourceFile;@@ -243,6 +313,9 @@ function applyEvent(snapshot, entry, inheritedDiagnostics = []) {break;case 'discard':next.phase = 'discard_requested';+ next.generationCanceled = true;+ next.generationCanceledAt = event.at ?? (Date.parse(entry.ts || '') || Date.now());+ next.cancelReason = 'discard';next.pendingEventSeq = entry.seq ?? next.pendingEventSeq;next.pendingEvent = toPendingEvent(event);break;@@ -260,6 +333,10 @@ function applyEvent(snapshot, entry, inheritedDiagnostics = []) {next.pendingEvent = null;break;case 'agent_error':+ if (next.generationCanceled && event.sourceEventType === 'generate') {+ next.diagnostics.push({ error: 'late_generation_event_ignored', type: event.type, phase: next.phase });+ break;+ }next.phase = 'agent_error';next.pendingEventSeq = null;next.pendingEvent = null;diff --git a/plugin/skills/impeccable/scripts/live/source-lock.mjs b/plugin/skills/impeccable/scripts/live/source-lock.mjsnew file mode 100644index 000000000..9ccc557be--- /dev/null+++ b/plugin/skills/impeccable/scripts/live/source-lock.mjs@@ -0,0 +1,105 @@+import fs from 'node:fs';+import path from 'node:path';+import { createHash, randomUUID } from 'node:crypto';+import { getLiveDir, isLiveServerPidReachable } from '../lib/impeccable-paths.mjs';++// Only used to retire a lock whose contents we cannot read (empty or truncated+// by a crash mid-write). A readable lock's fate is decided by its owner's+// liveness instead, so a slow critical section is never swept.+const UNREADABLE_LOCK_STALE_MS = 60_000;++export function sourceLockPath(file, cwd = process.cwd()) {+ const digest = createHash('sha256').update(path.resolve(cwd, file)).digest('hex').slice(0, 24);+ return path.join(getLiveDir(cwd), 'locks', digest + '.lock');+}++export function withSourceLockSync(file, owner, fn, {+ cwd = process.cwd(),+ waitMs = 0,+ retryMs = 5,+} = {}) {+ const lockPath = sourceLockPath(file, cwd);+ fs.mkdirSync(path.dirname(lockPath), { recursive: true });+ const deadline = Date.now() + Math.max(0, Number(waitMs) || 0);+ // Identifies this acquisition specifically, so release can tell our own lock+ // from a replacement that some other writer created.+ const token = randomUUID();+ let acquired = false;++ while (!acquired) {+ clearStaleLock(lockPath);+ let fd;+ try {+ fd = fs.openSync(lockPath, 'wx');+ fs.writeFileSync(fd, JSON.stringify({+ owner,+ token,+ pid: process.pid,+ at: Date.now(),+ file: path.resolve(cwd, file),+ }) + '\n');+ acquired = true;+ } catch (error) {+ if (error?.code !== 'EEXIST') throw error;+ if (Date.now() >= deadline) {+ const locked = new Error('source_locked');+ locked.code = 'SOURCE_LOCKED';+ locked.lockPath = lockPath;+ throw locked;+ }+ sleepSync(Math.max(1, Math.min(Number(retryMs) || 5, deadline - Date.now())));+ } finally {+ try { if (fd !== undefined) fs.closeSync(fd); } catch {}+ }+ }++ try {+ return fn();+ } finally {+ releaseOwnLock(lockPath, token);+ }+}++function sleepSync(ms) {+ Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, ms);+}++function readLock(lockPath) {+ try { return JSON.parse(fs.readFileSync(lockPath, 'utf-8')); } catch { return null; }+}++/**+ * Remove the lock only if it is still the one this call created. If a sweeper+ * judged our lock stale and another writer replaced it, unlinking here would+ * end *their* critical section and admit a third writer to the same file.+ */+function releaseOwnLock(lockPath, token) {+ const held = readLock(lockPath);+ if (held && held.token !== token) return;+ try { fs.unlinkSync(lockPath); } catch {}+}++/**+ * A lock is stale when its owner is gone, not when it is old.+ *+ * Age alone cuts both ways: it sweeps a live holder whose critical section+ * outran the timeout (a suspended laptop, a stopped process), letting two+ * writers into the same source file, while still making every accept on a+ * crashed holder's file wait out the full timeout. Asking the OS whether the+ * recorded pid is alive answers both correctly: a dead owner releases at once,+ * and a live owner keeps its lock however long it needs.+ */+function clearStaleLock(lockPath) {+ const held = readLock(lockPath);+ if (!held) {+ // Unreadable: either a crash truncated it, or we caught the brief window+ // between create and write in a live acquisition. mtime distinguishes them.+ try {+ const stat = fs.statSync(lockPath);+ if (Date.now() - stat.mtimeMs > UNREADABLE_LOCK_STALE_MS) fs.unlinkSync(lockPath);+ } catch { /* gone already */ }+ return;+ }+ if (typeof held.pid === 'number' && isLiveServerPidReachable(held.pid)) return;+ try { fs.unlinkSync(lockPath); } catch {}+}