The design language that makes your AI harness better at design.
JavaScript
feat(live): make live sessions recoverable (#125)
Ngo Quoc Huyd874af046a1f
diff --git a/.agents/skills/impeccable/reference/document.md b/.agents/skills/impeccable/reference/document.mdindex 12e9a02d2..ebafe4f41 100644--- a/.agents/skills/impeccable/reference/document.md+++ b/.agents/skills/impeccable/reference/document.md@@ -237,11 +237,11 @@ Concrete, forceful guardrails. Lead each with "Do" or "Don't". Be specific: incl- **Don't** [...]```-### Step 4b: Write DESIGN.json sidecar (extensions only)+### Step 4b: Write .impeccable/design.json sidecar (extensions only)-The frontmatter owns token primitives (colors, typography, rounded, spacing, components). The sidecar at `DESIGN.json` carries **what Stitch's schema can't hold**: tonal ramps per color, shadow/elevation tokens, motion tokens, breakpoints, full component HTML/CSS snippets (the panel renders these into a shadow DOM), and narrative (north star, rules, do's/don'ts). It extends the frontmatter, it doesn't duplicate it.+The frontmatter owns token primitives (colors, typography, rounded, spacing, components). The sidecar at `.impeccable/design.json` carries **what Stitch's schema can't hold**: tonal ramps per color, shadow/elevation tokens, motion tokens, breakpoints, full component HTML/CSS snippets (the panel renders these into a shadow DOM), and narrative (north star, rules, do's/don'ts). It extends the frontmatter, it doesn't duplicate it.-Regenerate the sidecar whenever you regenerate DESIGN.md. If the user only asks to refresh the sidecar (e.g., from the live panel's stale-hint), preserve DESIGN.md and write only DESIGN.json.+Regenerate the sidecar whenever you regenerate root `DESIGN.md`. If the user only asks to refresh the sidecar (e.g., from the live panel's stale-hint), preserve `DESIGN.md` and write only `.impeccable/design.json`.#### Schema@@ -310,7 +310,7 @@ Aim for a tight set of **5-10 components** that best represent the visual system- **Signature components (include if distinctive):** hero CTA, featured card, filter pill, any custom pattern the user mentioned as important in PRODUCT.md.- **Skip the rest.** Utility components, form building blocks, wrapper layouts: not worth documenting unless visually distinctive.-If the project has **no component library yet** (bare landing page, new project), synthesize canonical primitives from the tokens using best-practice defaults consistent with the DESIGN.md's rules. Every DESIGN.json has *something* to render, even on day zero.+If the project has **no component library yet** (bare landing page, new project), synthesize canonical primitives from the tokens using best-practice defaults consistent with the DESIGN.md's rules. Every `.impeccable/design.json` has *something* to render, even on day zero.#### Tonal ramps@@ -331,7 +331,7 @@ Do not reword. The panel shows these as secondary collapsible context; the same### Step 5: Confirm, refine, and refresh session cache1. Show the user the full DESIGN.md you wrote. Briefly highlight the non-obvious creative choices (descriptive color names, atmosphere language, named rules).-2. Mention that `DESIGN.json` was also written alongside; the live panel will now render this project's actual button/input/nav primitives instead of generic approximations.+2. Mention that `.impeccable/design.json` was also written alongside; the live panel will now render this project's actual button/input/nav primitives instead of generic approximations.3. Offer to refine any section: "Want me to revise a section, add component patterns I missed, or adjust the atmosphere language?"4. **Refresh the session cache.** Run `node .agents/skills/impeccable/scripts/load-context.mjs` one final time so the newly-written DESIGN.md lands in conversation. Subsequent commands in this session will use the fresh version automatically without re-reading.@@ -392,7 +392,7 @@ Per-section guidance in seed mode:- **Components**: omit entirely; no components exist yet.- **Do's and Don'ts**: carry PRODUCT.md's anti-references directly plus the anti-reference named in Q5.-Seed mode writes a minimal frontmatter with `name` and `description` only; no colors, typography, rounded, spacing, or components yet. Real tokens land on the next Scan-mode run. Skip the `DESIGN.json` sidecar in seed mode for the same reason: nothing to render.+Seed mode writes a minimal frontmatter with `name` and `description` only; no colors, typography, rounded, spacing, or components yet. Real tokens land on the next Scan-mode run. Skip the `.impeccable/design.json` sidecar in seed mode for the same reason: nothing to render.### Step 4: Confirm and refresh session cachediff --git a/.agents/skills/impeccable/reference/live.md b/.agents/skills/impeccable/reference/live.mdindex 598c1d00f..71cd3f5a2 100644--- a/.agents/skills/impeccable/reference/live.md+++ b/.agents/skills/impeccable/reference/live.md@@ -12,8 +12,9 @@ Execute in order. No step skipped, no step reordered.2. Navigate to the URL that serves `pageFile` (infer from `package.json`, docs, terminal output, or an open tab). If you can't infer it confidently, tell the user once to open their dev/preview URL. Never use `serverPort` as that URL; it's the helper, not the app.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=`.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.-5. On `accept` / `discard`: the poll script already cleaned up; just poll again.-6. On `exit`: run the cleanup at the bottom.+5. 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. If interrupted, run `live-status.mjs` or `live-resume.mjs` before guessing. The durable journal replays unacknowledged work after helper restart.+7. 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.@@ -43,13 +44,31 @@ LOOP:Read JSON; dispatch on "type""generate" → Handle Generate; reply done; LOOP- "accept" → Handle Accept; LOOP+ "accept" → Handle Accept; complete carbonize cleanup if required; LOOP"discard" → Handle Discard; LOOP"prefetch" → Handle Prefetch; LOOP"timeout" → LOOP"exit" → break → Cleanup```+## Recovery commands++The live helper persists an append-only journal under `.impeccable/live/sessions/`. Browser checkpoints are advisory but durable; the journal is canonical. This is local durable recovery state, not project source.++Use these commands when the chat was interrupted, polling was missed, the helper restarted, or the browser reloaded:++```bash+node .agents/skills/impeccable/scripts/live-status.mjs+node .agents/skills/impeccable/scripts/live-resume.mjs --id SESSION_ID+node .agents/skills/impeccable/scripts/live-complete.mjs --id SESSION_ID+```++- `live-status.mjs` prints connected helper state, active durable sessions, and queued pending events. It works even when the helper is down by reading the journal directly.+- `live-resume.mjs` prints the active snapshot, pending event, checkpoint phase, visible variant, parameter values, and the next safe agent action.+- `live-complete.mjs` is the canonical manual final acknowledgement. Use it after carbonize/manual cleanup is verified and no further poll acknowledgement will happen automatically.++Server restart rule: start `live-server.mjs` again, then poll. Startup requeues unacknowledged pending events from the journal, so do not ask the user to click Go again unless `live-resume.mjs` says no active session exists.+## Handle `generate`Event: `{id, action, freeformPrompt?, count, pageUrl, element, screenshotPath?, comments?, strokes?}`.@@ -88,7 +107,14 @@ The helper searches ID first, then classes, then tag + class combo. If `event.paIf `--text` matches multiple candidates equally well, wrap exits with `{ error: "element_ambiguous", candidates: [...] }` and `fallback: "agent-driven"`: read the candidate line ranges, decide which one matches the picked element from page context, and write the wrapper manually per the fallback flow.-Output on success: `{ file, insertLine, commentSyntax }`.+Output on success: `{ file, insertLine, commentSyntax, styleMode, styleTag, cssSelectorPrefixExamples, cssAuthoring }`.++`styleMode` controls how preview CSS must be authored. Treat it as a detected capability mode, not a framework guess:++- `scoped`: use `@scope ([data-impeccable-variant="N"])` rules.+- `astro-global-prefixed`: use explicit `[data-impeccable-variant="N"]` selector prefixes and the exact `styleTag` returned by the tool.++Use `cssAuthoring` as the source of truth for the current file. It includes the exact `styleTag`, selector strategy, selector examples, requirements, and forbidden patterns. Do not apply a framework-specific exception unless the returned `styleMode` / `cssAuthoring.mode` says to.**Fallback errors.** Wrap only writes into files it judges to be source (tracked by git, not marked GENERATED, not listed in config's `generatedFiles`). If it can't land on a source file, it errors without writing; accepting a variant into a generated file is silent data loss. Three shapes:@@ -208,13 +234,14 @@ When the prompt and PRODUCT.md anti-references conflict (the prompt asks for X,Complete 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 scoped 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).+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).++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:```html<!-- Variants: insert below this line --><style data-impeccable-css="SESSION_ID">- @scope ([data-impeccable-variant="1"]) { ... }- @scope ([data-impeccable-variant="2"]) { ... }+ /* rules matching cssAuthoring.rulePattern */</style><div data-impeccable-variant="1"><!-- variant 1: full element replacement (single top-level element) -->@@ -229,11 +256,11 @@ Write CSS + all variants in ONE edit at the `insertLine` reported by `wrap`. Col**Each variant div contains exactly one top-level element: the full replacement for the original.** Use the same tag as the original (e.g. `<section>` if the user picked a `<section>`). Loose siblings (heading + paragraph + div as direct children of the variant div) break the outline tracking and the accept flow, which both assume one child.-The first variant has no `display: none` (visible by default). All others do. If variants use only inline styles and no scoped CSS, omit the `<style>` tag entirely. Use `@scope` for CSS isolation (Chrome 118+ / Firefox 128+ / Safari 17.4+).+The 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.-**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 rule starts `:scope > ...`.+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 > ...`.**JSX / TSX target files.** Wrap `<style>` content in a template literal so the CSS `{` / `}` aren't parsed as JSX expressions, and use `className=` / `style={{…}}` on every variant element. Keep `data-impeccable-*` attributes as-is; they're plain strings:@@ -369,10 +396,11 @@ Remove the wrapper you inserted in Step 2. Nothing else to do.## Handle `accept`-Event: `{id, variantId, _acceptResult}`. The poll script already ran `live-accept.mjs` to handle the file operation deterministically; the browser DOM is already updated.+Event: `{id, variantId, _acceptResult, _completionAck}`. The poll script already ran `live-accept.mjs` to handle the file operation deterministically, then acknowledged event delivery to the helper. The browser DOM is already updated.+- `_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 and a stderr banner both list the steps explicitly; neither is decorative.+- `_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: 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` without `mode`: manual cleanup: read file, find markers, edit.@@ -388,13 +416,13 @@ Do these five steps in the current thread, synchronously, before the next poll.4. **Unwrap the accepted content.** Delete the `<div data-impeccable-variant="N" style="display: contents">` that wraps it. Drop `data-impeccable-params` and any `data-p-*` attributes from it; 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.-Then poll again.+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.## Handle `discard`-Event: `{id, _acceptResult}`. The poll script already restored the original and removed all variant markers. Nothing to do. Poll again.+Event: `{id, _acceptResult, _completionAck}`. The poll script already restored the original, removed all variant markers, and acknowledged `discarded` durable completion. Nothing to do unless `_completionAck.ok !== true`; in that case run `live-complete.mjs --id EVENT_ID --discarded`, then poll again.## Handle `prefetch`@@ -424,7 +452,7 @@ When the poll returns `exit`, proceed to cleanup. If the poll is still running anode .agents/skills/impeccable/scripts/live-server.mjs stop```-Stops the HTTP server and runs `live-inject.mjs --remove` to strip `localhost:…/live.js` from the HTML entry. To stop the server but keep the inject tag (for a quick restart), use `stop --keep-inject`. `config.json` persists for future sessions.+Stops the HTTP server and runs `live-inject.mjs --remove` to strip `localhost:…/live.js` from the HTML entry. To stop the server but keep the inject tag (for a quick restart), use `stop --keep-inject`. `.impeccable/live/config.json` persists as project config for future sessions.Then:- Remove any leftover variant wrappers (search for `impeccable-variants-start` markers).@@ -432,7 +460,7 @@ Then:## First-time setup (config missing or invalid)-If `live.mjs` outputs `{ ok: false, error: "config_missing" | "config_invalid", path }`, write `config.json` at the reported path.+If `live.mjs` outputs `{ ok: false, error: "config_missing" | "config_invalid", path }`, write the live config at the reported path. By default this is `.impeccable/live/config.json`.Schema:@@ -512,7 +540,7 @@ node .agents/skills/impeccable/scripts/detect-csp.mjsOutput: `{ shape, signals }` where `shape` is one of `append-arrays`, `append-string`, `middleware`, `meta-tag`, or `null`. The shape is named by *patch mechanism*, so one template covers many frameworks.-- **`null`**: no CSP; skip to writing `config.json` with `cspChecked: true`.+- **`null`**: no CSP; skip to writing `.impeccable/live/config.json` with `cspChecked: true`.- **`append-arrays`**: CSP defined as structured directive arrays. Auto-patchable. See *append-arrays* below. Covers:- Monorepo helpers with `additionalScriptSrc` / `additionalConnectSrc` options (Next.js + shared config package)- SvelteKit `kit.csp.directives`@@ -589,6 +617,6 @@ Reference outputs:### Troubleshooting-If a user says "no" to the CSP patch at setup time and later complains that live doesn't work: their dev CSP blocks `http://localhost:8400`. Fix: delete `cspChecked` from `config.json` and re-run `live.mjs`: setup will ask again.+If a user says "no" to the CSP patch at setup time and later complains that live doesn't work: their dev CSP blocks `http://localhost:8400`. Fix: delete `cspChecked` from `.impeccable/live/config.json` and re-run `live.mjs`: setup will ask again.Then re-run `live.mjs`.diff --git a/.agents/skills/impeccable/reference/teach.md b/.agents/skills/impeccable/reference/teach.mdindex 66c7e2a48..6b7df209c 100644--- a/.agents/skills/impeccable/reference/teach.md+++ b/.agents/skills/impeccable/reference/teach.md@@ -2,8 +2,8 @@Gathers design context for a project and writes two complementary files at the project root:-- **PRODUCT.md** (strategic): register, target users, product purpose, brand personality, anti-references, strategic design principles. Answers "who/what/why".-- **DESIGN.md** (visual): visual theme, color palette, typography, components, layout. Follows the [Google Stitch DESIGN.md format](https://stitch.withgoogle.com/docs/design-md/format/). Answers "how it looks".+- **PRODUCT.md** (strategic): root project file for register, target users, product purpose, brand personality, anti-references, strategic design principles. Answers "who/what/why".+- **DESIGN.md** (visual): root project file for visual theme, color palette, typography, components, layout. Follows the [Google Stitch DESIGN.md format](https://stitch.withgoogle.com/docs/design-md/format/). Answers "how it looks".Every other impeccable command reads these files before doing any work.diff --git a/.agents/skills/impeccable/scripts/impeccable-paths.mjs b/.agents/skills/impeccable/scripts/impeccable-paths.mjsnew file mode 100644index 000000000..ba852bae9--- /dev/null+++ b/.agents/skills/impeccable/scripts/impeccable-paths.mjs@@ -0,0 +1,105 @@+import fs from 'node:fs';+import path from 'node:path';++export const IMPECCABLE_DIR = '.impeccable';+export const LIVE_DIR = 'live';++export function getImpeccableDir(cwd = process.cwd()) {+ return path.join(cwd, IMPECCABLE_DIR);+}++export function getDesignSidecarPath(cwd = process.cwd()) {+ return path.join(getImpeccableDir(cwd), 'design.json');+}++export function getDesignSidecarCandidates(cwd = process.cwd(), contextDir = cwd) {+ const candidates = [+ getDesignSidecarPath(cwd),+ path.join(cwd, 'DESIGN.json'),+ ];+ const contextLegacy = path.join(contextDir, 'DESIGN.json');+ if (!candidates.includes(contextLegacy)) candidates.push(contextLegacy);+ return candidates;+}++export function resolveDesignSidecarPath(cwd = process.cwd(), contextDir = cwd) {+ return firstExisting(getDesignSidecarCandidates(cwd, contextDir));+}++export function getLiveDir(cwd = process.cwd()) {+ return path.join(getImpeccableDir(cwd), LIVE_DIR);+}++export function getLiveConfigPath(cwd = process.cwd()) {+ return path.join(getLiveDir(cwd), 'config.json');+}++export function getLegacyLiveConfigPath(scriptsDir) {+ return path.join(scriptsDir, 'config.json');+}++export function resolveLiveConfigPath({ cwd = process.cwd(), scriptsDir, env = process.env } = {}) {+ if (env.IMPECCABLE_LIVE_CONFIG && env.IMPECCABLE_LIVE_CONFIG.trim()) {+ const configured = env.IMPECCABLE_LIVE_CONFIG.trim();+ return path.isAbsolute(configured) ? configured : path.resolve(cwd, configured);+ }+ const primary = getLiveConfigPath(cwd);+ if (fs.existsSync(primary)) return primary;+ if (scriptsDir) {+ const legacy = getLegacyLiveConfigPath(scriptsDir);+ if (fs.existsSync(legacy)) return legacy;+ }+ return primary;+}++export function getLiveServerPath(cwd = process.cwd()) {+ return path.join(getLiveDir(cwd), 'server.json');+}++export function getLegacyLiveServerPath(cwd = process.cwd()) {+ return path.join(cwd, '.impeccable-live.json');+}++export function readLiveServerInfo(cwd = process.cwd()) {+ for (const filePath of [getLiveServerPath(cwd), getLegacyLiveServerPath(cwd)]) {+ try {+ return { info: JSON.parse(fs.readFileSync(filePath, 'utf-8')), path: filePath };+ } catch {+ /* try next */+ }+ }+ return null;+}++export function writeLiveServerInfo(cwd = process.cwd(), info) {+ const filePath = getLiveServerPath(cwd);+ fs.mkdirSync(path.dirname(filePath), { recursive: true });+ fs.writeFileSync(filePath, JSON.stringify(info));+ return filePath;+}++export function removeLiveServerInfo(cwd = process.cwd()) {+ for (const filePath of [getLiveServerPath(cwd), getLegacyLiveServerPath(cwd)]) {+ try { fs.unlinkSync(filePath); } catch {}+ }+}++export function getLiveSessionsDir(cwd = process.cwd()) {+ return path.join(getLiveDir(cwd), 'sessions');+}++export function getLegacyLiveSessionsDir(cwd = process.cwd()) {+ return path.join(cwd, '.impeccable-live', 'sessions');+}++export function getLiveAnnotationsDir(cwd = process.cwd()) {+ return path.join(getLiveDir(cwd), 'annotations');+}++export function getLegacyLiveAnnotationsDir(cwd = process.cwd()) {+ return path.join(cwd, '.impeccable-live', 'annotations');+}++function firstExisting(paths) {+ return paths.find((filePath) => fs.existsSync(filePath)) || null;+}diff --git a/.agents/skills/impeccable/scripts/live-browser-session.js b/.agents/skills/impeccable/scripts/live-browser-session.jsnew file mode 100644index 000000000..0e362d6be--- /dev/null+++ b/.agents/skills/impeccable/scripts/live-browser-session.js@@ -0,0 +1,123 @@+/**+ * Browser-side durable session helpers for Impeccable live mode.+ *+ * Kept separate from live-browser.js so recovery state can be tested without+ * booting the full overlay UI. Served before live-browser.js and attached to+ * window.__IMPECCABLE_LIVE_SESSION__.+ */+(function (root) {+ 'use strict';++ function createLiveBrowserSessionState({ prefix, storage, idFactory }) {+ if (!prefix) throw new Error('prefix required');+ const store = storage || root.localStorage;+ const makeId = idFactory || function () { return Math.random().toString(16).slice(2, 10); };+ const sessionKey = prefix + '-session';+ const handledKey = sessionKey + '-handled';+ const scrollKey = sessionKey + '-scroll';+ let checkpointRevision = 0;+ const owner = makeId();++ function safeRead(key) {+ try { return store.getItem(key); } catch { return null; }+ }++ function safeWrite(key, value) {+ try { store.setItem(key, value); } catch { /* quota exceeded or private mode */ }+ }++ function safeRemove(key) {+ try { store.removeItem(key); } catch { /* unavailable storage */ }+ }++ function loadSession() {+ try {+ const raw = safeRead(sessionKey);+ if (!raw) return null;+ const parsed = JSON.parse(raw);+ if (Number.isInteger(parsed.checkpointRevision)) {+ checkpointRevision = Math.max(checkpointRevision, parsed.checkpointRevision);+ }+ return parsed;+ } catch { return null; }+ }++ function saveSession(session) {+ if (!session || !session.id) return;+ const payload = {+ ...session,+ checkpointRevision,+ };+ safeWrite(sessionKey, JSON.stringify(payload));+ }++ function clearSession() {+ safeRemove(sessionKey);+ }++ function nextCheckpointRevision() {+ checkpointRevision += 1;+ const existing = loadSession();+ if (existing?.id) saveSession(existing);+ return checkpointRevision;+ }++ function seedCheckpointRevision(value) {+ if (Number.isInteger(value)) checkpointRevision = Math.max(checkpointRevision, value);+ return checkpointRevision;+ }++ function currentCheckpointRevision() {+ return checkpointRevision;+ }++ function markHandled(id) {+ if (!id) return;+ safeWrite(handledKey, id);+ }++ function isHandled(id) {+ return !!id && safeRead(handledKey) === id;+ }++ function clearHandled() {+ safeRemove(handledKey);+ }++ function writeScrollY(y) {+ safeWrite(scrollKey, String(y));+ }++ function readScrollY() {+ const raw = safeRead(scrollKey);+ if (raw == null) return null;+ const n = parseFloat(raw);+ return isFinite(n) ? n : null;+ }++ function clearScrollY() {+ safeRemove(scrollKey);+ }++ return {+ owner,+ sessionKey,+ handledKey,+ scrollKey,+ saveSession,+ loadSession,+ clearSession,+ nextCheckpointRevision,+ seedCheckpointRevision,+ currentCheckpointRevision,+ markHandled,+ isHandled,+ clearHandled,+ writeScrollY,+ readScrollY,+ clearScrollY,+ };+ }++ root.__IMPECCABLE_LIVE_SESSION__ = { createLiveBrowserSessionState };+})(typeof window !== 'undefined' ? window : globalThis);diff --git a/.agents/skills/impeccable/scripts/live-browser.js b/.agents/skills/impeccable/scripts/live-browser.jsindex 3da76bb96..e67cd01ed 100644--- a/.agents/skills/impeccable/scripts/live-browser.js+++ b/.agents/skills/impeccable/scripts/live-browser.js@@ -50,6 +50,16 @@const Z = { highlight: 100001, bar: 100005, picker: 100007, toast: 100010 };const EASE = 'cubic-bezier(0.22, 1, 0.36, 1)'; // ease-out-quintconst PREFIX = 'impeccable-live';+ const sessionState = window.__IMPECCABLE_LIVE_SESSION__?.createLiveBrowserSessionState({+ prefix: PREFIX,+ storage: localStorage,+ idFactory: () => crypto.randomUUID().replace(/-/g, '').slice(0, 8),+ });+ if (!sessionState) {+ console.error('[impeccable] live-browser-session.js was not loaded. Live mode cannot start safely.');+ window.__IMPECCABLE_LIVE_INIT__ = false;+ return;+ }const HIGHLIGHT_TRANSITION ='top 140ms ' + EASE +', left 140ms ' + EASE +@@ -112,6 +122,8 @@let hasProjectContext = false;let selectedAction = 'impeccable';let selectedCount = 3;+ const browserOwner = sessionState.owner;+ let checkpointTimer = null;// Scroll lock — holds window.scrollY at a fixed value while the session is// active, so HMR DOM patches and variant swaps can't drift the page. See@@ -126,21 +138,9 @@// (Previously: saveSession wrote scrollY alongside state, so every call// during resume overwrote the pre-reload value with whatever the browser// had landed on, typically 0.)- const SCROLL_KEY_SUFFIX = '-scroll';- function writeScrollY(y) {- try { localStorage.setItem(LS_KEY + SCROLL_KEY_SUFFIX, String(y)); } catch {}- }- function readScrollY() {- try {- const raw = localStorage.getItem(LS_KEY + SCROLL_KEY_SUFFIX);- if (raw == null) return null;- const n = parseFloat(raw);- return isFinite(n) ? n : null;- } catch { return null; }- }- function clearScrollY() {- try { localStorage.removeItem(LS_KEY + SCROLL_KEY_SUFFIX); } catch {}- }+ function writeScrollY(y) { sessionState.writeScrollY(y); }+ function readScrollY() { return sessionState.readScrollY(); }+ function clearScrollY() { sessionState.clearScrollY(); }// Pre-empt the browser: apply manual scroll restoration and jump to the// saved scrollY at script-parse time. Retries on fonts.ready and load@@ -1585,6 +1585,7 @@paramsCurrentValues[p.id] = v;readout.textContent = formatRangeValue(input);applyParamValue(variantEl, p, v);+ queueCheckpoint('param_changed');});row.appendChild(input);} else if (p.kind === 'toggle') {@@ -1615,6 +1616,7 @@knob.style.left = next ? '18px' : '2px';readout.textContent = next ? 'On' : 'Off';applyParamValue(variantEl, p, next);+ queueCheckpoint('param_changed');});row.appendChild(track);} else if (p.kind === 'steps') {@@ -1651,6 +1653,7 @@btn.style.color = on ? 'oklch(98% 0 0)' : P.text;});applyParamValue(variantEl, p, o.value);+ queueCheckpoint('param_changed');});segRow.appendChild(b);segBtns.push({ btn: b, val: o.value });@@ -1872,19 +1875,26 @@return;}+ const previousVisibleVariant = currentSessionId === sessionId ? visibleVariant : 0;+// Replace the live element with the full wrapper from sourceconst wrapper = srcWrapper.cloneNode(true);liveEl.parentElement.replaceChild(wrapper, liveEl);- // Update state: count variants, show the first one+ // Update state: count variants, preserving the user's current variant+ // when a late HMR/source reinjection lands after they have cycled.const variants = wrapper.querySelectorAll('[data-impeccable-variant]:not([data-impeccable-variant="original"])');arrivedVariants = variants.length;expectedVariants = parseInt(wrapper.dataset.impeccableVariantCount || arrivedVariants);- visibleVariant = 1;- showVariantInDOM(sessionId, 1);+ const saved = loadSession();+ const savedVisibleVariant = saved && saved.id === sessionId ? saved.visible : 0;+ visibleVariant = previousVisibleVariant > 0 && previousVisibleVariant <= arrivedVariants+ ? previousVisibleVariant+ : (savedVisibleVariant > 0 && savedVisibleVariant <= arrivedVariants ? savedVisibleVariant : 1);+ showVariantInDOM(sessionId, visibleVariant);// Update selectedElement to the visible variant's content- selectedElement = pickVariantContent(wrapper, 1) || wrapper.parentElement;+ selectedElement = pickVariantContent(wrapper, visibleVariant) || wrapper.parentElement;state = 'CYCLING';hideShaderOverlay();@@ -1907,6 +1917,7 @@updateSelectedElement();updateBarContent('cycling');saveSession();+ queueCheckpoint('variant_changed');}function updateSelectedElement() {@@ -1917,6 +1928,18 @@if (visEl) selectedElement = visEl;}+ function readVisibleVariantFromDOM(sessionId) {+ const wrapper = document.querySelector('[data-impeccable-variants="' + sessionId + '"]');+ if (!wrapper) return 0;+ const variants = wrapper.querySelectorAll('[data-impeccable-variant]:not([data-impeccable-variant="original"])');+ for (const variant of variants) {+ if (variant.style.display === 'none') continue;+ const idx = parseInt(variant.dataset.impeccableVariant || '0', 10);+ if (idx > 0) return idx;+ }+ return 0;+ }+// Resolve the element that represents the variant's visible content.// Contract: each variant div should contain exactly one top-level element// (the full replacement). In practice a model may ship loose siblings or@@ -2107,8 +2130,10 @@updating = true;arrivedVariants = count;if (visibleVariant === 0 && arrivedVariants > 0) {- visibleVariant = 1;- showVariantInDOM(sessionId, 1);+ const saved = loadSession();+ const savedVisibleVariant = saved && saved.id === sessionId ? saved.visible : 0;+ visibleVariant = savedVisibleVariant > 0 && savedVisibleVariant <= arrivedVariants ? savedVisibleVariant : 1;+ showVariantInDOM(sessionId, visibleVariant);// showVariantInDOM hid the original (display:none); if we were still// anchored to the original's content, its boundingRect is now zero// and the bar snaps to (0,0). Re-point at the visible variant instead.@@ -2128,6 +2153,7 @@updateBarContent('generating');}saveSession();+ queueCheckpoint(state === 'CYCLING' ? 'variants_ready' : 'variants_progress');updating = false;});@@ -2236,6 +2262,7 @@/** Server died or became unreachable. Reset UI to a clean state. */function handleServerLost() {+ const recoveryState = currentSessionId ? state : 'IDLE';if (state === 'GENERATING' || state === 'CYCLING' || state === 'SAVING') {showToast('Live server disconnected. Session ended.', 5000);}@@ -2246,21 +2273,61 @@stopScrollTracking();if (variantObserver) { variantObserver.disconnect(); variantObserver = null; }stopScrollLock();- clearScrollY();- clearSession();+ // Preserve local session state on server loss. The durable journal is the+ // source of truth, but localStorage plus the variant wrapper lets the UI+ // resume after a helper restart or page reload instead of treating a+ // transient disconnect as an explicit discard.selectedElement = null;- currentSessionId = null;selectedAction = 'impeccable';- state = 'IDLE';+ state = recoveryState;+ if (currentSessionId) saveSession();}- function sendEvent(msg) {+ function sendEvent(msg, opts) {msg.token = TOKEN;- fetch('http://localhost:' + PORT + '/events', {+ function handleFailure(err) {+ console.error('[impeccable] Failed to send event:', err);+ if (opts && opts.throwOnError) throw err;+ return null;+ }+ return fetch('http://localhost:' + PORT + '/events', {method: 'POST',headers: { 'Content-Type': 'application/json' },body: JSON.stringify(msg),- }).catch(err => console.error('[impeccable] Failed to send event:', err));+ }).then(res => {+ if (res.ok) return res;+ return handleFailure(new Error('HTTP ' + res.status + ' ' + res.statusText));+ }).catch(handleFailure);+ }++ function checkpointPayload(reason) {+ return {+ type: 'checkpoint',+ id: currentSessionId,+ revision: sessionState.nextCheckpointRevision(),+ owner: browserOwner,+ phase: String(state || '').toLowerCase(),+ reason,+ pageUrl: location.pathname,+ expectedVariants,+ arrivedVariants,+ visibleVariant,+ paramValues: { ...paramsCurrentValues },+ };+ }++ function sendCheckpoint(reason) {+ if (!currentSessionId) return Promise.resolve(null);+ return sendEvent(checkpointPayload(reason)).catch(() => null);+ }++ function queueCheckpoint(reason) {+ if (!currentSessionId) return;+ if (checkpointTimer) clearTimeout(checkpointTimer);+ checkpointTimer = setTimeout(() => {+ checkpointTimer = null;+ sendCheckpoint(reason);+ }, 120);}// ---------------------------------------------------------------------------@@ -2496,6 +2563,7 @@state = 'GENERATING';showBar('generating');saveSession();+ sendCheckpoint('generate_started');writeScrollY(window.scrollY);if (variantObserver) variantObserver.disconnect();variantObserver = startVariantObserver(currentSessionId);@@ -2920,13 +2988,12 @@ void main() {function handleAccept() {if (!currentSessionId || arrivedVariants === 0) return;+ const domVisibleVariant = readVisibleVariantFromDOM(currentSessionId);+ if (domVisibleVariant > 0) visibleVariant = domVisibleVariant;const acceptPayload = { type: 'accept', id: currentSessionId, variantId: String(visibleVariant) };if (Object.keys(paramsCurrentValues).length > 0) {acceptPayload.paramValues = { ...paramsCurrentValues };}- sendEvent(acceptPayload);- markSessionHandled();-// The accepted variant is already the only visible child of the wrapper// (all other variants are display:none). HMR from the source rewrite will// replace the wrapper imminently. Don't eagerly replaceChild here — React@@ -2936,9 +3003,28 @@ void main() {const acceptedSessionId = currentSessionId;const acceptedVariant = visibleVariant;- state = 'CONFIRMED';- updateBarContent('confirmed');- setTimeout(function() {+ state = 'SAVING';+ updateBarContent('saving');++ sendEvent(acceptPayload, { throwOnError: true })+ .then(() => {+ markSessionHandled();+ confirmAcceptAfterReceipt();+ })+ .catch(() => {+ state = 'CYCLING';+ updateBarContent('cycling');+ showToast('Could not confirm accept with the live server. Session kept for recovery; try Accept again.', 5000);+ });++ function confirmAcceptAfterReceipt() {+ state = 'CONFIRMED';+ updateBarContent('confirmed');+ scheduleAcceptCleanup();+ }++ function scheduleAcceptCleanup() {+ setTimeout(function() {hideBar();hideHighlight();stopScrollTracking();@@ -2967,50 +3053,46 @@ void main() {accepted.style.display = 'contents';parent.replaceChild(accepted, wrapper);}- }, 2000);+ }, 2000);+ }}function handleDiscard() {if (!currentSessionId) return;- sendEvent({ type: 'discard', id: currentSessionId });- markSessionHandled();- // Instant DOM restore + fire-and-forget (script handles file cleanup)- cleanup();+ sendEvent({ type: 'discard', id: currentSessionId }, { throwOnError: true })+ .then(() => {+ markSessionHandled();+ cleanup();+ })+ .catch(() => showToast('Could not confirm discard with the live server. Session kept for recovery.', 5000));}// ---------------------------------------------------------------------------- // Session persistence via localStorage+ // Session persistence via live-browser-session.js// ---------------------------------------------------------------------------// Survives page reloads, browser close/reopen, HMR, and accidental refreshes.- const LS_KEY = PREFIX + '-session';-function saveSession() {if (!currentSessionId) return;// NOTE: scrollY is stored under a separate key (writeScrollY). Storing// it here would overwrite the Go-time value every time state changes.- try {- localStorage.setItem(LS_KEY, JSON.stringify({- id: currentSessionId,- state: state,- action: selectedAction,- count: selectedCount,- expected: expectedVariants,- arrived: arrivedVariants,- visible: visibleVariant,- }));- } catch { /* quota exceeded or private mode */ }+ sessionState.saveSession({+ id: currentSessionId,+ state,+ action: selectedAction,+ count: selectedCount,+ expected: expectedVariants,+ arrived: arrivedVariants,+ visible: visibleVariant,+ });}function loadSession() {- try {- const raw = localStorage.getItem(LS_KEY);- return raw ? JSON.parse(raw) : null;- } catch { return null; }+ return sessionState.loadSession();}function clearSession() {- try { localStorage.removeItem(LS_KEY); } catch {}+ sessionState.clearSession();}/** Mark session as handled (accepted/discarded). The agent will clean up@@ -3018,19 +3100,15 @@ void main() {* prevents resumeSession from picking it up again after reload. */function markSessionHandled() {if (!currentSessionId) return;- try {- localStorage.setItem(LS_KEY + '-handled', currentSessionId);- } catch {}+ sessionState.markHandled(currentSessionId);}function isSessionHandled(id) {- try {- return localStorage.getItem(LS_KEY + '-handled') === id;- } catch { return false; }+ return sessionState.isHandled(id);}function clearHandled() {- try { localStorage.removeItem(LS_KEY + '-handled'); } catch {}+ sessionState.clearHandled();}function cleanup() {@@ -3161,6 +3239,7 @@ void main() {// hid. Now that state is CYCLING, re-fire.if (state === 'CYCLING') refreshParamsPanel();saveSession();+ queueCheckpoint('browser_resumed');// Start observing for more variants AFTER initial setupif (variantObserver) variantObserver.disconnect();@@ -3617,7 +3696,7 @@ void main() {}// ---------------------------------------------------------------------------- // Design System Panel — visualizes the project's DESIGN.json sidecar+ // Design System Panel — visualizes the project's .impeccable/design.json sidecar// ---------------------------------------------------------------------------const DESIGN_PREFS_KEY = 'impeccable-live-design-panel';@@ -3629,7 +3708,7 @@ void main() {open: false,tab: 'visual', // 'visual' | 'raw'parsed: null, // parseDesignMd output (frontmatter + body sections)- sidecar: null, // DESIGN.json v2 payload (extensions + components + narrative)+ sidecar: null, // .impeccable/design.json v2 payload (extensions + components + narrative)hasMd: false,hasSidecar: false,present: null, // true/false once fetch resolves@@ -4130,7 +4209,7 @@ void main() {box.className = 'stale';box.innerHTML = `<span class="stale-dot"></span>- <span class="stale-text"><strong>DESIGN.md is newer than DESIGN.json.</strong> Run <code>/impeccable document</code> to refresh the sidecar.</span>+ <span class="stale-text"><strong>DESIGN.md is newer than .impeccable/design.json.</strong> Run <code>/impeccable document</code> to refresh the sidecar.</span>`;return box;}@@ -4138,7 +4217,7 @@ void main() {function renderParsedMdCta() {const box = document.createElement('div');box.className = 'parsed-md-cta';- box.innerHTML = `<strong>Basic view</strong>This panel reads the tokens in your <code>DESIGN.md</code> frontmatter. Running <code>/impeccable document</code> also generates a <code>DESIGN.json</code> sidecar with your project's actual component snippets (button, input, nav) and tonal ramps, rendered live below the tokens.`;+ box.innerHTML = `<strong>Basic view</strong>This panel reads the tokens in your <code>DESIGN.md</code> frontmatter. Running <code>/impeccable document</code> also generates a <code>.impeccable/design.json</code> sidecar with your project's actual component snippets (button, input, nav) and tonal ramps, rendered live below the tokens.`;return box;}@@ -4598,7 +4677,7 @@ void main() {function cssSafe(v) {// Strip anything outside valid CSS value chars to prevent injection via- // DESIGN.json values rendered into inline style strings.+ // .impeccable/design.json values rendered into inline style strings.return String(v).replace(/[<>"'`\n]/g, '');}diff --git a/.agents/skills/impeccable/scripts/live-complete.mjs b/.agents/skills/impeccable/scripts/live-complete.mjsnew file mode 100644index 000000000..78155af85--- /dev/null+++ b/.agents/skills/impeccable/scripts/live-complete.mjs@@ -0,0 +1,75 @@+#!/usr/bin/env node+/**+ * Canonical durable completion acknowledgement for Impeccable live sessions.+ */++import { createLiveSessionStore } from './live-session-store.mjs';+import { readLiveServerInfo } from './impeccable-paths.mjs';++function parseArgs(argv) {+ const out = { status: 'complete' };+ for (let i = 0; i < argv.length; i++) {+ const arg = argv[i];+ if (arg === '--id') out.id = argv[++i];+ else if (arg.startsWith('--id=')) out.id = arg.slice('--id='.length);+ else if (arg === '--discarded' || arg === '--discard') out.status = 'discarded';+ else if (arg === '--error') { out.status = 'agent_error'; out.message = argv[++i] || 'unknown error'; }+ else if (arg.startsWith('--error=')) { out.status = 'agent_error'; out.message = arg.slice('--error='.length); }+ else if (arg === '--help' || arg === '-h') out.help = true;+ }+ return out;+}++export async function completeCli() {+ const args = parseArgs(process.argv.slice(2));+ if (args.help || !args.id) {+ console.log(`Usage: node live-complete.mjs --id SESSION_ID [--discarded|--error MESSAGE]\n\nAppend the final durable session acknowledgement. Use after accept/discard cleanup is verified.`);+ process.exit(args.help ? 0 : 1);+ }++ const serverInfo = readServerInfo();+ const serverResult = serverInfo ? await completeThroughServer(serverInfo, args) : null;+ if (serverResult?.ok) {+ const store = createLiveSessionStore({ cwd: process.cwd(), sessionId: args.id });+ const snapshot = store.getSnapshot(args.id, { includeCompleted: true });+ console.log(JSON.stringify({ ok: true, id: args.id, phase: snapshot?.phase || args.status, snapshot }, null, 2));+ return;+ }++ const store = createLiveSessionStore({ cwd: process.cwd(), sessionId: args.id });+ const event = args.status === 'discarded'+ ? { type: 'discarded', id: args.id }+ : args.status === 'agent_error'+ ? { type: 'agent_error', id: args.id, message: args.message || 'unknown error' }+ : { type: 'complete', id: args.id };+ const snapshot = store.appendEvent(event);+ console.log(JSON.stringify({ ok: true, id: args.id, phase: snapshot.phase, snapshot }, null, 2));+}++function readServerInfo() {+ return readLiveServerInfo(process.cwd())?.info || null;+}++async function completeThroughServer(info, args) {+ const type = args.status === 'discarded'+ ? 'discarded'+ : args.status === 'agent_error'+ ? 'error'+ : 'complete';+ try {+ const res = await fetch(`http://localhost:${info.port}/poll`, {+ method: 'POST',+ headers: { 'Content-Type': 'application/json' },+ body: JSON.stringify({ token: info.token, id: args.id, type, message: args.message }),+ });+ if (!res.ok) return null;+ return await res.json();+ } catch {+ return null;+ }+}++const _running = process.argv[1];+if (_running?.endsWith('live-complete.mjs') || _running?.endsWith('live-complete.mjs/')) {+ completeCli();+}diff --git a/.agents/skills/impeccable/scripts/live-completion.mjs b/.agents/skills/impeccable/scripts/live-completion.mjsnew file mode 100644index 000000000..86b637fff--- /dev/null+++ b/.agents/skills/impeccable/scripts/live-completion.mjs@@ -0,0 +1,18 @@+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';+ return 'agent_done';+}++export function completionAckForAcceptResult(eventId, completionType, acceptResult) {+ const ack = { ok: true, type: completionType };+ if (acceptResult?.handled === true && acceptResult?.carbonize === true) {+ ack.final = false;+ ack.requiresComplete = true;+ ack.nextCommand = `live-complete.mjs --id ${eventId}`;+ ack.message = 'Carbonize cleanup must be verified, then the session must be completed explicitly before polling again.';+ }+ return ack;+}diff --git a/.agents/skills/impeccable/scripts/live-inject.mjs b/.agents/skills/impeccable/scripts/live-inject.mjsindex 1d2ae12f7..555c3a36a 100644--- a/.agents/skills/impeccable/scripts/live-inject.mjs+++ b/.agents/skills/impeccable/scripts/live-inject.mjs@@ -2,23 +2,24 @@* CLI helper: insert/remove the live variant mode script tag in the project's* main HTML entry point.*- * On first live run, the agent generates `config.json` in this script's- * directory with the project's insertion target (framework-specific). On+ * On first live run, the agent generates `.impeccable/live/config.json`+ * with the project's insertion target (framework-specific). On* every subsequent run, this script handles insert/remove deterministically* with zero LLM involvement.** Usage:* node live-inject.mjs --port PORT # Insert the live script tag* node live-inject.mjs --remove # Remove the live script tag- * node live-inject.mjs --check # Check whether config.json exists+ * node live-inject.mjs --check # Check whether live config exists*/import fs from 'node:fs';import path from 'node:path';import { fileURLToPath } from 'node:url';+import { resolveLiveConfigPath } from './impeccable-paths.mjs';const __dirname = path.dirname(fileURLToPath(import.meta.url));-const CONFIG_PATH = process.env.IMPECCABLE_LIVE_CONFIG || path.join(__dirname, 'config.json');+const CONFIG_PATH = resolveLiveConfigPath({ cwd: process.cwd(), scriptsDir: __dirname });const MARKER_OPEN_TEXT = 'impeccable-live-start';const MARKER_CLOSE_TEXT = 'impeccable-live-end';@@ -39,12 +40,12 @@ export async function injectCli() {console.log(`Usage: node live-inject.mjs [options]Insert or remove the live mode script tag in the project's HTML entry point.-Reads configuration from config.json (in this same directory).+Reads configuration from .impeccable/live/config.json.Modes:--port PORT Insert script tag pointing at http://localhost:PORT/live.js--remove Remove the script tag (if present)- --check Print whether config.json exists and its content+ --check Print whether .impeccable/live/config.json exists and its contentOutput (JSON):{ ok, file, inserted|removed, config? }`);diff --git a/.agents/skills/impeccable/scripts/live-poll.mjs b/.agents/skills/impeccable/scripts/live-poll.mjsindex eb8f1586a..10d452491 100644--- a/.agents/skills/impeccable/scripts/live-poll.mjs+++ b/.agents/skills/impeccable/scripts/live-poll.mjs@@ -9,10 +9,10 @@*/import { execFileSync } from 'node:child_process';-import fs from 'node:fs';import path from 'node:path';-import os from 'node:os';import { fileURLToPath } from 'node:url';+import { completionAckForAcceptResult, completionTypeForAcceptResult } from './live-completion.mjs';+import { readLiveServerInfo } from './impeccable-paths.mjs';// Node's built-in fetch (undici under the hood) enforces a 300s headers// timeout that can't be lowered per-request. We cap each request below@@ -20,15 +20,29 @@ import { fileURLToPath } from 'node:url';// depending on the standalone undici package.const PER_REQUEST_TIMEOUT_MS = 270_000;-const LIVE_PID_FILE = path.join(process.cwd(), '.impeccable-live.json');-function readServerInfo() {- try {- return JSON.parse(fs.readFileSync(LIVE_PID_FILE, 'utf-8'));- } catch {+ const record = readLiveServerInfo(process.cwd());+ if (!record) {console.error('No running live server found. Start one with: npx impeccable live');process.exit(1);}+ return record.info;+}++export function buildPollReplyPayload(token, { id, type, message, file, data }) {+ return { token, id, type, message, file, data };+}++async function postReply(base, token, reply) {+ const res = await fetch(`${base}/poll`, {+ method: 'POST',+ headers: { 'Content-Type': 'application/json' },+ body: JSON.stringify(buildPollReplyPayload(token, reply)),+ });+ if (!res.ok) {+ const body = await res.json().catch(() => ({}));+ throw new Error(body.error || res.statusText);+ }}export async function pollCli() {@@ -69,23 +83,7 @@ Options:}try {- const res = await fetch(`${base}/poll`, {- method: 'POST',- headers: { 'Content-Type': 'application/json' },- body: JSON.stringify({- token: info.token,- id,- type: status,- message,- file: filePath,- }),- });-- if (!res.ok) {- const body = await res.json().catch(() => ({}));- console.error(`Reply failed (${res.status}):`, body.error || res.statusText);- process.exit(1);- }+ await postReply(base, info.token, { id, type: status, message, file: filePath });// Success — silent exit (agent doesn't need output for replies)} catch (err) {@@ -156,7 +154,23 @@ Options:);event._acceptResult = JSON.parse(out.trim());} catch (err) {- event._acceptResult = { handled: false, error: err.message };+ event._acceptResult = { handled: false, mode: 'error', error: err.message };+ }++ const completionType = completionTypeForAcceptResult(event.type, event._acceptResult);+ try {+ await postReply(base, info.token, {+ id: event.id,+ type: completionType,+ message: event._acceptResult?.error,+ file: event._acceptResult?.file,+ data: event._acceptResult?.carbonize === true ? { carbonize: true } : undefined,+ });+ } catch (err) {+ event._completionAck = { ok: false, error: err.message };+ }+ if (!event._completionAck) {+ event._completionAck = completionAckForAcceptResult(event.id, completionType, event._acceptResult);}}@@ -164,7 +178,7 @@ Options:// JSON but skips nested fields. One line is enough — the full checklist// is in reference/live.md.if (event._acceptResult?.carbonize === true) {- process.stderr.write('\n⚠ Carbonize cleanup REQUIRED before next poll. See reference/live.md "Required after accept".\n\n');+ process.stderr.write('\n⚠ Carbonize cleanup REQUIRED before next poll. After cleanup, run live-complete.mjs --id ' + event.id + '. See reference/live.md "Required after accept".\n\n');}// Print the event as JSON — the agent reads this from stdoutdiff --git a/.agents/skills/impeccable/scripts/live-resume.mjs b/.agents/skills/impeccable/scripts/live-resume.mjsnew file mode 100644index 000000000..a3465c9b5--- /dev/null+++ b/.agents/skills/impeccable/scripts/live-resume.mjs@@ -0,0 +1,48 @@+#!/usr/bin/env node+/**+ * Recover the next agent action from the durable live-session journal.+ */++import { createLiveSessionStore } from './live-session-store.mjs';++function parseArgs(argv) {+ const out = { id: null };+ for (let i = 0; i < argv.length; i++) {+ const arg = argv[i];+ if (arg === '--id') out.id = argv[++i];+ else if (arg.startsWith('--id=')) out.id = arg.slice('--id='.length);+ else if (arg === '--help' || arg === '-h') out.help = true;+ }+ return out;+}++export async function resumeCli() {+ const args = parseArgs(process.argv.slice(2));+ if (args.help) {+ console.log(`Usage: node live-resume.mjs [--id SESSION_ID]\n\nPrint the active durable session checkpoint and the next safe agent action.`);+ return;+ }++ const store = createLiveSessionStore({ cwd: process.cwd(), sessionId: args.id || undefined });+ const snapshot = args.id ? store.getSnapshot(args.id) : store.listActiveSessions()[0] || null;+ if (!snapshot) {+ console.log(JSON.stringify({ active: false, nextAction: 'No active durable live session found.' }, null, 2));+ return;+ }++ const pending = snapshot.pendingEvent || null;+ const nextAction = pending+ ? `Run live-poll.mjs, handle ${pending.type} ${pending.id}, then acknowledge with live-poll.mjs --reply ${pending.id} done.`+ : snapshot.phase === 'carbonize_required'+ ? `Finish carbonize cleanup${snapshot.sourceFile ? ` in ${snapshot.sourceFile}` : ''}, then run live-complete.mjs --id ${snapshot.id}.`+ : snapshot.phase === 'accept_requested'+ ? `Run live-complete.mjs --id ${snapshot.id} after verifying the accepted variant is written.`+ : `Inspect ${snapshot.id}; no pending agent event is currently queued.`;++ console.log(JSON.stringify({ active: true, snapshot, pendingEvent: pending, nextAction }, null, 2));+}++const _running = process.argv[1];+if (_running?.endsWith('live-resume.mjs') || _running?.endsWith('live-resume.mjs/')) {+ resumeCli();+}diff --git a/.agents/skills/impeccable/scripts/live-server.mjs b/.agents/skills/impeccable/scripts/live-server.mjsindex 90614fbf7..53d8f21cb 100644--- a/.agents/skills/impeccable/scripts/live-server.mjs+++ b/.agents/skills/impeccable/scripts/live-server.mjs@@ -22,14 +22,20 @@ import net from 'node:net';import { fileURLToPath } from 'node:url';import { parseDesignMd } from './design-parser.mjs';import { resolveContextDir } from './load-context.mjs';+import { createLiveSessionStore } from './live-session-store.mjs';+import {+ getDesignSidecarPath,+ getLiveAnnotationsDir,+ readLiveServerInfo,+ removeLiveServerInfo,+ resolveDesignSidecarPath,+ writeLiveServerInfo,+} from './impeccable-paths.mjs';const __dirname = path.dirname(fileURLToPath(import.meta.url));-// PID file in the project root so both the server and agent can find it-// predictably (os.tmpdir() varies across platforms).-const LIVE_PID_FILE = path.join(process.cwd(), '.impeccable-live.json');-// PRODUCT.md / DESIGN.md / DESIGN.json live wherever load-context.mjs resolves.-// Keeps live-server in sync with the loader when users keep the docs in-// .agents/context/, docs/, or a path set via IMPECCABLE_CONTEXT_DIR.+// PRODUCT.md / DESIGN.md live wherever load-context.mjs resolves. The generated+// DESIGN sidecar is project-local at .impeccable/design.json, with legacy+// DESIGN.json fallback for existing projects.const CONTEXT_DIR = resolveContextDir(process.cwd());const DEFAULT_POLL_TIMEOUT = 600_000; // 10 min — agent re-polls on timeout anywayconst SSE_HEARTBEAT_INTERVAL = 30_000; // keepalive ping every 30s@@ -57,10 +63,12 @@ const state = {token: null,port: null,sseClients: new Set(), // SSE response objects (server→browser push)- pendingEvents: [], // browser events waiting for agent poll+ pendingEvents: [], // browser events waiting for agent ack ({ event, leaseUntil })pendingPolls: [], // agent poll callbacks waiting for browser eventsexitTimer: null,sessionDir: null, // per-session tmp dir for annotation screenshots+ sessionStore: null,+ leaseTimer: null,};// Cap per-annotation upload size. A full 1920×1080 PNG is typically <1 MB;@@ -68,11 +76,70 @@ const state = {const MAX_ANNOTATION_BYTES = 10 * 1024 * 1024;function enqueueEvent(event) {- if (state.pendingPolls.length > 0) {- state.pendingPolls.shift()(event);- } else {- state.pendingEvents.push(event);+ if (!event || (event.id && state.pendingEvents.some((entry) => entry.event?.id === event.id && entry.event?.type === event.type))) return;+ state.pendingEvents.push({ event, leaseUntil: 0 });+ flushPendingPolls();+}++function restorePendingEventsFromStore() {+ if (!state.sessionStore) return;+ for (const snapshot of state.sessionStore.listActiveSessions()) {+ if (snapshot.pendingEvent) enqueueEvent(snapshot.pendingEvent);+ }+}++function findAvailablePendingEvent(now = Date.now()) {+ return state.pendingEvents.find((entry) => !entry.leaseUntil || entry.leaseUntil <= now);+}++function leaseEvent(entry, leaseMs) {+ if (!entry.event?.id) {+ const idx = state.pendingEvents.indexOf(entry);+ if (idx !== -1) state.pendingEvents.splice(idx, 1);+ return entry.event;}+ entry.leaseUntil = Date.now() + leaseMs;+ return entry.event;+}++function acknowledgePendingEvent(id) {+ if (!id) return false;+ const idx = state.pendingEvents.findIndex((entry) => entry.event?.id === id);+ if (idx === -1) return false;+ state.pendingEvents.splice(idx, 1);+ scheduleLeaseFlush();+ return true;+}++function scheduleLeaseFlush() {+ if (state.leaseTimer) {+ clearTimeout(state.leaseTimer);+ state.leaseTimer = null;+ }+ if (state.pendingPolls.length === 0) return;+ const now = Date.now();+ const nextLeaseUntil = state.pendingEvents+ .map((entry) => entry.leaseUntil || 0)+ .filter((leaseUntil) => leaseUntil > now)+ .sort((a, b) => a - b)[0];+ if (!nextLeaseUntil) return;+ state.leaseTimer = setTimeout(() => {+ state.leaseTimer = null;+ flushPendingPolls();+ }, Math.max(0, nextLeaseUntil - now));+}++function flushPendingPolls() {+ while (state.pendingPolls.length > 0) {+ const entry = findAvailablePendingEvent();+ if (!entry) {+ scheduleLeaseFlush();+ return;+ }+ const poll = state.pendingPolls.shift();+ poll.resolve(leaseEvent(entry, poll.leaseMs));+ }+ scheduleLeaseFlush();}/** Push a message to all connected SSE clients. */@@ -103,13 +170,16 @@ function loadBrowserScripts() {// live-browser.js: DO NOT cache. Return the path so the /live.js handler// can re-read on every request. Editing the browser script during iteration// should land on the next tab reload, not require a server restart.+ const sessionPath = path.join(__dirname, 'live-browser-session.js');const livePath = path.join(__dirname, 'live-browser.js');- if (!fs.existsSync(livePath)) {- process.stderr.write('Error: live-browser.js not found at ' + livePath + '\n');- process.exit(1);+ for (const p of [sessionPath, livePath]) {+ if (!fs.existsSync(p)) {+ process.stderr.write('Error: live browser script not found at ' + p + '\n');+ process.exit(1);+ }}- return { detectScript, livePath };+ return { detectScript, sessionPath, livePath };}function hasProjectContext() {@@ -170,6 +240,13 @@ function validateEvent(msg) {return null;case 'discard':return isValidId(msg.id) ? null : 'discard: missing or malformed id';+ case 'checkpoint':+ if (!isValidId(msg.id)) return 'checkpoint: missing or malformed id';+ if (!Number.isInteger(msg.revision) || msg.revision < 0) return 'checkpoint: revision must be a non-negative integer';+ if (msg.paramValues !== undefined && (typeof msg.paramValues !== 'object' || msg.paramValues === null || Array.isArray(msg.paramValues))) {+ return 'checkpoint: paramValues must be an object';+ }+ return null;case 'exit':return null;case 'prefetch':@@ -184,7 +261,7 @@ function validateEvent(msg) {// HTTP request handler// ----------------------------------------------------------------------------function createRequestHandler({ detectScript, livePath }) {+function createRequestHandler({ detectScript, sessionPath, livePath }) {return (req, res) => {const url = new URL(req.url, `http://localhost:${state.port}`);res.setHeader('Access-Control-Allow-Origin', '*');@@ -200,17 +277,20 @@ function createRequestHandler({ detectScript, livePath }) {// the next tab reload. No-store headers prevent browser caching across// sessions — during iteration, a cached old script silently breaks// every subsequent session.+ let sessionScript;let liveScript;try {+ sessionScript = fs.readFileSync(sessionPath, 'utf-8');liveScript = fs.readFileSync(livePath, 'utf-8');} catch (err) {res.writeHead(500, { 'Content-Type': 'text/plain' });- res.end('Error reading live-browser.js: ' + err.message);+ res.end('Error reading live browser scripts: ' + err.message);return;}const body =`window.__IMPECCABLE_TOKEN__ = '${state.token}';\n` +`window.__IMPECCABLE_PORT__ = ${state.port};\n` ++ sessionScript + '\n' +liveScript;res.writeHead(200, {'Content-Type': 'application/javascript',@@ -305,6 +385,26 @@ function createRequestHandler({ detectScript, livePath }) {}// --- Health ---+ if (p === '/status') {+ const token = url.searchParams.get('token');+ if (token !== state.token) { res.writeHead(401, { 'Content-Type': 'application/json' }); res.end(JSON.stringify({ error: 'Unauthorized' })); return; }+ const sessions = state.sessionStore ? state.sessionStore.listActiveSessions() : [];+ res.writeHead(200, { 'Content-Type': 'application/json' });+ res.end(JSON.stringify({+ status: 'ok',+ port: state.port,+ connectedClients: state.sseClients.size,+ pendingEvents: state.pendingEvents.map((entry) => ({+ id: entry.event?.id,+ type: entry.event?.type,+ leased: !!(entry.leaseUntil && entry.leaseUntil > Date.now()),+ leaseUntil: entry.leaseUntil || null,+ })),+ activeSessions: sessions,+ }));+ return;+ }+if (p === '/health') {res.writeHead(200, { 'Content-Type': 'application/json' });res.end(JSON.stringify({@@ -316,13 +416,13 @@ function createRequestHandler({ detectScript, livePath }) {}// --- Design system (unified v2 response) + raw ---- // /design-system.json returns both parsed DESIGN.md and DESIGN.json+ // /design-system.json returns both parsed DESIGN.md and .impeccable/design.json// sidecar when present. Panel merges them:// { present, parsed, sidecar, hasMd, hasSidecar,// mdNewerThanJson, parseError?, sidecarError? }// - parsed: output of parseDesignMd (frontmatter// + six canonical sections) when DESIGN.md exists.- // - sidecar: DESIGN.json contents when present.+ // - sidecar: .impeccable/design.json contents when present.// Expected shape: schemaVersion 2, carrying// extensions + components + narrative.// /design-system/raw returns DESIGN.md markdown verbatim@@ -331,7 +431,7 @@ function createRequestHandler({ detectScript, livePath }) {if (token !== state.token) { res.writeHead(401); res.end('Unauthorized'); return; }const mdPath = path.join(CONTEXT_DIR, 'DESIGN.md');- const jsonPath = path.join(CONTEXT_DIR, 'DESIGN.json');+ const jsonPath = resolveDesignSidecarPath(process.cwd(), CONTEXT_DIR) || getDesignSidecarPath(process.cwd());const mdStat = statOrNull(mdPath);const jsonStat = statOrNull(jsonPath);@@ -367,7 +467,7 @@ function createRequestHandler({ detectScript, livePath }) {try {response.sidecar = JSON.parse(fs.readFileSync(jsonPath, 'utf-8'));} catch (err) {- response.sidecarError = 'Failed to parse DESIGN.json: ' + err.message;+ response.sidecarError = 'Failed to parse .impeccable/design.json: ' + err.message;}}@@ -449,7 +549,16 @@ function createRequestHandler({ detectScript, livePath }) {res.end(JSON.stringify({ error }));return;}- enqueueEvent(msg);+ if (state.sessionStore && msg.id) {+ try {+ state.sessionStore.appendEvent(msg);+ } catch (err) {+ res.writeHead(500, { 'Content-Type': 'application/json' });+ res.end(JSON.stringify({ error: 'session_store_append_failed', message: err.message }));+ return;+ }+ }+ if (msg.type !== 'checkpoint') enqueueEvent(msg);res.writeHead(200, { 'Content-Type': 'application/json' });res.end(JSON.stringify({ ok: true }));});@@ -492,13 +601,16 @@ function handlePollGet(req, res, url) {return;}const timeout = parseInt(url.searchParams.get('timeout') || DEFAULT_POLL_TIMEOUT, 10);- if (state.pendingEvents.length > 0) {+ const leaseMs = parseInt(url.searchParams.get('leaseMs') || '30000', 10);+ const available = findAvailablePendingEvent();+ if (available) {res.writeHead(200, { 'Content-Type': 'application/json' });- res.end(JSON.stringify(state.pendingEvents.shift()));+ res.end(JSON.stringify(leaseEvent(available, leaseMs)));return;}+ const poll = { resolve, leaseMs };const timer = setTimeout(() => {- const idx = state.pendingPolls.indexOf(resolve);+ const idx = state.pendingPolls.indexOf(poll);if (idx !== -1) state.pendingPolls.splice(idx, 1);res.writeHead(200, { 'Content-Type': 'application/json' });res.end(JSON.stringify({ type: 'timeout' }));@@ -508,10 +620,11 @@ function handlePollGet(req, res, url) {res.writeHead(200, { 'Content-Type': 'application/json' });res.end(JSON.stringify(event));}- state.pendingPolls.push(resolve);+ state.pendingPolls.push(poll);+ scheduleLeaseFlush();req.on('close', () => {clearTimeout(timer);- const idx = state.pendingPolls.indexOf(resolve);+ const idx = state.pendingPolls.indexOf(poll);if (idx !== -1) state.pendingPolls.splice(idx, 1);});}@@ -531,6 +644,26 @@ function handlePollPost(req, res) {res.end(JSON.stringify({ error: 'Unauthorized' }));return;}+ acknowledgePendingEvent(msg.id);+ if (state.sessionStore && msg.id) {+ try {+ const eventType = msg.type === 'discard' || msg.type === 'discarded'+ ? 'discarded'+ : msg.type === 'complete'+ ? 'complete'+ : msg.type === 'error'+ ? 'agent_error'+ : 'agent_done';+ state.sessionStore.appendEvent({+ type: eventType,+ id: msg.id,+ file: msg.file,+ message: msg.message,+ carbonize: msg.data?.carbonize === true,+ });+ } catch { /* keep reply path best-effort; browser still needs SSE */ }+ }+ flushPendingPolls();// Forward the reply to the browser via SSEbroadcast({ type: msg.type || 'done', id: msg.id, message: msg.message, file: msg.file, data: msg.data });res.writeHead(200, { 'Content-Type': 'application/json' });@@ -545,13 +678,15 @@ function handlePollPost(req, res) {let httpServer = null;function shutdown() {- try { fs.unlinkSync(LIVE_PID_FILE); } catch {}+ removeLiveServerInfo(process.cwd());+ if (state.leaseTimer) clearTimeout(state.leaseTimer);+ state.leaseTimer = null;if (state.sessionDir) {try { fs.rmSync(state.sessionDir, { recursive: true, force: true }); } catch {}}for (const res of state.sseClients) { try { res.end(); } catch {} }state.sseClients.clear();- for (const resolve of state.pendingPolls) resolve({ type: 'exit' });+ for (const poll of state.pendingPolls) poll.resolve({ type: 'exit' });state.pendingPolls.length = 0;if (httpServer) httpServer.close();process.exit(0);@@ -587,6 +722,7 @@ Endpoints:/events SSE stream (server→browser) + POST (browser→server)/poll Long-poll for agent CLI/source Raw source file reader (no-HMR fallback)+ /status Durable recovery status (token-protected)/health Health check`);process.exit(0);}@@ -594,7 +730,7 @@ Endpoints:if (args.includes('stop')) {const keepInject = args.includes('--keep-inject');try {- const info = JSON.parse(fs.readFileSync(LIVE_PID_FILE, 'utf-8'));+ const { info } = readLiveServerInfo(process.cwd()) || {};const res = await fetch(`http://localhost:${info.port}/stop?token=${info.token}`);if (res.ok) console.log(`Stopped live server on port ${info.port}.`);} catch {@@ -645,7 +781,7 @@ if (args.includes('--background')) {const deadline = Date.now() + 10_000;while (Date.now() < deadline) {try {- const info = JSON.parse(fs.readFileSync(LIVE_PID_FILE, 'utf-8'));+ const { info } = readLiveServerInfo(process.cwd()) || {};if (info.pid !== process.pid) {// Output JSON so the agent can read port + token from stdout.console.log(JSON.stringify(info));@@ -659,30 +795,36 @@ if (args.includes('--background')) {}// Check for existing session-try {- const existing = JSON.parse(fs.readFileSync(LIVE_PID_FILE, 'utf-8'));- try { process.kill(existing.pid, 0);+const existingRecord = readLiveServerInfo(process.cwd());+if (existingRecord?.info) {+ const existing = existingRecord.info;+ try {+ process.kill(existing.pid, 0);console.error(`Live server already running on port ${existing.port} (pid ${existing.pid}).`);console.error('Stop it first with: node ' + path.basename(fileURLToPath(import.meta.url)) + ' stop');process.exit(1);- } catch { fs.unlinkSync(LIVE_PID_FILE); }-} catch {}+ } catch {+ try { fs.unlinkSync(existingRecord.path); } catch {}+ }+}state.token = randomUUID();+state.sessionStore = createLiveSessionStore({ cwd: process.cwd() });+restorePendingEventsFromStore();const portArg = args.find(a => a.startsWith('--port='));state.port = portArg ? parseInt(portArg.split('=')[1], 10) : await findOpenPort();// Annotation screenshots live in the project root so the agent's Read tool// doesn't trip a per-file permission prompt. Sessioned by token so concurrent// projects (or quick restarts) don't collide.-const annotRoot = path.join(process.cwd(), '.impeccable-live', 'annotations');+const annotRoot = getLiveAnnotationsDir(process.cwd());fs.mkdirSync(annotRoot, { recursive: true });state.sessionDir = fs.mkdtempSync(path.join(annotRoot, 'session-'));-const { detectScript, livePath } = loadBrowserScripts();-httpServer = http.createServer(createRequestHandler({ detectScript, livePath }));+const { detectScript, sessionPath, livePath } = loadBrowserScripts();+httpServer = http.createServer(createRequestHandler({ detectScript, sessionPath, livePath }));httpServer.listen(state.port, '127.0.0.1', () => {- fs.writeFileSync(LIVE_PID_FILE, JSON.stringify({ pid: process.pid, port: state.port, token: state.token }));+ writeLiveServerInfo(process.cwd(), { pid: process.pid, port: state.port, token: state.token });const url = `http://localhost:${state.port}`;console.log(`\nImpeccable live server running on ${url}`);console.log(`Token: ${state.token}\n`);diff --git a/.agents/skills/impeccable/scripts/live-session-store.mjs b/.agents/skills/impeccable/scripts/live-session-store.mjsnew file mode 100644index 000000000..d55ed2d3a--- /dev/null+++ b/.agents/skills/impeccable/scripts/live-session-store.mjs@@ -0,0 +1,254 @@+import fs from 'node:fs';+import path from 'node:path';+import { getLegacyLiveSessionsDir, getLiveSessionsDir } from './impeccable-paths.mjs';++const COMPLETED_PHASES = new Set(['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;+ }++ function getReadableJournalPath(id) {+ const primary = getJournalPath(rootDir, id);+ if (fs.existsSync(primary)) return primary;+ const legacy = getJournalPath(legacyRootDir, id);+ if (fs.existsSync(legacy)) return legacy;+ return primary;+ }++ return {+ rootDir,+ legacyRootDir,+ appendEvent(event) {+ const normalized = normalizeEvent(event, sessionId);+ const journalPath = getJournalPath(rootDir, normalized.id);+ const snapshotPath = getSnapshotPath(rootDir, normalized.id);+ const legacyJournalPath = getJournalPath(legacyRootDir, normalized.id);+ if (!fs.existsSync(journalPath) && fs.existsSync(legacyJournalPath)) {+ fs.copyFileSync(legacyJournalPath, journalPath);+ }+ const prior = loadCachedOrRebuild(normalized.id);+ const seq = prior.nextSeq;+ const entry = {+ seq,+ id: normalized.id,+ type: normalized.type,+ ts: new Date().toISOString(),+ event: normalized,+ };+ 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;+ },+ getSnapshot(id = sessionId, opts = {}) {+ if (!id) throw new Error('session id required');+ 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;+ },+ listActiveSessions() {+ const ids = new Set();+ for (const dir of [legacyRootDir, rootDir]) {+ if (!fs.existsSync(dir)) continue;+ for (const name of fs.readdirSync(dir)) {+ if (name.endsWith('.jsonl')) ids.add(name.slice(0, -'.jsonl'.length));+ }+ }+ return [...ids]+ .sort()+ .map((id) => this.getSnapshot(id))+ .filter(Boolean);+ },+ };+}++function normalizeEvent(event, fallbackId) {+ if (!event || typeof event !== 'object') throw new Error('event object required');+ const id = event.id || fallbackId;+ if (!id || typeof id !== 'string') throw new Error('event id required');+ if (!event.type || typeof event.type !== 'string') throw new Error('event type required');+ return { ...event, id };+}++function getJournalPath(rootDir, id) {+ return path.join(rootDir, safeSessionId(id) + '.jsonl');+}++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,+ phase: 'new',+ pageUrl: null,+ sourceFile: null,+ expectedVariants: 0,+ arrivedVariants: 0,+ visibleVariant: null,+ paramValues: {},+ pendingEventSeq: null,+ pendingEvent: null,+ deliveryLease: null,+ checkpointRevision: 0,+ activeOwner: null,+ sourceMarkers: {},+ fallbackMode: null,+ annotationArtifacts: [],+ diagnostics: [],+ updatedAt: null,+ };+}++function rebuildSnapshotFromJournal(journalPath, id) {+ let snapshot = baseSnapshot(id);+ const diagnostics = [];+ let nextSeq = 1;+ if (!fs.existsSync(journalPath)) return { snapshot, diagnostics, nextSeq };++ const lines = fs.readFileSync(journalPath, 'utf-8').split('\n');+ for (let i = 0; i < lines.length; i++) {+ const line = lines[i];+ if (!line.trim()) continue;+ try {+ const entry = JSON.parse(line);+ if (!entry || typeof entry !== 'object') throw new Error('entry is not object');+ if (Number.isInteger(entry.seq)) nextSeq = Math.max(nextSeq, entry.seq + 1);+ snapshot = applyEvent(snapshot, entry);+ } catch (err) {+ diagnostics.push({+ error: 'journal_parse_failed',+ line: i + 1,+ message: err.message,+ });+ }+ }+ snapshot.diagnostics = [...snapshot.diagnostics, ...diagnostics];+ return { snapshot, diagnostics, nextSeq };+}++function applyEvent(snapshot, entry, inheritedDiagnostics = []) {+ const event = entry.event || entry;+ const next = {+ ...snapshot,+ paramValues: { ...(snapshot.paramValues || {}) },+ sourceMarkers: { ...(snapshot.sourceMarkers || {}) },+ annotationArtifacts: [...(snapshot.annotationArtifacts || [])],+ diagnostics: [...(snapshot.diagnostics || [])],+ updatedAt: entry.ts || new Date().toISOString(),+ };++ if (inheritedDiagnostics.length && next.diagnostics.length === 0) {+ next.diagnostics = [...inheritedDiagnostics];+ }++ switch (event.type) {+ case 'generate':+ next.phase = 'generate_requested';+ next.pageUrl = event.pageUrl ?? next.pageUrl;+ next.expectedVariants = event.count ?? next.expectedVariants;+ next.pendingEventSeq = entry.seq ?? next.pendingEventSeq;+ next.pendingEvent = toPendingEvent(event);+ if (event.screenshotPath) upsertArtifact(next.annotationArtifacts, { type: 'screenshot', path: event.screenshotPath });+ break;+ case 'variants_ready':+ case 'agent_done':+ next.phase = event.carbonize === true ? 'carbonize_required' : 'variants_ready';+ next.sourceFile = event.file ?? next.sourceFile;+ next.arrivedVariants = event.arrivedVariants ?? (next.arrivedVariants ?? next.expectedVariants);+ next.pendingEventSeq = null;+ next.pendingEvent = null;+ if (event.carbonize === true) {+ next.diagnostics.push({+ error: 'carbonize_cleanup_required',+ file: event.file || null,+ message: 'Accepted variant still has carbonize markers that must be folded into source CSS.',+ });+ }+ break;+ case 'checkpoint':+ 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;+ if (event.paramValues) next.paramValues = { ...event.paramValues };+ } else {+ next.diagnostics.push({ error: 'stale_checkpoint_ignored', revision: event.revision });+ }+ break;+ case 'accept':+ case 'accept_intent':+ next.phase = 'accept_requested';+ next.visibleVariant = Number(event.variantId ?? next.visibleVariant);+ if (event.paramValues) next.paramValues = { ...event.paramValues };+ next.pendingEventSeq = entry.seq ?? next.pendingEventSeq;+ next.pendingEvent = toPendingEvent(event);+ break;+ case 'discard':+ next.phase = 'discard_requested';+ next.pendingEventSeq = entry.seq ?? next.pendingEventSeq;+ next.pendingEvent = toPendingEvent(event);+ break;+ case 'discarded':+ next.phase = 'discarded';+ next.pendingEventSeq = null;+ next.pendingEvent = null;+ break;+ case 'complete':+ next.phase = 'completed';+ next.pendingEventSeq = null;+ next.pendingEvent = null;+ break;+ case 'agent_error':+ next.phase = 'agent_error';+ next.pendingEventSeq = null;+ next.pendingEvent = null;+ next.diagnostics.push({ error: 'agent_error', message: event.message || 'unknown agent error' });+ break;+ default:+ next.diagnostics.push({ error: 'unknown_event_type', type: event.type });+ break;+ }+ return next;+}++function toPendingEvent(event) {+ const pending = { ...event };+ delete pending.token;+ return pending;+}++function upsertArtifact(artifacts, artifact) {+ if (!artifacts.some((existing) => existing.path === artifact.path && existing.type === artifact.type)) {+ artifacts.push(artifact);+ }+}++function writeSnapshot(snapshotPath, snapshot) {+ fs.writeFileSync(snapshotPath, JSON.stringify(snapshot, null, 2) + '\n');+}diff --git a/.agents/skills/impeccable/scripts/live-status.mjs b/.agents/skills/impeccable/scripts/live-status.mjsnew file mode 100644index 000000000..dce1fbca2--- /dev/null+++ b/.agents/skills/impeccable/scripts/live-status.mjs@@ -0,0 +1,47 @@+#!/usr/bin/env node+/**+ * Print durable recovery status for Impeccable live sessions.+ */++import { createLiveSessionStore } from './live-session-store.mjs';+import { readLiveServerInfo } from './impeccable-paths.mjs';++function readServerInfo() {+ return readLiveServerInfo(process.cwd())?.info || null;+}++async function fetchServerStatus(info) {+ if (!info) return null;+ try {+ const res = await fetch(`http://localhost:${info.port}/status?token=${info.token}`);+ if (!res.ok) return null;+ return await res.json();+ } catch {+ return null;+ }+}++export async function statusCli() {+ const info = readServerInfo();+ const server = await fetchServerStatus(info);+ const store = createLiveSessionStore({ cwd: process.cwd() });+ const activeSessions = store.listActiveSessions();+ const payload = {+ liveServer: server ? {+ status: server.status,+ port: server.port,+ connectedClients: server.connectedClients,+ pendingEvents: server.pendingEvents,+ } : null,+ activeSessions: server?.activeSessions || activeSessions,+ recoveryHint: 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.',+ };+ console.log(JSON.stringify(payload, null, 2));+}++const _running = process.argv[1];+if (_running?.endsWith('live-status.mjs') || _running?.endsWith('live-status.mjs/')) {+ statusCli();+}diff --git a/.agents/skills/impeccable/scripts/live-wrap.mjs b/.agents/skills/impeccable/scripts/live-wrap.mjsindex a5769a50a..d46328b9f 100644--- a/.agents/skills/impeccable/scripts/live-wrap.mjs+++ b/.agents/skills/impeccable/scripts/live-wrap.mjs@@ -185,6 +185,7 @@ The agent should insert variant HTML at insertLine.`);const { startLine, endLine } = match;const commentSyntax = detectCommentSyntax(targetFile);+ const styleMode = detectStyleMode(targetFile);const isJsx = commentSyntax.open === '{/*';const indent = lines[startLine].match(/^(\s*)/)[1];@@ -269,6 +270,10 @@ The agent should insert variant HTML at insertLine.`);endLine: startLine + wrapperLines.length + (originalLines.length - 1), // 1-indexedinsertLine: insertLine + 1, // 1-indexed: where variants gocommentSyntax: commentSyntax,+ styleMode: styleMode.mode,+ styleTag: styleMode.styleTag,+ cssSelectorPrefixExamples: buildCssSelectorPrefixExamples(styleMode.mode, count),+ cssAuthoring: buildCssAuthoring(styleMode, count),originalLineCount: originalLines.length,}));}@@ -335,6 +340,62 @@ function detectCommentSyntax(filePath) {return { open: '<!--', close: '-->' };}+function detectStyleMode(filePath) {+ const ext = path.extname(filePath).toLowerCase();+ if (ext === '.astro') {+ return {+ mode: 'astro-global-prefixed',+ styleTag: '<style is:inline data-impeccable-css="SESSION_ID">',+ };+ }+ return {+ mode: 'scoped',+ styleTag: '<style data-impeccable-css="SESSION_ID">',+ };+}++function buildCssSelectorPrefixExamples(styleMode, count) {+ if (styleMode !== 'astro-global-prefixed') return [];+ return Array.from({ length: count }, (_, i) => `[data-impeccable-variant="${i + 1}"]`);+}++function buildCssAuthoring(styleMode, count) {+ const variantNumbers = Array.from({ length: count }, (_, i) => i + 1);+ if (styleMode.mode === 'astro-global-prefixed') {+ return {+ mode: styleMode.mode,+ styleTag: styleMode.styleTag,+ strategy: 'global-prefixed',+ rulePattern: '[data-impeccable-variant="N"] > .variant-class { ... }',+ selectorExamples: variantNumbers.map((n) => `[data-impeccable-variant="${n}"] > .variant-class`),+ requirements: [+ 'Use the styleTag exactly; the is:inline attribute is required for this file.',+ 'Prefix every preview selector with the matching [data-impeccable-variant="N"] selector.',+ 'Keep selectors anchored to the generated variant wrapper; do not rely on component CSS scoping for preview rules.',+ ],+ forbidden: [+ 'Do not use @scope for this styleMode.',+ ],+ };+ }+ return {+ mode: styleMode.mode,+ styleTag: styleMode.styleTag,+ strategy: 'scope-rule',+ rulePattern: '@scope ([data-impeccable-variant="N"]) { :scope > .variant-class { ... } }',+ selectorExamples: variantNumbers.map((n) => `@scope ([data-impeccable-variant="${n}"]) { :scope > .variant-class { ... } }`),+ requirements: [+ 'Use @scope blocks keyed to each [data-impeccable-variant="N"] wrapper.',+ 'Inside each @scope block, make :scope rules step into the replacement element with a descendant combinator.',+ 'Use the styleTag exactly; do not add framework-specific style attributes unless this object says to.',+ ],+ forbidden: [+ 'Do not use global [data-impeccable-variant="N"] selector prefixes for this styleMode.',+ 'Do not add is:inline to the style tag for this styleMode.',+ ],+ };+}+/*** Search project files for the query string (class name, ID, etc.)* Returns the first matching file path, or null.diff --git a/.agents/skills/impeccable/scripts/live.mjs b/.agents/skills/impeccable/scripts/live.mjsindex befbdb8ed..cafb0eca9 100644--- a/.agents/skills/impeccable/scripts/live.mjs+++ b/.agents/skills/impeccable/scripts/live.mjs@@ -2,10 +2,10 @@* CLI entry point: prepare everything needed to enter the live variant poll loop.** Does (all in one command):- * 1. Check config.json (returns config_missing if first-ever run)+ * 1. Check .impeccable/live/config.json (returns config_missing if first-ever run)* 2. Start the live server in the background (or reuse a running one)* 3. Inject the browser script tag into the project's entry file- * 4. Read .impeccable.md for design context (if present)+ * 4. Read PRODUCT.md / DESIGN.md for project context* 5. Print a single JSON blob with everything the agent needs** After this, the agent's only remaining steps are:@@ -23,9 +23,9 @@ import path from 'node:path';import { fileURLToPath } from 'node:url';import { loadContext } from './load-context.mjs';import { resolveFiles } from './live-inject.mjs';+import { readLiveServerInfo } from './impeccable-paths.mjs';const __dirname = path.dirname(fileURLToPath(import.meta.url));-const PID_FILE = path.join(process.cwd(), '.impeccable-live.json');async function liveCli() {const args = process.argv.slice(2);@@ -34,10 +34,10 @@ async function liveCli() {console.log(`Usage: node live.mjsPrepare everything for live variant mode in a single command:- - Checks scripts/config.json (required, created once per project)+ - Checks .impeccable/live/config.json (required, created once per project)- Starts (or reuses) the live server in the background- Injects the browser script tag- - Reads .impeccable.md for design context+ - Reads PRODUCT.md / DESIGN.md for project contextOn success, prints a JSON blob with:{ ok, serverPort, serverToken, pageFile, hasContext, context }@@ -223,7 +223,7 @@ function safeParse(out) {function ensureServerRunning() {// Try to reuse an existing servertry {- const existing = JSON.parse(fs.readFileSync(PID_FILE, 'utf-8'));+ const existing = readLiveServerInfo(process.cwd())?.info;if (existing && existing.pid) {try {process.kill(existing.pid, 0); // throws if deaddiff --git a/.agents/skills/impeccable/scripts/load-context.mjs b/.agents/skills/impeccable/scripts/load-context.mjsindex dca23c1f8..dc340bf16 100644--- a/.agents/skills/impeccable/scripts/load-context.mjs+++ b/.agents/skills/impeccable/scripts/load-context.mjs@@ -39,7 +39,7 @@ const LEGACY_NAMES = ['.impeccable.md'];const FALLBACK_DIRS = ['.agents/context', 'docs'];/**- * Resolve the directory that holds PRODUCT.md / DESIGN.md / DESIGN.json for+ * Resolve the directory that holds PRODUCT.md / DESIGN.md for* this project. Exported so other scripts (e.g. live-server.mjs) can read the* design files from the same location the loader uses.*/diff --git a/.claude/skills/impeccable/reference/document.md b/.claude/skills/impeccable/reference/document.mdindex 44f123bed..a091ec98e 100644--- a/.claude/skills/impeccable/reference/document.md+++ b/.claude/skills/impeccable/reference/document.md@@ -237,11 +237,11 @@ Concrete, forceful guardrails. Lead each with "Do" or "Don't". Be specific: incl- **Don't** [...]```-### Step 4b: Write DESIGN.json sidecar (extensions only)+### Step 4b: Write .impeccable/design.json sidecar (extensions only)-The frontmatter owns token primitives (colors, typography, rounded, spacing, components). The sidecar at `DESIGN.json` carries **what Stitch's schema can't hold**: tonal ramps per color, shadow/elevation tokens, motion tokens, breakpoints, full component HTML/CSS snippets (the panel renders these into a shadow DOM), and narrative (north star, rules, do's/don'ts). It extends the frontmatter, it doesn't duplicate it.+The frontmatter owns token primitives (colors, typography, rounded, spacing, components). The sidecar at `.impeccable/design.json` carries **what Stitch's schema can't hold**: tonal ramps per color, shadow/elevation tokens, motion tokens, breakpoints, full component HTML/CSS snippets (the panel renders these into a shadow DOM), and narrative (north star, rules, do's/don'ts). It extends the frontmatter, it doesn't duplicate it.-Regenerate the sidecar whenever you regenerate DESIGN.md. If the user only asks to refresh the sidecar (e.g., from the live panel's stale-hint), preserve DESIGN.md and write only DESIGN.json.+Regenerate the sidecar whenever you regenerate root `DESIGN.md`. If the user only asks to refresh the sidecar (e.g., from the live panel's stale-hint), preserve `DESIGN.md` and write only `.impeccable/design.json`.#### Schema@@ -310,7 +310,7 @@ Aim for a tight set of **5-10 components** that best represent the visual system- **Signature components (include if distinctive):** hero CTA, featured card, filter pill, any custom pattern the user mentioned as important in PRODUCT.md.- **Skip the rest.** Utility components, form building blocks, wrapper layouts: not worth documenting unless visually distinctive.-If the project has **no component library yet** (bare landing page, new project), synthesize canonical primitives from the tokens using best-practice defaults consistent with the DESIGN.md's rules. Every DESIGN.json has *something* to render, even on day zero.+If the project has **no component library yet** (bare landing page, new project), synthesize canonical primitives from the tokens using best-practice defaults consistent with the DESIGN.md's rules. Every `.impeccable/design.json` has *something* to render, even on day zero.#### Tonal ramps@@ -331,7 +331,7 @@ Do not reword. The panel shows these as secondary collapsible context; the same### Step 5: Confirm, refine, and refresh session cache1. Show the user the full DESIGN.md you wrote. Briefly highlight the non-obvious creative choices (descriptive color names, atmosphere language, named rules).-2. Mention that `DESIGN.json` was also written alongside; the live panel will now render this project's actual button/input/nav primitives instead of generic approximations.+2. Mention that `.impeccable/design.json` was also written alongside; the live panel will now render this project's actual button/input/nav primitives instead of generic approximations.3. Offer to refine any section: "Want me to revise a section, add component patterns I missed, or adjust the atmosphere language?"4. **Refresh the session cache.** Run `node .claude/skills/impeccable/scripts/load-context.mjs` one final time so the newly-written DESIGN.md lands in conversation. Subsequent commands in this session will use the fresh version automatically without re-reading.@@ -392,7 +392,7 @@ Per-section guidance in seed mode:- **Components**: omit entirely; no components exist yet.- **Do's and Don'ts**: carry PRODUCT.md's anti-references directly plus the anti-reference named in Q5.-Seed mode writes a minimal frontmatter with `name` and `description` only; no colors, typography, rounded, spacing, or components yet. Real tokens land on the next Scan-mode run. Skip the `DESIGN.json` sidecar in seed mode for the same reason: nothing to render.+Seed mode writes a minimal frontmatter with `name` and `description` only; no colors, typography, rounded, spacing, or components yet. Real tokens land on the next Scan-mode run. Skip the `.impeccable/design.json` sidecar in seed mode for the same reason: nothing to render.### Step 4: Confirm and refresh session cachediff --git a/.claude/skills/impeccable/reference/live.md b/.claude/skills/impeccable/reference/live.mdindex d65c00bd4..8943721ca 100644--- a/.claude/skills/impeccable/reference/live.md+++ b/.claude/skills/impeccable/reference/live.md@@ -12,8 +12,9 @@ Execute in order. No step skipped, no step reordered.2. Navigate to the URL that serves `pageFile` (infer from `package.json`, docs, terminal output, or an open tab). If you can't infer it confidently, tell the user once to open their dev/preview URL. Never use `serverPort` as that URL; it's the helper, not the app.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=`.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.-5. On `accept` / `discard`: the poll script already cleaned up; just poll again.-6. On `exit`: run the cleanup at the bottom.+5. 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. If interrupted, run `live-status.mjs` or `live-resume.mjs` before guessing. The durable journal replays unacknowledged work after helper restart.+7. 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.@@ -43,13 +44,31 @@ LOOP:Read JSON; dispatch on "type""generate" → Handle Generate; reply done; LOOP- "accept" → Handle Accept; LOOP+ "accept" → Handle Accept; complete carbonize cleanup if required; LOOP"discard" → Handle Discard; LOOP"prefetch" → Handle Prefetch; LOOP"timeout" → LOOP"exit" → break → Cleanup```+## Recovery commands++The live helper persists an append-only journal under `.impeccable/live/sessions/`. Browser checkpoints are advisory but durable; the journal is canonical. This is local durable recovery state, not project source.++Use these commands when the chat was interrupted, polling was missed, the helper restarted, or the browser reloaded:++```bash+node .claude/skills/impeccable/scripts/live-status.mjs+node .claude/skills/impeccable/scripts/live-resume.mjs --id SESSION_ID+node .claude/skills/impeccable/scripts/live-complete.mjs --id SESSION_ID+```++- `live-status.mjs` prints connected helper state, active durable sessions, and queued pending events. It works even when the helper is down by reading the journal directly.+- `live-resume.mjs` prints the active snapshot, pending event, checkpoint phase, visible variant, parameter values, and the next safe agent action.+- `live-complete.mjs` is the canonical manual final acknowledgement. Use it after carbonize/manual cleanup is verified and no further poll acknowledgement will happen automatically.++Server restart rule: start `live-server.mjs` again, then poll. Startup requeues unacknowledged pending events from the journal, so do not ask the user to click Go again unless `live-resume.mjs` says no active session exists.+## Handle `generate`Event: `{id, action, freeformPrompt?, count, pageUrl, element, screenshotPath?, comments?, strokes?}`.@@ -88,7 +107,14 @@ The helper searches ID first, then classes, then tag + class combo. If `event.paIf `--text` matches multiple candidates equally well, wrap exits with `{ error: "element_ambiguous", candidates: [...] }` and `fallback: "agent-driven"`: read the candidate line ranges, decide which one matches the picked element from page context, and write the wrapper manually per the fallback flow.-Output on success: `{ file, insertLine, commentSyntax }`.+Output on success: `{ file, insertLine, commentSyntax, styleMode, styleTag, cssSelectorPrefixExamples, cssAuthoring }`.++`styleMode` controls how preview CSS must be authored. Treat it as a detected capability mode, not a framework guess:++- `scoped`: use `@scope ([data-impeccable-variant="N"])` rules.+- `astro-global-prefixed`: use explicit `[data-impeccable-variant="N"]` selector prefixes and the exact `styleTag` returned by the tool.++Use `cssAuthoring` as the source of truth for the current file. It includes the exact `styleTag`, selector strategy, selector examples, requirements, and forbidden patterns. Do not apply a framework-specific exception unless the returned `styleMode` / `cssAuthoring.mode` says to.**Fallback errors.** Wrap only writes into files it judges to be source (tracked by git, not marked GENERATED, not listed in config's `generatedFiles`). If it can't land on a source file, it errors without writing; accepting a variant into a generated file is silent data loss. Three shapes:@@ -208,13 +234,14 @@ When the prompt and PRODUCT.md anti-references conflict (the prompt asks for X,Complete 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 scoped 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).+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).++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:```html<!-- Variants: insert below this line --><style data-impeccable-css="SESSION_ID">- @scope ([data-impeccable-variant="1"]) { ... }- @scope ([data-impeccable-variant="2"]) { ... }+ /* rules matching cssAuthoring.rulePattern */</style><div data-impeccable-variant="1"><!-- variant 1: full element replacement (single top-level element) -->@@ -229,11 +256,11 @@ Write CSS + all variants in ONE edit at the `insertLine` reported by `wrap`. Col**Each variant div contains exactly one top-level element: the full replacement for the original.** Use the same tag as the original (e.g. `<section>` if the user picked a `<section>`). Loose siblings (heading + paragraph + div as direct children of the variant div) break the outline tracking and the accept flow, which both assume one child.-The first variant has no `display: none` (visible by default). All others do. If variants use only inline styles and no scoped CSS, omit the `<style>` tag entirely. Use `@scope` for CSS isolation (Chrome 118+ / Firefox 128+ / Safari 17.4+).+The 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.-**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 rule starts `:scope > ...`.+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 > ...`.**JSX / TSX target files.** Wrap `<style>` content in a template literal so the CSS `{` / `}` aren't parsed as JSX expressions, and use `className=` / `style={{…}}` on every variant element. Keep `data-impeccable-*` attributes as-is; they're plain strings:@@ -369,10 +396,11 @@ Remove the wrapper you inserted in Step 2. Nothing else to do.## Handle `accept`-Event: `{id, variantId, _acceptResult}`. The poll script already ran `live-accept.mjs` to handle the file operation deterministically; the browser DOM is already updated.+Event: `{id, variantId, _acceptResult, _completionAck}`. The poll script already ran `live-accept.mjs` to handle the file operation deterministically, then acknowledged event delivery to the helper. The browser DOM is already updated.+- `_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 and a stderr banner both list the steps explicitly; neither is decorative.+- `_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: 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` without `mode`: manual cleanup: read file, find markers, edit.@@ -388,13 +416,13 @@ Do these five steps in the current thread, synchronously, before the next poll.4. **Unwrap the accepted content.** Delete the `<div data-impeccable-variant="N" style="display: contents">` that wraps it. Drop `data-impeccable-params` and any `data-p-*` attributes from it; 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.-Then poll again.+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.## Handle `discard`-Event: `{id, _acceptResult}`. The poll script already restored the original and removed all variant markers. Nothing to do. Poll again.+Event: `{id, _acceptResult, _completionAck}`. The poll script already restored the original, removed all variant markers, and acknowledged `discarded` durable completion. Nothing to do unless `_completionAck.ok !== true`; in that case run `live-complete.mjs --id EVENT_ID --discarded`, then poll again.## Handle `prefetch`@@ -424,7 +452,7 @@ When the poll returns `exit`, proceed to cleanup. If the poll is still running anode .claude/skills/impeccable/scripts/live-server.mjs stop```-Stops the HTTP server and runs `live-inject.mjs --remove` to strip `localhost:…/live.js` from the HTML entry. To stop the server but keep the inject tag (for a quick restart), use `stop --keep-inject`. `config.json` persists for future sessions.+Stops the HTTP server and runs `live-inject.mjs --remove` to strip `localhost:…/live.js` from the HTML entry. To stop the server but keep the inject tag (for a quick restart), use `stop --keep-inject`. `.impeccable/live/config.json` persists as project config for future sessions.Then:- Remove any leftover variant wrappers (search for `impeccable-variants-start` markers).@@ -432,7 +460,7 @@ Then:## First-time setup (config missing or invalid)-If `live.mjs` outputs `{ ok: false, error: "config_missing" | "config_invalid", path }`, write `config.json` at the reported path.+If `live.mjs` outputs `{ ok: false, error: "config_missing" | "config_invalid", path }`, write the live config at the reported path. By default this is `.impeccable/live/config.json`.Schema:@@ -512,7 +540,7 @@ node .claude/skills/impeccable/scripts/detect-csp.mjsOutput: `{ shape, signals }` where `shape` is one of `append-arrays`, `append-string`, `middleware`, `meta-tag`, or `null`. The shape is named by *patch mechanism*, so one template covers many frameworks.-- **`null`**: no CSP; skip to writing `config.json` with `cspChecked: true`.+- **`null`**: no CSP; skip to writing `.impeccable/live/config.json` with `cspChecked: true`.- **`append-arrays`**: CSP defined as structured directive arrays. Auto-patchable. See *append-arrays* below. Covers:- Monorepo helpers with `additionalScriptSrc` / `additionalConnectSrc` options (Next.js + shared config package)- SvelteKit `kit.csp.directives`@@ -589,6 +617,6 @@ Reference outputs:### Troubleshooting-If a user says "no" to the CSP patch at setup time and later complains that live doesn't work: their dev CSP blocks `http://localhost:8400`. Fix: delete `cspChecked` from `config.json` and re-run `live.mjs`: setup will ask again.+If a user says "no" to the CSP patch at setup time and later complains that live doesn't work: their dev CSP blocks `http://localhost:8400`. Fix: delete `cspChecked` from `.impeccable/live/config.json` and re-run `live.mjs`: setup will ask again.Then re-run `live.mjs`.diff --git a/.claude/skills/impeccable/reference/teach.md b/.claude/skills/impeccable/reference/teach.mdindex 2aeeb9d73..34a189055 100644--- a/.claude/skills/impeccable/reference/teach.md+++ b/.claude/skills/impeccable/reference/teach.md@@ -2,8 +2,8 @@Gathers design context for a project and writes two complementary files at the project root:-- **PRODUCT.md** (strategic): register, target users, product purpose, brand personality, anti-references, strategic design principles. Answers "who/what/why".-- **DESIGN.md** (visual): visual theme, color palette, typography, components, layout. Follows the [Google Stitch DESIGN.md format](https://stitch.withgoogle.com/docs/design-md/format/). Answers "how it looks".+- **PRODUCT.md** (strategic): root project file for register, target users, product purpose, brand personality, anti-references, strategic design principles. Answers "who/what/why".+- **DESIGN.md** (visual): root project file for visual theme, color palette, typography, components, layout. Follows the [Google Stitch DESIGN.md format](https://stitch.withgoogle.com/docs/design-md/format/). Answers "how it looks".Every other impeccable command reads these files before doing any work.diff --git a/.claude/skills/impeccable/scripts/impeccable-paths.mjs b/.claude/skills/impeccable/scripts/impeccable-paths.mjsnew file mode 100644index 000000000..ba852bae9--- /dev/null+++ b/.claude/skills/impeccable/scripts/impeccable-paths.mjs@@ -0,0 +1,105 @@+import fs from 'node:fs';+import path from 'node:path';++export const IMPECCABLE_DIR = '.impeccable';+export const LIVE_DIR = 'live';++export function getImpeccableDir(cwd = process.cwd()) {+ return path.join(cwd, IMPECCABLE_DIR);+}++export function getDesignSidecarPath(cwd = process.cwd()) {+ return path.join(getImpeccableDir(cwd), 'design.json');+}++export function getDesignSidecarCandidates(cwd = process.cwd(), contextDir = cwd) {+ const candidates = [+ getDesignSidecarPath(cwd),+ path.join(cwd, 'DESIGN.json'),+ ];+ const contextLegacy = path.join(contextDir, 'DESIGN.json');+ if (!candidates.includes(contextLegacy)) candidates.push(contextLegacy);+ return candidates;+}++export function resolveDesignSidecarPath(cwd = process.cwd(), contextDir = cwd) {+ return firstExisting(getDesignSidecarCandidates(cwd, contextDir));+}++export function getLiveDir(cwd = process.cwd()) {+ return path.join(getImpeccableDir(cwd), LIVE_DIR);+}++export function getLiveConfigPath(cwd = process.cwd()) {+ return path.join(getLiveDir(cwd), 'config.json');+}++export function getLegacyLiveConfigPath(scriptsDir) {+ return path.join(scriptsDir, 'config.json');+}++export function resolveLiveConfigPath({ cwd = process.cwd(), scriptsDir, env = process.env } = {}) {+ if (env.IMPECCABLE_LIVE_CONFIG && env.IMPECCABLE_LIVE_CONFIG.trim()) {+ const configured = env.IMPECCABLE_LIVE_CONFIG.trim();+ return path.isAbsolute(configured) ? configured : path.resolve(cwd, configured);+ }+ const primary = getLiveConfigPath(cwd);+ if (fs.existsSync(primary)) return primary;+ if (scriptsDir) {+ const legacy = getLegacyLiveConfigPath(scriptsDir);+ if (fs.existsSync(legacy)) return legacy;+ }+ return primary;+}++export function getLiveServerPath(cwd = process.cwd()) {+ return path.join(getLiveDir(cwd), 'server.json');+}++export function getLegacyLiveServerPath(cwd = process.cwd()) {+ return path.join(cwd, '.impeccable-live.json');+}++export function readLiveServerInfo(cwd = process.cwd()) {+ for (const filePath of [getLiveServerPath(cwd), getLegacyLiveServerPath(cwd)]) {+ try {+ return { info: JSON.parse(fs.readFileSync(filePath, 'utf-8')), path: filePath };+ } catch {+ /* try next */+ }+ }+ return null;+}++export function writeLiveServerInfo(cwd = process.cwd(), info) {+ const filePath = getLiveServerPath(cwd);+ fs.mkdirSync(path.dirname(filePath), { recursive: true });+ fs.writeFileSync(filePath, JSON.stringify(info));+ return filePath;+}++export function removeLiveServerInfo(cwd = process.cwd()) {+ for (const filePath of [getLiveServerPath(cwd), getLegacyLiveServerPath(cwd)]) {+ try { fs.unlinkSync(filePath); } catch {}+ }+}++export function getLiveSessionsDir(cwd = process.cwd()) {+ return path.join(getLiveDir(cwd), 'sessions');+}++export function getLegacyLiveSessionsDir(cwd = process.cwd()) {+ return path.join(cwd, '.impeccable-live', 'sessions');+}++export function getLiveAnnotationsDir(cwd = process.cwd()) {+ return path.join(getLiveDir(cwd), 'annotations');+}++export function getLegacyLiveAnnotationsDir(cwd = process.cwd()) {+ return path.join(cwd, '.impeccable-live', 'annotations');+}++function firstExisting(paths) {+ return paths.find((filePath) => fs.existsSync(filePath)) || null;+}diff --git a/.claude/skills/impeccable/scripts/live-browser-session.js b/.claude/skills/impeccable/scripts/live-browser-session.jsnew file mode 100644index 000000000..0e362d6be--- /dev/null+++ b/.claude/skills/impeccable/scripts/live-browser-session.js@@ -0,0 +1,123 @@+/**+ * Browser-side durable session helpers for Impeccable live mode.+ *+ * Kept separate from live-browser.js so recovery state can be tested without+ * booting the full overlay UI. Served before live-browser.js and attached to+ * window.__IMPECCABLE_LIVE_SESSION__.+ */+(function (root) {+ 'use strict';++ function createLiveBrowserSessionState({ prefix, storage, idFactory }) {+ if (!prefix) throw new Error('prefix required');+ const store = storage || root.localStorage;+ const makeId = idFactory || function () { return Math.random().toString(16).slice(2, 10); };+ const sessionKey = prefix + '-session';+ const handledKey = sessionKey + '-handled';+ const scrollKey = sessionKey + '-scroll';+ let checkpointRevision = 0;+ const owner = makeId();++ function safeRead(key) {+ try { return store.getItem(key); } catch { return null; }+ }++ function safeWrite(key, value) {+ try { store.setItem(key, value); } catch { /* quota exceeded or private mode */ }+ }++ function safeRemove(key) {+ try { store.removeItem(key); } catch { /* unavailable storage */ }+ }++ function loadSession() {+ try {+ const raw = safeRead(sessionKey);+ if (!raw) return null;+ const parsed = JSON.parse(raw);+ if (Number.isInteger(parsed.checkpointRevision)) {+ checkpointRevision = Math.max(checkpointRevision, parsed.checkpointRevision);+ }+ return parsed;+ } catch { return null; }+ }++ function saveSession(session) {+ if (!session || !session.id) return;+ const payload = {+ ...session,+ checkpointRevision,+ };+ safeWrite(sessionKey, JSON.stringify(payload));+ }++ function clearSession() {+ safeRemove(sessionKey);+ }++ function nextCheckpointRevision() {+ checkpointRevision += 1;+ const existing = loadSession();+ if (existing?.id) saveSession(existing);+ return checkpointRevision;+ }++ function seedCheckpointRevision(value) {+ if (Number.isInteger(value)) checkpointRevision = Math.max(checkpointRevision, value);+ return checkpointRevision;+ }++ function currentCheckpointRevision() {+ return checkpointRevision;+ }++ function markHandled(id) {+ if (!id) return;+ safeWrite(handledKey, id);+ }++ function isHandled(id) {+ return !!id && safeRead(handledKey) === id;+ }++ function clearHandled() {+ safeRemove(handledKey);+ }++ function writeScrollY(y) {+ safeWrite(scrollKey, String(y));+ }++ function readScrollY() {+ const raw = safeRead(scrollKey);+ if (raw == null) return null;+ const n = parseFloat(raw);+ return isFinite(n) ? n : null;+ }++ function clearScrollY() {+ safeRemove(scrollKey);+ }++ return {+ owner,+ sessionKey,+ handledKey,+ scrollKey,+ saveSession,+ loadSession,+ clearSession,+ nextCheckpointRevision,+ seedCheckpointRevision,+ currentCheckpointRevision,+ markHandled,+ isHandled,+ clearHandled,+ writeScrollY,+ readScrollY,+ clearScrollY,+ };+ }++ root.__IMPECCABLE_LIVE_SESSION__ = { createLiveBrowserSessionState };+})(typeof window !== 'undefined' ? window : globalThis);diff --git a/.claude/skills/impeccable/scripts/live-browser.js b/.claude/skills/impeccable/scripts/live-browser.jsindex 3da76bb96..e67cd01ed 100644--- a/.claude/skills/impeccable/scripts/live-browser.js+++ b/.claude/skills/impeccable/scripts/live-browser.js@@ -50,6 +50,16 @@const Z = { highlight: 100001, bar: 100005, picker: 100007, toast: 100010 };const EASE = 'cubic-bezier(0.22, 1, 0.36, 1)'; // ease-out-quintconst PREFIX = 'impeccable-live';+ const sessionState = window.__IMPECCABLE_LIVE_SESSION__?.createLiveBrowserSessionState({+ prefix: PREFIX,+ storage: localStorage,+ idFactory: () => crypto.randomUUID().replace(/-/g, '').slice(0, 8),+ });+ if (!sessionState) {+ console.error('[impeccable] live-browser-session.js was not loaded. Live mode cannot start safely.');+ window.__IMPECCABLE_LIVE_INIT__ = false;+ return;+ }const HIGHLIGHT_TRANSITION ='top 140ms ' + EASE +', left 140ms ' + EASE +@@ -112,6 +122,8 @@let hasProjectContext = false;let selectedAction = 'impeccable';let selectedCount = 3;+ const browserOwner = sessionState.owner;+ let checkpointTimer = null;// Scroll lock — holds window.scrollY at a fixed value while the session is// active, so HMR DOM patches and variant swaps can't drift the page. See@@ -126,21 +138,9 @@// (Previously: saveSession wrote scrollY alongside state, so every call// during resume overwrote the pre-reload value with whatever the browser// had landed on, typically 0.)- const SCROLL_KEY_SUFFIX = '-scroll';- function writeScrollY(y) {- try { localStorage.setItem(LS_KEY + SCROLL_KEY_SUFFIX, String(y)); } catch {}- }- function readScrollY() {- try {- const raw = localStorage.getItem(LS_KEY + SCROLL_KEY_SUFFIX);- if (raw == null) return null;- const n = parseFloat(raw);- return isFinite(n) ? n : null;- } catch { return null; }- }- function clearScrollY() {- try { localStorage.removeItem(LS_KEY + SCROLL_KEY_SUFFIX); } catch {}- }+ function writeScrollY(y) { sessionState.writeScrollY(y); }+ function readScrollY() { return sessionState.readScrollY(); }+ function clearScrollY() { sessionState.clearScrollY(); }// Pre-empt the browser: apply manual scroll restoration and jump to the// saved scrollY at script-parse time. Retries on fonts.ready and load@@ -1585,6 +1585,7 @@paramsCurrentValues[p.id] = v;readout.textContent = formatRangeValue(input);applyParamValue(variantEl, p, v);+ queueCheckpoint('param_changed');});row.appendChild(input);} else if (p.kind === 'toggle') {@@ -1615,6 +1616,7 @@knob.style.left = next ? '18px' : '2px';readout.textContent = next ? 'On' : 'Off';applyParamValue(variantEl, p, next);+ queueCheckpoint('param_changed');});row.appendChild(track);} else if (p.kind === 'steps') {@@ -1651,6 +1653,7 @@btn.style.color = on ? 'oklch(98% 0 0)' : P.text;});applyParamValue(variantEl, p, o.value);+ queueCheckpoint('param_changed');});segRow.appendChild(b);segBtns.push({ btn: b, val: o.value });@@ -1872,19 +1875,26 @@return;}+ const previousVisibleVariant = currentSessionId === sessionId ? visibleVariant : 0;+// Replace the live element with the full wrapper from sourceconst wrapper = srcWrapper.cloneNode(true);liveEl.parentElement.replaceChild(wrapper, liveEl);- // Update state: count variants, show the first one+ // Update state: count variants, preserving the user's current variant+ // when a late HMR/source reinjection lands after they have cycled.const variants = wrapper.querySelectorAll('[data-impeccable-variant]:not([data-impeccable-variant="original"])');arrivedVariants = variants.length;expectedVariants = parseInt(wrapper.dataset.impeccableVariantCount || arrivedVariants);- visibleVariant = 1;- showVariantInDOM(sessionId, 1);+ const saved = loadSession();+ const savedVisibleVariant = saved && saved.id === sessionId ? saved.visible : 0;+ visibleVariant = previousVisibleVariant > 0 && previousVisibleVariant <= arrivedVariants+ ? previousVisibleVariant+ : (savedVisibleVariant > 0 && savedVisibleVariant <= arrivedVariants ? savedVisibleVariant : 1);+ showVariantInDOM(sessionId, visibleVariant);// Update selectedElement to the visible variant's content- selectedElement = pickVariantContent(wrapper, 1) || wrapper.parentElement;+ selectedElement = pickVariantContent(wrapper, visibleVariant) || wrapper.parentElement;state = 'CYCLING';hideShaderOverlay();@@ -1907,6 +1917,7 @@updateSelectedElement();updateBarContent('cycling');saveSession();+ queueCheckpoint('variant_changed');}function updateSelectedElement() {@@ -1917,6 +1928,18 @@if (visEl) selectedElement = visEl;}+ function readVisibleVariantFromDOM(sessionId) {+ const wrapper = document.querySelector('[data-impeccable-variants="' + sessionId + '"]');+ if (!wrapper) return 0;+ const variants = wrapper.querySelectorAll('[data-impeccable-variant]:not([data-impeccable-variant="original"])');+ for (const variant of variants) {+ if (variant.style.display === 'none') continue;+ const idx = parseInt(variant.dataset.impeccableVariant || '0', 10);+ if (idx > 0) return idx;+ }+ return 0;+ }+// Resolve the element that represents the variant's visible content.// Contract: each variant div should contain exactly one top-level element// (the full replacement). In practice a model may ship loose siblings or@@ -2107,8 +2130,10 @@updating = true;arrivedVariants = count;if (visibleVariant === 0 && arrivedVariants > 0) {- visibleVariant = 1;- showVariantInDOM(sessionId, 1);+ const saved = loadSession();+ const savedVisibleVariant = saved && saved.id === sessionId ? saved.visible : 0;+ visibleVariant = savedVisibleVariant > 0 && savedVisibleVariant <= arrivedVariants ? savedVisibleVariant : 1;+ showVariantInDOM(sessionId, visibleVariant);// showVariantInDOM hid the original (display:none); if we were still// anchored to the original's content, its boundingRect is now zero// and the bar snaps to (0,0). Re-point at the visible variant instead.@@ -2128,6 +2153,7 @@updateBarContent('generating');}saveSession();+ queueCheckpoint(state === 'CYCLING' ? 'variants_ready' : 'variants_progress');updating = false;});@@ -2236,6 +2262,7 @@/** Server died or became unreachable. Reset UI to a clean state. */function handleServerLost() {+ const recoveryState = currentSessionId ? state : 'IDLE';if (state === 'GENERATING' || state === 'CYCLING' || state === 'SAVING') {showToast('Live server disconnected. Session ended.', 5000);}@@ -2246,21 +2273,61 @@stopScrollTracking();if (variantObserver) { variantObserver.disconnect(); variantObserver = null; }stopScrollLock();- clearScrollY();- clearSession();+ // Preserve local session state on server loss. The durable journal is the+ // source of truth, but localStorage plus the variant wrapper lets the UI+ // resume after a helper restart or page reload instead of treating a+ // transient disconnect as an explicit discard.selectedElement = null;- currentSessionId = null;selectedAction = 'impeccable';- state = 'IDLE';+ state = recoveryState;+ if (currentSessionId) saveSession();}- function sendEvent(msg) {+ function sendEvent(msg, opts) {msg.token = TOKEN;- fetch('http://localhost:' + PORT + '/events', {+ function handleFailure(err) {+ console.error('[impeccable] Failed to send event:', err);+ if (opts && opts.throwOnError) throw err;+ return null;+ }+ return fetch('http://localhost:' + PORT + '/events', {method: 'POST',headers: { 'Content-Type': 'application/json' },body: JSON.stringify(msg),- }).catch(err => console.error('[impeccable] Failed to send event:', err));+ }).then(res => {+ if (res.ok) return res;+ return handleFailure(new Error('HTTP ' + res.status + ' ' + res.statusText));+ }).catch(handleFailure);+ }++ function checkpointPayload(reason) {+ return {+ type: 'checkpoint',+ id: currentSessionId,+ revision: sessionState.nextCheckpointRevision(),+ owner: browserOwner,+ phase: String(state || '').toLowerCase(),+ reason,+ pageUrl: location.pathname,+ expectedVariants,+ arrivedVariants,+ visibleVariant,+ paramValues: { ...paramsCurrentValues },+ };+ }++ function sendCheckpoint(reason) {+ if (!currentSessionId) return Promise.resolve(null);+ return sendEvent(checkpointPayload(reason)).catch(() => null);+ }++ function queueCheckpoint(reason) {+ if (!currentSessionId) return;+ if (checkpointTimer) clearTimeout(checkpointTimer);+ checkpointTimer = setTimeout(() => {+ checkpointTimer = null;+ sendCheckpoint(reason);+ }, 120);}// ---------------------------------------------------------------------------@@ -2496,6 +2563,7 @@state = 'GENERATING';showBar('generating');saveSession();+ sendCheckpoint('generate_started');writeScrollY(window.scrollY);if (variantObserver) variantObserver.disconnect();variantObserver = startVariantObserver(currentSessionId);@@ -2920,13 +2988,12 @@ void main() {function handleAccept() {if (!currentSessionId || arrivedVariants === 0) return;+ const domVisibleVariant = readVisibleVariantFromDOM(currentSessionId);+ if (domVisibleVariant > 0) visibleVariant = domVisibleVariant;const acceptPayload = { type: 'accept', id: currentSessionId, variantId: String(visibleVariant) };if (Object.keys(paramsCurrentValues).length > 0) {acceptPayload.paramValues = { ...paramsCurrentValues };}- sendEvent(acceptPayload);- markSessionHandled();-// The accepted variant is already the only visible child of the wrapper// (all other variants are display:none). HMR from the source rewrite will// replace the wrapper imminently. Don't eagerly replaceChild here — React@@ -2936,9 +3003,28 @@ void main() {const acceptedSessionId = currentSessionId;const acceptedVariant = visibleVariant;- state = 'CONFIRMED';- updateBarContent('confirmed');- setTimeout(function() {+ state = 'SAVING';+ updateBarContent('saving');++ sendEvent(acceptPayload, { throwOnError: true })+ .then(() => {+ markSessionHandled();+ confirmAcceptAfterReceipt();+ })+ .catch(() => {+ state = 'CYCLING';+ updateBarContent('cycling');+ showToast('Could not confirm accept with the live server. Session kept for recovery; try Accept again.', 5000);+ });++ function confirmAcceptAfterReceipt() {+ state = 'CONFIRMED';+ updateBarContent('confirmed');+ scheduleAcceptCleanup();+ }++ function scheduleAcceptCleanup() {+ setTimeout(function() {hideBar();hideHighlight();stopScrollTracking();@@ -2967,50 +3053,46 @@ void main() {accepted.style.display = 'contents';parent.replaceChild(accepted, wrapper);}- }, 2000);+ }, 2000);+ }}function handleDiscard() {if (!currentSessionId) return;- sendEvent({ type: 'discard', id: currentSessionId });- markSessionHandled();- // Instant DOM restore + fire-and-forget (script handles file cleanup)- cleanup();+ sendEvent({ type: 'discard', id: currentSessionId }, { throwOnError: true })+ .then(() => {+ markSessionHandled();+ cleanup();+ })+ .catch(() => showToast('Could not confirm discard with the live server. Session kept for recovery.', 5000));}// ---------------------------------------------------------------------------- // Session persistence via localStorage+ // Session persistence via live-browser-session.js// ---------------------------------------------------------------------------// Survives page reloads, browser close/reopen, HMR, and accidental refreshes.- const LS_KEY = PREFIX + '-session';-function saveSession() {if (!currentSessionId) return;// NOTE: scrollY is stored under a separate key (writeScrollY). Storing// it here would overwrite the Go-time value every time state changes.- try {- localStorage.setItem(LS_KEY, JSON.stringify({- id: currentSessionId,- state: state,- action: selectedAction,- count: selectedCount,- expected: expectedVariants,- arrived: arrivedVariants,- visible: visibleVariant,- }));- } catch { /* quota exceeded or private mode */ }+ sessionState.saveSession({+ id: currentSessionId,+ state,+ action: selectedAction,+ count: selectedCount,+ expected: expectedVariants,+ arrived: arrivedVariants,+ visible: visibleVariant,+ });}function loadSession() {- try {- const raw = localStorage.getItem(LS_KEY);- return raw ? JSON.parse(raw) : null;- } catch { return null; }+ return sessionState.loadSession();}function clearSession() {- try { localStorage.removeItem(LS_KEY); } catch {}+ sessionState.clearSession();}/** Mark session as handled (accepted/discarded). The agent will clean up@@ -3018,19 +3100,15 @@ void main() {* prevents resumeSession from picking it up again after reload. */function markSessionHandled() {if (!currentSessionId) return;- try {- localStorage.setItem(LS_KEY + '-handled', currentSessionId);- } catch {}+ sessionState.markHandled(currentSessionId);}function isSessionHandled(id) {- try {- return localStorage.getItem(LS_KEY + '-handled') === id;- } catch { return false; }+ return sessionState.isHandled(id);}function clearHandled() {- try { localStorage.removeItem(LS_KEY + '-handled'); } catch {}+ sessionState.clearHandled();}function cleanup() {@@ -3161,6 +3239,7 @@ void main() {// hid. Now that state is CYCLING, re-fire.if (state === 'CYCLING') refreshParamsPanel();saveSession();+ queueCheckpoint('browser_resumed');// Start observing for more variants AFTER initial setupif (variantObserver) variantObserver.disconnect();@@ -3617,7 +3696,7 @@ void main() {}// ---------------------------------------------------------------------------- // Design System Panel — visualizes the project's DESIGN.json sidecar+ // Design System Panel — visualizes the project's .impeccable/design.json sidecar// ---------------------------------------------------------------------------const DESIGN_PREFS_KEY = 'impeccable-live-design-panel';@@ -3629,7 +3708,7 @@ void main() {open: false,tab: 'visual', // 'visual' | 'raw'parsed: null, // parseDesignMd output (frontmatter + body sections)- sidecar: null, // DESIGN.json v2 payload (extensions + components + narrative)+ sidecar: null, // .impeccable/design.json v2 payload (extensions + components + narrative)hasMd: false,hasSidecar: false,present: null, // true/false once fetch resolves@@ -4130,7 +4209,7 @@ void main() {box.className = 'stale';box.innerHTML = `<span class="stale-dot"></span>- <span class="stale-text"><strong>DESIGN.md is newer than DESIGN.json.</strong> Run <code>/impeccable document</code> to refresh the sidecar.</span>+ <span class="stale-text"><strong>DESIGN.md is newer than .impeccable/design.json.</strong> Run <code>/impeccable document</code> to refresh the sidecar.</span>`;return box;}@@ -4138,7 +4217,7 @@ void main() {function renderParsedMdCta() {const box = document.createElement('div');box.className = 'parsed-md-cta';- box.innerHTML = `<strong>Basic view</strong>This panel reads the tokens in your <code>DESIGN.md</code> frontmatter. Running <code>/impeccable document</code> also generates a <code>DESIGN.json</code> sidecar with your project's actual component snippets (button, input, nav) and tonal ramps, rendered live below the tokens.`;+ box.innerHTML = `<strong>Basic view</strong>This panel reads the tokens in your <code>DESIGN.md</code> frontmatter. Running <code>/impeccable document</code> also generates a <code>.impeccable/design.json</code> sidecar with your project's actual component snippets (button, input, nav) and tonal ramps, rendered live below the tokens.`;return box;}@@ -4598,7 +4677,7 @@ void main() {function cssSafe(v) {// Strip anything outside valid CSS value chars to prevent injection via- // DESIGN.json values rendered into inline style strings.+ // .impeccable/design.json values rendered into inline style strings.return String(v).replace(/[<>"'`\n]/g, '');}diff --git a/.claude/skills/impeccable/scripts/live-complete.mjs b/.claude/skills/impeccable/scripts/live-complete.mjsnew file mode 100644index 000000000..78155af85--- /dev/null+++ b/.claude/skills/impeccable/scripts/live-complete.mjs@@ -0,0 +1,75 @@+#!/usr/bin/env node+/**+ * Canonical durable completion acknowledgement for Impeccable live sessions.+ */++import { createLiveSessionStore } from './live-session-store.mjs';+import { readLiveServerInfo } from './impeccable-paths.mjs';++function parseArgs(argv) {+ const out = { status: 'complete' };+ for (let i = 0; i < argv.length; i++) {+ const arg = argv[i];+ if (arg === '--id') out.id = argv[++i];+ else if (arg.startsWith('--id=')) out.id = arg.slice('--id='.length);+ else if (arg === '--discarded' || arg === '--discard') out.status = 'discarded';+ else if (arg === '--error') { out.status = 'agent_error'; out.message = argv[++i] || 'unknown error'; }+ else if (arg.startsWith('--error=')) { out.status = 'agent_error'; out.message = arg.slice('--error='.length); }+ else if (arg === '--help' || arg === '-h') out.help = true;+ }+ return out;+}++export async function completeCli() {+ const args = parseArgs(process.argv.slice(2));+ if (args.help || !args.id) {+ console.log(`Usage: node live-complete.mjs --id SESSION_ID [--discarded|--error MESSAGE]\n\nAppend the final durable session acknowledgement. Use after accept/discard cleanup is verified.`);+ process.exit(args.help ? 0 : 1);+ }++ const serverInfo = readServerInfo();+ const serverResult = serverInfo ? await completeThroughServer(serverInfo, args) : null;+ if (serverResult?.ok) {+ const store = createLiveSessionStore({ cwd: process.cwd(), sessionId: args.id });+ const snapshot = store.getSnapshot(args.id, { includeCompleted: true });+ console.log(JSON.stringify({ ok: true, id: args.id, phase: snapshot?.phase || args.status, snapshot }, null, 2));+ return;+ }++ const store = createLiveSessionStore({ cwd: process.cwd(), sessionId: args.id });+ const event = args.status === 'discarded'+ ? { type: 'discarded', id: args.id }+ : args.status === 'agent_error'+ ? { type: 'agent_error', id: args.id, message: args.message || 'unknown error' }+ : { type: 'complete', id: args.id };+ const snapshot = store.appendEvent(event);+ console.log(JSON.stringify({ ok: true, id: args.id, phase: snapshot.phase, snapshot }, null, 2));+}++function readServerInfo() {+ return readLiveServerInfo(process.cwd())?.info || null;+}++async function completeThroughServer(info, args) {+ const type = args.status === 'discarded'+ ? 'discarded'+ : args.status === 'agent_error'+ ? 'error'+ : 'complete';+ try {+ const res = await fetch(`http://localhost:${info.port}/poll`, {+ method: 'POST',+ headers: { 'Content-Type': 'application/json' },+ body: JSON.stringify({ token: info.token, id: args.id, type, message: args.message }),+ });+ if (!res.ok) return null;+ return await res.json();+ } catch {+ return null;+ }+}++const _running = process.argv[1];+if (_running?.endsWith('live-complete.mjs') || _running?.endsWith('live-complete.mjs/')) {+ completeCli();+}diff --git a/.claude/skills/impeccable/scripts/live-completion.mjs b/.claude/skills/impeccable/scripts/live-completion.mjsnew file mode 100644index 000000000..86b637fff--- /dev/null+++ b/.claude/skills/impeccable/scripts/live-completion.mjs@@ -0,0 +1,18 @@+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';+ return 'agent_done';+}++export function completionAckForAcceptResult(eventId, completionType, acceptResult) {+ const ack = { ok: true, type: completionType };+ if (acceptResult?.handled === true && acceptResult?.carbonize === true) {+ ack.final = false;+ ack.requiresComplete = true;+ ack.nextCommand = `live-complete.mjs --id ${eventId}`;+ ack.message = 'Carbonize cleanup must be verified, then the session must be completed explicitly before polling again.';+ }+ return ack;+}diff --git a/.claude/skills/impeccable/scripts/live-inject.mjs b/.claude/skills/impeccable/scripts/live-inject.mjsindex 1d2ae12f7..555c3a36a 100644--- a/.claude/skills/impeccable/scripts/live-inject.mjs+++ b/.claude/skills/impeccable/scripts/live-inject.mjs@@ -2,23 +2,24 @@* CLI helper: insert/remove the live variant mode script tag in the project's* main HTML entry point.*- * On first live run, the agent generates `config.json` in this script's- * directory with the project's insertion target (framework-specific). On+ * On first live run, the agent generates `.impeccable/live/config.json`+ * with the project's insertion target (framework-specific). On* every subsequent run, this script handles insert/remove deterministically* with zero LLM involvement.** Usage:* node live-inject.mjs --port PORT # Insert the live script tag* node live-inject.mjs --remove # Remove the live script tag- * node live-inject.mjs --check # Check whether config.json exists+ * node live-inject.mjs --check # Check whether live config exists*/import fs from 'node:fs';import path from 'node:path';import { fileURLToPath } from 'node:url';+import { resolveLiveConfigPath } from './impeccable-paths.mjs';const __dirname = path.dirname(fileURLToPath(import.meta.url));-const CONFIG_PATH = process.env.IMPECCABLE_LIVE_CONFIG || path.join(__dirname, 'config.json');+const CONFIG_PATH = resolveLiveConfigPath({ cwd: process.cwd(), scriptsDir: __dirname });const MARKER_OPEN_TEXT = 'impeccable-live-start';const MARKER_CLOSE_TEXT = 'impeccable-live-end';@@ -39,12 +40,12 @@ export async function injectCli() {console.log(`Usage: node live-inject.mjs [options]Insert or remove the live mode script tag in the project's HTML entry point.-Reads configuration from config.json (in this same directory).+Reads configuration from .impeccable/live/config.json.Modes:--port PORT Insert script tag pointing at http://localhost:PORT/live.js--remove Remove the script tag (if present)- --check Print whether config.json exists and its content+ --check Print whether .impeccable/live/config.json exists and its contentOutput (JSON):{ ok, file, inserted|removed, config? }`);diff --git a/.claude/skills/impeccable/scripts/live-poll.mjs b/.claude/skills/impeccable/scripts/live-poll.mjsindex eb8f1586a..10d452491 100644--- a/.claude/skills/impeccable/scripts/live-poll.mjs+++ b/.claude/skills/impeccable/scripts/live-poll.mjs@@ -9,10 +9,10 @@*/import { execFileSync } from 'node:child_process';-import fs from 'node:fs';import path from 'node:path';-import os from 'node:os';import { fileURLToPath } from 'node:url';+import { completionAckForAcceptResult, completionTypeForAcceptResult } from './live-completion.mjs';+import { readLiveServerInfo } from './impeccable-paths.mjs';// Node's built-in fetch (undici under the hood) enforces a 300s headers// timeout that can't be lowered per-request. We cap each request below@@ -20,15 +20,29 @@ import { fileURLToPath } from 'node:url';// depending on the standalone undici package.const PER_REQUEST_TIMEOUT_MS = 270_000;-const LIVE_PID_FILE = path.join(process.cwd(), '.impeccable-live.json');-function readServerInfo() {- try {- return JSON.parse(fs.readFileSync(LIVE_PID_FILE, 'utf-8'));- } catch {+ const record = readLiveServerInfo(process.cwd());+ if (!record) {console.error('No running live server found. Start one with: npx impeccable live');process.exit(1);}+ return record.info;+}++export function buildPollReplyPayload(token, { id, type, message, file, data }) {+ return { token, id, type, message, file, data };+}++async function postReply(base, token, reply) {+ const res = await fetch(`${base}/poll`, {+ method: 'POST',+ headers: { 'Content-Type': 'application/json' },+ body: JSON.stringify(buildPollReplyPayload(token, reply)),+ });+ if (!res.ok) {+ const body = await res.json().catch(() => ({}));+ throw new Error(body.error || res.statusText);+ }}export async function pollCli() {@@ -69,23 +83,7 @@ Options:}try {- const res = await fetch(`${base}/poll`, {- method: 'POST',- headers: { 'Content-Type': 'application/json' },- body: JSON.stringify({- token: info.token,- id,- type: status,- message,- file: filePath,- }),- });-- if (!res.ok) {- const body = await res.json().catch(() => ({}));- console.error(`Reply failed (${res.status}):`, body.error || res.statusText);- process.exit(1);- }+ await postReply(base, info.token, { id, type: status, message, file: filePath });// Success — silent exit (agent doesn't need output for replies)} catch (err) {@@ -156,7 +154,23 @@ Options:);event._acceptResult = JSON.parse(out.trim());} catch (err) {- event._acceptResult = { handled: false, error: err.message };+ event._acceptResult = { handled: false, mode: 'error', error: err.message };+ }++ const completionType = completionTypeForAcceptResult(event.type, event._acceptResult);+ try {+ await postReply(base, info.token, {+ id: event.id,+ type: completionType,+ message: event._acceptResult?.error,+ file: event._acceptResult?.file,+ data: event._acceptResult?.carbonize === true ? { carbonize: true } : undefined,+ });+ } catch (err) {+ event._completionAck = { ok: false, error: err.message };+ }+ if (!event._completionAck) {+ event._completionAck = completionAckForAcceptResult(event.id, completionType, event._acceptResult);}}@@ -164,7 +178,7 @@ Options:// JSON but skips nested fields. One line is enough — the full checklist// is in reference/live.md.if (event._acceptResult?.carbonize === true) {- process.stderr.write('\n⚠ Carbonize cleanup REQUIRED before next poll. See reference/live.md "Required after accept".\n\n');+ process.stderr.write('\n⚠ Carbonize cleanup REQUIRED before next poll. After cleanup, run live-complete.mjs --id ' + event.id + '. See reference/live.md "Required after accept".\n\n');}// Print the event as JSON — the agent reads this from stdoutdiff --git a/.claude/skills/impeccable/scripts/live-resume.mjs b/.claude/skills/impeccable/scripts/live-resume.mjsnew file mode 100644index 000000000..a3465c9b5--- /dev/null+++ b/.claude/skills/impeccable/scripts/live-resume.mjs@@ -0,0 +1,48 @@+#!/usr/bin/env node+/**+ * Recover the next agent action from the durable live-session journal.+ */++import { createLiveSessionStore } from './live-session-store.mjs';++function parseArgs(argv) {+ const out = { id: null };+ for (let i = 0; i < argv.length; i++) {+ const arg = argv[i];+ if (arg === '--id') out.id = argv[++i];+ else if (arg.startsWith('--id=')) out.id = arg.slice('--id='.length);+ else if (arg === '--help' || arg === '-h') out.help = true;+ }+ return out;+}++export async function resumeCli() {+ const args = parseArgs(process.argv.slice(2));+ if (args.help) {+ console.log(`Usage: node live-resume.mjs [--id SESSION_ID]\n\nPrint the active durable session checkpoint and the next safe agent action.`);+ return;+ }++ const store = createLiveSessionStore({ cwd: process.cwd(), sessionId: args.id || undefined });+ const snapshot = args.id ? store.getSnapshot(args.id) : store.listActiveSessions()[0] || null;+ if (!snapshot) {+ console.log(JSON.stringify({ active: false, nextAction: 'No active durable live session found.' }, null, 2));+ return;+ }++ const pending = snapshot.pendingEvent || null;+ const nextAction = pending+ ? `Run live-poll.mjs, handle ${pending.type} ${pending.id}, then acknowledge with live-poll.mjs --reply ${pending.id} done.`+ : snapshot.phase === 'carbonize_required'+ ? `Finish carbonize cleanup${snapshot.sourceFile ? ` in ${snapshot.sourceFile}` : ''}, then run live-complete.mjs --id ${snapshot.id}.`+ : snapshot.phase === 'accept_requested'+ ? `Run live-complete.mjs --id ${snapshot.id} after verifying the accepted variant is written.`+ : `Inspect ${snapshot.id}; no pending agent event is currently queued.`;++ console.log(JSON.stringify({ active: true, snapshot, pendingEvent: pending, nextAction }, null, 2));+}++const _running = process.argv[1];+if (_running?.endsWith('live-resume.mjs') || _running?.endsWith('live-resume.mjs/')) {+ resumeCli();+}diff --git a/.claude/skills/impeccable/scripts/live-server.mjs b/.claude/skills/impeccable/scripts/live-server.mjsindex 90614fbf7..53d8f21cb 100644--- a/.claude/skills/impeccable/scripts/live-server.mjs+++ b/.claude/skills/impeccable/scripts/live-server.mjs@@ -22,14 +22,20 @@ import net from 'node:net';import { fileURLToPath } from 'node:url';import { parseDesignMd } from './design-parser.mjs';import { resolveContextDir } from './load-context.mjs';+import { createLiveSessionStore } from './live-session-store.mjs';+import {+ getDesignSidecarPath,+ getLiveAnnotationsDir,+ readLiveServerInfo,+ removeLiveServerInfo,+ resolveDesignSidecarPath,+ writeLiveServerInfo,+} from './impeccable-paths.mjs';const __dirname = path.dirname(fileURLToPath(import.meta.url));-// PID file in the project root so both the server and agent can find it-// predictably (os.tmpdir() varies across platforms).-const LIVE_PID_FILE = path.join(process.cwd(), '.impeccable-live.json');-// PRODUCT.md / DESIGN.md / DESIGN.json live wherever load-context.mjs resolves.-// Keeps live-server in sync with the loader when users keep the docs in-// .agents/context/, docs/, or a path set via IMPECCABLE_CONTEXT_DIR.+// PRODUCT.md / DESIGN.md live wherever load-context.mjs resolves. The generated+// DESIGN sidecar is project-local at .impeccable/design.json, with legacy+// DESIGN.json fallback for existing projects.const CONTEXT_DIR = resolveContextDir(process.cwd());const DEFAULT_POLL_TIMEOUT = 600_000; // 10 min — agent re-polls on timeout anywayconst SSE_HEARTBEAT_INTERVAL = 30_000; // keepalive ping every 30s@@ -57,10 +63,12 @@ const state = {token: null,port: null,sseClients: new Set(), // SSE response objects (server→browser push)- pendingEvents: [], // browser events waiting for agent poll+ pendingEvents: [], // browser events waiting for agent ack ({ event, leaseUntil })pendingPolls: [], // agent poll callbacks waiting for browser eventsexitTimer: null,sessionDir: null, // per-session tmp dir for annotation screenshots+ sessionStore: null,+ leaseTimer: null,};// Cap per-annotation upload size. A full 1920×1080 PNG is typically <1 MB;@@ -68,11 +76,70 @@ const state = {const MAX_ANNOTATION_BYTES = 10 * 1024 * 1024;function enqueueEvent(event) {- if (state.pendingPolls.length > 0) {- state.pendingPolls.shift()(event);- } else {- state.pendingEvents.push(event);+ if (!event || (event.id && state.pendingEvents.some((entry) => entry.event?.id === event.id && entry.event?.type === event.type))) return;+ state.pendingEvents.push({ event, leaseUntil: 0 });+ flushPendingPolls();+}++function restorePendingEventsFromStore() {+ if (!state.sessionStore) return;+ for (const snapshot of state.sessionStore.listActiveSessions()) {+ if (snapshot.pendingEvent) enqueueEvent(snapshot.pendingEvent);+ }+}++function findAvailablePendingEvent(now = Date.now()) {+ return state.pendingEvents.find((entry) => !entry.leaseUntil || entry.leaseUntil <= now);+}++function leaseEvent(entry, leaseMs) {+ if (!entry.event?.id) {+ const idx = state.pendingEvents.indexOf(entry);+ if (idx !== -1) state.pendingEvents.splice(idx, 1);+ return entry.event;}+ entry.leaseUntil = Date.now() + leaseMs;+ return entry.event;+}++function acknowledgePendingEvent(id) {+ if (!id) return false;+ const idx = state.pendingEvents.findIndex((entry) => entry.event?.id === id);+ if (idx === -1) return false;+ state.pendingEvents.splice(idx, 1);+ scheduleLeaseFlush();+ return true;+}++function scheduleLeaseFlush() {+ if (state.leaseTimer) {+ clearTimeout(state.leaseTimer);+ state.leaseTimer = null;+ }+ if (state.pendingPolls.length === 0) return;+ const now = Date.now();+ const nextLeaseUntil = state.pendingEvents+ .map((entry) => entry.leaseUntil || 0)+ .filter((leaseUntil) => leaseUntil > now)+ .sort((a, b) => a - b)[0];+ if (!nextLeaseUntil) return;+ state.leaseTimer = setTimeout(() => {+ state.leaseTimer = null;+ flushPendingPolls();+ }, Math.max(0, nextLeaseUntil - now));+}++function flushPendingPolls() {+ while (state.pendingPolls.length > 0) {+ const entry = findAvailablePendingEvent();+ if (!entry) {+ scheduleLeaseFlush();+ return;+ }+ const poll = state.pendingPolls.shift();+ poll.resolve(leaseEvent(entry, poll.leaseMs));+ }+ scheduleLeaseFlush();}/** Push a message to all connected SSE clients. */@@ -103,13 +170,16 @@ function loadBrowserScripts() {// live-browser.js: DO NOT cache. Return the path so the /live.js handler// can re-read on every request. Editing the browser script during iteration// should land on the next tab reload, not require a server restart.+ const sessionPath = path.join(__dirname, 'live-browser-session.js');const livePath = path.join(__dirname, 'live-browser.js');- if (!fs.existsSync(livePath)) {- process.stderr.write('Error: live-browser.js not found at ' + livePath + '\n');- process.exit(1);+ for (const p of [sessionPath, livePath]) {+ if (!fs.existsSync(p)) {+ process.stderr.write('Error: live browser script not found at ' + p + '\n');+ process.exit(1);+ }}- return { detectScript, livePath };+ return { detectScript, sessionPath, livePath };}function hasProjectContext() {@@ -170,6 +240,13 @@ function validateEvent(msg) {return null;case 'discard':return isValidId(msg.id) ? null : 'discard: missing or malformed id';+ case 'checkpoint':+ if (!isValidId(msg.id)) return 'checkpoint: missing or malformed id';+ if (!Number.isInteger(msg.revision) || msg.revision < 0) return 'checkpoint: revision must be a non-negative integer';+ if (msg.paramValues !== undefined && (typeof msg.paramValues !== 'object' || msg.paramValues === null || Array.isArray(msg.paramValues))) {+ return 'checkpoint: paramValues must be an object';+ }+ return null;case 'exit':return null;case 'prefetch':@@ -184,7 +261,7 @@ function validateEvent(msg) {// HTTP request handler// ----------------------------------------------------------------------------function createRequestHandler({ detectScript, livePath }) {+function createRequestHandler({ detectScript, sessionPath, livePath }) {return (req, res) => {const url = new URL(req.url, `http://localhost:${state.port}`);res.setHeader('Access-Control-Allow-Origin', '*');@@ -200,17 +277,20 @@ function createRequestHandler({ detectScript, livePath }) {// the next tab reload. No-store headers prevent browser caching across// sessions — during iteration, a cached old script silently breaks// every subsequent session.+ let sessionScript;let liveScript;try {+ sessionScript = fs.readFileSync(sessionPath, 'utf-8');liveScript = fs.readFileSync(livePath, 'utf-8');} catch (err) {res.writeHead(500, { 'Content-Type': 'text/plain' });- res.end('Error reading live-browser.js: ' + err.message);+ res.end('Error reading live browser scripts: ' + err.message);return;}const body =`window.__IMPECCABLE_TOKEN__ = '${state.token}';\n` +`window.__IMPECCABLE_PORT__ = ${state.port};\n` ++ sessionScript + '\n' +liveScript;res.writeHead(200, {'Content-Type': 'application/javascript',@@ -305,6 +385,26 @@ function createRequestHandler({ detectScript, livePath }) {}// --- Health ---+ if (p === '/status') {+ const token = url.searchParams.get('token');+ if (token !== state.token) { res.writeHead(401, { 'Content-Type': 'application/json' }); res.end(JSON.stringify({ error: 'Unauthorized' })); return; }+ const sessions = state.sessionStore ? state.sessionStore.listActiveSessions() : [];+ res.writeHead(200, { 'Content-Type': 'application/json' });+ res.end(JSON.stringify({+ status: 'ok',+ port: state.port,+ connectedClients: state.sseClients.size,+ pendingEvents: state.pendingEvents.map((entry) => ({+ id: entry.event?.id,+ type: entry.event?.type,+ leased: !!(entry.leaseUntil && entry.leaseUntil > Date.now()),+ leaseUntil: entry.leaseUntil || null,+ })),+ activeSessions: sessions,+ }));+ return;+ }+if (p === '/health') {res.writeHead(200, { 'Content-Type': 'application/json' });res.end(JSON.stringify({@@ -316,13 +416,13 @@ function createRequestHandler({ detectScript, livePath }) {}// --- Design system (unified v2 response) + raw ---- // /design-system.json returns both parsed DESIGN.md and DESIGN.json+ // /design-system.json returns both parsed DESIGN.md and .impeccable/design.json// sidecar when present. Panel merges them:// { present, parsed, sidecar, hasMd, hasSidecar,// mdNewerThanJson, parseError?, sidecarError? }// - parsed: output of parseDesignMd (frontmatter// + six canonical sections) when DESIGN.md exists.- // - sidecar: DESIGN.json contents when present.+ // - sidecar: .impeccable/design.json contents when present.// Expected shape: schemaVersion 2, carrying// extensions + components + narrative.// /design-system/raw returns DESIGN.md markdown verbatim@@ -331,7 +431,7 @@ function createRequestHandler({ detectScript, livePath }) {if (token !== state.token) { res.writeHead(401); res.end('Unauthorized'); return; }const mdPath = path.join(CONTEXT_DIR, 'DESIGN.md');- const jsonPath = path.join(CONTEXT_DIR, 'DESIGN.json');+ const jsonPath = resolveDesignSidecarPath(process.cwd(), CONTEXT_DIR) || getDesignSidecarPath(process.cwd());const mdStat = statOrNull(mdPath);const jsonStat = statOrNull(jsonPath);@@ -367,7 +467,7 @@ function createRequestHandler({ detectScript, livePath }) {try {response.sidecar = JSON.parse(fs.readFileSync(jsonPath, 'utf-8'));} catch (err) {- response.sidecarError = 'Failed to parse DESIGN.json: ' + err.message;+ response.sidecarError = 'Failed to parse .impeccable/design.json: ' + err.message;}}@@ -449,7 +549,16 @@ function createRequestHandler({ detectScript, livePath }) {res.end(JSON.stringify({ error }));return;}- enqueueEvent(msg);+ if (state.sessionStore && msg.id) {+ try {+ state.sessionStore.appendEvent(msg);+ } catch (err) {+ res.writeHead(500, { 'Content-Type': 'application/json' });+ res.end(JSON.stringify({ error: 'session_store_append_failed', message: err.message }));+ return;+ }+ }+ if (msg.type !== 'checkpoint') enqueueEvent(msg);res.writeHead(200, { 'Content-Type': 'application/json' });res.end(JSON.stringify({ ok: true }));});@@ -492,13 +601,16 @@ function handlePollGet(req, res, url) {return;}const timeout = parseInt(url.searchParams.get('timeout') || DEFAULT_POLL_TIMEOUT, 10);- if (state.pendingEvents.length > 0) {+ const leaseMs = parseInt(url.searchParams.get('leaseMs') || '30000', 10);+ const available = findAvailablePendingEvent();+ if (available) {res.writeHead(200, { 'Content-Type': 'application/json' });- res.end(JSON.stringify(state.pendingEvents.shift()));+ res.end(JSON.stringify(leaseEvent(available, leaseMs)));return;}+ const poll = { resolve, leaseMs };const timer = setTimeout(() => {- const idx = state.pendingPolls.indexOf(resolve);+ const idx = state.pendingPolls.indexOf(poll);if (idx !== -1) state.pendingPolls.splice(idx, 1);res.writeHead(200, { 'Content-Type': 'application/json' });res.end(JSON.stringify({ type: 'timeout' }));@@ -508,10 +620,11 @@ function handlePollGet(req, res, url) {res.writeHead(200, { 'Content-Type': 'application/json' });res.end(JSON.stringify(event));}- state.pendingPolls.push(resolve);+ state.pendingPolls.push(poll);+ scheduleLeaseFlush();req.on('close', () => {clearTimeout(timer);- const idx = state.pendingPolls.indexOf(resolve);+ const idx = state.pendingPolls.indexOf(poll);if (idx !== -1) state.pendingPolls.splice(idx, 1);});}@@ -531,6 +644,26 @@ function handlePollPost(req, res) {res.end(JSON.stringify({ error: 'Unauthorized' }));return;}+ acknowledgePendingEvent(msg.id);+ if (state.sessionStore && msg.id) {+ try {+ const eventType = msg.type === 'discard' || msg.type === 'discarded'+ ? 'discarded'+ : msg.type === 'complete'+ ? 'complete'+ : msg.type === 'error'+ ? 'agent_error'+ : 'agent_done';+ state.sessionStore.appendEvent({+ type: eventType,+ id: msg.id,+ file: msg.file,+ message: msg.message,+ carbonize: msg.data?.carbonize === true,+ });+ } catch { /* keep reply path best-effort; browser still needs SSE */ }+ }+ flushPendingPolls();// Forward the reply to the browser via SSEbroadcast({ type: msg.type || 'done', id: msg.id, message: msg.message, file: msg.file, data: msg.data });res.writeHead(200, { 'Content-Type': 'application/json' });@@ -545,13 +678,15 @@ function handlePollPost(req, res) {let httpServer = null;function shutdown() {- try { fs.unlinkSync(LIVE_PID_FILE); } catch {}+ removeLiveServerInfo(process.cwd());+ if (state.leaseTimer) clearTimeout(state.leaseTimer);+ state.leaseTimer = null;if (state.sessionDir) {try { fs.rmSync(state.sessionDir, { recursive: true, force: true }); } catch {}}for (const res of state.sseClients) { try { res.end(); } catch {} }state.sseClients.clear();- for (const resolve of state.pendingPolls) resolve({ type: 'exit' });+ for (const poll of state.pendingPolls) poll.resolve({ type: 'exit' });state.pendingPolls.length = 0;if (httpServer) httpServer.close();process.exit(0);@@ -587,6 +722,7 @@ Endpoints:/events SSE stream (server→browser) + POST (browser→server)/poll Long-poll for agent CLI/source Raw source file reader (no-HMR fallback)+ /status Durable recovery status (token-protected)/health Health check`);process.exit(0);}@@ -594,7 +730,7 @@ Endpoints:if (args.includes('stop')) {const keepInject = args.includes('--keep-inject');try {- const info = JSON.parse(fs.readFileSync(LIVE_PID_FILE, 'utf-8'));+ const { info } = readLiveServerInfo(process.cwd()) || {};const res = await fetch(`http://localhost:${info.port}/stop?token=${info.token}`);if (res.ok) console.log(`Stopped live server on port ${info.port}.`);} catch {@@ -645,7 +781,7 @@ if (args.includes('--background')) {const deadline = Date.now() + 10_000;while (Date.now() < deadline) {try {- const info = JSON.parse(fs.readFileSync(LIVE_PID_FILE, 'utf-8'));+ const { info } = readLiveServerInfo(process.cwd()) || {};if (info.pid !== process.pid) {// Output JSON so the agent can read port + token from stdout.console.log(JSON.stringify(info));@@ -659,30 +795,36 @@ if (args.includes('--background')) {}// Check for existing session-try {- const existing = JSON.parse(fs.readFileSync(LIVE_PID_FILE, 'utf-8'));- try { process.kill(existing.pid, 0);+const existingRecord = readLiveServerInfo(process.cwd());+if (existingRecord?.info) {+ const existing = existingRecord.info;+ try {+ process.kill(existing.pid, 0);console.error(`Live server already running on port ${existing.port} (pid ${existing.pid}).`);console.error('Stop it first with: node ' + path.basename(fileURLToPath(import.meta.url)) + ' stop');process.exit(1);- } catch { fs.unlinkSync(LIVE_PID_FILE); }-} catch {}+ } catch {+ try { fs.unlinkSync(existingRecord.path); } catch {}+ }+}state.token = randomUUID();+state.sessionStore = createLiveSessionStore({ cwd: process.cwd() });+restorePendingEventsFromStore();const portArg = args.find(a => a.startsWith('--port='));state.port = portArg ? parseInt(portArg.split('=')[1], 10) : await findOpenPort();// Annotation screenshots live in the project root so the agent's Read tool// doesn't trip a per-file permission prompt. Sessioned by token so concurrent// projects (or quick restarts) don't collide.-const annotRoot = path.join(process.cwd(), '.impeccable-live', 'annotations');+const annotRoot = getLiveAnnotationsDir(process.cwd());fs.mkdirSync(annotRoot, { recursive: true });state.sessionDir = fs.mkdtempSync(path.join(annotRoot, 'session-'));-const { detectScript, livePath } = loadBrowserScripts();-httpServer = http.createServer(createRequestHandler({ detectScript, livePath }));+const { detectScript, sessionPath, livePath } = loadBrowserScripts();+httpServer = http.createServer(createRequestHandler({ detectScript, sessionPath, livePath }));httpServer.listen(state.port, '127.0.0.1', () => {- fs.writeFileSync(LIVE_PID_FILE, JSON.stringify({ pid: process.pid, port: state.port, token: state.token }));+ writeLiveServerInfo(process.cwd(), { pid: process.pid, port: state.port, token: state.token });const url = `http://localhost:${state.port}`;console.log(`\nImpeccable live server running on ${url}`);console.log(`Token: ${state.token}\n`);diff --git a/.claude/skills/impeccable/scripts/live-session-store.mjs b/.claude/skills/impeccable/scripts/live-session-store.mjsnew file mode 100644index 000000000..d55ed2d3a--- /dev/null+++ b/.claude/skills/impeccable/scripts/live-session-store.mjs@@ -0,0 +1,254 @@+import fs from 'node:fs';+import path from 'node:path';+import { getLegacyLiveSessionsDir, getLiveSessionsDir } from './impeccable-paths.mjs';++const COMPLETED_PHASES = new Set(['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;+ }++ function getReadableJournalPath(id) {+ const primary = getJournalPath(rootDir, id);+ if (fs.existsSync(primary)) return primary;+ const legacy = getJournalPath(legacyRootDir, id);+ if (fs.existsSync(legacy)) return legacy;+ return primary;+ }++ return {+ rootDir,+ legacyRootDir,+ appendEvent(event) {+ const normalized = normalizeEvent(event, sessionId);+ const journalPath = getJournalPath(rootDir, normalized.id);+ const snapshotPath = getSnapshotPath(rootDir, normalized.id);+ const legacyJournalPath = getJournalPath(legacyRootDir, normalized.id);+ if (!fs.existsSync(journalPath) && fs.existsSync(legacyJournalPath)) {+ fs.copyFileSync(legacyJournalPath, journalPath);+ }+ const prior = loadCachedOrRebuild(normalized.id);+ const seq = prior.nextSeq;+ const entry = {+ seq,+ id: normalized.id,+ type: normalized.type,+ ts: new Date().toISOString(),+ event: normalized,+ };+ 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;+ },+ getSnapshot(id = sessionId, opts = {}) {+ if (!id) throw new Error('session id required');+ 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;+ },+ listActiveSessions() {+ const ids = new Set();+ for (const dir of [legacyRootDir, rootDir]) {+ if (!fs.existsSync(dir)) continue;+ for (const name of fs.readdirSync(dir)) {+ if (name.endsWith('.jsonl')) ids.add(name.slice(0, -'.jsonl'.length));+ }+ }+ return [...ids]+ .sort()+ .map((id) => this.getSnapshot(id))+ .filter(Boolean);+ },+ };+}++function normalizeEvent(event, fallbackId) {+ if (!event || typeof event !== 'object') throw new Error('event object required');+ const id = event.id || fallbackId;+ if (!id || typeof id !== 'string') throw new Error('event id required');+ if (!event.type || typeof event.type !== 'string') throw new Error('event type required');+ return { ...event, id };+}++function getJournalPath(rootDir, id) {+ return path.join(rootDir, safeSessionId(id) + '.jsonl');+}++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,+ phase: 'new',+ pageUrl: null,+ sourceFile: null,+ expectedVariants: 0,+ arrivedVariants: 0,+ visibleVariant: null,+ paramValues: {},+ pendingEventSeq: null,+ pendingEvent: null,+ deliveryLease: null,+ checkpointRevision: 0,+ activeOwner: null,+ sourceMarkers: {},+ fallbackMode: null,+ annotationArtifacts: [],+ diagnostics: [],+ updatedAt: null,+ };+}++function rebuildSnapshotFromJournal(journalPath, id) {+ let snapshot = baseSnapshot(id);+ const diagnostics = [];+ let nextSeq = 1;+ if (!fs.existsSync(journalPath)) return { snapshot, diagnostics, nextSeq };++ const lines = fs.readFileSync(journalPath, 'utf-8').split('\n');+ for (let i = 0; i < lines.length; i++) {+ const line = lines[i];+ if (!line.trim()) continue;+ try {+ const entry = JSON.parse(line);+ if (!entry || typeof entry !== 'object') throw new Error('entry is not object');+ if (Number.isInteger(entry.seq)) nextSeq = Math.max(nextSeq, entry.seq + 1);+ snapshot = applyEvent(snapshot, entry);+ } catch (err) {+ diagnostics.push({+ error: 'journal_parse_failed',+ line: i + 1,+ message: err.message,+ });+ }+ }+ snapshot.diagnostics = [...snapshot.diagnostics, ...diagnostics];+ return { snapshot, diagnostics, nextSeq };+}++function applyEvent(snapshot, entry, inheritedDiagnostics = []) {+ const event = entry.event || entry;+ const next = {+ ...snapshot,+ paramValues: { ...(snapshot.paramValues || {}) },+ sourceMarkers: { ...(snapshot.sourceMarkers || {}) },+ annotationArtifacts: [...(snapshot.annotationArtifacts || [])],+ diagnostics: [...(snapshot.diagnostics || [])],+ updatedAt: entry.ts || new Date().toISOString(),+ };++ if (inheritedDiagnostics.length && next.diagnostics.length === 0) {+ next.diagnostics = [...inheritedDiagnostics];+ }++ switch (event.type) {+ case 'generate':+ next.phase = 'generate_requested';+ next.pageUrl = event.pageUrl ?? next.pageUrl;+ next.expectedVariants = event.count ?? next.expectedVariants;+ next.pendingEventSeq = entry.seq ?? next.pendingEventSeq;+ next.pendingEvent = toPendingEvent(event);+ if (event.screenshotPath) upsertArtifact(next.annotationArtifacts, { type: 'screenshot', path: event.screenshotPath });+ break;+ case 'variants_ready':+ case 'agent_done':+ next.phase = event.carbonize === true ? 'carbonize_required' : 'variants_ready';+ next.sourceFile = event.file ?? next.sourceFile;+ next.arrivedVariants = event.arrivedVariants ?? (next.arrivedVariants ?? next.expectedVariants);+ next.pendingEventSeq = null;+ next.pendingEvent = null;+ if (event.carbonize === true) {+ next.diagnostics.push({+ error: 'carbonize_cleanup_required',+ file: event.file || null,+ message: 'Accepted variant still has carbonize markers that must be folded into source CSS.',+ });+ }+ break;+ case 'checkpoint':+ 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;+ if (event.paramValues) next.paramValues = { ...event.paramValues };+ } else {+ next.diagnostics.push({ error: 'stale_checkpoint_ignored', revision: event.revision });+ }+ break;+ case 'accept':+ case 'accept_intent':+ next.phase = 'accept_requested';+ next.visibleVariant = Number(event.variantId ?? next.visibleVariant);+ if (event.paramValues) next.paramValues = { ...event.paramValues };+ next.pendingEventSeq = entry.seq ?? next.pendingEventSeq;+ next.pendingEvent = toPendingEvent(event);+ break;+ case 'discard':+ next.phase = 'discard_requested';+ next.pendingEventSeq = entry.seq ?? next.pendingEventSeq;+ next.pendingEvent = toPendingEvent(event);+ break;+ case 'discarded':+ next.phase = 'discarded';+ next.pendingEventSeq = null;+ next.pendingEvent = null;+ break;+ case 'complete':+ next.phase = 'completed';+ next.pendingEventSeq = null;+ next.pendingEvent = null;+ break;+ case 'agent_error':+ next.phase = 'agent_error';+ next.pendingEventSeq = null;+ next.pendingEvent = null;+ next.diagnostics.push({ error: 'agent_error', message: event.message || 'unknown agent error' });+ break;+ default:+ next.diagnostics.push({ error: 'unknown_event_type', type: event.type });+ break;+ }+ return next;+}++function toPendingEvent(event) {+ const pending = { ...event };+ delete pending.token;+ return pending;+}++function upsertArtifact(artifacts, artifact) {+ if (!artifacts.some((existing) => existing.path === artifact.path && existing.type === artifact.type)) {+ artifacts.push(artifact);+ }+}++function writeSnapshot(snapshotPath, snapshot) {+ fs.writeFileSync(snapshotPath, JSON.stringify(snapshot, null, 2) + '\n');+}diff --git a/.claude/skills/impeccable/scripts/live-status.mjs b/.claude/skills/impeccable/scripts/live-status.mjsnew file mode 100644index 000000000..dce1fbca2--- /dev/null+++ b/.claude/skills/impeccable/scripts/live-status.mjs@@ -0,0 +1,47 @@+#!/usr/bin/env node+/**+ * Print durable recovery status for Impeccable live sessions.+ */++import { createLiveSessionStore } from './live-session-store.mjs';+import { readLiveServerInfo } from './impeccable-paths.mjs';++function readServerInfo() {+ return readLiveServerInfo(process.cwd())?.info || null;+}++async function fetchServerStatus(info) {+ if (!info) return null;+ try {+ const res = await fetch(`http://localhost:${info.port}/status?token=${info.token}`);+ if (!res.ok) return null;+ return await res.json();+ } catch {+ return null;+ }+}++export async function statusCli() {+ const info = readServerInfo();+ const server = await fetchServerStatus(info);+ const store = createLiveSessionStore({ cwd: process.cwd() });+ const activeSessions = store.listActiveSessions();+ const payload = {+ liveServer: server ? {+ status: server.status,+ port: server.port,+ connectedClients: server.connectedClients,+ pendingEvents: server.pendingEvents,+ } : null,+ activeSessions: server?.activeSessions || activeSessions,+ recoveryHint: 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.',+ };+ console.log(JSON.stringify(payload, null, 2));+}++const _running = process.argv[1];+if (_running?.endsWith('live-status.mjs') || _running?.endsWith('live-status.mjs/')) {+ statusCli();+}diff --git a/.claude/skills/impeccable/scripts/live-wrap.mjs b/.claude/skills/impeccable/scripts/live-wrap.mjsindex a5769a50a..d46328b9f 100644--- a/.claude/skills/impeccable/scripts/live-wrap.mjs+++ b/.claude/skills/impeccable/scripts/live-wrap.mjs@@ -185,6 +185,7 @@ The agent should insert variant HTML at insertLine.`);const { startLine, endLine } = match;const commentSyntax = detectCommentSyntax(targetFile);+ const styleMode = detectStyleMode(targetFile);const isJsx = commentSyntax.open === '{/*';const indent = lines[startLine].match(/^(\s*)/)[1];@@ -269,6 +270,10 @@ The agent should insert variant HTML at insertLine.`);endLine: startLine + wrapperLines.length + (originalLines.length - 1), // 1-indexedinsertLine: insertLine + 1, // 1-indexed: where variants gocommentSyntax: commentSyntax,+ styleMode: styleMode.mode,+ styleTag: styleMode.styleTag,+ cssSelectorPrefixExamples: buildCssSelectorPrefixExamples(styleMode.mode, count),+ cssAuthoring: buildCssAuthoring(styleMode, count),originalLineCount: originalLines.length,}));}@@ -335,6 +340,62 @@ function detectCommentSyntax(filePath) {return { open: '<!--', close: '-->' };}+function detectStyleMode(filePath) {+ const ext = path.extname(filePath).toLowerCase();+ if (ext === '.astro') {+ return {+ mode: 'astro-global-prefixed',+ styleTag: '<style is:inline data-impeccable-css="SESSION_ID">',+ };+ }+ return {+ mode: 'scoped',+ styleTag: '<style data-impeccable-css="SESSION_ID">',+ };+}++function buildCssSelectorPrefixExamples(styleMode, count) {+ if (styleMode !== 'astro-global-prefixed') return [];+ return Array.from({ length: count }, (_, i) => `[data-impeccable-variant="${i + 1}"]`);+}++function buildCssAuthoring(styleMode, count) {+ const variantNumbers = Array.from({ length: count }, (_, i) => i + 1);+ if (styleMode.mode === 'astro-global-prefixed') {+ return {+ mode: styleMode.mode,+ styleTag: styleMode.styleTag,+ strategy: 'global-prefixed',+ rulePattern: '[data-impeccable-variant="N"] > .variant-class { ... }',+ selectorExamples: variantNumbers.map((n) => `[data-impeccable-variant="${n}"] > .variant-class`),+ requirements: [+ 'Use the styleTag exactly; the is:inline attribute is required for this file.',+ 'Prefix every preview selector with the matching [data-impeccable-variant="N"] selector.',+ 'Keep selectors anchored to the generated variant wrapper; do not rely on component CSS scoping for preview rules.',+ ],+ forbidden: [+ 'Do not use @scope for this styleMode.',+ ],+ };+ }+ return {+ mode: styleMode.mode,+ styleTag: styleMode.styleTag,+ strategy: 'scope-rule',+ rulePattern: '@scope ([data-impeccable-variant="N"]) { :scope > .variant-class { ... } }',+ selectorExamples: variantNumbers.map((n) => `@scope ([data-impeccable-variant="${n}"]) { :scope > .variant-class { ... } }`),+ requirements: [+ 'Use @scope blocks keyed to each [data-impeccable-variant="N"] wrapper.',+ 'Inside each @scope block, make :scope rules step into the replacement element with a descendant combinator.',+ 'Use the styleTag exactly; do not add framework-specific style attributes unless this object says to.',+ ],+ forbidden: [+ 'Do not use global [data-impeccable-variant="N"] selector prefixes for this styleMode.',+ 'Do not add is:inline to the style tag for this styleMode.',+ ],+ };+}+/*** Search project files for the query string (class name, ID, etc.)* Returns the first matching file path, or null.diff --git a/.claude/skills/impeccable/scripts/live.mjs b/.claude/skills/impeccable/scripts/live.mjsindex befbdb8ed..cafb0eca9 100644--- a/.claude/skills/impeccable/scripts/live.mjs+++ b/.claude/skills/impeccable/scripts/live.mjs@@ -2,10 +2,10 @@* CLI entry point: prepare everything needed to enter the live variant poll loop.** Does (all in one command):- * 1. Check config.json (returns config_missing if first-ever run)+ * 1. Check .impeccable/live/config.json (returns config_missing if first-ever run)* 2. Start the live server in the background (or reuse a running one)* 3. Inject the browser script tag into the project's entry file- * 4. Read .impeccable.md for design context (if present)+ * 4. Read PRODUCT.md / DESIGN.md for project context* 5. Print a single JSON blob with everything the agent needs** After this, the agent's only remaining steps are:@@ -23,9 +23,9 @@ import path from 'node:path';import { fileURLToPath } from 'node:url';import { loadContext } from './load-context.mjs';import { resolveFiles } from './live-inject.mjs';+import { readLiveServerInfo } from './impeccable-paths.mjs';const __dirname = path.dirname(fileURLToPath(import.meta.url));-const PID_FILE = path.join(process.cwd(), '.impeccable-live.json');async function liveCli() {const args = process.argv.slice(2);@@ -34,10 +34,10 @@ async function liveCli() {console.log(`Usage: node live.mjsPrepare everything for live variant mode in a single command:- - Checks scripts/config.json (required, created once per project)+ - Checks .impeccable/live/config.json (required, created once per project)- Starts (or reuses) the live server in the background- Injects the browser script tag- - Reads .impeccable.md for design context+ - Reads PRODUCT.md / DESIGN.md for project contextOn success, prints a JSON blob with:{ ok, serverPort, serverToken, pageFile, hasContext, context }@@ -223,7 +223,7 @@ function safeParse(out) {function ensureServerRunning() {// Try to reuse an existing servertry {- const existing = JSON.parse(fs.readFileSync(PID_FILE, 'utf-8'));+ const existing = readLiveServerInfo(process.cwd())?.info;if (existing && existing.pid) {try {process.kill(existing.pid, 0); // throws if deaddiff --git a/.claude/skills/impeccable/scripts/load-context.mjs b/.claude/skills/impeccable/scripts/load-context.mjsindex dca23c1f8..dc340bf16 100644--- a/.claude/skills/impeccable/scripts/load-context.mjs+++ b/.claude/skills/impeccable/scripts/load-context.mjs@@ -39,7 +39,7 @@ const LEGACY_NAMES = ['.impeccable.md'];const FALLBACK_DIRS = ['.agents/context', 'docs'];/**- * Resolve the directory that holds PRODUCT.md / DESIGN.md / DESIGN.json for+ * Resolve the directory that holds PRODUCT.md / DESIGN.md for* this project. Exported so other scripts (e.g. live-server.mjs) can read the* design files from the same location the loader uses.*/diff --git a/.cursor/skills/impeccable/reference/document.md b/.cursor/skills/impeccable/reference/document.mdindex 490c21528..254e0183c 100644--- a/.cursor/skills/impeccable/reference/document.md+++ b/.cursor/skills/impeccable/reference/document.md@@ -237,11 +237,11 @@ Concrete, forceful guardrails. Lead each with "Do" or "Don't". Be specific: incl- **Don't** [...]```-### Step 4b: Write DESIGN.json sidecar (extensions only)+### Step 4b: Write .impeccable/design.json sidecar (extensions only)-The frontmatter owns token primitives (colors, typography, rounded, spacing, components). The sidecar at `DESIGN.json` carries **what Stitch's schema can't hold**: tonal ramps per color, shadow/elevation tokens, motion tokens, breakpoints, full component HTML/CSS snippets (the panel renders these into a shadow DOM), and narrative (north star, rules, do's/don'ts). It extends the frontmatter, it doesn't duplicate it.+The frontmatter owns token primitives (colors, typography, rounded, spacing, components). The sidecar at `.impeccable/design.json` carries **what Stitch's schema can't hold**: tonal ramps per color, shadow/elevation tokens, motion tokens, breakpoints, full component HTML/CSS snippets (the panel renders these into a shadow DOM), and narrative (north star, rules, do's/don'ts). It extends the frontmatter, it doesn't duplicate it.-Regenerate the sidecar whenever you regenerate DESIGN.md. If the user only asks to refresh the sidecar (e.g., from the live panel's stale-hint), preserve DESIGN.md and write only DESIGN.json.+Regenerate the sidecar whenever you regenerate root `DESIGN.md`. If the user only asks to refresh the sidecar (e.g., from the live panel's stale-hint), preserve `DESIGN.md` and write only `.impeccable/design.json`.#### Schema@@ -310,7 +310,7 @@ Aim for a tight set of **5-10 components** that best represent the visual system- **Signature components (include if distinctive):** hero CTA, featured card, filter pill, any custom pattern the user mentioned as important in PRODUCT.md.- **Skip the rest.** Utility components, form building blocks, wrapper layouts: not worth documenting unless visually distinctive.-If the project has **no component library yet** (bare landing page, new project), synthesize canonical primitives from the tokens using best-practice defaults consistent with the DESIGN.md's rules. Every DESIGN.json has *something* to render, even on day zero.+If the project has **no component library yet** (bare landing page, new project), synthesize canonical primitives from the tokens using best-practice defaults consistent with the DESIGN.md's rules. Every `.impeccable/design.json` has *something* to render, even on day zero.#### Tonal ramps@@ -331,7 +331,7 @@ Do not reword. The panel shows these as secondary collapsible context; the same### Step 5: Confirm, refine, and refresh session cache1. Show the user the full DESIGN.md you wrote. Briefly highlight the non-obvious creative choices (descriptive color names, atmosphere language, named rules).-2. Mention that `DESIGN.json` was also written alongside; the live panel will now render this project's actual button/input/nav primitives instead of generic approximations.+2. Mention that `.impeccable/design.json` was also written alongside; the live panel will now render this project's actual button/input/nav primitives instead of generic approximations.3. Offer to refine any section: "Want me to revise a section, add component patterns I missed, or adjust the atmosphere language?"4. **Refresh the session cache.** Run `node .cursor/skills/impeccable/scripts/load-context.mjs` one final time so the newly-written DESIGN.md lands in conversation. Subsequent commands in this session will use the fresh version automatically without re-reading.@@ -392,7 +392,7 @@ Per-section guidance in seed mode:- **Components**: omit entirely; no components exist yet.- **Do's and Don'ts**: carry PRODUCT.md's anti-references directly plus the anti-reference named in Q5.-Seed mode writes a minimal frontmatter with `name` and `description` only; no colors, typography, rounded, spacing, or components yet. Real tokens land on the next Scan-mode run. Skip the `DESIGN.json` sidecar in seed mode for the same reason: nothing to render.+Seed mode writes a minimal frontmatter with `name` and `description` only; no colors, typography, rounded, spacing, or components yet. Real tokens land on the next Scan-mode run. Skip the `.impeccable/design.json` sidecar in seed mode for the same reason: nothing to render.### Step 4: Confirm and refresh session cachediff --git a/.cursor/skills/impeccable/reference/live.md b/.cursor/skills/impeccable/reference/live.mdindex 93a7763cb..899fa4e54 100644--- a/.cursor/skills/impeccable/reference/live.md+++ b/.cursor/skills/impeccable/reference/live.md@@ -12,8 +12,9 @@ Execute in order. No step skipped, no step reordered.2. Navigate to the URL that serves `pageFile` (infer from `package.json`, docs, terminal output, or an open tab). If you can't infer it confidently, tell the user once to open their dev/preview URL. Never use `serverPort` as that URL; it's the helper, not the app.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=`.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.-5. On `accept` / `discard`: the poll script already cleaned up; just poll again.-6. On `exit`: run the cleanup at the bottom.+5. 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. If interrupted, run `live-status.mjs` or `live-resume.mjs` before guessing. The durable journal replays unacknowledged work after helper restart.+7. 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.@@ -43,13 +44,31 @@ LOOP:Read JSON; dispatch on "type""generate" → Handle Generate; reply done; LOOP- "accept" → Handle Accept; LOOP+ "accept" → Handle Accept; complete carbonize cleanup if required; LOOP"discard" → Handle Discard; LOOP"prefetch" → Handle Prefetch; LOOP"timeout" → LOOP"exit" → break → Cleanup```+## Recovery commands++The live helper persists an append-only journal under `.impeccable/live/sessions/`. Browser checkpoints are advisory but durable; the journal is canonical. This is local durable recovery state, not project source.++Use these commands when the chat was interrupted, polling was missed, the helper restarted, or the browser reloaded:++```bash+node .cursor/skills/impeccable/scripts/live-status.mjs+node .cursor/skills/impeccable/scripts/live-resume.mjs --id SESSION_ID+node .cursor/skills/impeccable/scripts/live-complete.mjs --id SESSION_ID+```++- `live-status.mjs` prints connected helper state, active durable sessions, and queued pending events. It works even when the helper is down by reading the journal directly.+- `live-resume.mjs` prints the active snapshot, pending event, checkpoint phase, visible variant, parameter values, and the next safe agent action.+- `live-complete.mjs` is the canonical manual final acknowledgement. Use it after carbonize/manual cleanup is verified and no further poll acknowledgement will happen automatically.++Server restart rule: start `live-server.mjs` again, then poll. Startup requeues unacknowledged pending events from the journal, so do not ask the user to click Go again unless `live-resume.mjs` says no active session exists.+## Handle `generate`Event: `{id, action, freeformPrompt?, count, pageUrl, element, screenshotPath?, comments?, strokes?}`.@@ -88,7 +107,14 @@ The helper searches ID first, then classes, then tag + class combo. If `event.paIf `--text` matches multiple candidates equally well, wrap exits with `{ error: "element_ambiguous", candidates: [...] }` and `fallback: "agent-driven"`: read the candidate line ranges, decide which one matches the picked element from page context, and write the wrapper manually per the fallback flow.-Output on success: `{ file, insertLine, commentSyntax }`.+Output on success: `{ file, insertLine, commentSyntax, styleMode, styleTag, cssSelectorPrefixExamples, cssAuthoring }`.++`styleMode` controls how preview CSS must be authored. Treat it as a detected capability mode, not a framework guess:++- `scoped`: use `@scope ([data-impeccable-variant="N"])` rules.+- `astro-global-prefixed`: use explicit `[data-impeccable-variant="N"]` selector prefixes and the exact `styleTag` returned by the tool.++Use `cssAuthoring` as the source of truth for the current file. It includes the exact `styleTag`, selector strategy, selector examples, requirements, and forbidden patterns. Do not apply a framework-specific exception unless the returned `styleMode` / `cssAuthoring.mode` says to.**Fallback errors.** Wrap only writes into files it judges to be source (tracked by git, not marked GENERATED, not listed in config's `generatedFiles`). If it can't land on a source file, it errors without writing; accepting a variant into a generated file is silent data loss. Three shapes:@@ -208,13 +234,14 @@ When the prompt and PRODUCT.md anti-references conflict (the prompt asks for X,Complete 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 scoped 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).+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).++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:```html<!-- Variants: insert below this line --><style data-impeccable-css="SESSION_ID">- @scope ([data-impeccable-variant="1"]) { ... }- @scope ([data-impeccable-variant="2"]) { ... }+ /* rules matching cssAuthoring.rulePattern */</style><div data-impeccable-variant="1"><!-- variant 1: full element replacement (single top-level element) -->@@ -229,11 +256,11 @@ Write CSS + all variants in ONE edit at the `insertLine` reported by `wrap`. Col**Each variant div contains exactly one top-level element: the full replacement for the original.** Use the same tag as the original (e.g. `<section>` if the user picked a `<section>`). Loose siblings (heading + paragraph + div as direct children of the variant div) break the outline tracking and the accept flow, which both assume one child.-The first variant has no `display: none` (visible by default). All others do. If variants use only inline styles and no scoped CSS, omit the `<style>` tag entirely. Use `@scope` for CSS isolation (Chrome 118+ / Firefox 128+ / Safari 17.4+).+The 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.-**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 rule starts `:scope > ...`.+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 > ...`.**JSX / TSX target files.** Wrap `<style>` content in a template literal so the CSS `{` / `}` aren't parsed as JSX expressions, and use `className=` / `style={{…}}` on every variant element. Keep `data-impeccable-*` attributes as-is; they're plain strings:@@ -369,10 +396,11 @@ Remove the wrapper you inserted in Step 2. Nothing else to do.## Handle `accept`-Event: `{id, variantId, _acceptResult}`. The poll script already ran `live-accept.mjs` to handle the file operation deterministically; the browser DOM is already updated.+Event: `{id, variantId, _acceptResult, _completionAck}`. The poll script already ran `live-accept.mjs` to handle the file operation deterministically, then acknowledged event delivery to the helper. The browser DOM is already updated.+- `_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 and a stderr banner both list the steps explicitly; neither is decorative.+- `_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: 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` without `mode`: manual cleanup: read file, find markers, edit.@@ -388,13 +416,13 @@ Do these five steps in the current thread, synchronously, before the next poll.4. **Unwrap the accepted content.** Delete the `<div data-impeccable-variant="N" style="display: contents">` that wraps it. Drop `data-impeccable-params` and any `data-p-*` attributes from it; 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.-Then poll again.+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.## Handle `discard`-Event: `{id, _acceptResult}`. The poll script already restored the original and removed all variant markers. Nothing to do. Poll again.+Event: `{id, _acceptResult, _completionAck}`. The poll script already restored the original, removed all variant markers, and acknowledged `discarded` durable completion. Nothing to do unless `_completionAck.ok !== true`; in that case run `live-complete.mjs --id EVENT_ID --discarded`, then poll again.## Handle `prefetch`@@ -424,7 +452,7 @@ When the poll returns `exit`, proceed to cleanup. If the poll is still running anode .cursor/skills/impeccable/scripts/live-server.mjs stop```-Stops the HTTP server and runs `live-inject.mjs --remove` to strip `localhost:…/live.js` from the HTML entry. To stop the server but keep the inject tag (for a quick restart), use `stop --keep-inject`. `config.json` persists for future sessions.+Stops the HTTP server and runs `live-inject.mjs --remove` to strip `localhost:…/live.js` from the HTML entry. To stop the server but keep the inject tag (for a quick restart), use `stop --keep-inject`. `.impeccable/live/config.json` persists as project config for future sessions.Then:- Remove any leftover variant wrappers (search for `impeccable-variants-start` markers).@@ -432,7 +460,7 @@ Then:## First-time setup (config missing or invalid)-If `live.mjs` outputs `{ ok: false, error: "config_missing" | "config_invalid", path }`, write `config.json` at the reported path.+If `live.mjs` outputs `{ ok: false, error: "config_missing" | "config_invalid", path }`, write the live config at the reported path. By default this is `.impeccable/live/config.json`.Schema:@@ -512,7 +540,7 @@ node .cursor/skills/impeccable/scripts/detect-csp.mjsOutput: `{ shape, signals }` where `shape` is one of `append-arrays`, `append-string`, `middleware`, `meta-tag`, or `null`. The shape is named by *patch mechanism*, so one template covers many frameworks.-- **`null`**: no CSP; skip to writing `config.json` with `cspChecked: true`.+- **`null`**: no CSP; skip to writing `.impeccable/live/config.json` with `cspChecked: true`.- **`append-arrays`**: CSP defined as structured directive arrays. Auto-patchable. See *append-arrays* below. Covers:- Monorepo helpers with `additionalScriptSrc` / `additionalConnectSrc` options (Next.js + shared config package)- SvelteKit `kit.csp.directives`@@ -589,6 +617,6 @@ Reference outputs:### Troubleshooting-If a user says "no" to the CSP patch at setup time and later complains that live doesn't work: their dev CSP blocks `http://localhost:8400`. Fix: delete `cspChecked` from `config.json` and re-run `live.mjs`: setup will ask again.+If a user says "no" to the CSP patch at setup time and later complains that live doesn't work: their dev CSP blocks `http://localhost:8400`. Fix: delete `cspChecked` from `.impeccable/live/config.json` and re-run `live.mjs`: setup will ask again.Then re-run `live.mjs`.diff --git a/.cursor/skills/impeccable/reference/teach.md b/.cursor/skills/impeccable/reference/teach.mdindex b40385ab1..c5d09b9f3 100644--- a/.cursor/skills/impeccable/reference/teach.md+++ b/.cursor/skills/impeccable/reference/teach.md@@ -2,8 +2,8 @@Gathers design context for a project and writes two complementary files at the project root:-- **PRODUCT.md** (strategic): register, target users, product purpose, brand personality, anti-references, strategic design principles. Answers "who/what/why".-- **DESIGN.md** (visual): visual theme, color palette, typography, components, layout. Follows the [Google Stitch DESIGN.md format](https://stitch.withgoogle.com/docs/design-md/format/). Answers "how it looks".+- **PRODUCT.md** (strategic): root project file for register, target users, product purpose, brand personality, anti-references, strategic design principles. Answers "who/what/why".+- **DESIGN.md** (visual): root project file for visual theme, color palette, typography, components, layout. Follows the [Google Stitch DESIGN.md format](https://stitch.withgoogle.com/docs/design-md/format/). Answers "how it looks".Every other impeccable command reads these files before doing any work.diff --git a/.cursor/skills/impeccable/scripts/impeccable-paths.mjs b/.cursor/skills/impeccable/scripts/impeccable-paths.mjsnew file mode 100644index 000000000..ba852bae9--- /dev/null+++ b/.cursor/skills/impeccable/scripts/impeccable-paths.mjs@@ -0,0 +1,105 @@+import fs from 'node:fs';+import path from 'node:path';++export const IMPECCABLE_DIR = '.impeccable';+export const LIVE_DIR = 'live';++export function getImpeccableDir(cwd = process.cwd()) {+ return path.join(cwd, IMPECCABLE_DIR);+}++export function getDesignSidecarPath(cwd = process.cwd()) {+ return path.join(getImpeccableDir(cwd), 'design.json');+}++export function getDesignSidecarCandidates(cwd = process.cwd(), contextDir = cwd) {+ const candidates = [+ getDesignSidecarPath(cwd),+ path.join(cwd, 'DESIGN.json'),+ ];+ const contextLegacy = path.join(contextDir, 'DESIGN.json');+ if (!candidates.includes(contextLegacy)) candidates.push(contextLegacy);+ return candidates;+}++export function resolveDesignSidecarPath(cwd = process.cwd(), contextDir = cwd) {+ return firstExisting(getDesignSidecarCandidates(cwd, contextDir));+}++export function getLiveDir(cwd = process.cwd()) {+ return path.join(getImpeccableDir(cwd), LIVE_DIR);+}++export function getLiveConfigPath(cwd = process.cwd()) {+ return path.join(getLiveDir(cwd), 'config.json');+}++export function getLegacyLiveConfigPath(scriptsDir) {+ return path.join(scriptsDir, 'config.json');+}++export function resolveLiveConfigPath({ cwd = process.cwd(), scriptsDir, env = process.env } = {}) {+ if (env.IMPECCABLE_LIVE_CONFIG && env.IMPECCABLE_LIVE_CONFIG.trim()) {+ const configured = env.IMPECCABLE_LIVE_CONFIG.trim();+ return path.isAbsolute(configured) ? configured : path.resolve(cwd, configured);+ }+ const primary = getLiveConfigPath(cwd);+ if (fs.existsSync(primary)) return primary;+ if (scriptsDir) {+ const legacy = getLegacyLiveConfigPath(scriptsDir);+ if (fs.existsSync(legacy)) return legacy;+ }+ return primary;+}++export function getLiveServerPath(cwd = process.cwd()) {+ return path.join(getLiveDir(cwd), 'server.json');+}++export function getLegacyLiveServerPath(cwd = process.cwd()) {+ return path.join(cwd, '.impeccable-live.json');+}++export function readLiveServerInfo(cwd = process.cwd()) {+ for (const filePath of [getLiveServerPath(cwd), getLegacyLiveServerPath(cwd)]) {+ try {+ return { info: JSON.parse(fs.readFileSync(filePath, 'utf-8')), path: filePath };+ } catch {+ /* try next */+ }+ }+ return null;+}++export function writeLiveServerInfo(cwd = process.cwd(), info) {+ const filePath = getLiveServerPath(cwd);+ fs.mkdirSync(path.dirname(filePath), { recursive: true });+ fs.writeFileSync(filePath, JSON.stringify(info));+ return filePath;+}++export function removeLiveServerInfo(cwd = process.cwd()) {+ for (const filePath of [getLiveServerPath(cwd), getLegacyLiveServerPath(cwd)]) {+ try { fs.unlinkSync(filePath); } catch {}+ }+}++export function getLiveSessionsDir(cwd = process.cwd()) {+ return path.join(getLiveDir(cwd), 'sessions');+}++export function getLegacyLiveSessionsDir(cwd = process.cwd()) {+ return path.join(cwd, '.impeccable-live', 'sessions');+}++export function getLiveAnnotationsDir(cwd = process.cwd()) {+ return path.join(getLiveDir(cwd), 'annotations');+}++export function getLegacyLiveAnnotationsDir(cwd = process.cwd()) {+ return path.join(cwd, '.impeccable-live', 'annotations');+}++function firstExisting(paths) {+ return paths.find((filePath) => fs.existsSync(filePath)) || null;+}diff --git a/.cursor/skills/impeccable/scripts/live-browser-session.js b/.cursor/skills/impeccable/scripts/live-browser-session.jsnew file mode 100644index 000000000..0e362d6be--- /dev/null+++ b/.cursor/skills/impeccable/scripts/live-browser-session.js@@ -0,0 +1,123 @@+/**+ * Browser-side durable session helpers for Impeccable live mode.+ *+ * Kept separate from live-browser.js so recovery state can be tested without+ * booting the full overlay UI. Served before live-browser.js and attached to+ * window.__IMPECCABLE_LIVE_SESSION__.+ */+(function (root) {+ 'use strict';++ function createLiveBrowserSessionState({ prefix, storage, idFactory }) {+ if (!prefix) throw new Error('prefix required');+ const store = storage || root.localStorage;+ const makeId = idFactory || function () { return Math.random().toString(16).slice(2, 10); };+ const sessionKey = prefix + '-session';+ const handledKey = sessionKey + '-handled';+ const scrollKey = sessionKey + '-scroll';+ let checkpointRevision = 0;+ const owner = makeId();++ function safeRead(key) {+ try { return store.getItem(key); } catch { return null; }+ }++ function safeWrite(key, value) {+ try { store.setItem(key, value); } catch { /* quota exceeded or private mode */ }+ }++ function safeRemove(key) {+ try { store.removeItem(key); } catch { /* unavailable storage */ }+ }++ function loadSession() {+ try {+ const raw = safeRead(sessionKey);+ if (!raw) return null;+ const parsed = JSON.parse(raw);+ if (Number.isInteger(parsed.checkpointRevision)) {+ checkpointRevision = Math.max(checkpointRevision, parsed.checkpointRevision);+ }+ return parsed;+ } catch { return null; }+ }++ function saveSession(session) {+ if (!session || !session.id) return;+ const payload = {+ ...session,+ checkpointRevision,+ };+ safeWrite(sessionKey, JSON.stringify(payload));+ }++ function clearSession() {+ safeRemove(sessionKey);+ }++ function nextCheckpointRevision() {+ checkpointRevision += 1;+ const existing = loadSession();+ if (existing?.id) saveSession(existing);+ return checkpointRevision;+ }++ function seedCheckpointRevision(value) {+ if (Number.isInteger(value)) checkpointRevision = Math.max(checkpointRevision, value);+ return checkpointRevision;+ }++ function currentCheckpointRevision() {+ return checkpointRevision;+ }++ function markHandled(id) {+ if (!id) return;+ safeWrite(handledKey, id);+ }++ function isHandled(id) {+ return !!id && safeRead(handledKey) === id;+ }++ function clearHandled() {+ safeRemove(handledKey);+ }++ function writeScrollY(y) {+ safeWrite(scrollKey, String(y));+ }++ function readScrollY() {+ const raw = safeRead(scrollKey);+ if (raw == null) return null;+ const n = parseFloat(raw);+ return isFinite(n) ? n : null;+ }++ function clearScrollY() {+ safeRemove(scrollKey);+ }++ return {+ owner,+ sessionKey,+ handledKey,+ scrollKey,+ saveSession,+ loadSession,+ clearSession,+ nextCheckpointRevision,+ seedCheckpointRevision,+ currentCheckpointRevision,+ markHandled,+ isHandled,+ clearHandled,+ writeScrollY,+ readScrollY,+ clearScrollY,+ };+ }++ root.__IMPECCABLE_LIVE_SESSION__ = { createLiveBrowserSessionState };+})(typeof window !== 'undefined' ? window : globalThis);diff --git a/.cursor/skills/impeccable/scripts/live-browser.js b/.cursor/skills/impeccable/scripts/live-browser.jsindex 3da76bb96..e67cd01ed 100644--- a/.cursor/skills/impeccable/scripts/live-browser.js+++ b/.cursor/skills/impeccable/scripts/live-browser.js@@ -50,6 +50,16 @@const Z = { highlight: 100001, bar: 100005, picker: 100007, toast: 100010 };const EASE = 'cubic-bezier(0.22, 1, 0.36, 1)'; // ease-out-quintconst PREFIX = 'impeccable-live';+ const sessionState = window.__IMPECCABLE_LIVE_SESSION__?.createLiveBrowserSessionState({+ prefix: PREFIX,+ storage: localStorage,+ idFactory: () => crypto.randomUUID().replace(/-/g, '').slice(0, 8),+ });+ if (!sessionState) {+ console.error('[impeccable] live-browser-session.js was not loaded. Live mode cannot start safely.');+ window.__IMPECCABLE_LIVE_INIT__ = false;+ return;+ }const HIGHLIGHT_TRANSITION ='top 140ms ' + EASE +', left 140ms ' + EASE +@@ -112,6 +122,8 @@let hasProjectContext = false;let selectedAction = 'impeccable';let selectedCount = 3;+ const browserOwner = sessionState.owner;+ let checkpointTimer = null;// Scroll lock — holds window.scrollY at a fixed value while the session is// active, so HMR DOM patches and variant swaps can't drift the page. See@@ -126,21 +138,9 @@// (Previously: saveSession wrote scrollY alongside state, so every call// during resume overwrote the pre-reload value with whatever the browser// had landed on, typically 0.)- const SCROLL_KEY_SUFFIX = '-scroll';- function writeScrollY(y) {- try { localStorage.setItem(LS_KEY + SCROLL_KEY_SUFFIX, String(y)); } catch {}- }- function readScrollY() {- try {- const raw = localStorage.getItem(LS_KEY + SCROLL_KEY_SUFFIX);- if (raw == null) return null;- const n = parseFloat(raw);- return isFinite(n) ? n : null;- } catch { return null; }- }- function clearScrollY() {- try { localStorage.removeItem(LS_KEY + SCROLL_KEY_SUFFIX); } catch {}- }+ function writeScrollY(y) { sessionState.writeScrollY(y); }+ function readScrollY() { return sessionState.readScrollY(); }+ function clearScrollY() { sessionState.clearScrollY(); }// Pre-empt the browser: apply manual scroll restoration and jump to the// saved scrollY at script-parse time. Retries on fonts.ready and load@@ -1585,6 +1585,7 @@paramsCurrentValues[p.id] = v;readout.textContent = formatRangeValue(input);applyParamValue(variantEl, p, v);+ queueCheckpoint('param_changed');});row.appendChild(input);} else if (p.kind === 'toggle') {@@ -1615,6 +1616,7 @@knob.style.left = next ? '18px' : '2px';readout.textContent = next ? 'On' : 'Off';applyParamValue(variantEl, p, next);+ queueCheckpoint('param_changed');});row.appendChild(track);} else if (p.kind === 'steps') {@@ -1651,6 +1653,7 @@btn.style.color = on ? 'oklch(98% 0 0)' : P.text;});applyParamValue(variantEl, p, o.value);+ queueCheckpoint('param_changed');});segRow.appendChild(b);segBtns.push({ btn: b, val: o.value });@@ -1872,19 +1875,26 @@return;}+ const previousVisibleVariant = currentSessionId === sessionId ? visibleVariant : 0;+// Replace the live element with the full wrapper from sourceconst wrapper = srcWrapper.cloneNode(true);liveEl.parentElement.replaceChild(wrapper, liveEl);- // Update state: count variants, show the first one+ // Update state: count variants, preserving the user's current variant+ // when a late HMR/source reinjection lands after they have cycled.const variants = wrapper.querySelectorAll('[data-impeccable-variant]:not([data-impeccable-variant="original"])');arrivedVariants = variants.length;expectedVariants = parseInt(wrapper.dataset.impeccableVariantCount || arrivedVariants);- visibleVariant = 1;- showVariantInDOM(sessionId, 1);+ const saved = loadSession();+ const savedVisibleVariant = saved && saved.id === sessionId ? saved.visible : 0;+ visibleVariant = previousVisibleVariant > 0 && previousVisibleVariant <= arrivedVariants+ ? previousVisibleVariant+ : (savedVisibleVariant > 0 && savedVisibleVariant <= arrivedVariants ? savedVisibleVariant : 1);+ showVariantInDOM(sessionId, visibleVariant);// Update selectedElement to the visible variant's content- selectedElement = pickVariantContent(wrapper, 1) || wrapper.parentElement;+ selectedElement = pickVariantContent(wrapper, visibleVariant) || wrapper.parentElement;state = 'CYCLING';hideShaderOverlay();@@ -1907,6 +1917,7 @@updateSelectedElement();updateBarContent('cycling');saveSession();+ queueCheckpoint('variant_changed');}function updateSelectedElement() {@@ -1917,6 +1928,18 @@if (visEl) selectedElement = visEl;}+ function readVisibleVariantFromDOM(sessionId) {+ const wrapper = document.querySelector('[data-impeccable-variants="' + sessionId + '"]');+ if (!wrapper) return 0;+ const variants = wrapper.querySelectorAll('[data-impeccable-variant]:not([data-impeccable-variant="original"])');+ for (const variant of variants) {+ if (variant.style.display === 'none') continue;+ const idx = parseInt(variant.dataset.impeccableVariant || '0', 10);+ if (idx > 0) return idx;+ }+ return 0;+ }+// Resolve the element that represents the variant's visible content.// Contract: each variant div should contain exactly one top-level element// (the full replacement). In practice a model may ship loose siblings or@@ -2107,8 +2130,10 @@updating = true;arrivedVariants = count;if (visibleVariant === 0 && arrivedVariants > 0) {- visibleVariant = 1;- showVariantInDOM(sessionId, 1);+ const saved = loadSession();+ const savedVisibleVariant = saved && saved.id === sessionId ? saved.visible : 0;+ visibleVariant = savedVisibleVariant > 0 && savedVisibleVariant <= arrivedVariants ? savedVisibleVariant : 1;+ showVariantInDOM(sessionId, visibleVariant);// showVariantInDOM hid the original (display:none); if we were still// anchored to the original's content, its boundingRect is now zero// and the bar snaps to (0,0). Re-point at the visible variant instead.@@ -2128,6 +2153,7 @@updateBarContent('generating');}saveSession();+ queueCheckpoint(state === 'CYCLING' ? 'variants_ready' : 'variants_progress');updating = false;});@@ -2236,6 +2262,7 @@/** Server died or became unreachable. Reset UI to a clean state. */function handleServerLost() {+ const recoveryState = currentSessionId ? state : 'IDLE';if (state === 'GENERATING' || state === 'CYCLING' || state === 'SAVING') {showToast('Live server disconnected. Session ended.', 5000);}@@ -2246,21 +2273,61 @@stopScrollTracking();if (variantObserver) { variantObserver.disconnect(); variantObserver = null; }stopScrollLock();- clearScrollY();- clearSession();+ // Preserve local session state on server loss. The durable journal is the+ // source of truth, but localStorage plus the variant wrapper lets the UI+ // resume after a helper restart or page reload instead of treating a+ // transient disconnect as an explicit discard.selectedElement = null;- currentSessionId = null;selectedAction = 'impeccable';- state = 'IDLE';+ state = recoveryState;+ if (currentSessionId) saveSession();}- function sendEvent(msg) {+ function sendEvent(msg, opts) {msg.token = TOKEN;- fetch('http://localhost:' + PORT + '/events', {+ function handleFailure(err) {+ console.error('[impeccable] Failed to send event:', err);+ if (opts && opts.throwOnError) throw err;+ return null;+ }+ return fetch('http://localhost:' + PORT + '/events', {method: 'POST',headers: { 'Content-Type': 'application/json' },body: JSON.stringify(msg),- }).catch(err => console.error('[impeccable] Failed to send event:', err));+ }).then(res => {+ if (res.ok) return res;+ return handleFailure(new Error('HTTP ' + res.status + ' ' + res.statusText));+ }).catch(handleFailure);+ }++ function checkpointPayload(reason) {+ return {+ type: 'checkpoint',+ id: currentSessionId,+ revision: sessionState.nextCheckpointRevision(),+ owner: browserOwner,+ phase: String(state || '').toLowerCase(),+ reason,+ pageUrl: location.pathname,+ expectedVariants,+ arrivedVariants,+ visibleVariant,+ paramValues: { ...paramsCurrentValues },+ };+ }++ function sendCheckpoint(reason) {+ if (!currentSessionId) return Promise.resolve(null);+ return sendEvent(checkpointPayload(reason)).catch(() => null);+ }++ function queueCheckpoint(reason) {+ if (!currentSessionId) return;+ if (checkpointTimer) clearTimeout(checkpointTimer);+ checkpointTimer = setTimeout(() => {+ checkpointTimer = null;+ sendCheckpoint(reason);+ }, 120);}// ---------------------------------------------------------------------------@@ -2496,6 +2563,7 @@state = 'GENERATING';showBar('generating');saveSession();+ sendCheckpoint('generate_started');writeScrollY(window.scrollY);if (variantObserver) variantObserver.disconnect();variantObserver = startVariantObserver(currentSessionId);@@ -2920,13 +2988,12 @@ void main() {function handleAccept() {if (!currentSessionId || arrivedVariants === 0) return;+ const domVisibleVariant = readVisibleVariantFromDOM(currentSessionId);+ if (domVisibleVariant > 0) visibleVariant = domVisibleVariant;const acceptPayload = { type: 'accept', id: currentSessionId, variantId: String(visibleVariant) };if (Object.keys(paramsCurrentValues).length > 0) {acceptPayload.paramValues = { ...paramsCurrentValues };}- sendEvent(acceptPayload);- markSessionHandled();-// The accepted variant is already the only visible child of the wrapper// (all other variants are display:none). HMR from the source rewrite will// replace the wrapper imminently. Don't eagerly replaceChild here — React@@ -2936,9 +3003,28 @@ void main() {const acceptedSessionId = currentSessionId;const acceptedVariant = visibleVariant;- state = 'CONFIRMED';- updateBarContent('confirmed');- setTimeout(function() {+ state = 'SAVING';+ updateBarContent('saving');++ sendEvent(acceptPayload, { throwOnError: true })+ .then(() => {+ markSessionHandled();+ confirmAcceptAfterReceipt();+ })+ .catch(() => {+ state = 'CYCLING';+ updateBarContent('cycling');+ showToast('Could not confirm accept with the live server. Session kept for recovery; try Accept again.', 5000);+ });++ function confirmAcceptAfterReceipt() {+ state = 'CONFIRMED';+ updateBarContent('confirmed');+ scheduleAcceptCleanup();+ }++ function scheduleAcceptCleanup() {+ setTimeout(function() {hideBar();hideHighlight();stopScrollTracking();@@ -2967,50 +3053,46 @@ void main() {accepted.style.display = 'contents';parent.replaceChild(accepted, wrapper);}- }, 2000);+ }, 2000);+ }}function handleDiscard() {if (!currentSessionId) return;- sendEvent({ type: 'discard', id: currentSessionId });- markSessionHandled();- // Instant DOM restore + fire-and-forget (script handles file cleanup)- cleanup();+ sendEvent({ type: 'discard', id: currentSessionId }, { throwOnError: true })+ .then(() => {+ markSessionHandled();+ cleanup();+ })+ .catch(() => showToast('Could not confirm discard with the live server. Session kept for recovery.', 5000));}// ---------------------------------------------------------------------------- // Session persistence via localStorage+ // Session persistence via live-browser-session.js// ---------------------------------------------------------------------------// Survives page reloads, browser close/reopen, HMR, and accidental refreshes.- const LS_KEY = PREFIX + '-session';-function saveSession() {if (!currentSessionId) return;// NOTE: scrollY is stored under a separate key (writeScrollY). Storing// it here would overwrite the Go-time value every time state changes.- try {- localStorage.setItem(LS_KEY, JSON.stringify({- id: currentSessionId,- state: state,- action: selectedAction,- count: selectedCount,- expected: expectedVariants,- arrived: arrivedVariants,- visible: visibleVariant,- }));- } catch { /* quota exceeded or private mode */ }+ sessionState.saveSession({+ id: currentSessionId,+ state,+ action: selectedAction,+ count: selectedCount,+ expected: expectedVariants,+ arrived: arrivedVariants,+ visible: visibleVariant,+ });}function loadSession() {- try {- const raw = localStorage.getItem(LS_KEY);- return raw ? JSON.parse(raw) : null;- } catch { return null; }+ return sessionState.loadSession();}function clearSession() {- try { localStorage.removeItem(LS_KEY); } catch {}+ sessionState.clearSession();}/** Mark session as handled (accepted/discarded). The agent will clean up@@ -3018,19 +3100,15 @@ void main() {* prevents resumeSession from picking it up again after reload. */function markSessionHandled() {if (!currentSessionId) return;- try {- localStorage.setItem(LS_KEY + '-handled', currentSessionId);- } catch {}+ sessionState.markHandled(currentSessionId);}function isSessionHandled(id) {- try {- return localStorage.getItem(LS_KEY + '-handled') === id;- } catch { return false; }+ return sessionState.isHandled(id);}function clearHandled() {- try { localStorage.removeItem(LS_KEY + '-handled'); } catch {}+ sessionState.clearHandled();}function cleanup() {@@ -3161,6 +3239,7 @@ void main() {// hid. Now that state is CYCLING, re-fire.if (state === 'CYCLING') refreshParamsPanel();saveSession();+ queueCheckpoint('browser_resumed');// Start observing for more variants AFTER initial setupif (variantObserver) variantObserver.disconnect();@@ -3617,7 +3696,7 @@ void main() {}// ---------------------------------------------------------------------------- // Design System Panel — visualizes the project's DESIGN.json sidecar+ // Design System Panel — visualizes the project's .impeccable/design.json sidecar// ---------------------------------------------------------------------------const DESIGN_PREFS_KEY = 'impeccable-live-design-panel';@@ -3629,7 +3708,7 @@ void main() {open: false,tab: 'visual', // 'visual' | 'raw'parsed: null, // parseDesignMd output (frontmatter + body sections)- sidecar: null, // DESIGN.json v2 payload (extensions + components + narrative)+ sidecar: null, // .impeccable/design.json v2 payload (extensions + components + narrative)hasMd: false,hasSidecar: false,present: null, // true/false once fetch resolves@@ -4130,7 +4209,7 @@ void main() {box.className = 'stale';box.innerHTML = `<span class="stale-dot"></span>- <span class="stale-text"><strong>DESIGN.md is newer than DESIGN.json.</strong> Run <code>/impeccable document</code> to refresh the sidecar.</span>+ <span class="stale-text"><strong>DESIGN.md is newer than .impeccable/design.json.</strong> Run <code>/impeccable document</code> to refresh the sidecar.</span>`;return box;}@@ -4138,7 +4217,7 @@ void main() {function renderParsedMdCta() {const box = document.createElement('div');box.className = 'parsed-md-cta';- box.innerHTML = `<strong>Basic view</strong>This panel reads the tokens in your <code>DESIGN.md</code> frontmatter. Running <code>/impeccable document</code> also generates a <code>DESIGN.json</code> sidecar with your project's actual component snippets (button, input, nav) and tonal ramps, rendered live below the tokens.`;+ box.innerHTML = `<strong>Basic view</strong>This panel reads the tokens in your <code>DESIGN.md</code> frontmatter. Running <code>/impeccable document</code> also generates a <code>.impeccable/design.json</code> sidecar with your project's actual component snippets (button, input, nav) and tonal ramps, rendered live below the tokens.`;return box;}@@ -4598,7 +4677,7 @@ void main() {function cssSafe(v) {// Strip anything outside valid CSS value chars to prevent injection via- // DESIGN.json values rendered into inline style strings.+ // .impeccable/design.json values rendered into inline style strings.return String(v).replace(/[<>"'`\n]/g, '');}diff --git a/.cursor/skills/impeccable/scripts/live-complete.mjs b/.cursor/skills/impeccable/scripts/live-complete.mjsnew file mode 100644index 000000000..78155af85--- /dev/null+++ b/.cursor/skills/impeccable/scripts/live-complete.mjs@@ -0,0 +1,75 @@+#!/usr/bin/env node+/**+ * Canonical durable completion acknowledgement for Impeccable live sessions.+ */++import { createLiveSessionStore } from './live-session-store.mjs';+import { readLiveServerInfo } from './impeccable-paths.mjs';++function parseArgs(argv) {+ const out = { status: 'complete' };+ for (let i = 0; i < argv.length; i++) {+ const arg = argv[i];+ if (arg === '--id') out.id = argv[++i];+ else if (arg.startsWith('--id=')) out.id = arg.slice('--id='.length);+ else if (arg === '--discarded' || arg === '--discard') out.status = 'discarded';+ else if (arg === '--error') { out.status = 'agent_error'; out.message = argv[++i] || 'unknown error'; }+ else if (arg.startsWith('--error=')) { out.status = 'agent_error'; out.message = arg.slice('--error='.length); }+ else if (arg === '--help' || arg === '-h') out.help = true;+ }+ return out;+}++export async function completeCli() {+ const args = parseArgs(process.argv.slice(2));+ if (args.help || !args.id) {+ console.log(`Usage: node live-complete.mjs --id SESSION_ID [--discarded|--error MESSAGE]\n\nAppend the final durable session acknowledgement. Use after accept/discard cleanup is verified.`);+ process.exit(args.help ? 0 : 1);+ }++ const serverInfo = readServerInfo();+ const serverResult = serverInfo ? await completeThroughServer(serverInfo, args) : null;+ if (serverResult?.ok) {+ const store = createLiveSessionStore({ cwd: process.cwd(), sessionId: args.id });+ const snapshot = store.getSnapshot(args.id, { includeCompleted: true });+ console.log(JSON.stringify({ ok: true, id: args.id, phase: snapshot?.phase || args.status, snapshot }, null, 2));+ return;+ }++ const store = createLiveSessionStore({ cwd: process.cwd(), sessionId: args.id });+ const event = args.status === 'discarded'+ ? { type: 'discarded', id: args.id }+ : args.status === 'agent_error'+ ? { type: 'agent_error', id: args.id, message: args.message || 'unknown error' }+ : { type: 'complete', id: args.id };+ const snapshot = store.appendEvent(event);+ console.log(JSON.stringify({ ok: true, id: args.id, phase: snapshot.phase, snapshot }, null, 2));+}++function readServerInfo() {+ return readLiveServerInfo(process.cwd())?.info || null;+}++async function completeThroughServer(info, args) {+ const type = args.status === 'discarded'+ ? 'discarded'+ : args.status === 'agent_error'+ ? 'error'+ : 'complete';+ try {+ const res = await fetch(`http://localhost:${info.port}/poll`, {+ method: 'POST',+ headers: { 'Content-Type': 'application/json' },+ body: JSON.stringify({ token: info.token, id: args.id, type, message: args.message }),+ });+ if (!res.ok) return null;+ return await res.json();+ } catch {+ return null;+ }+}++const _running = process.argv[1];+if (_running?.endsWith('live-complete.mjs') || _running?.endsWith('live-complete.mjs/')) {+ completeCli();+}diff --git a/.cursor/skills/impeccable/scripts/live-completion.mjs b/.cursor/skills/impeccable/scripts/live-completion.mjsnew file mode 100644index 000000000..86b637fff--- /dev/null+++ b/.cursor/skills/impeccable/scripts/live-completion.mjs@@ -0,0 +1,18 @@+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';+ return 'agent_done';+}++export function completionAckForAcceptResult(eventId, completionType, acceptResult) {+ const ack = { ok: true, type: completionType };+ if (acceptResult?.handled === true && acceptResult?.carbonize === true) {+ ack.final = false;+ ack.requiresComplete = true;+ ack.nextCommand = `live-complete.mjs --id ${eventId}`;+ ack.message = 'Carbonize cleanup must be verified, then the session must be completed explicitly before polling again.';+ }+ return ack;+}diff --git a/.cursor/skills/impeccable/scripts/live-inject.mjs b/.cursor/skills/impeccable/scripts/live-inject.mjsindex 1d2ae12f7..555c3a36a 100644--- a/.cursor/skills/impeccable/scripts/live-inject.mjs+++ b/.cursor/skills/impeccable/scripts/live-inject.mjs@@ -2,23 +2,24 @@* CLI helper: insert/remove the live variant mode script tag in the project's* main HTML entry point.*- * On first live run, the agent generates `config.json` in this script's- * directory with the project's insertion target (framework-specific). On+ * On first live run, the agent generates `.impeccable/live/config.json`+ * with the project's insertion target (framework-specific). On* every subsequent run, this script handles insert/remove deterministically* with zero LLM involvement.** Usage:* node live-inject.mjs --port PORT # Insert the live script tag* node live-inject.mjs --remove # Remove the live script tag- * node live-inject.mjs --check # Check whether config.json exists+ * node live-inject.mjs --check # Check whether live config exists*/import fs from 'node:fs';import path from 'node:path';import { fileURLToPath } from 'node:url';+import { resolveLiveConfigPath } from './impeccable-paths.mjs';const __dirname = path.dirname(fileURLToPath(import.meta.url));-const CONFIG_PATH = process.env.IMPECCABLE_LIVE_CONFIG || path.join(__dirname, 'config.json');+const CONFIG_PATH = resolveLiveConfigPath({ cwd: process.cwd(), scriptsDir: __dirname });const MARKER_OPEN_TEXT = 'impeccable-live-start';const MARKER_CLOSE_TEXT = 'impeccable-live-end';@@ -39,12 +40,12 @@ export async function injectCli() {console.log(`Usage: node live-inject.mjs [options]Insert or remove the live mode script tag in the project's HTML entry point.-Reads configuration from config.json (in this same directory).+Reads configuration from .impeccable/live/config.json.Modes:--port PORT Insert script tag pointing at http://localhost:PORT/live.js--remove Remove the script tag (if present)- --check Print whether config.json exists and its content+ --check Print whether .impeccable/live/config.json exists and its contentOutput (JSON):{ ok, file, inserted|removed, config? }`);diff --git a/.cursor/skills/impeccable/scripts/live-poll.mjs b/.cursor/skills/impeccable/scripts/live-poll.mjsindex eb8f1586a..10d452491 100644--- a/.cursor/skills/impeccable/scripts/live-poll.mjs+++ b/.cursor/skills/impeccable/scripts/live-poll.mjs@@ -9,10 +9,10 @@*/import { execFileSync } from 'node:child_process';-import fs from 'node:fs';import path from 'node:path';-import os from 'node:os';import { fileURLToPath } from 'node:url';+import { completionAckForAcceptResult, completionTypeForAcceptResult } from './live-completion.mjs';+import { readLiveServerInfo } from './impeccable-paths.mjs';// Node's built-in fetch (undici under the hood) enforces a 300s headers// timeout that can't be lowered per-request. We cap each request below@@ -20,15 +20,29 @@ import { fileURLToPath } from 'node:url';// depending on the standalone undici package.const PER_REQUEST_TIMEOUT_MS = 270_000;-const LIVE_PID_FILE = path.join(process.cwd(), '.impeccable-live.json');-function readServerInfo() {- try {- return JSON.parse(fs.readFileSync(LIVE_PID_FILE, 'utf-8'));- } catch {+ const record = readLiveServerInfo(process.cwd());+ if (!record) {console.error('No running live server found. Start one with: npx impeccable live');process.exit(1);}+ return record.info;+}++export function buildPollReplyPayload(token, { id, type, message, file, data }) {+ return { token, id, type, message, file, data };+}++async function postReply(base, token, reply) {+ const res = await fetch(`${base}/poll`, {+ method: 'POST',+ headers: { 'Content-Type': 'application/json' },+ body: JSON.stringify(buildPollReplyPayload(token, reply)),+ });+ if (!res.ok) {+ const body = await res.json().catch(() => ({}));+ throw new Error(body.error || res.statusText);+ }}export async function pollCli() {@@ -69,23 +83,7 @@ Options:}try {- const res = await fetch(`${base}/poll`, {- method: 'POST',- headers: { 'Content-Type': 'application/json' },- body: JSON.stringify({- token: info.token,- id,- type: status,- message,- file: filePath,- }),- });-- if (!res.ok) {- const body = await res.json().catch(() => ({}));- console.error(`Reply failed (${res.status}):`, body.error || res.statusText);- process.exit(1);- }+ await postReply(base, info.token, { id, type: status, message, file: filePath });// Success — silent exit (agent doesn't need output for replies)} catch (err) {@@ -156,7 +154,23 @@ Options:);event._acceptResult = JSON.parse(out.trim());} catch (err) {- event._acceptResult = { handled: false, error: err.message };+ event._acceptResult = { handled: false, mode: 'error', error: err.message };+ }++ const completionType = completionTypeForAcceptResult(event.type, event._acceptResult);+ try {+ await postReply(base, info.token, {+ id: event.id,+ type: completionType,+ message: event._acceptResult?.error,+ file: event._acceptResult?.file,+ data: event._acceptResult?.carbonize === true ? { carbonize: true } : undefined,+ });+ } catch (err) {+ event._completionAck = { ok: false, error: err.message };+ }+ if (!event._completionAck) {+ event._completionAck = completionAckForAcceptResult(event.id, completionType, event._acceptResult);}}@@ -164,7 +178,7 @@ Options:// JSON but skips nested fields. One line is enough — the full checklist// is in reference/live.md.if (event._acceptResult?.carbonize === true) {- process.stderr.write('\n⚠ Carbonize cleanup REQUIRED before next poll. See reference/live.md "Required after accept".\n\n');+ process.stderr.write('\n⚠ Carbonize cleanup REQUIRED before next poll. After cleanup, run live-complete.mjs --id ' + event.id + '. See reference/live.md "Required after accept".\n\n');}// Print the event as JSON — the agent reads this from stdoutdiff --git a/.cursor/skills/impeccable/scripts/live-resume.mjs b/.cursor/skills/impeccable/scripts/live-resume.mjsnew file mode 100644index 000000000..a3465c9b5--- /dev/null+++ b/.cursor/skills/impeccable/scripts/live-resume.mjs@@ -0,0 +1,48 @@+#!/usr/bin/env node+/**+ * Recover the next agent action from the durable live-session journal.+ */++import { createLiveSessionStore } from './live-session-store.mjs';++function parseArgs(argv) {+ const out = { id: null };+ for (let i = 0; i < argv.length; i++) {+ const arg = argv[i];+ if (arg === '--id') out.id = argv[++i];+ else if (arg.startsWith('--id=')) out.id = arg.slice('--id='.length);+ else if (arg === '--help' || arg === '-h') out.help = true;+ }+ return out;+}++export async function resumeCli() {+ const args = parseArgs(process.argv.slice(2));+ if (args.help) {+ console.log(`Usage: node live-resume.mjs [--id SESSION_ID]\n\nPrint the active durable session checkpoint and the next safe agent action.`);+ return;+ }++ const store = createLiveSessionStore({ cwd: process.cwd(), sessionId: args.id || undefined });+ const snapshot = args.id ? store.getSnapshot(args.id) : store.listActiveSessions()[0] || null;+ if (!snapshot) {+ console.log(JSON.stringify({ active: false, nextAction: 'No active durable live session found.' }, null, 2));+ return;+ }++ const pending = snapshot.pendingEvent || null;+ const nextAction = pending+ ? `Run live-poll.mjs, handle ${pending.type} ${pending.id}, then acknowledge with live-poll.mjs --reply ${pending.id} done.`+ : snapshot.phase === 'carbonize_required'+ ? `Finish carbonize cleanup${snapshot.sourceFile ? ` in ${snapshot.sourceFile}` : ''}, then run live-complete.mjs --id ${snapshot.id}.`+ : snapshot.phase === 'accept_requested'+ ? `Run live-complete.mjs --id ${snapshot.id} after verifying the accepted variant is written.`+ : `Inspect ${snapshot.id}; no pending agent event is currently queued.`;++ console.log(JSON.stringify({ active: true, snapshot, pendingEvent: pending, nextAction }, null, 2));+}++const _running = process.argv[1];+if (_running?.endsWith('live-resume.mjs') || _running?.endsWith('live-resume.mjs/')) {+ resumeCli();+}diff --git a/.cursor/skills/impeccable/scripts/live-server.mjs b/.cursor/skills/impeccable/scripts/live-server.mjsindex 90614fbf7..53d8f21cb 100644--- a/.cursor/skills/impeccable/scripts/live-server.mjs+++ b/.cursor/skills/impeccable/scripts/live-server.mjs@@ -22,14 +22,20 @@ import net from 'node:net';import { fileURLToPath } from 'node:url';import { parseDesignMd } from './design-parser.mjs';import { resolveContextDir } from './load-context.mjs';+import { createLiveSessionStore } from './live-session-store.mjs';+import {+ getDesignSidecarPath,+ getLiveAnnotationsDir,+ readLiveServerInfo,+ removeLiveServerInfo,+ resolveDesignSidecarPath,+ writeLiveServerInfo,+} from './impeccable-paths.mjs';const __dirname = path.dirname(fileURLToPath(import.meta.url));-// PID file in the project root so both the server and agent can find it-// predictably (os.tmpdir() varies across platforms).-const LIVE_PID_FILE = path.join(process.cwd(), '.impeccable-live.json');-// PRODUCT.md / DESIGN.md / DESIGN.json live wherever load-context.mjs resolves.-// Keeps live-server in sync with the loader when users keep the docs in-// .agents/context/, docs/, or a path set via IMPECCABLE_CONTEXT_DIR.+// PRODUCT.md / DESIGN.md live wherever load-context.mjs resolves. The generated+// DESIGN sidecar is project-local at .impeccable/design.json, with legacy+// DESIGN.json fallback for existing projects.const CONTEXT_DIR = resolveContextDir(process.cwd());const DEFAULT_POLL_TIMEOUT = 600_000; // 10 min — agent re-polls on timeout anywayconst SSE_HEARTBEAT_INTERVAL = 30_000; // keepalive ping every 30s@@ -57,10 +63,12 @@ const state = {token: null,port: null,sseClients: new Set(), // SSE response objects (server→browser push)- pendingEvents: [], // browser events waiting for agent poll+ pendingEvents: [], // browser events waiting for agent ack ({ event, leaseUntil })pendingPolls: [], // agent poll callbacks waiting for browser eventsexitTimer: null,sessionDir: null, // per-session tmp dir for annotation screenshots+ sessionStore: null,+ leaseTimer: null,};// Cap per-annotation upload size. A full 1920×1080 PNG is typically <1 MB;@@ -68,11 +76,70 @@ const state = {const MAX_ANNOTATION_BYTES = 10 * 1024 * 1024;function enqueueEvent(event) {- if (state.pendingPolls.length > 0) {- state.pendingPolls.shift()(event);- } else {- state.pendingEvents.push(event);+ if (!event || (event.id && state.pendingEvents.some((entry) => entry.event?.id === event.id && entry.event?.type === event.type))) return;+ state.pendingEvents.push({ event, leaseUntil: 0 });+ flushPendingPolls();+}++function restorePendingEventsFromStore() {+ if (!state.sessionStore) return;+ for (const snapshot of state.sessionStore.listActiveSessions()) {+ if (snapshot.pendingEvent) enqueueEvent(snapshot.pendingEvent);+ }+}++function findAvailablePendingEvent(now = Date.now()) {+ return state.pendingEvents.find((entry) => !entry.leaseUntil || entry.leaseUntil <= now);+}++function leaseEvent(entry, leaseMs) {+ if (!entry.event?.id) {+ const idx = state.pendingEvents.indexOf(entry);+ if (idx !== -1) state.pendingEvents.splice(idx, 1);+ return entry.event;}+ entry.leaseUntil = Date.now() + leaseMs;+ return entry.event;+}++function acknowledgePendingEvent(id) {+ if (!id) return false;+ const idx = state.pendingEvents.findIndex((entry) => entry.event?.id === id);+ if (idx === -1) return false;+ state.pendingEvents.splice(idx, 1);+ scheduleLeaseFlush();+ return true;+}++function scheduleLeaseFlush() {+ if (state.leaseTimer) {+ clearTimeout(state.leaseTimer);+ state.leaseTimer = null;+ }+ if (state.pendingPolls.length === 0) return;+ const now = Date.now();+ const nextLeaseUntil = state.pendingEvents+ .map((entry) => entry.leaseUntil || 0)+ .filter((leaseUntil) => leaseUntil > now)+ .sort((a, b) => a - b)[0];+ if (!nextLeaseUntil) return;+ state.leaseTimer = setTimeout(() => {+ state.leaseTimer = null;+ flushPendingPolls();+ }, Math.max(0, nextLeaseUntil - now));+}++function flushPendingPolls() {+ while (state.pendingPolls.length > 0) {+ const entry = findAvailablePendingEvent();+ if (!entry) {+ scheduleLeaseFlush();+ return;+ }+ const poll = state.pendingPolls.shift();+ poll.resolve(leaseEvent(entry, poll.leaseMs));+ }+ scheduleLeaseFlush();}/** Push a message to all connected SSE clients. */@@ -103,13 +170,16 @@ function loadBrowserScripts() {// live-browser.js: DO NOT cache. Return the path so the /live.js handler// can re-read on every request. Editing the browser script during iteration// should land on the next tab reload, not require a server restart.+ const sessionPath = path.join(__dirname, 'live-browser-session.js');const livePath = path.join(__dirname, 'live-browser.js');- if (!fs.existsSync(livePath)) {- process.stderr.write('Error: live-browser.js not found at ' + livePath + '\n');- process.exit(1);+ for (const p of [sessionPath, livePath]) {+ if (!fs.existsSync(p)) {+ process.stderr.write('Error: live browser script not found at ' + p + '\n');+ process.exit(1);+ }}- return { detectScript, livePath };+ return { detectScript, sessionPath, livePath };}function hasProjectContext() {@@ -170,6 +240,13 @@ function validateEvent(msg) {return null;case 'discard':return isValidId(msg.id) ? null : 'discard: missing or malformed id';+ case 'checkpoint':+ if (!isValidId(msg.id)) return 'checkpoint: missing or malformed id';+ if (!Number.isInteger(msg.revision) || msg.revision < 0) return 'checkpoint: revision must be a non-negative integer';+ if (msg.paramValues !== undefined && (typeof msg.paramValues !== 'object' || msg.paramValues === null || Array.isArray(msg.paramValues))) {+ return 'checkpoint: paramValues must be an object';+ }+ return null;case 'exit':return null;case 'prefetch':@@ -184,7 +261,7 @@ function validateEvent(msg) {// HTTP request handler// ----------------------------------------------------------------------------function createRequestHandler({ detectScript, livePath }) {+function createRequestHandler({ detectScript, sessionPath, livePath }) {return (req, res) => {const url = new URL(req.url, `http://localhost:${state.port}`);res.setHeader('Access-Control-Allow-Origin', '*');@@ -200,17 +277,20 @@ function createRequestHandler({ detectScript, livePath }) {// the next tab reload. No-store headers prevent browser caching across// sessions — during iteration, a cached old script silently breaks// every subsequent session.+ let sessionScript;let liveScript;try {+ sessionScript = fs.readFileSync(sessionPath, 'utf-8');liveScript = fs.readFileSync(livePath, 'utf-8');} catch (err) {res.writeHead(500, { 'Content-Type': 'text/plain' });- res.end('Error reading live-browser.js: ' + err.message);+ res.end('Error reading live browser scripts: ' + err.message);return;}const body =`window.__IMPECCABLE_TOKEN__ = '${state.token}';\n` +`window.__IMPECCABLE_PORT__ = ${state.port};\n` ++ sessionScript + '\n' +liveScript;res.writeHead(200, {'Content-Type': 'application/javascript',@@ -305,6 +385,26 @@ function createRequestHandler({ detectScript, livePath }) {}// --- Health ---+ if (p === '/status') {+ const token = url.searchParams.get('token');+ if (token !== state.token) { res.writeHead(401, { 'Content-Type': 'application/json' }); res.end(JSON.stringify({ error: 'Unauthorized' })); return; }+ const sessions = state.sessionStore ? state.sessionStore.listActiveSessions() : [];+ res.writeHead(200, { 'Content-Type': 'application/json' });+ res.end(JSON.stringify({+ status: 'ok',+ port: state.port,+ connectedClients: state.sseClients.size,+ pendingEvents: state.pendingEvents.map((entry) => ({+ id: entry.event?.id,+ type: entry.event?.type,+ leased: !!(entry.leaseUntil && entry.leaseUntil > Date.now()),+ leaseUntil: entry.leaseUntil || null,+ })),+ activeSessions: sessions,+ }));+ return;+ }+if (p === '/health') {res.writeHead(200, { 'Content-Type': 'application/json' });res.end(JSON.stringify({@@ -316,13 +416,13 @@ function createRequestHandler({ detectScript, livePath }) {}// --- Design system (unified v2 response) + raw ---- // /design-system.json returns both parsed DESIGN.md and DESIGN.json+ // /design-system.json returns both parsed DESIGN.md and .impeccable/design.json// sidecar when present. Panel merges them:// { present, parsed, sidecar, hasMd, hasSidecar,// mdNewerThanJson, parseError?, sidecarError? }// - parsed: output of parseDesignMd (frontmatter// + six canonical sections) when DESIGN.md exists.- // - sidecar: DESIGN.json contents when present.+ // - sidecar: .impeccable/design.json contents when present.// Expected shape: schemaVersion 2, carrying// extensions + components + narrative.// /design-system/raw returns DESIGN.md markdown verbatim@@ -331,7 +431,7 @@ function createRequestHandler({ detectScript, livePath }) {if (token !== state.token) { res.writeHead(401); res.end('Unauthorized'); return; }const mdPath = path.join(CONTEXT_DIR, 'DESIGN.md');- const jsonPath = path.join(CONTEXT_DIR, 'DESIGN.json');+ const jsonPath = resolveDesignSidecarPath(process.cwd(), CONTEXT_DIR) || getDesignSidecarPath(process.cwd());const mdStat = statOrNull(mdPath);const jsonStat = statOrNull(jsonPath);@@ -367,7 +467,7 @@ function createRequestHandler({ detectScript, livePath }) {try {response.sidecar = JSON.parse(fs.readFileSync(jsonPath, 'utf-8'));} catch (err) {- response.sidecarError = 'Failed to parse DESIGN.json: ' + err.message;+ response.sidecarError = 'Failed to parse .impeccable/design.json: ' + err.message;}}@@ -449,7 +549,16 @@ function createRequestHandler({ detectScript, livePath }) {res.end(JSON.stringify({ error }));return;}- enqueueEvent(msg);+ if (state.sessionStore && msg.id) {+ try {+ state.sessionStore.appendEvent(msg);+ } catch (err) {+ res.writeHead(500, { 'Content-Type': 'application/json' });+ res.end(JSON.stringify({ error: 'session_store_append_failed', message: err.message }));+ return;+ }+ }+ if (msg.type !== 'checkpoint') enqueueEvent(msg);res.writeHead(200, { 'Content-Type': 'application/json' });res.end(JSON.stringify({ ok: true }));});@@ -492,13 +601,16 @@ function handlePollGet(req, res, url) {return;}const timeout = parseInt(url.searchParams.get('timeout') || DEFAULT_POLL_TIMEOUT, 10);- if (state.pendingEvents.length > 0) {+ const leaseMs = parseInt(url.searchParams.get('leaseMs') || '30000', 10);+ const available = findAvailablePendingEvent();+ if (available) {res.writeHead(200, { 'Content-Type': 'application/json' });- res.end(JSON.stringify(state.pendingEvents.shift()));+ res.end(JSON.stringify(leaseEvent(available, leaseMs)));return;}+ const poll = { resolve, leaseMs };const timer = setTimeout(() => {- const idx = state.pendingPolls.indexOf(resolve);+ const idx = state.pendingPolls.indexOf(poll);if (idx !== -1) state.pendingPolls.splice(idx, 1);res.writeHead(200, { 'Content-Type': 'application/json' });res.end(JSON.stringify({ type: 'timeout' }));@@ -508,10 +620,11 @@ function handlePollGet(req, res, url) {res.writeHead(200, { 'Content-Type': 'application/json' });res.end(JSON.stringify(event));}- state.pendingPolls.push(resolve);+ state.pendingPolls.push(poll);+ scheduleLeaseFlush();req.on('close', () => {clearTimeout(timer);- const idx = state.pendingPolls.indexOf(resolve);+ const idx = state.pendingPolls.indexOf(poll);if (idx !== -1) state.pendingPolls.splice(idx, 1);});}@@ -531,6 +644,26 @@ function handlePollPost(req, res) {res.end(JSON.stringify({ error: 'Unauthorized' }));return;}+ acknowledgePendingEvent(msg.id);+ if (state.sessionStore && msg.id) {+ try {+ const eventType = msg.type === 'discard' || msg.type === 'discarded'+ ? 'discarded'+ : msg.type === 'complete'+ ? 'complete'+ : msg.type === 'error'+ ? 'agent_error'+ : 'agent_done';+ state.sessionStore.appendEvent({+ type: eventType,+ id: msg.id,+ file: msg.file,+ message: msg.message,+ carbonize: msg.data?.carbonize === true,+ });+ } catch { /* keep reply path best-effort; browser still needs SSE */ }+ }+ flushPendingPolls();// Forward the reply to the browser via SSEbroadcast({ type: msg.type || 'done', id: msg.id, message: msg.message, file: msg.file, data: msg.data });res.writeHead(200, { 'Content-Type': 'application/json' });@@ -545,13 +678,15 @@ function handlePollPost(req, res) {let httpServer = null;function shutdown() {- try { fs.unlinkSync(LIVE_PID_FILE); } catch {}+ removeLiveServerInfo(process.cwd());+ if (state.leaseTimer) clearTimeout(state.leaseTimer);+ state.leaseTimer = null;if (state.sessionDir) {try { fs.rmSync(state.sessionDir, { recursive: true, force: true }); } catch {}}for (const res of state.sseClients) { try { res.end(); } catch {} }state.sseClients.clear();- for (const resolve of state.pendingPolls) resolve({ type: 'exit' });+ for (const poll of state.pendingPolls) poll.resolve({ type: 'exit' });state.pendingPolls.length = 0;if (httpServer) httpServer.close();process.exit(0);@@ -587,6 +722,7 @@ Endpoints:/events SSE stream (server→browser) + POST (browser→server)/poll Long-poll for agent CLI/source Raw source file reader (no-HMR fallback)+ /status Durable recovery status (token-protected)/health Health check`);process.exit(0);}@@ -594,7 +730,7 @@ Endpoints:if (args.includes('stop')) {const keepInject = args.includes('--keep-inject');try {- const info = JSON.parse(fs.readFileSync(LIVE_PID_FILE, 'utf-8'));+ const { info } = readLiveServerInfo(process.cwd()) || {};const res = await fetch(`http://localhost:${info.port}/stop?token=${info.token}`);if (res.ok) console.log(`Stopped live server on port ${info.port}.`);} catch {@@ -645,7 +781,7 @@ if (args.includes('--background')) {const deadline = Date.now() + 10_000;while (Date.now() < deadline) {try {- const info = JSON.parse(fs.readFileSync(LIVE_PID_FILE, 'utf-8'));+ const { info } = readLiveServerInfo(process.cwd()) || {};if (info.pid !== process.pid) {// Output JSON so the agent can read port + token from stdout.console.log(JSON.stringify(info));@@ -659,30 +795,36 @@ if (args.includes('--background')) {}// Check for existing session-try {- const existing = JSON.parse(fs.readFileSync(LIVE_PID_FILE, 'utf-8'));- try { process.kill(existing.pid, 0);+const existingRecord = readLiveServerInfo(process.cwd());+if (existingRecord?.info) {+ const existing = existingRecord.info;+ try {+ process.kill(existing.pid, 0);console.error(`Live server already running on port ${existing.port} (pid ${existing.pid}).`);console.error('Stop it first with: node ' + path.basename(fileURLToPath(import.meta.url)) + ' stop');process.exit(1);- } catch { fs.unlinkSync(LIVE_PID_FILE); }-} catch {}+ } catch {+ try { fs.unlinkSync(existingRecord.path); } catch {}+ }+}state.token = randomUUID();+state.sessionStore = createLiveSessionStore({ cwd: process.cwd() });+restorePendingEventsFromStore();const portArg = args.find(a => a.startsWith('--port='));state.port = portArg ? parseInt(portArg.split('=')[1], 10) : await findOpenPort();// Annotation screenshots live in the project root so the agent's Read tool// doesn't trip a per-file permission prompt. Sessioned by token so concurrent// projects (or quick restarts) don't collide.-const annotRoot = path.join(process.cwd(), '.impeccable-live', 'annotations');+const annotRoot = getLiveAnnotationsDir(process.cwd());fs.mkdirSync(annotRoot, { recursive: true });state.sessionDir = fs.mkdtempSync(path.join(annotRoot, 'session-'));-const { detectScript, livePath } = loadBrowserScripts();-httpServer = http.createServer(createRequestHandler({ detectScript, livePath }));+const { detectScript, sessionPath, livePath } = loadBrowserScripts();+httpServer = http.createServer(createRequestHandler({ detectScript, sessionPath, livePath }));httpServer.listen(state.port, '127.0.0.1', () => {- fs.writeFileSync(LIVE_PID_FILE, JSON.stringify({ pid: process.pid, port: state.port, token: state.token }));+ writeLiveServerInfo(process.cwd(), { pid: process.pid, port: state.port, token: state.token });const url = `http://localhost:${state.port}`;console.log(`\nImpeccable live server running on ${url}`);console.log(`Token: ${state.token}\n`);diff --git a/.cursor/skills/impeccable/scripts/live-session-store.mjs b/.cursor/skills/impeccable/scripts/live-session-store.mjsnew file mode 100644index 000000000..d55ed2d3a--- /dev/null+++ b/.cursor/skills/impeccable/scripts/live-session-store.mjs@@ -0,0 +1,254 @@+import fs from 'node:fs';+import path from 'node:path';+import { getLegacyLiveSessionsDir, getLiveSessionsDir } from './impeccable-paths.mjs';++const COMPLETED_PHASES = new Set(['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;+ }++ function getReadableJournalPath(id) {+ const primary = getJournalPath(rootDir, id);+ if (fs.existsSync(primary)) return primary;+ const legacy = getJournalPath(legacyRootDir, id);+ if (fs.existsSync(legacy)) return legacy;+ return primary;+ }++ return {+ rootDir,+ legacyRootDir,+ appendEvent(event) {+ const normalized = normalizeEvent(event, sessionId);+ const journalPath = getJournalPath(rootDir, normalized.id);+ const snapshotPath = getSnapshotPath(rootDir, normalized.id);+ const legacyJournalPath = getJournalPath(legacyRootDir, normalized.id);+ if (!fs.existsSync(journalPath) && fs.existsSync(legacyJournalPath)) {+ fs.copyFileSync(legacyJournalPath, journalPath);+ }+ const prior = loadCachedOrRebuild(normalized.id);+ const seq = prior.nextSeq;+ const entry = {+ seq,+ id: normalized.id,+ type: normalized.type,+ ts: new Date().toISOString(),+ event: normalized,+ };+ 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;+ },+ getSnapshot(id = sessionId, opts = {}) {+ if (!id) throw new Error('session id required');+ 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;+ },+ listActiveSessions() {+ const ids = new Set();+ for (const dir of [legacyRootDir, rootDir]) {+ if (!fs.existsSync(dir)) continue;+ for (const name of fs.readdirSync(dir)) {+ if (name.endsWith('.jsonl')) ids.add(name.slice(0, -'.jsonl'.length));+ }+ }+ return [...ids]+ .sort()+ .map((id) => this.getSnapshot(id))+ .filter(Boolean);+ },+ };+}++function normalizeEvent(event, fallbackId) {+ if (!event || typeof event !== 'object') throw new Error('event object required');+ const id = event.id || fallbackId;+ if (!id || typeof id !== 'string') throw new Error('event id required');+ if (!event.type || typeof event.type !== 'string') throw new Error('event type required');+ return { ...event, id };+}++function getJournalPath(rootDir, id) {+ return path.join(rootDir, safeSessionId(id) + '.jsonl');+}++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,+ phase: 'new',+ pageUrl: null,+ sourceFile: null,+ expectedVariants: 0,+ arrivedVariants: 0,+ visibleVariant: null,+ paramValues: {},+ pendingEventSeq: null,+ pendingEvent: null,+ deliveryLease: null,+ checkpointRevision: 0,+ activeOwner: null,+ sourceMarkers: {},+ fallbackMode: null,+ annotationArtifacts: [],+ diagnostics: [],+ updatedAt: null,+ };+}++function rebuildSnapshotFromJournal(journalPath, id) {+ let snapshot = baseSnapshot(id);+ const diagnostics = [];+ let nextSeq = 1;+ if (!fs.existsSync(journalPath)) return { snapshot, diagnostics, nextSeq };++ const lines = fs.readFileSync(journalPath, 'utf-8').split('\n');+ for (let i = 0; i < lines.length; i++) {+ const line = lines[i];+ if (!line.trim()) continue;+ try {+ const entry = JSON.parse(line);+ if (!entry || typeof entry !== 'object') throw new Error('entry is not object');+ if (Number.isInteger(entry.seq)) nextSeq = Math.max(nextSeq, entry.seq + 1);+ snapshot = applyEvent(snapshot, entry);+ } catch (err) {+ diagnostics.push({+ error: 'journal_parse_failed',+ line: i + 1,+ message: err.message,+ });+ }+ }+ snapshot.diagnostics = [...snapshot.diagnostics, ...diagnostics];+ return { snapshot, diagnostics, nextSeq };+}++function applyEvent(snapshot, entry, inheritedDiagnostics = []) {+ const event = entry.event || entry;+ const next = {+ ...snapshot,+ paramValues: { ...(snapshot.paramValues || {}) },+ sourceMarkers: { ...(snapshot.sourceMarkers || {}) },+ annotationArtifacts: [...(snapshot.annotationArtifacts || [])],+ diagnostics: [...(snapshot.diagnostics || [])],+ updatedAt: entry.ts || new Date().toISOString(),+ };++ if (inheritedDiagnostics.length && next.diagnostics.length === 0) {+ next.diagnostics = [...inheritedDiagnostics];+ }++ switch (event.type) {+ case 'generate':+ next.phase = 'generate_requested';+ next.pageUrl = event.pageUrl ?? next.pageUrl;+ next.expectedVariants = event.count ?? next.expectedVariants;+ next.pendingEventSeq = entry.seq ?? next.pendingEventSeq;+ next.pendingEvent = toPendingEvent(event);+ if (event.screenshotPath) upsertArtifact(next.annotationArtifacts, { type: 'screenshot', path: event.screenshotPath });+ break;+ case 'variants_ready':+ case 'agent_done':+ next.phase = event.carbonize === true ? 'carbonize_required' : 'variants_ready';+ next.sourceFile = event.file ?? next.sourceFile;+ next.arrivedVariants = event.arrivedVariants ?? (next.arrivedVariants ?? next.expectedVariants);+ next.pendingEventSeq = null;+ next.pendingEvent = null;+ if (event.carbonize === true) {+ next.diagnostics.push({+ error: 'carbonize_cleanup_required',+ file: event.file || null,+ message: 'Accepted variant still has carbonize markers that must be folded into source CSS.',+ });+ }+ break;+ case 'checkpoint':+ 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;+ if (event.paramValues) next.paramValues = { ...event.paramValues };+ } else {+ next.diagnostics.push({ error: 'stale_checkpoint_ignored', revision: event.revision });+ }+ break;+ case 'accept':+ case 'accept_intent':+ next.phase = 'accept_requested';+ next.visibleVariant = Number(event.variantId ?? next.visibleVariant);+ if (event.paramValues) next.paramValues = { ...event.paramValues };+ next.pendingEventSeq = entry.seq ?? next.pendingEventSeq;+ next.pendingEvent = toPendingEvent(event);+ break;+ case 'discard':+ next.phase = 'discard_requested';+ next.pendingEventSeq = entry.seq ?? next.pendingEventSeq;+ next.pendingEvent = toPendingEvent(event);+ break;+ case 'discarded':+ next.phase = 'discarded';+ next.pendingEventSeq = null;+ next.pendingEvent = null;+ break;+ case 'complete':+ next.phase = 'completed';+ next.pendingEventSeq = null;+ next.pendingEvent = null;+ break;+ case 'agent_error':+ next.phase = 'agent_error';+ next.pendingEventSeq = null;+ next.pendingEvent = null;+ next.diagnostics.push({ error: 'agent_error', message: event.message || 'unknown agent error' });+ break;+ default:+ next.diagnostics.push({ error: 'unknown_event_type', type: event.type });+ break;+ }+ return next;+}++function toPendingEvent(event) {+ const pending = { ...event };+ delete pending.token;+ return pending;+}++function upsertArtifact(artifacts, artifact) {+ if (!artifacts.some((existing) => existing.path === artifact.path && existing.type === artifact.type)) {+ artifacts.push(artifact);+ }+}++function writeSnapshot(snapshotPath, snapshot) {+ fs.writeFileSync(snapshotPath, JSON.stringify(snapshot, null, 2) + '\n');+}diff --git a/.cursor/skills/impeccable/scripts/live-status.mjs b/.cursor/skills/impeccable/scripts/live-status.mjsnew file mode 100644index 000000000..dce1fbca2--- /dev/null+++ b/.cursor/skills/impeccable/scripts/live-status.mjs@@ -0,0 +1,47 @@+#!/usr/bin/env node+/**+ * Print durable recovery status for Impeccable live sessions.+ */++import { createLiveSessionStore } from './live-session-store.mjs';+import { readLiveServerInfo } from './impeccable-paths.mjs';++function readServerInfo() {+ return readLiveServerInfo(process.cwd())?.info || null;+}++async function fetchServerStatus(info) {+ if (!info) return null;+ try {+ const res = await fetch(`http://localhost:${info.port}/status?token=${info.token}`);+ if (!res.ok) return null;+ return await res.json();+ } catch {+ return null;+ }+}++export async function statusCli() {+ const info = readServerInfo();+ const server = await fetchServerStatus(info);+ const store = createLiveSessionStore({ cwd: process.cwd() });+ const activeSessions = store.listActiveSessions();+ const payload = {+ liveServer: server ? {+ status: server.status,+ port: server.port,+ connectedClients: server.connectedClients,+ pendingEvents: server.pendingEvents,+ } : null,+ activeSessions: server?.activeSessions || activeSessions,+ recoveryHint: 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.',+ };+ console.log(JSON.stringify(payload, null, 2));+}++const _running = process.argv[1];+if (_running?.endsWith('live-status.mjs') || _running?.endsWith('live-status.mjs/')) {+ statusCli();+}diff --git a/.cursor/skills/impeccable/scripts/live-wrap.mjs b/.cursor/skills/impeccable/scripts/live-wrap.mjsindex a5769a50a..d46328b9f 100644--- a/.cursor/skills/impeccable/scripts/live-wrap.mjs+++ b/.cursor/skills/impeccable/scripts/live-wrap.mjs@@ -185,6 +185,7 @@ The agent should insert variant HTML at insertLine.`);const { startLine, endLine } = match;const commentSyntax = detectCommentSyntax(targetFile);+ const styleMode = detectStyleMode(targetFile);const isJsx = commentSyntax.open === '{/*';const indent = lines[startLine].match(/^(\s*)/)[1];@@ -269,6 +270,10 @@ The agent should insert variant HTML at insertLine.`);endLine: startLine + wrapperLines.length + (originalLines.length - 1), // 1-indexedinsertLine: insertLine + 1, // 1-indexed: where variants gocommentSyntax: commentSyntax,+ styleMode: styleMode.mode,+ styleTag: styleMode.styleTag,+ cssSelectorPrefixExamples: buildCssSelectorPrefixExamples(styleMode.mode, count),+ cssAuthoring: buildCssAuthoring(styleMode, count),originalLineCount: originalLines.length,}));}@@ -335,6 +340,62 @@ function detectCommentSyntax(filePath) {return { open: '<!--', close: '-->' };}+function detectStyleMode(filePath) {+ const ext = path.extname(filePath).toLowerCase();+ if (ext === '.astro') {+ return {+ mode: 'astro-global-prefixed',+ styleTag: '<style is:inline data-impeccable-css="SESSION_ID">',+ };+ }+ return {+ mode: 'scoped',+ styleTag: '<style data-impeccable-css="SESSION_ID">',+ };+}++function buildCssSelectorPrefixExamples(styleMode, count) {+ if (styleMode !== 'astro-global-prefixed') return [];+ return Array.from({ length: count }, (_, i) => `[data-impeccable-variant="${i + 1}"]`);+}++function buildCssAuthoring(styleMode, count) {+ const variantNumbers = Array.from({ length: count }, (_, i) => i + 1);+ if (styleMode.mode === 'astro-global-prefixed') {+ return {+ mode: styleMode.mode,+ styleTag: styleMode.styleTag,+ strategy: 'global-prefixed',+ rulePattern: '[data-impeccable-variant="N"] > .variant-class { ... }',+ selectorExamples: variantNumbers.map((n) => `[data-impeccable-variant="${n}"] > .variant-class`),+ requirements: [+ 'Use the styleTag exactly; the is:inline attribute is required for this file.',+ 'Prefix every preview selector with the matching [data-impeccable-variant="N"] selector.',+ 'Keep selectors anchored to the generated variant wrapper; do not rely on component CSS scoping for preview rules.',+ ],+ forbidden: [+ 'Do not use @scope for this styleMode.',+ ],+ };+ }+ return {+ mode: styleMode.mode,+ styleTag: styleMode.styleTag,+ strategy: 'scope-rule',+ rulePattern: '@scope ([data-impeccable-variant="N"]) { :scope > .variant-class { ... } }',+ selectorExamples: variantNumbers.map((n) => `@scope ([data-impeccable-variant="${n}"]) { :scope > .variant-class { ... } }`),+ requirements: [+ 'Use @scope blocks keyed to each [data-impeccable-variant="N"] wrapper.',+ 'Inside each @scope block, make :scope rules step into the replacement element with a descendant combinator.',+ 'Use the styleTag exactly; do not add framework-specific style attributes unless this object says to.',+ ],+ forbidden: [+ 'Do not use global [data-impeccable-variant="N"] selector prefixes for this styleMode.',+ 'Do not add is:inline to the style tag for this styleMode.',+ ],+ };+}+/*** Search project files for the query string (class name, ID, etc.)* Returns the first matching file path, or null.diff --git a/.cursor/skills/impeccable/scripts/live.mjs b/.cursor/skills/impeccable/scripts/live.mjsindex befbdb8ed..cafb0eca9 100644--- a/.cursor/skills/impeccable/scripts/live.mjs+++ b/.cursor/skills/impeccable/scripts/live.mjs@@ -2,10 +2,10 @@* CLI entry point: prepare everything needed to enter the live variant poll loop.** Does (all in one command):- * 1. Check config.json (returns config_missing if first-ever run)+ * 1. Check .impeccable/live/config.json (returns config_missing if first-ever run)* 2. Start the live server in the background (or reuse a running one)* 3. Inject the browser script tag into the project's entry file- * 4. Read .impeccable.md for design context (if present)+ * 4. Read PRODUCT.md / DESIGN.md for project context* 5. Print a single JSON blob with everything the agent needs** After this, the agent's only remaining steps are:@@ -23,9 +23,9 @@ import path from 'node:path';import { fileURLToPath } from 'node:url';import { loadContext } from './load-context.mjs';import { resolveFiles } from './live-inject.mjs';+import { readLiveServerInfo } from './impeccable-paths.mjs';const __dirname = path.dirname(fileURLToPath(import.meta.url));-const PID_FILE = path.join(process.cwd(), '.impeccable-live.json');async function liveCli() {const args = process.argv.slice(2);@@ -34,10 +34,10 @@ async function liveCli() {console.log(`Usage: node live.mjsPrepare everything for live variant mode in a single command:- - Checks scripts/config.json (required, created once per project)+ - Checks .impeccable/live/config.json (required, created once per project)- Starts (or reuses) the live server in the background- Injects the browser script tag- - Reads .impeccable.md for design context+ - Reads PRODUCT.md / DESIGN.md for project contextOn success, prints a JSON blob with:{ ok, serverPort, serverToken, pageFile, hasContext, context }@@ -223,7 +223,7 @@ function safeParse(out) {function ensureServerRunning() {// Try to reuse an existing servertry {- const existing = JSON.parse(fs.readFileSync(PID_FILE, 'utf-8'));+ const existing = readLiveServerInfo(process.cwd())?.info;if (existing && existing.pid) {try {process.kill(existing.pid, 0); // throws if deaddiff --git a/.cursor/skills/impeccable/scripts/load-context.mjs b/.cursor/skills/impeccable/scripts/load-context.mjsindex dca23c1f8..dc340bf16 100644--- a/.cursor/skills/impeccable/scripts/load-context.mjs+++ b/.cursor/skills/impeccable/scripts/load-context.mjs@@ -39,7 +39,7 @@ const LEGACY_NAMES = ['.impeccable.md'];const FALLBACK_DIRS = ['.agents/context', 'docs'];/**- * Resolve the directory that holds PRODUCT.md / DESIGN.md / DESIGN.json for+ * Resolve the directory that holds PRODUCT.md / DESIGN.md for* this project. Exported so other scripts (e.g. live-server.mjs) can read the* design files from the same location the loader uses.*/diff --git a/.gemini/skills/impeccable/reference/document.md b/.gemini/skills/impeccable/reference/document.mdindex c0a3c8c15..9dbd30435 100644--- a/.gemini/skills/impeccable/reference/document.md+++ b/.gemini/skills/impeccable/reference/document.md@@ -237,11 +237,11 @@ Concrete, forceful guardrails. Lead each with "Do" or "Don't". Be specific: incl- **Don't** [...]```-### Step 4b: Write DESIGN.json sidecar (extensions only)+### Step 4b: Write .impeccable/design.json sidecar (extensions only)-The frontmatter owns token primitives (colors, typography, rounded, spacing, components). The sidecar at `DESIGN.json` carries **what Stitch's schema can't hold**: tonal ramps per color, shadow/elevation tokens, motion tokens, breakpoints, full component HTML/CSS snippets (the panel renders these into a shadow DOM), and narrative (north star, rules, do's/don'ts). It extends the frontmatter, it doesn't duplicate it.+The frontmatter owns token primitives (colors, typography, rounded, spacing, components). The sidecar at `.impeccable/design.json` carries **what Stitch's schema can't hold**: tonal ramps per color, shadow/elevation tokens, motion tokens, breakpoints, full component HTML/CSS snippets (the panel renders these into a shadow DOM), and narrative (north star, rules, do's/don'ts). It extends the frontmatter, it doesn't duplicate it.-Regenerate the sidecar whenever you regenerate DESIGN.md. If the user only asks to refresh the sidecar (e.g., from the live panel's stale-hint), preserve DESIGN.md and write only DESIGN.json.+Regenerate the sidecar whenever you regenerate root `DESIGN.md`. If the user only asks to refresh the sidecar (e.g., from the live panel's stale-hint), preserve `DESIGN.md` and write only `.impeccable/design.json`.#### Schema@@ -310,7 +310,7 @@ Aim for a tight set of **5-10 components** that best represent the visual system- **Signature components (include if distinctive):** hero CTA, featured card, filter pill, any custom pattern the user mentioned as important in PRODUCT.md.- **Skip the rest.** Utility components, form building blocks, wrapper layouts: not worth documenting unless visually distinctive.-If the project has **no component library yet** (bare landing page, new project), synthesize canonical primitives from the tokens using best-practice defaults consistent with the DESIGN.md's rules. Every DESIGN.json has *something* to render, even on day zero.+If the project has **no component library yet** (bare landing page, new project), synthesize canonical primitives from the tokens using best-practice defaults consistent with the DESIGN.md's rules. Every `.impeccable/design.json` has *something* to render, even on day zero.#### Tonal ramps@@ -331,7 +331,7 @@ Do not reword. The panel shows these as secondary collapsible context; the same### Step 5: Confirm, refine, and refresh session cache1. Show the user the full DESIGN.md you wrote. Briefly highlight the non-obvious creative choices (descriptive color names, atmosphere language, named rules).-2. Mention that `DESIGN.json` was also written alongside; the live panel will now render this project's actual button/input/nav primitives instead of generic approximations.+2. Mention that `.impeccable/design.json` was also written alongside; the live panel will now render this project's actual button/input/nav primitives instead of generic approximations.3. Offer to refine any section: "Want me to revise a section, add component patterns I missed, or adjust the atmosphere language?"4. **Refresh the session cache.** Run `node .gemini/skills/impeccable/scripts/load-context.mjs` one final time so the newly-written DESIGN.md lands in conversation. Subsequent commands in this session will use the fresh version automatically without re-reading.@@ -392,7 +392,7 @@ Per-section guidance in seed mode:- **Components**: omit entirely; no components exist yet.- **Do's and Don'ts**: carry PRODUCT.md's anti-references directly plus the anti-reference named in Q5.-Seed mode writes a minimal frontmatter with `name` and `description` only; no colors, typography, rounded, spacing, or components yet. Real tokens land on the next Scan-mode run. Skip the `DESIGN.json` sidecar in seed mode for the same reason: nothing to render.+Seed mode writes a minimal frontmatter with `name` and `description` only; no colors, typography, rounded, spacing, or components yet. Real tokens land on the next Scan-mode run. Skip the `.impeccable/design.json` sidecar in seed mode for the same reason: nothing to render.### Step 4: Confirm and refresh session cachediff --git a/.gemini/skills/impeccable/reference/live.md b/.gemini/skills/impeccable/reference/live.mdindex f80d6a6b0..e7faeef72 100644--- a/.gemini/skills/impeccable/reference/live.md+++ b/.gemini/skills/impeccable/reference/live.md@@ -12,8 +12,9 @@ Execute in order. No step skipped, no step reordered.2. Navigate to the URL that serves `pageFile` (infer from `package.json`, docs, terminal output, or an open tab). If you can't infer it confidently, tell the user once to open their dev/preview URL. Never use `serverPort` as that URL; it's the helper, not the app.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=`.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.-5. On `accept` / `discard`: the poll script already cleaned up; just poll again.-6. On `exit`: run the cleanup at the bottom.+5. 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. If interrupted, run `live-status.mjs` or `live-resume.mjs` before guessing. The durable journal replays unacknowledged work after helper restart.+7. 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.@@ -43,13 +44,31 @@ LOOP:Read JSON; dispatch on "type""generate" → Handle Generate; reply done; LOOP- "accept" → Handle Accept; LOOP+ "accept" → Handle Accept; complete carbonize cleanup if required; LOOP"discard" → Handle Discard; LOOP"prefetch" → Handle Prefetch; LOOP"timeout" → LOOP"exit" → break → Cleanup```+## Recovery commands++The live helper persists an append-only journal under `.impeccable/live/sessions/`. Browser checkpoints are advisory but durable; the journal is canonical. This is local durable recovery state, not project source.++Use these commands when the chat was interrupted, polling was missed, the helper restarted, or the browser reloaded:++```bash+node .gemini/skills/impeccable/scripts/live-status.mjs+node .gemini/skills/impeccable/scripts/live-resume.mjs --id SESSION_ID+node .gemini/skills/impeccable/scripts/live-complete.mjs --id SESSION_ID+```++- `live-status.mjs` prints connected helper state, active durable sessions, and queued pending events. It works even when the helper is down by reading the journal directly.+- `live-resume.mjs` prints the active snapshot, pending event, checkpoint phase, visible variant, parameter values, and the next safe agent action.+- `live-complete.mjs` is the canonical manual final acknowledgement. Use it after carbonize/manual cleanup is verified and no further poll acknowledgement will happen automatically.++Server restart rule: start `live-server.mjs` again, then poll. Startup requeues unacknowledged pending events from the journal, so do not ask the user to click Go again unless `live-resume.mjs` says no active session exists.+## Handle `generate`Event: `{id, action, freeformPrompt?, count, pageUrl, element, screenshotPath?, comments?, strokes?}`.@@ -88,7 +107,14 @@ The helper searches ID first, then classes, then tag + class combo. If `event.paIf `--text` matches multiple candidates equally well, wrap exits with `{ error: "element_ambiguous", candidates: [...] }` and `fallback: "agent-driven"`: read the candidate line ranges, decide which one matches the picked element from page context, and write the wrapper manually per the fallback flow.-Output on success: `{ file, insertLine, commentSyntax }`.+Output on success: `{ file, insertLine, commentSyntax, styleMode, styleTag, cssSelectorPrefixExamples, cssAuthoring }`.++`styleMode` controls how preview CSS must be authored. Treat it as a detected capability mode, not a framework guess:++- `scoped`: use `@scope ([data-impeccable-variant="N"])` rules.+- `astro-global-prefixed`: use explicit `[data-impeccable-variant="N"]` selector prefixes and the exact `styleTag` returned by the tool.++Use `cssAuthoring` as the source of truth for the current file. It includes the exact `styleTag`, selector strategy, selector examples, requirements, and forbidden patterns. Do not apply a framework-specific exception unless the returned `styleMode` / `cssAuthoring.mode` says to.**Fallback errors.** Wrap only writes into files it judges to be source (tracked by git, not marked GENERATED, not listed in config's `generatedFiles`). If it can't land on a source file, it errors without writing; accepting a variant into a generated file is silent data loss. Three shapes:@@ -208,13 +234,14 @@ When the prompt and PRODUCT.md anti-references conflict (the prompt asks for X,Complete 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 scoped 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).+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).++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:```html<!-- Variants: insert below this line --><style data-impeccable-css="SESSION_ID">- @scope ([data-impeccable-variant="1"]) { ... }- @scope ([data-impeccable-variant="2"]) { ... }+ /* rules matching cssAuthoring.rulePattern */</style><div data-impeccable-variant="1"><!-- variant 1: full element replacement (single top-level element) -->@@ -229,11 +256,11 @@ Write CSS + all variants in ONE edit at the `insertLine` reported by `wrap`. Col**Each variant div contains exactly one top-level element: the full replacement for the original.** Use the same tag as the original (e.g. `<section>` if the user picked a `<section>`). Loose siblings (heading + paragraph + div as direct children of the variant div) break the outline tracking and the accept flow, which both assume one child.-The first variant has no `display: none` (visible by default). All others do. If variants use only inline styles and no scoped CSS, omit the `<style>` tag entirely. Use `@scope` for CSS isolation (Chrome 118+ / Firefox 128+ / Safari 17.4+).+The 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.-**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 rule starts `:scope > ...`.+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 > ...`.**JSX / TSX target files.** Wrap `<style>` content in a template literal so the CSS `{` / `}` aren't parsed as JSX expressions, and use `className=` / `style={{…}}` on every variant element. Keep `data-impeccable-*` attributes as-is; they're plain strings:@@ -369,10 +396,11 @@ Remove the wrapper you inserted in Step 2. Nothing else to do.## Handle `accept`-Event: `{id, variantId, _acceptResult}`. The poll script already ran `live-accept.mjs` to handle the file operation deterministically; the browser DOM is already updated.+Event: `{id, variantId, _acceptResult, _completionAck}`. The poll script already ran `live-accept.mjs` to handle the file operation deterministically, then acknowledged event delivery to the helper. The browser DOM is already updated.+- `_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 and a stderr banner both list the steps explicitly; neither is decorative.+- `_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: 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` without `mode`: manual cleanup: read file, find markers, edit.@@ -388,13 +416,13 @@ Do these five steps in the current thread, synchronously, before the next poll.4. **Unwrap the accepted content.** Delete the `<div data-impeccable-variant="N" style="display: contents">` that wraps it. Drop `data-impeccable-params` and any `data-p-*` attributes from it; 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.-Then poll again.+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.## Handle `discard`-Event: `{id, _acceptResult}`. The poll script already restored the original and removed all variant markers. Nothing to do. Poll again.+Event: `{id, _acceptResult, _completionAck}`. The poll script already restored the original, removed all variant markers, and acknowledged `discarded` durable completion. Nothing to do unless `_completionAck.ok !== true`; in that case run `live-complete.mjs --id EVENT_ID --discarded`, then poll again.## Handle `prefetch`@@ -424,7 +452,7 @@ When the poll returns `exit`, proceed to cleanup. If the poll is still running anode .gemini/skills/impeccable/scripts/live-server.mjs stop```-Stops the HTTP server and runs `live-inject.mjs --remove` to strip `localhost:…/live.js` from the HTML entry. To stop the server but keep the inject tag (for a quick restart), use `stop --keep-inject`. `config.json` persists for future sessions.+Stops the HTTP server and runs `live-inject.mjs --remove` to strip `localhost:…/live.js` from the HTML entry. To stop the server but keep the inject tag (for a quick restart), use `stop --keep-inject`. `.impeccable/live/config.json` persists as project config for future sessions.Then:- Remove any leftover variant wrappers (search for `impeccable-variants-start` markers).@@ -432,7 +460,7 @@ Then:## First-time setup (config missing or invalid)-If `live.mjs` outputs `{ ok: false, error: "config_missing" | "config_invalid", path }`, write `config.json` at the reported path.+If `live.mjs` outputs `{ ok: false, error: "config_missing" | "config_invalid", path }`, write the live config at the reported path. By default this is `.impeccable/live/config.json`.Schema:@@ -512,7 +540,7 @@ node .gemini/skills/impeccable/scripts/detect-csp.mjsOutput: `{ shape, signals }` where `shape` is one of `append-arrays`, `append-string`, `middleware`, `meta-tag`, or `null`. The shape is named by *patch mechanism*, so one template covers many frameworks.-- **`null`**: no CSP; skip to writing `config.json` with `cspChecked: true`.+- **`null`**: no CSP; skip to writing `.impeccable/live/config.json` with `cspChecked: true`.- **`append-arrays`**: CSP defined as structured directive arrays. Auto-patchable. See *append-arrays* below. Covers:- Monorepo helpers with `additionalScriptSrc` / `additionalConnectSrc` options (Next.js + shared config package)- SvelteKit `kit.csp.directives`@@ -589,6 +617,6 @@ Reference outputs:### Troubleshooting-If a user says "no" to the CSP patch at setup time and later complains that live doesn't work: their dev CSP blocks `http://localhost:8400`. Fix: delete `cspChecked` from `config.json` and re-run `live.mjs`: setup will ask again.+If a user says "no" to the CSP patch at setup time and later complains that live doesn't work: their dev CSP blocks `http://localhost:8400`. Fix: delete `cspChecked` from `.impeccable/live/config.json` and re-run `live.mjs`: setup will ask again.Then re-run `live.mjs`.diff --git a/.gemini/skills/impeccable/reference/teach.md b/.gemini/skills/impeccable/reference/teach.mdindex 78ccd9fd4..4857a9b1c 100644--- a/.gemini/skills/impeccable/reference/teach.md+++ b/.gemini/skills/impeccable/reference/teach.md@@ -2,8 +2,8 @@Gathers design context for a project and writes two complementary files at the project root:-- **PRODUCT.md** (strategic): register, target users, product purpose, brand personality, anti-references, strategic design principles. Answers "who/what/why".-- **DESIGN.md** (visual): visual theme, color palette, typography, components, layout. Follows the [Google Stitch DESIGN.md format](https://stitch.withgoogle.com/docs/design-md/format/). Answers "how it looks".+- **PRODUCT.md** (strategic): root project file for register, target users, product purpose, brand personality, anti-references, strategic design principles. Answers "who/what/why".+- **DESIGN.md** (visual): root project file for visual theme, color palette, typography, components, layout. Follows the [Google Stitch DESIGN.md format](https://stitch.withgoogle.com/docs/design-md/format/). Answers "how it looks".Every other impeccable command reads these files before doing any work.diff --git a/.gemini/skills/impeccable/scripts/impeccable-paths.mjs b/.gemini/skills/impeccable/scripts/impeccable-paths.mjsnew file mode 100644index 000000000..ba852bae9--- /dev/null+++ b/.gemini/skills/impeccable/scripts/impeccable-paths.mjs@@ -0,0 +1,105 @@+import fs from 'node:fs';+import path from 'node:path';++export const IMPECCABLE_DIR = '.impeccable';+export const LIVE_DIR = 'live';++export function getImpeccableDir(cwd = process.cwd()) {+ return path.join(cwd, IMPECCABLE_DIR);+}++export function getDesignSidecarPath(cwd = process.cwd()) {+ return path.join(getImpeccableDir(cwd), 'design.json');+}++export function getDesignSidecarCandidates(cwd = process.cwd(), contextDir = cwd) {+ const candidates = [+ getDesignSidecarPath(cwd),+ path.join(cwd, 'DESIGN.json'),+ ];+ const contextLegacy = path.join(contextDir, 'DESIGN.json');+ if (!candidates.includes(contextLegacy)) candidates.push(contextLegacy);+ return candidates;+}++export function resolveDesignSidecarPath(cwd = process.cwd(), contextDir = cwd) {+ return firstExisting(getDesignSidecarCandidates(cwd, contextDir));+}++export function getLiveDir(cwd = process.cwd()) {+ return path.join(getImpeccableDir(cwd), LIVE_DIR);+}++export function getLiveConfigPath(cwd = process.cwd()) {+ return path.join(getLiveDir(cwd), 'config.json');+}++export function getLegacyLiveConfigPath(scriptsDir) {+ return path.join(scriptsDir, 'config.json');+}++export function resolveLiveConfigPath({ cwd = process.cwd(), scriptsDir, env = process.env } = {}) {+ if (env.IMPECCABLE_LIVE_CONFIG && env.IMPECCABLE_LIVE_CONFIG.trim()) {+ const configured = env.IMPECCABLE_LIVE_CONFIG.trim();+ return path.isAbsolute(configured) ? configured : path.resolve(cwd, configured);+ }+ const primary = getLiveConfigPath(cwd);+ if (fs.existsSync(primary)) return primary;+ if (scriptsDir) {+ const legacy = getLegacyLiveConfigPath(scriptsDir);+ if (fs.existsSync(legacy)) return legacy;+ }+ return primary;+}++export function getLiveServerPath(cwd = process.cwd()) {+ return path.join(getLiveDir(cwd), 'server.json');+}++export function getLegacyLiveServerPath(cwd = process.cwd()) {+ return path.join(cwd, '.impeccable-live.json');+}++export function readLiveServerInfo(cwd = process.cwd()) {+ for (const filePath of [getLiveServerPath(cwd), getLegacyLiveServerPath(cwd)]) {+ try {+ return { info: JSON.parse(fs.readFileSync(filePath, 'utf-8')), path: filePath };+ } catch {+ /* try next */+ }+ }+ return null;+}++export function writeLiveServerInfo(cwd = process.cwd(), info) {+ const filePath = getLiveServerPath(cwd);+ fs.mkdirSync(path.dirname(filePath), { recursive: true });+ fs.writeFileSync(filePath, JSON.stringify(info));+ return filePath;+}++export function removeLiveServerInfo(cwd = process.cwd()) {+ for (const filePath of [getLiveServerPath(cwd), getLegacyLiveServerPath(cwd)]) {+ try { fs.unlinkSync(filePath); } catch {}+ }+}++export function getLiveSessionsDir(cwd = process.cwd()) {+ return path.join(getLiveDir(cwd), 'sessions');+}++export function getLegacyLiveSessionsDir(cwd = process.cwd()) {+ return path.join(cwd, '.impeccable-live', 'sessions');+}++export function getLiveAnnotationsDir(cwd = process.cwd()) {+ return path.join(getLiveDir(cwd), 'annotations');+}++export function getLegacyLiveAnnotationsDir(cwd = process.cwd()) {+ return path.join(cwd, '.impeccable-live', 'annotations');+}++function firstExisting(paths) {+ return paths.find((filePath) => fs.existsSync(filePath)) || null;+}diff --git a/.gemini/skills/impeccable/scripts/live-browser-session.js b/.gemini/skills/impeccable/scripts/live-browser-session.jsnew file mode 100644index 000000000..0e362d6be--- /dev/null+++ b/.gemini/skills/impeccable/scripts/live-browser-session.js@@ -0,0 +1,123 @@+/**+ * Browser-side durable session helpers for Impeccable live mode.+ *+ * Kept separate from live-browser.js so recovery state can be tested without+ * booting the full overlay UI. Served before live-browser.js and attached to+ * window.__IMPECCABLE_LIVE_SESSION__.+ */+(function (root) {+ 'use strict';++ function createLiveBrowserSessionState({ prefix, storage, idFactory }) {+ if (!prefix) throw new Error('prefix required');+ const store = storage || root.localStorage;+ const makeId = idFactory || function () { return Math.random().toString(16).slice(2, 10); };+ const sessionKey = prefix + '-session';+ const handledKey = sessionKey + '-handled';+ const scrollKey = sessionKey + '-scroll';+ let checkpointRevision = 0;+ const owner = makeId();++ function safeRead(key) {+ try { return store.getItem(key); } catch { return null; }+ }++ function safeWrite(key, value) {+ try { store.setItem(key, value); } catch { /* quota exceeded or private mode */ }+ }++ function safeRemove(key) {+ try { store.removeItem(key); } catch { /* unavailable storage */ }+ }++ function loadSession() {+ try {+ const raw = safeRead(sessionKey);+ if (!raw) return null;+ const parsed = JSON.parse(raw);+ if (Number.isInteger(parsed.checkpointRevision)) {+ checkpointRevision = Math.max(checkpointRevision, parsed.checkpointRevision);+ }+ return parsed;+ } catch { return null; }+ }++ function saveSession(session) {+ if (!session || !session.id) return;+ const payload = {+ ...session,+ checkpointRevision,+ };+ safeWrite(sessionKey, JSON.stringify(payload));+ }++ function clearSession() {+ safeRemove(sessionKey);+ }++ function nextCheckpointRevision() {+ checkpointRevision += 1;+ const existing = loadSession();+ if (existing?.id) saveSession(existing);+ return checkpointRevision;+ }++ function seedCheckpointRevision(value) {+ if (Number.isInteger(value)) checkpointRevision = Math.max(checkpointRevision, value);+ return checkpointRevision;+ }++ function currentCheckpointRevision() {+ return checkpointRevision;+ }++ function markHandled(id) {+ if (!id) return;+ safeWrite(handledKey, id);+ }++ function isHandled(id) {+ return !!id && safeRead(handledKey) === id;+ }++ function clearHandled() {+ safeRemove(handledKey);+ }++ function writeScrollY(y) {+ safeWrite(scrollKey, String(y));+ }++ function readScrollY() {+ const raw = safeRead(scrollKey);+ if (raw == null) return null;+ const n = parseFloat(raw);+ return isFinite(n) ? n : null;+ }++ function clearScrollY() {+ safeRemove(scrollKey);+ }++ return {+ owner,+ sessionKey,+ handledKey,+ scrollKey,+ saveSession,+ loadSession,+ clearSession,+ nextCheckpointRevision,+ seedCheckpointRevision,+ currentCheckpointRevision,+ markHandled,+ isHandled,+ clearHandled,+ writeScrollY,+ readScrollY,+ clearScrollY,+ };+ }++ root.__IMPECCABLE_LIVE_SESSION__ = { createLiveBrowserSessionState };+})(typeof window !== 'undefined' ? window : globalThis);diff --git a/.gemini/skills/impeccable/scripts/live-browser.js b/.gemini/skills/impeccable/scripts/live-browser.jsindex 3da76bb96..e67cd01ed 100644--- a/.gemini/skills/impeccable/scripts/live-browser.js+++ b/.gemini/skills/impeccable/scripts/live-browser.js@@ -50,6 +50,16 @@const Z = { highlight: 100001, bar: 100005, picker: 100007, toast: 100010 };const EASE = 'cubic-bezier(0.22, 1, 0.36, 1)'; // ease-out-quintconst PREFIX = 'impeccable-live';+ const sessionState = window.__IMPECCABLE_LIVE_SESSION__?.createLiveBrowserSessionState({+ prefix: PREFIX,+ storage: localStorage,+ idFactory: () => crypto.randomUUID().replace(/-/g, '').slice(0, 8),+ });+ if (!sessionState) {+ console.error('[impeccable] live-browser-session.js was not loaded. Live mode cannot start safely.');+ window.__IMPECCABLE_LIVE_INIT__ = false;+ return;+ }const HIGHLIGHT_TRANSITION ='top 140ms ' + EASE +', left 140ms ' + EASE +@@ -112,6 +122,8 @@let hasProjectContext = false;let selectedAction = 'impeccable';let selectedCount = 3;+ const browserOwner = sessionState.owner;+ let checkpointTimer = null;// Scroll lock — holds window.scrollY at a fixed value while the session is// active, so HMR DOM patches and variant swaps can't drift the page. See@@ -126,21 +138,9 @@// (Previously: saveSession wrote scrollY alongside state, so every call// during resume overwrote the pre-reload value with whatever the browser// had landed on, typically 0.)- const SCROLL_KEY_SUFFIX = '-scroll';- function writeScrollY(y) {- try { localStorage.setItem(LS_KEY + SCROLL_KEY_SUFFIX, String(y)); } catch {}- }- function readScrollY() {- try {- const raw = localStorage.getItem(LS_KEY + SCROLL_KEY_SUFFIX);- if (raw == null) return null;- const n = parseFloat(raw);- return isFinite(n) ? n : null;- } catch { return null; }- }- function clearScrollY() {- try { localStorage.removeItem(LS_KEY + SCROLL_KEY_SUFFIX); } catch {}- }+ function writeScrollY(y) { sessionState.writeScrollY(y); }+ function readScrollY() { return sessionState.readScrollY(); }+ function clearScrollY() { sessionState.clearScrollY(); }// Pre-empt the browser: apply manual scroll restoration and jump to the// saved scrollY at script-parse time. Retries on fonts.ready and load@@ -1585,6 +1585,7 @@paramsCurrentValues[p.id] = v;readout.textContent = formatRangeValue(input);applyParamValue(variantEl, p, v);+ queueCheckpoint('param_changed');});row.appendChild(input);} else if (p.kind === 'toggle') {@@ -1615,6 +1616,7 @@knob.style.left = next ? '18px' : '2px';readout.textContent = next ? 'On' : 'Off';applyParamValue(variantEl, p, next);+ queueCheckpoint('param_changed');});row.appendChild(track);} else if (p.kind === 'steps') {@@ -1651,6 +1653,7 @@btn.style.color = on ? 'oklch(98% 0 0)' : P.text;});applyParamValue(variantEl, p, o.value);+ queueCheckpoint('param_changed');});segRow.appendChild(b);segBtns.push({ btn: b, val: o.value });@@ -1872,19 +1875,26 @@return;}+ const previousVisibleVariant = currentSessionId === sessionId ? visibleVariant : 0;+// Replace the live element with the full wrapper from sourceconst wrapper = srcWrapper.cloneNode(true);liveEl.parentElement.replaceChild(wrapper, liveEl);- // Update state: count variants, show the first one+ // Update state: count variants, preserving the user's current variant+ // when a late HMR/source reinjection lands after they have cycled.const variants = wrapper.querySelectorAll('[data-impeccable-variant]:not([data-impeccable-variant="original"])');arrivedVariants = variants.length;expectedVariants = parseInt(wrapper.dataset.impeccableVariantCount || arrivedVariants);- visibleVariant = 1;- showVariantInDOM(sessionId, 1);+ const saved = loadSession();+ const savedVisibleVariant = saved && saved.id === sessionId ? saved.visible : 0;+ visibleVariant = previousVisibleVariant > 0 && previousVisibleVariant <= arrivedVariants+ ? previousVisibleVariant+ : (savedVisibleVariant > 0 && savedVisibleVariant <= arrivedVariants ? savedVisibleVariant : 1);+ showVariantInDOM(sessionId, visibleVariant);// Update selectedElement to the visible variant's content- selectedElement = pickVariantContent(wrapper, 1) || wrapper.parentElement;+ selectedElement = pickVariantContent(wrapper, visibleVariant) || wrapper.parentElement;state = 'CYCLING';hideShaderOverlay();@@ -1907,6 +1917,7 @@updateSelectedElement();updateBarContent('cycling');saveSession();+ queueCheckpoint('variant_changed');}function updateSelectedElement() {@@ -1917,6 +1928,18 @@if (visEl) selectedElement = visEl;}+ function readVisibleVariantFromDOM(sessionId) {+ const wrapper = document.querySelector('[data-impeccable-variants="' + sessionId + '"]');+ if (!wrapper) return 0;+ const variants = wrapper.querySelectorAll('[data-impeccable-variant]:not([data-impeccable-variant="original"])');+ for (const variant of variants) {+ if (variant.style.display === 'none') continue;+ const idx = parseInt(variant.dataset.impeccableVariant || '0', 10);+ if (idx > 0) return idx;+ }+ return 0;+ }+// Resolve the element that represents the variant's visible content.// Contract: each variant div should contain exactly one top-level element// (the full replacement). In practice a model may ship loose siblings or@@ -2107,8 +2130,10 @@updating = true;arrivedVariants = count;if (visibleVariant === 0 && arrivedVariants > 0) {- visibleVariant = 1;- showVariantInDOM(sessionId, 1);+ const saved = loadSession();+ const savedVisibleVariant = saved && saved.id === sessionId ? saved.visible : 0;+ visibleVariant = savedVisibleVariant > 0 && savedVisibleVariant <= arrivedVariants ? savedVisibleVariant : 1;+ showVariantInDOM(sessionId, visibleVariant);// showVariantInDOM hid the original (display:none); if we were still// anchored to the original's content, its boundingRect is now zero// and the bar snaps to (0,0). Re-point at the visible variant instead.@@ -2128,6 +2153,7 @@updateBarContent('generating');}saveSession();+ queueCheckpoint(state === 'CYCLING' ? 'variants_ready' : 'variants_progress');updating = false;});@@ -2236,6 +2262,7 @@/** Server died or became unreachable. Reset UI to a clean state. */function handleServerLost() {+ const recoveryState = currentSessionId ? state : 'IDLE';if (state === 'GENERATING' || state === 'CYCLING' || state === 'SAVING') {showToast('Live server disconnected. Session ended.', 5000);}@@ -2246,21 +2273,61 @@stopScrollTracking();if (variantObserver) { variantObserver.disconnect(); variantObserver = null; }stopScrollLock();- clearScrollY();- clearSession();+ // Preserve local session state on server loss. The durable journal is the+ // source of truth, but localStorage plus the variant wrapper lets the UI+ // resume after a helper restart or page reload instead of treating a+ // transient disconnect as an explicit discard.selectedElement = null;- currentSessionId = null;selectedAction = 'impeccable';- state = 'IDLE';+ state = recoveryState;+ if (currentSessionId) saveSession();}- function sendEvent(msg) {+ function sendEvent(msg, opts) {msg.token = TOKEN;- fetch('http://localhost:' + PORT + '/events', {+ function handleFailure(err) {+ console.error('[impeccable] Failed to send event:', err);+ if (opts && opts.throwOnError) throw err;+ return null;+ }+ return fetch('http://localhost:' + PORT + '/events', {method: 'POST',headers: { 'Content-Type': 'application/json' },body: JSON.stringify(msg),- }).catch(err => console.error('[impeccable] Failed to send event:', err));+ }).then(res => {+ if (res.ok) return res;+ return handleFailure(new Error('HTTP ' + res.status + ' ' + res.statusText));+ }).catch(handleFailure);+ }++ function checkpointPayload(reason) {+ return {+ type: 'checkpoint',+ id: currentSessionId,+ revision: sessionState.nextCheckpointRevision(),+ owner: browserOwner,+ phase: String(state || '').toLowerCase(),+ reason,+ pageUrl: location.pathname,+ expectedVariants,+ arrivedVariants,+ visibleVariant,+ paramValues: { ...paramsCurrentValues },+ };+ }++ function sendCheckpoint(reason) {+ if (!currentSessionId) return Promise.resolve(null);+ return sendEvent(checkpointPayload(reason)).catch(() => null);+ }++ function queueCheckpoint(reason) {+ if (!currentSessionId) return;+ if (checkpointTimer) clearTimeout(checkpointTimer);+ checkpointTimer = setTimeout(() => {+ checkpointTimer = null;+ sendCheckpoint(reason);+ }, 120);}// ---------------------------------------------------------------------------@@ -2496,6 +2563,7 @@state = 'GENERATING';showBar('generating');saveSession();+ sendCheckpoint('generate_started');writeScrollY(window.scrollY);if (variantObserver) variantObserver.disconnect();variantObserver = startVariantObserver(currentSessionId);@@ -2920,13 +2988,12 @@ void main() {function handleAccept() {if (!currentSessionId || arrivedVariants === 0) return;+ const domVisibleVariant = readVisibleVariantFromDOM(currentSessionId);+ if (domVisibleVariant > 0) visibleVariant = domVisibleVariant;const acceptPayload = { type: 'accept', id: currentSessionId, variantId: String(visibleVariant) };if (Object.keys(paramsCurrentValues).length > 0) {acceptPayload.paramValues = { ...paramsCurrentValues };}- sendEvent(acceptPayload);- markSessionHandled();-// The accepted variant is already the only visible child of the wrapper// (all other variants are display:none). HMR from the source rewrite will// replace the wrapper imminently. Don't eagerly replaceChild here — React@@ -2936,9 +3003,28 @@ void main() {const acceptedSessionId = currentSessionId;const acceptedVariant = visibleVariant;- state = 'CONFIRMED';- updateBarContent('confirmed');- setTimeout(function() {+ state = 'SAVING';+ updateBarContent('saving');++ sendEvent(acceptPayload, { throwOnError: true })+ .then(() => {+ markSessionHandled();+ confirmAcceptAfterReceipt();+ })+ .catch(() => {+ state = 'CYCLING';+ updateBarContent('cycling');+ showToast('Could not confirm accept with the live server. Session kept for recovery; try Accept again.', 5000);+ });++ function confirmAcceptAfterReceipt() {+ state = 'CONFIRMED';+ updateBarContent('confirmed');+ scheduleAcceptCleanup();+ }++ function scheduleAcceptCleanup() {+ setTimeout(function() {hideBar();hideHighlight();stopScrollTracking();@@ -2967,50 +3053,46 @@ void main() {accepted.style.display = 'contents';parent.replaceChild(accepted, wrapper);}- }, 2000);+ }, 2000);+ }}function handleDiscard() {if (!currentSessionId) return;- sendEvent({ type: 'discard', id: currentSessionId });- markSessionHandled();- // Instant DOM restore + fire-and-forget (script handles file cleanup)- cleanup();+ sendEvent({ type: 'discard', id: currentSessionId }, { throwOnError: true })+ .then(() => {+ markSessionHandled();+ cleanup();+ })+ .catch(() => showToast('Could not confirm discard with the live server. Session kept for recovery.', 5000));}// ---------------------------------------------------------------------------- // Session persistence via localStorage+ // Session persistence via live-browser-session.js// ---------------------------------------------------------------------------// Survives page reloads, browser close/reopen, HMR, and accidental refreshes.- const LS_KEY = PREFIX + '-session';-function saveSession() {if (!currentSessionId) return;// NOTE: scrollY is stored under a separate key (writeScrollY). Storing// it here would overwrite the Go-time value every time state changes.- try {- localStorage.setItem(LS_KEY, JSON.stringify({- id: currentSessionId,- state: state,- action: selectedAction,- count: selectedCount,- expected: expectedVariants,- arrived: arrivedVariants,- visible: visibleVariant,- }));- } catch { /* quota exceeded or private mode */ }+ sessionState.saveSession({+ id: currentSessionId,+ state,+ action: selectedAction,+ count: selectedCount,+ expected: expectedVariants,+ arrived: arrivedVariants,+ visible: visibleVariant,+ });}function loadSession() {- try {- const raw = localStorage.getItem(LS_KEY);- return raw ? JSON.parse(raw) : null;- } catch { return null; }+ return sessionState.loadSession();}function clearSession() {- try { localStorage.removeItem(LS_KEY); } catch {}+ sessionState.clearSession();}/** Mark session as handled (accepted/discarded). The agent will clean up@@ -3018,19 +3100,15 @@ void main() {* prevents resumeSession from picking it up again after reload. */function markSessionHandled() {if (!currentSessionId) return;- try {- localStorage.setItem(LS_KEY + '-handled', currentSessionId);- } catch {}+ sessionState.markHandled(currentSessionId);}function isSessionHandled(id) {- try {- return localStorage.getItem(LS_KEY + '-handled') === id;- } catch { return false; }+ return sessionState.isHandled(id);}function clearHandled() {- try { localStorage.removeItem(LS_KEY + '-handled'); } catch {}+ sessionState.clearHandled();}function cleanup() {@@ -3161,6 +3239,7 @@ void main() {// hid. Now that state is CYCLING, re-fire.if (state === 'CYCLING') refreshParamsPanel();saveSession();+ queueCheckpoint('browser_resumed');// Start observing for more variants AFTER initial setupif (variantObserver) variantObserver.disconnect();@@ -3617,7 +3696,7 @@ void main() {}// ---------------------------------------------------------------------------- // Design System Panel — visualizes the project's DESIGN.json sidecar+ // Design System Panel — visualizes the project's .impeccable/design.json sidecar// ---------------------------------------------------------------------------const DESIGN_PREFS_KEY = 'impeccable-live-design-panel';@@ -3629,7 +3708,7 @@ void main() {open: false,tab: 'visual', // 'visual' | 'raw'parsed: null, // parseDesignMd output (frontmatter + body sections)- sidecar: null, // DESIGN.json v2 payload (extensions + components + narrative)+ sidecar: null, // .impeccable/design.json v2 payload (extensions + components + narrative)hasMd: false,hasSidecar: false,present: null, // true/false once fetch resolves@@ -4130,7 +4209,7 @@ void main() {box.className = 'stale';box.innerHTML = `<span class="stale-dot"></span>- <span class="stale-text"><strong>DESIGN.md is newer than DESIGN.json.</strong> Run <code>/impeccable document</code> to refresh the sidecar.</span>+ <span class="stale-text"><strong>DESIGN.md is newer than .impeccable/design.json.</strong> Run <code>/impeccable document</code> to refresh the sidecar.</span>`;return box;}@@ -4138,7 +4217,7 @@ void main() {function renderParsedMdCta() {const box = document.createElement('div');box.className = 'parsed-md-cta';- box.innerHTML = `<strong>Basic view</strong>This panel reads the tokens in your <code>DESIGN.md</code> frontmatter. Running <code>/impeccable document</code> also generates a <code>DESIGN.json</code> sidecar with your project's actual component snippets (button, input, nav) and tonal ramps, rendered live below the tokens.`;+ box.innerHTML = `<strong>Basic view</strong>This panel reads the tokens in your <code>DESIGN.md</code> frontmatter. Running <code>/impeccable document</code> also generates a <code>.impeccable/design.json</code> sidecar with your project's actual component snippets (button, input, nav) and tonal ramps, rendered live below the tokens.`;return box;}@@ -4598,7 +4677,7 @@ void main() {function cssSafe(v) {// Strip anything outside valid CSS value chars to prevent injection via- // DESIGN.json values rendered into inline style strings.+ // .impeccable/design.json values rendered into inline style strings.return String(v).replace(/[<>"'`\n]/g, '');}diff --git a/.gemini/skills/impeccable/scripts/live-complete.mjs b/.gemini/skills/impeccable/scripts/live-complete.mjsnew file mode 100644index 000000000..78155af85--- /dev/null+++ b/.gemini/skills/impeccable/scripts/live-complete.mjs@@ -0,0 +1,75 @@+#!/usr/bin/env node+/**+ * Canonical durable completion acknowledgement for Impeccable live sessions.+ */++import { createLiveSessionStore } from './live-session-store.mjs';+import { readLiveServerInfo } from './impeccable-paths.mjs';++function parseArgs(argv) {+ const out = { status: 'complete' };+ for (let i = 0; i < argv.length; i++) {+ const arg = argv[i];+ if (arg === '--id') out.id = argv[++i];+ else if (arg.startsWith('--id=')) out.id = arg.slice('--id='.length);+ else if (arg === '--discarded' || arg === '--discard') out.status = 'discarded';+ else if (arg === '--error') { out.status = 'agent_error'; out.message = argv[++i] || 'unknown error'; }+ else if (arg.startsWith('--error=')) { out.status = 'agent_error'; out.message = arg.slice('--error='.length); }+ else if (arg === '--help' || arg === '-h') out.help = true;+ }+ return out;+}++export async function completeCli() {+ const args = parseArgs(process.argv.slice(2));+ if (args.help || !args.id) {+ console.log(`Usage: node live-complete.mjs --id SESSION_ID [--discarded|--error MESSAGE]\n\nAppend the final durable session acknowledgement. Use after accept/discard cleanup is verified.`);+ process.exit(args.help ? 0 : 1);+ }++ const serverInfo = readServerInfo();+ const serverResult = serverInfo ? await completeThroughServer(serverInfo, args) : null;+ if (serverResult?.ok) {+ const store = createLiveSessionStore({ cwd: process.cwd(), sessionId: args.id });+ const snapshot = store.getSnapshot(args.id, { includeCompleted: true });+ console.log(JSON.stringify({ ok: true, id: args.id, phase: snapshot?.phase || args.status, snapshot }, null, 2));+ return;+ }++ const store = createLiveSessionStore({ cwd: process.cwd(), sessionId: args.id });+ const event = args.status === 'discarded'+ ? { type: 'discarded', id: args.id }+ : args.status === 'agent_error'+ ? { type: 'agent_error', id: args.id, message: args.message || 'unknown error' }+ : { type: 'complete', id: args.id };+ const snapshot = store.appendEvent(event);+ console.log(JSON.stringify({ ok: true, id: args.id, phase: snapshot.phase, snapshot }, null, 2));+}++function readServerInfo() {+ return readLiveServerInfo(process.cwd())?.info || null;+}++async function completeThroughServer(info, args) {+ const type = args.status === 'discarded'+ ? 'discarded'+ : args.status === 'agent_error'+ ? 'error'+ : 'complete';+ try {+ const res = await fetch(`http://localhost:${info.port}/poll`, {+ method: 'POST',+ headers: { 'Content-Type': 'application/json' },+ body: JSON.stringify({ token: info.token, id: args.id, type, message: args.message }),+ });+ if (!res.ok) return null;+ return await res.json();+ } catch {+ return null;+ }+}++const _running = process.argv[1];+if (_running?.endsWith('live-complete.mjs') || _running?.endsWith('live-complete.mjs/')) {+ completeCli();+}diff --git a/.gemini/skills/impeccable/scripts/live-completion.mjs b/.gemini/skills/impeccable/scripts/live-completion.mjsnew file mode 100644index 000000000..86b637fff--- /dev/null+++ b/.gemini/skills/impeccable/scripts/live-completion.mjs@@ -0,0 +1,18 @@+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';+ return 'agent_done';+}++export function completionAckForAcceptResult(eventId, completionType, acceptResult) {+ const ack = { ok: true, type: completionType };+ if (acceptResult?.handled === true && acceptResult?.carbonize === true) {+ ack.final = false;+ ack.requiresComplete = true;+ ack.nextCommand = `live-complete.mjs --id ${eventId}`;+ ack.message = 'Carbonize cleanup must be verified, then the session must be completed explicitly before polling again.';+ }+ return ack;+}diff --git a/.gemini/skills/impeccable/scripts/live-inject.mjs b/.gemini/skills/impeccable/scripts/live-inject.mjsindex 1d2ae12f7..555c3a36a 100644--- a/.gemini/skills/impeccable/scripts/live-inject.mjs+++ b/.gemini/skills/impeccable/scripts/live-inject.mjs@@ -2,23 +2,24 @@* CLI helper: insert/remove the live variant mode script tag in the project's* main HTML entry point.*- * On first live run, the agent generates `config.json` in this script's- * directory with the project's insertion target (framework-specific). On+ * On first live run, the agent generates `.impeccable/live/config.json`+ * with the project's insertion target (framework-specific). On* every subsequent run, this script handles insert/remove deterministically* with zero LLM involvement.** Usage:* node live-inject.mjs --port PORT # Insert the live script tag* node live-inject.mjs --remove # Remove the live script tag- * node live-inject.mjs --check # Check whether config.json exists+ * node live-inject.mjs --check # Check whether live config exists*/import fs from 'node:fs';import path from 'node:path';import { fileURLToPath } from 'node:url';+import { resolveLiveConfigPath } from './impeccable-paths.mjs';const __dirname = path.dirname(fileURLToPath(import.meta.url));-const CONFIG_PATH = process.env.IMPECCABLE_LIVE_CONFIG || path.join(__dirname, 'config.json');+const CONFIG_PATH = resolveLiveConfigPath({ cwd: process.cwd(), scriptsDir: __dirname });const MARKER_OPEN_TEXT = 'impeccable-live-start';const MARKER_CLOSE_TEXT = 'impeccable-live-end';@@ -39,12 +40,12 @@ export async function injectCli() {console.log(`Usage: node live-inject.mjs [options]Insert or remove the live mode script tag in the project's HTML entry point.-Reads configuration from config.json (in this same directory).+Reads configuration from .impeccable/live/config.json.Modes:--port PORT Insert script tag pointing at http://localhost:PORT/live.js--remove Remove the script tag (if present)- --check Print whether config.json exists and its content+ --check Print whether .impeccable/live/config.json exists and its contentOutput (JSON):{ ok, file, inserted|removed, config? }`);diff --git a/.gemini/skills/impeccable/scripts/live-poll.mjs b/.gemini/skills/impeccable/scripts/live-poll.mjsindex eb8f1586a..10d452491 100644--- a/.gemini/skills/impeccable/scripts/live-poll.mjs+++ b/.gemini/skills/impeccable/scripts/live-poll.mjs@@ -9,10 +9,10 @@*/import { execFileSync } from 'node:child_process';-import fs from 'node:fs';import path from 'node:path';-import os from 'node:os';import { fileURLToPath } from 'node:url';+import { completionAckForAcceptResult, completionTypeForAcceptResult } from './live-completion.mjs';+import { readLiveServerInfo } from './impeccable-paths.mjs';// Node's built-in fetch (undici under the hood) enforces a 300s headers// timeout that can't be lowered per-request. We cap each request below@@ -20,15 +20,29 @@ import { fileURLToPath } from 'node:url';// depending on the standalone undici package.const PER_REQUEST_TIMEOUT_MS = 270_000;-const LIVE_PID_FILE = path.join(process.cwd(), '.impeccable-live.json');-function readServerInfo() {- try {- return JSON.parse(fs.readFileSync(LIVE_PID_FILE, 'utf-8'));- } catch {+ const record = readLiveServerInfo(process.cwd());+ if (!record) {console.error('No running live server found. Start one with: npx impeccable live');process.exit(1);}+ return record.info;+}++export function buildPollReplyPayload(token, { id, type, message, file, data }) {+ return { token, id, type, message, file, data };+}++async function postReply(base, token, reply) {+ const res = await fetch(`${base}/poll`, {+ method: 'POST',+ headers: { 'Content-Type': 'application/json' },+ body: JSON.stringify(buildPollReplyPayload(token, reply)),+ });+ if (!res.ok) {+ const body = await res.json().catch(() => ({}));+ throw new Error(body.error || res.statusText);+ }}export async function pollCli() {@@ -69,23 +83,7 @@ Options:}try {- const res = await fetch(`${base}/poll`, {- method: 'POST',- headers: { 'Content-Type': 'application/json' },- body: JSON.stringify({- token: info.token,- id,- type: status,- message,- file: filePath,- }),- });-- if (!res.ok) {- const body = await res.json().catch(() => ({}));- console.error(`Reply failed (${res.status}):`, body.error || res.statusText);- process.exit(1);- }+ await postReply(base, info.token, { id, type: status, message, file: filePath });// Success — silent exit (agent doesn't need output for replies)} catch (err) {@@ -156,7 +154,23 @@ Options:);event._acceptResult = JSON.parse(out.trim());} catch (err) {- event._acceptResult = { handled: false, error: err.message };+ event._acceptResult = { handled: false, mode: 'error', error: err.message };+ }++ const completionType = completionTypeForAcceptResult(event.type, event._acceptResult);+ try {+ await postReply(base, info.token, {+ id: event.id,+ type: completionType,+ message: event._acceptResult?.error,+ file: event._acceptResult?.file,+ data: event._acceptResult?.carbonize === true ? { carbonize: true } : undefined,+ });+ } catch (err) {+ event._completionAck = { ok: false, error: err.message };+ }+ if (!event._completionAck) {+ event._completionAck = completionAckForAcceptResult(event.id, completionType, event._acceptResult);}}@@ -164,7 +178,7 @@ Options:// JSON but skips nested fields. One line is enough — the full checklist// is in reference/live.md.if (event._acceptResult?.carbonize === true) {- process.stderr.write('\n⚠ Carbonize cleanup REQUIRED before next poll. See reference/live.md "Required after accept".\n\n');+ process.stderr.write('\n⚠ Carbonize cleanup REQUIRED before next poll. After cleanup, run live-complete.mjs --id ' + event.id + '. See reference/live.md "Required after accept".\n\n');}// Print the event as JSON — the agent reads this from stdoutdiff --git a/.gemini/skills/impeccable/scripts/live-resume.mjs b/.gemini/skills/impeccable/scripts/live-resume.mjsnew file mode 100644index 000000000..a3465c9b5--- /dev/null+++ b/.gemini/skills/impeccable/scripts/live-resume.mjs@@ -0,0 +1,48 @@+#!/usr/bin/env node+/**+ * Recover the next agent action from the durable live-session journal.+ */++import { createLiveSessionStore } from './live-session-store.mjs';++function parseArgs(argv) {+ const out = { id: null };+ for (let i = 0; i < argv.length; i++) {+ const arg = argv[i];+ if (arg === '--id') out.id = argv[++i];+ else if (arg.startsWith('--id=')) out.id = arg.slice('--id='.length);+ else if (arg === '--help' || arg === '-h') out.help = true;+ }+ return out;+}++export async function resumeCli() {+ const args = parseArgs(process.argv.slice(2));+ if (args.help) {+ console.log(`Usage: node live-resume.mjs [--id SESSION_ID]\n\nPrint the active durable session checkpoint and the next safe agent action.`);+ return;+ }++ const store = createLiveSessionStore({ cwd: process.cwd(), sessionId: args.id || undefined });+ const snapshot = args.id ? store.getSnapshot(args.id) : store.listActiveSessions()[0] || null;+ if (!snapshot) {+ console.log(JSON.stringify({ active: false, nextAction: 'No active durable live session found.' }, null, 2));+ return;+ }++ const pending = snapshot.pendingEvent || null;+ const nextAction = pending+ ? `Run live-poll.mjs, handle ${pending.type} ${pending.id}, then acknowledge with live-poll.mjs --reply ${pending.id} done.`+ : snapshot.phase === 'carbonize_required'+ ? `Finish carbonize cleanup${snapshot.sourceFile ? ` in ${snapshot.sourceFile}` : ''}, then run live-complete.mjs --id ${snapshot.id}.`+ : snapshot.phase === 'accept_requested'+ ? `Run live-complete.mjs --id ${snapshot.id} after verifying the accepted variant is written.`+ : `Inspect ${snapshot.id}; no pending agent event is currently queued.`;++ console.log(JSON.stringify({ active: true, snapshot, pendingEvent: pending, nextAction }, null, 2));+}++const _running = process.argv[1];+if (_running?.endsWith('live-resume.mjs') || _running?.endsWith('live-resume.mjs/')) {+ resumeCli();+}diff --git a/.gemini/skills/impeccable/scripts/live-server.mjs b/.gemini/skills/impeccable/scripts/live-server.mjsindex 90614fbf7..53d8f21cb 100644--- a/.gemini/skills/impeccable/scripts/live-server.mjs+++ b/.gemini/skills/impeccable/scripts/live-server.mjs@@ -22,14 +22,20 @@ import net from 'node:net';import { fileURLToPath } from 'node:url';import { parseDesignMd } from './design-parser.mjs';import { resolveContextDir } from './load-context.mjs';+import { createLiveSessionStore } from './live-session-store.mjs';+import {+ getDesignSidecarPath,+ getLiveAnnotationsDir,+ readLiveServerInfo,+ removeLiveServerInfo,+ resolveDesignSidecarPath,+ writeLiveServerInfo,+} from './impeccable-paths.mjs';const __dirname = path.dirname(fileURLToPath(import.meta.url));-// PID file in the project root so both the server and agent can find it-// predictably (os.tmpdir() varies across platforms).-const LIVE_PID_FILE = path.join(process.cwd(), '.impeccable-live.json');-// PRODUCT.md / DESIGN.md / DESIGN.json live wherever load-context.mjs resolves.-// Keeps live-server in sync with the loader when users keep the docs in-// .agents/context/, docs/, or a path set via IMPECCABLE_CONTEXT_DIR.+// PRODUCT.md / DESIGN.md live wherever load-context.mjs resolves. The generated+// DESIGN sidecar is project-local at .impeccable/design.json, with legacy+// DESIGN.json fallback for existing projects.const CONTEXT_DIR = resolveContextDir(process.cwd());const DEFAULT_POLL_TIMEOUT = 600_000; // 10 min — agent re-polls on timeout anywayconst SSE_HEARTBEAT_INTERVAL = 30_000; // keepalive ping every 30s@@ -57,10 +63,12 @@ const state = {token: null,port: null,sseClients: new Set(), // SSE response objects (server→browser push)- pendingEvents: [], // browser events waiting for agent poll+ pendingEvents: [], // browser events waiting for agent ack ({ event, leaseUntil })pendingPolls: [], // agent poll callbacks waiting for browser eventsexitTimer: null,sessionDir: null, // per-session tmp dir for annotation screenshots+ sessionStore: null,+ leaseTimer: null,};// Cap per-annotation upload size. A full 1920×1080 PNG is typically <1 MB;@@ -68,11 +76,70 @@ const state = {const MAX_ANNOTATION_BYTES = 10 * 1024 * 1024;function enqueueEvent(event) {- if (state.pendingPolls.length > 0) {- state.pendingPolls.shift()(event);- } else {- state.pendingEvents.push(event);+ if (!event || (event.id && state.pendingEvents.some((entry) => entry.event?.id === event.id && entry.event?.type === event.type))) return;+ state.pendingEvents.push({ event, leaseUntil: 0 });+ flushPendingPolls();+}++function restorePendingEventsFromStore() {+ if (!state.sessionStore) return;+ for (const snapshot of state.sessionStore.listActiveSessions()) {+ if (snapshot.pendingEvent) enqueueEvent(snapshot.pendingEvent);+ }+}++function findAvailablePendingEvent(now = Date.now()) {+ return state.pendingEvents.find((entry) => !entry.leaseUntil || entry.leaseUntil <= now);+}++function leaseEvent(entry, leaseMs) {+ if (!entry.event?.id) {+ const idx = state.pendingEvents.indexOf(entry);+ if (idx !== -1) state.pendingEvents.splice(idx, 1);+ return entry.event;}+ entry.leaseUntil = Date.now() + leaseMs;+ return entry.event;+}++function acknowledgePendingEvent(id) {+ if (!id) return false;+ const idx = state.pendingEvents.findIndex((entry) => entry.event?.id === id);+ if (idx === -1) return false;+ state.pendingEvents.splice(idx, 1);+ scheduleLeaseFlush();+ return true;+}++function scheduleLeaseFlush() {+ if (state.leaseTimer) {+ clearTimeout(state.leaseTimer);+ state.leaseTimer = null;+ }+ if (state.pendingPolls.length === 0) return;+ const now = Date.now();+ const nextLeaseUntil = state.pendingEvents+ .map((entry) => entry.leaseUntil || 0)+ .filter((leaseUntil) => leaseUntil > now)+ .sort((a, b) => a - b)[0];+ if (!nextLeaseUntil) return;+ state.leaseTimer = setTimeout(() => {+ state.leaseTimer = null;+ flushPendingPolls();+ }, Math.max(0, nextLeaseUntil - now));+}++function flushPendingPolls() {+ while (state.pendingPolls.length > 0) {+ const entry = findAvailablePendingEvent();+ if (!entry) {+ scheduleLeaseFlush();+ return;+ }+ const poll = state.pendingPolls.shift();+ poll.resolve(leaseEvent(entry, poll.leaseMs));+ }+ scheduleLeaseFlush();}/** Push a message to all connected SSE clients. */@@ -103,13 +170,16 @@ function loadBrowserScripts() {// live-browser.js: DO NOT cache. Return the path so the /live.js handler// can re-read on every request. Editing the browser script during iteration// should land on the next tab reload, not require a server restart.+ const sessionPath = path.join(__dirname, 'live-browser-session.js');const livePath = path.join(__dirname, 'live-browser.js');- if (!fs.existsSync(livePath)) {- process.stderr.write('Error: live-browser.js not found at ' + livePath + '\n');- process.exit(1);+ for (const p of [sessionPath, livePath]) {+ if (!fs.existsSync(p)) {+ process.stderr.write('Error: live browser script not found at ' + p + '\n');+ process.exit(1);+ }}- return { detectScript, livePath };+ return { detectScript, sessionPath, livePath };}function hasProjectContext() {@@ -170,6 +240,13 @@ function validateEvent(msg) {return null;case 'discard':return isValidId(msg.id) ? null : 'discard: missing or malformed id';+ case 'checkpoint':+ if (!isValidId(msg.id)) return 'checkpoint: missing or malformed id';+ if (!Number.isInteger(msg.revision) || msg.revision < 0) return 'checkpoint: revision must be a non-negative integer';+ if (msg.paramValues !== undefined && (typeof msg.paramValues !== 'object' || msg.paramValues === null || Array.isArray(msg.paramValues))) {+ return 'checkpoint: paramValues must be an object';+ }+ return null;case 'exit':return null;case 'prefetch':@@ -184,7 +261,7 @@ function validateEvent(msg) {// HTTP request handler// ----------------------------------------------------------------------------function createRequestHandler({ detectScript, livePath }) {+function createRequestHandler({ detectScript, sessionPath, livePath }) {return (req, res) => {const url = new URL(req.url, `http://localhost:${state.port}`);res.setHeader('Access-Control-Allow-Origin', '*');@@ -200,17 +277,20 @@ function createRequestHandler({ detectScript, livePath }) {// the next tab reload. No-store headers prevent browser caching across// sessions — during iteration, a cached old script silently breaks// every subsequent session.+ let sessionScript;let liveScript;try {+ sessionScript = fs.readFileSync(sessionPath, 'utf-8');liveScript = fs.readFileSync(livePath, 'utf-8');} catch (err) {res.writeHead(500, { 'Content-Type': 'text/plain' });- res.end('Error reading live-browser.js: ' + err.message);+ res.end('Error reading live browser scripts: ' + err.message);return;}const body =`window.__IMPECCABLE_TOKEN__ = '${state.token}';\n` +`window.__IMPECCABLE_PORT__ = ${state.port};\n` ++ sessionScript + '\n' +liveScript;res.writeHead(200, {'Content-Type': 'application/javascript',@@ -305,6 +385,26 @@ function createRequestHandler({ detectScript, livePath }) {}// --- Health ---+ if (p === '/status') {+ const token = url.searchParams.get('token');+ if (token !== state.token) { res.writeHead(401, { 'Content-Type': 'application/json' }); res.end(JSON.stringify({ error: 'Unauthorized' })); return; }+ const sessions = state.sessionStore ? state.sessionStore.listActiveSessions() : [];+ res.writeHead(200, { 'Content-Type': 'application/json' });+ res.end(JSON.stringify({+ status: 'ok',+ port: state.port,+ connectedClients: state.sseClients.size,+ pendingEvents: state.pendingEvents.map((entry) => ({+ id: entry.event?.id,+ type: entry.event?.type,+ leased: !!(entry.leaseUntil && entry.leaseUntil > Date.now()),+ leaseUntil: entry.leaseUntil || null,+ })),+ activeSessions: sessions,+ }));+ return;+ }+if (p === '/health') {res.writeHead(200, { 'Content-Type': 'application/json' });res.end(JSON.stringify({@@ -316,13 +416,13 @@ function createRequestHandler({ detectScript, livePath }) {}// --- Design system (unified v2 response) + raw ---- // /design-system.json returns both parsed DESIGN.md and DESIGN.json+ // /design-system.json returns both parsed DESIGN.md and .impeccable/design.json// sidecar when present. Panel merges them:// { present, parsed, sidecar, hasMd, hasSidecar,// mdNewerThanJson, parseError?, sidecarError? }// - parsed: output of parseDesignMd (frontmatter// + six canonical sections) when DESIGN.md exists.- // - sidecar: DESIGN.json contents when present.+ // - sidecar: .impeccable/design.json contents when present.// Expected shape: schemaVersion 2, carrying// extensions + components + narrative.// /design-system/raw returns DESIGN.md markdown verbatim@@ -331,7 +431,7 @@ function createRequestHandler({ detectScript, livePath }) {if (token !== state.token) { res.writeHead(401); res.end('Unauthorized'); return; }const mdPath = path.join(CONTEXT_DIR, 'DESIGN.md');- const jsonPath = path.join(CONTEXT_DIR, 'DESIGN.json');+ const jsonPath = resolveDesignSidecarPath(process.cwd(), CONTEXT_DIR) || getDesignSidecarPath(process.cwd());const mdStat = statOrNull(mdPath);const jsonStat = statOrNull(jsonPath);@@ -367,7 +467,7 @@ function createRequestHandler({ detectScript, livePath }) {try {response.sidecar = JSON.parse(fs.readFileSync(jsonPath, 'utf-8'));} catch (err) {- response.sidecarError = 'Failed to parse DESIGN.json: ' + err.message;+ response.sidecarError = 'Failed to parse .impeccable/design.json: ' + err.message;}}@@ -449,7 +549,16 @@ function createRequestHandler({ detectScript, livePath }) {res.end(JSON.stringify({ error }));return;}- enqueueEvent(msg);+ if (state.sessionStore && msg.id) {+ try {+ state.sessionStore.appendEvent(msg);+ } catch (err) {+ res.writeHead(500, { 'Content-Type': 'application/json' });+ res.end(JSON.stringify({ error: 'session_store_append_failed', message: err.message }));+ return;+ }+ }+ if (msg.type !== 'checkpoint') enqueueEvent(msg);res.writeHead(200, { 'Content-Type': 'application/json' });res.end(JSON.stringify({ ok: true }));});@@ -492,13 +601,16 @@ function handlePollGet(req, res, url) {return;}const timeout = parseInt(url.searchParams.get('timeout') || DEFAULT_POLL_TIMEOUT, 10);- if (state.pendingEvents.length > 0) {+ const leaseMs = parseInt(url.searchParams.get('leaseMs') || '30000', 10);+ const available = findAvailablePendingEvent();+ if (available) {res.writeHead(200, { 'Content-Type': 'application/json' });- res.end(JSON.stringify(state.pendingEvents.shift()));+ res.end(JSON.stringify(leaseEvent(available, leaseMs)));return;}+ const poll = { resolve, leaseMs };const timer = setTimeout(() => {- const idx = state.pendingPolls.indexOf(resolve);+ const idx = state.pendingPolls.indexOf(poll);if (idx !== -1) state.pendingPolls.splice(idx, 1);res.writeHead(200, { 'Content-Type': 'application/json' });res.end(JSON.stringify({ type: 'timeout' }));@@ -508,10 +620,11 @@ function handlePollGet(req, res, url) {res.writeHead(200, { 'Content-Type': 'application/json' });res.end(JSON.stringify(event));}- state.pendingPolls.push(resolve);+ state.pendingPolls.push(poll);+ scheduleLeaseFlush();req.on('close', () => {clearTimeout(timer);- const idx = state.pendingPolls.indexOf(resolve);+ const idx = state.pendingPolls.indexOf(poll);if (idx !== -1) state.pendingPolls.splice(idx, 1);});}@@ -531,6 +644,26 @@ function handlePollPost(req, res) {res.end(JSON.stringify({ error: 'Unauthorized' }));return;}+ acknowledgePendingEvent(msg.id);+ if (state.sessionStore && msg.id) {+ try {+ const eventType = msg.type === 'discard' || msg.type === 'discarded'+ ? 'discarded'+ : msg.type === 'complete'+ ? 'complete'+ : msg.type === 'error'+ ? 'agent_error'+ : 'agent_done';+ state.sessionStore.appendEvent({+ type: eventType,+ id: msg.id,+ file: msg.file,+ message: msg.message,+ carbonize: msg.data?.carbonize === true,+ });+ } catch { /* keep reply path best-effort; browser still needs SSE */ }+ }+ flushPendingPolls();// Forward the reply to the browser via SSEbroadcast({ type: msg.type || 'done', id: msg.id, message: msg.message, file: msg.file, data: msg.data });res.writeHead(200, { 'Content-Type': 'application/json' });@@ -545,13 +678,15 @@ function handlePollPost(req, res) {let httpServer = null;function shutdown() {- try { fs.unlinkSync(LIVE_PID_FILE); } catch {}+ removeLiveServerInfo(process.cwd());+ if (state.leaseTimer) clearTimeout(state.leaseTimer);+ state.leaseTimer = null;if (state.sessionDir) {try { fs.rmSync(state.sessionDir, { recursive: true, force: true }); } catch {}}for (const res of state.sseClients) { try { res.end(); } catch {} }state.sseClients.clear();- for (const resolve of state.pendingPolls) resolve({ type: 'exit' });+ for (const poll of state.pendingPolls) poll.resolve({ type: 'exit' });state.pendingPolls.length = 0;if (httpServer) httpServer.close();process.exit(0);@@ -587,6 +722,7 @@ Endpoints:/events SSE stream (server→browser) + POST (browser→server)/poll Long-poll for agent CLI/source Raw source file reader (no-HMR fallback)+ /status Durable recovery status (token-protected)/health Health check`);process.exit(0);}@@ -594,7 +730,7 @@ Endpoints:if (args.includes('stop')) {const keepInject = args.includes('--keep-inject');try {- const info = JSON.parse(fs.readFileSync(LIVE_PID_FILE, 'utf-8'));+ const { info } = readLiveServerInfo(process.cwd()) || {};const res = await fetch(`http://localhost:${info.port}/stop?token=${info.token}`);if (res.ok) console.log(`Stopped live server on port ${info.port}.`);} catch {@@ -645,7 +781,7 @@ if (args.includes('--background')) {const deadline = Date.now() + 10_000;while (Date.now() < deadline) {try {- const info = JSON.parse(fs.readFileSync(LIVE_PID_FILE, 'utf-8'));+ const { info } = readLiveServerInfo(process.cwd()) || {};if (info.pid !== process.pid) {// Output JSON so the agent can read port + token from stdout.console.log(JSON.stringify(info));@@ -659,30 +795,36 @@ if (args.includes('--background')) {}// Check for existing session-try {- const existing = JSON.parse(fs.readFileSync(LIVE_PID_FILE, 'utf-8'));- try { process.kill(existing.pid, 0);+const existingRecord = readLiveServerInfo(process.cwd());+if (existingRecord?.info) {+ const existing = existingRecord.info;+ try {+ process.kill(existing.pid, 0);console.error(`Live server already running on port ${existing.port} (pid ${existing.pid}).`);console.error('Stop it first with: node ' + path.basename(fileURLToPath(import.meta.url)) + ' stop');process.exit(1);- } catch { fs.unlinkSync(LIVE_PID_FILE); }-} catch {}+ } catch {+ try { fs.unlinkSync(existingRecord.path); } catch {}+ }+}state.token = randomUUID();+state.sessionStore = createLiveSessionStore({ cwd: process.cwd() });+restorePendingEventsFromStore();const portArg = args.find(a => a.startsWith('--port='));state.port = portArg ? parseInt(portArg.split('=')[1], 10) : await findOpenPort();// Annotation screenshots live in the project root so the agent's Read tool// doesn't trip a per-file permission prompt. Sessioned by token so concurrent// projects (or quick restarts) don't collide.-const annotRoot = path.join(process.cwd(), '.impeccable-live', 'annotations');+const annotRoot = getLiveAnnotationsDir(process.cwd());fs.mkdirSync(annotRoot, { recursive: true });state.sessionDir = fs.mkdtempSync(path.join(annotRoot, 'session-'));-const { detectScript, livePath } = loadBrowserScripts();-httpServer = http.createServer(createRequestHandler({ detectScript, livePath }));+const { detectScript, sessionPath, livePath } = loadBrowserScripts();+httpServer = http.createServer(createRequestHandler({ detectScript, sessionPath, livePath }));httpServer.listen(state.port, '127.0.0.1', () => {- fs.writeFileSync(LIVE_PID_FILE, JSON.stringify({ pid: process.pid, port: state.port, token: state.token }));+ writeLiveServerInfo(process.cwd(), { pid: process.pid, port: state.port, token: state.token });const url = `http://localhost:${state.port}`;console.log(`\nImpeccable live server running on ${url}`);console.log(`Token: ${state.token}\n`);diff --git a/.gemini/skills/impeccable/scripts/live-session-store.mjs b/.gemini/skills/impeccable/scripts/live-session-store.mjsnew file mode 100644index 000000000..d55ed2d3a--- /dev/null+++ b/.gemini/skills/impeccable/scripts/live-session-store.mjs@@ -0,0 +1,254 @@+import fs from 'node:fs';+import path from 'node:path';+import { getLegacyLiveSessionsDir, getLiveSessionsDir } from './impeccable-paths.mjs';++const COMPLETED_PHASES = new Set(['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;+ }++ function getReadableJournalPath(id) {+ const primary = getJournalPath(rootDir, id);+ if (fs.existsSync(primary)) return primary;+ const legacy = getJournalPath(legacyRootDir, id);+ if (fs.existsSync(legacy)) return legacy;+ return primary;+ }++ return {+ rootDir,+ legacyRootDir,+ appendEvent(event) {+ const normalized = normalizeEvent(event, sessionId);+ const journalPath = getJournalPath(rootDir, normalized.id);+ const snapshotPath = getSnapshotPath(rootDir, normalized.id);+ const legacyJournalPath = getJournalPath(legacyRootDir, normalized.id);+ if (!fs.existsSync(journalPath) && fs.existsSync(legacyJournalPath)) {+ fs.copyFileSync(legacyJournalPath, journalPath);+ }+ const prior = loadCachedOrRebuild(normalized.id);+ const seq = prior.nextSeq;+ const entry = {+ seq,+ id: normalized.id,+ type: normalized.type,+ ts: new Date().toISOString(),+ event: normalized,+ };+ 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;+ },+ getSnapshot(id = sessionId, opts = {}) {+ if (!id) throw new Error('session id required');+ 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;+ },+ listActiveSessions() {+ const ids = new Set();+ for (const dir of [legacyRootDir, rootDir]) {+ if (!fs.existsSync(dir)) continue;+ for (const name of fs.readdirSync(dir)) {+ if (name.endsWith('.jsonl')) ids.add(name.slice(0, -'.jsonl'.length));+ }+ }+ return [...ids]+ .sort()+ .map((id) => this.getSnapshot(id))+ .filter(Boolean);+ },+ };+}++function normalizeEvent(event, fallbackId) {+ if (!event || typeof event !== 'object') throw new Error('event object required');+ const id = event.id || fallbackId;+ if (!id || typeof id !== 'string') throw new Error('event id required');+ if (!event.type || typeof event.type !== 'string') throw new Error('event type required');+ return { ...event, id };+}++function getJournalPath(rootDir, id) {+ return path.join(rootDir, safeSessionId(id) + '.jsonl');+}++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,+ phase: 'new',+ pageUrl: null,+ sourceFile: null,+ expectedVariants: 0,+ arrivedVariants: 0,+ visibleVariant: null,+ paramValues: {},+ pendingEventSeq: null,+ pendingEvent: null,+ deliveryLease: null,+ checkpointRevision: 0,+ activeOwner: null,+ sourceMarkers: {},+ fallbackMode: null,+ annotationArtifacts: [],+ diagnostics: [],+ updatedAt: null,+ };+}++function rebuildSnapshotFromJournal(journalPath, id) {+ let snapshot = baseSnapshot(id);+ const diagnostics = [];+ let nextSeq = 1;+ if (!fs.existsSync(journalPath)) return { snapshot, diagnostics, nextSeq };++ const lines = fs.readFileSync(journalPath, 'utf-8').split('\n');+ for (let i = 0; i < lines.length; i++) {+ const line = lines[i];+ if (!line.trim()) continue;+ try {+ const entry = JSON.parse(line);+ if (!entry || typeof entry !== 'object') throw new Error('entry is not object');+ if (Number.isInteger(entry.seq)) nextSeq = Math.max(nextSeq, entry.seq + 1);+ snapshot = applyEvent(snapshot, entry);+ } catch (err) {+ diagnostics.push({+ error: 'journal_parse_failed',+ line: i + 1,+ message: err.message,+ });+ }+ }+ snapshot.diagnostics = [...snapshot.diagnostics, ...diagnostics];+ return { snapshot, diagnostics, nextSeq };+}++function applyEvent(snapshot, entry, inheritedDiagnostics = []) {+ const event = entry.event || entry;+ const next = {+ ...snapshot,+ paramValues: { ...(snapshot.paramValues || {}) },+ sourceMarkers: { ...(snapshot.sourceMarkers || {}) },+ annotationArtifacts: [...(snapshot.annotationArtifacts || [])],+ diagnostics: [...(snapshot.diagnostics || [])],+ updatedAt: entry.ts || new Date().toISOString(),+ };++ if (inheritedDiagnostics.length && next.diagnostics.length === 0) {+ next.diagnostics = [...inheritedDiagnostics];+ }++ switch (event.type) {+ case 'generate':+ next.phase = 'generate_requested';+ next.pageUrl = event.pageUrl ?? next.pageUrl;+ next.expectedVariants = event.count ?? next.expectedVariants;+ next.pendingEventSeq = entry.seq ?? next.pendingEventSeq;+ next.pendingEvent = toPendingEvent(event);+ if (event.screenshotPath) upsertArtifact(next.annotationArtifacts, { type: 'screenshot', path: event.screenshotPath });+ break;+ case 'variants_ready':+ case 'agent_done':+ next.phase = event.carbonize === true ? 'carbonize_required' : 'variants_ready';+ next.sourceFile = event.file ?? next.sourceFile;+ next.arrivedVariants = event.arrivedVariants ?? (next.arrivedVariants ?? next.expectedVariants);+ next.pendingEventSeq = null;+ next.pendingEvent = null;+ if (event.carbonize === true) {+ next.diagnostics.push({+ error: 'carbonize_cleanup_required',+ file: event.file || null,+ message: 'Accepted variant still has carbonize markers that must be folded into source CSS.',+ });+ }+ break;+ case 'checkpoint':+ 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;+ if (event.paramValues) next.paramValues = { ...event.paramValues };+ } else {+ next.diagnostics.push({ error: 'stale_checkpoint_ignored', revision: event.revision });+ }+ break;+ case 'accept':+ case 'accept_intent':+ next.phase = 'accept_requested';+ next.visibleVariant = Number(event.variantId ?? next.visibleVariant);+ if (event.paramValues) next.paramValues = { ...event.paramValues };+ next.pendingEventSeq = entry.seq ?? next.pendingEventSeq;+ next.pendingEvent = toPendingEvent(event);+ break;+ case 'discard':+ next.phase = 'discard_requested';+ next.pendingEventSeq = entry.seq ?? next.pendingEventSeq;+ next.pendingEvent = toPendingEvent(event);+ break;+ case 'discarded':+ next.phase = 'discarded';+ next.pendingEventSeq = null;+ next.pendingEvent = null;+ break;+ case 'complete':+ next.phase = 'completed';+ next.pendingEventSeq = null;+ next.pendingEvent = null;+ break;+ case 'agent_error':+ next.phase = 'agent_error';+ next.pendingEventSeq = null;+ next.pendingEvent = null;+ next.diagnostics.push({ error: 'agent_error', message: event.message || 'unknown agent error' });+ break;+ default:+ next.diagnostics.push({ error: 'unknown_event_type', type: event.type });+ break;+ }+ return next;+}++function toPendingEvent(event) {+ const pending = { ...event };+ delete pending.token;+ return pending;+}++function upsertArtifact(artifacts, artifact) {+ if (!artifacts.some((existing) => existing.path === artifact.path && existing.type === artifact.type)) {+ artifacts.push(artifact);+ }+}++function writeSnapshot(snapshotPath, snapshot) {+ fs.writeFileSync(snapshotPath, JSON.stringify(snapshot, null, 2) + '\n');+}diff --git a/.gemini/skills/impeccable/scripts/live-status.mjs b/.gemini/skills/impeccable/scripts/live-status.mjsnew file mode 100644index 000000000..dce1fbca2--- /dev/null+++ b/.gemini/skills/impeccable/scripts/live-status.mjs@@ -0,0 +1,47 @@+#!/usr/bin/env node+/**+ * Print durable recovery status for Impeccable live sessions.+ */++import { createLiveSessionStore } from './live-session-store.mjs';+import { readLiveServerInfo } from './impeccable-paths.mjs';++function readServerInfo() {+ return readLiveServerInfo(process.cwd())?.info || null;+}++async function fetchServerStatus(info) {+ if (!info) return null;+ try {+ const res = await fetch(`http://localhost:${info.port}/status?token=${info.token}`);+ if (!res.ok) return null;+ return await res.json();+ } catch {+ return null;+ }+}++export async function statusCli() {+ const info = readServerInfo();+ const server = await fetchServerStatus(info);+ const store = createLiveSessionStore({ cwd: process.cwd() });+ const activeSessions = store.listActiveSessions();+ const payload = {+ liveServer: server ? {+ status: server.status,+ port: server.port,+ connectedClients: server.connectedClients,+ pendingEvents: server.pendingEvents,+ } : null,+ activeSessions: server?.activeSessions || activeSessions,+ recoveryHint: 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.',+ };+ console.log(JSON.stringify(payload, null, 2));+}++const _running = process.argv[1];+if (_running?.endsWith('live-status.mjs') || _running?.endsWith('live-status.mjs/')) {+ statusCli();+}diff --git a/.gemini/skills/impeccable/scripts/live-wrap.mjs b/.gemini/skills/impeccable/scripts/live-wrap.mjsindex a5769a50a..d46328b9f 100644--- a/.gemini/skills/impeccable/scripts/live-wrap.mjs+++ b/.gemini/skills/impeccable/scripts/live-wrap.mjs@@ -185,6 +185,7 @@ The agent should insert variant HTML at insertLine.`);const { startLine, endLine } = match;const commentSyntax = detectCommentSyntax(targetFile);+ const styleMode = detectStyleMode(targetFile);const isJsx = commentSyntax.open === '{/*';const indent = lines[startLine].match(/^(\s*)/)[1];@@ -269,6 +270,10 @@ The agent should insert variant HTML at insertLine.`);endLine: startLine + wrapperLines.length + (originalLines.length - 1), // 1-indexedinsertLine: insertLine + 1, // 1-indexed: where variants gocommentSyntax: commentSyntax,+ styleMode: styleMode.mode,+ styleTag: styleMode.styleTag,+ cssSelectorPrefixExamples: buildCssSelectorPrefixExamples(styleMode.mode, count),+ cssAuthoring: buildCssAuthoring(styleMode, count),originalLineCount: originalLines.length,}));}@@ -335,6 +340,62 @@ function detectCommentSyntax(filePath) {return { open: '<!--', close: '-->' };}+function detectStyleMode(filePath) {+ const ext = path.extname(filePath).toLowerCase();+ if (ext === '.astro') {+ return {+ mode: 'astro-global-prefixed',+ styleTag: '<style is:inline data-impeccable-css="SESSION_ID">',+ };+ }+ return {+ mode: 'scoped',+ styleTag: '<style data-impeccable-css="SESSION_ID">',+ };+}++function buildCssSelectorPrefixExamples(styleMode, count) {+ if (styleMode !== 'astro-global-prefixed') return [];+ return Array.from({ length: count }, (_, i) => `[data-impeccable-variant="${i + 1}"]`);+}++function buildCssAuthoring(styleMode, count) {+ const variantNumbers = Array.from({ length: count }, (_, i) => i + 1);+ if (styleMode.mode === 'astro-global-prefixed') {+ return {+ mode: styleMode.mode,+ styleTag: styleMode.styleTag,+ strategy: 'global-prefixed',+ rulePattern: '[data-impeccable-variant="N"] > .variant-class { ... }',+ selectorExamples: variantNumbers.map((n) => `[data-impeccable-variant="${n}"] > .variant-class`),+ requirements: [+ 'Use the styleTag exactly; the is:inline attribute is required for this file.',+ 'Prefix every preview selector with the matching [data-impeccable-variant="N"] selector.',+ 'Keep selectors anchored to the generated variant wrapper; do not rely on component CSS scoping for preview rules.',+ ],+ forbidden: [+ 'Do not use @scope for this styleMode.',+ ],+ };+ }+ return {+ mode: styleMode.mode,+ styleTag: styleMode.styleTag,+ strategy: 'scope-rule',+ rulePattern: '@scope ([data-impeccable-variant="N"]) { :scope > .variant-class { ... } }',+ selectorExamples: variantNumbers.map((n) => `@scope ([data-impeccable-variant="${n}"]) { :scope > .variant-class { ... } }`),+ requirements: [+ 'Use @scope blocks keyed to each [data-impeccable-variant="N"] wrapper.',+ 'Inside each @scope block, make :scope rules step into the replacement element with a descendant combinator.',+ 'Use the styleTag exactly; do not add framework-specific style attributes unless this object says to.',+ ],+ forbidden: [+ 'Do not use global [data-impeccable-variant="N"] selector prefixes for this styleMode.',+ 'Do not add is:inline to the style tag for this styleMode.',+ ],+ };+}+/*** Search project files for the query string (class name, ID, etc.)* Returns the first matching file path, or null.diff --git a/.gemini/skills/impeccable/scripts/live.mjs b/.gemini/skills/impeccable/scripts/live.mjsindex befbdb8ed..cafb0eca9 100644--- a/.gemini/skills/impeccable/scripts/live.mjs+++ b/.gemini/skills/impeccable/scripts/live.mjs@@ -2,10 +2,10 @@* CLI entry point: prepare everything needed to enter the live variant poll loop.** Does (all in one command):- * 1. Check config.json (returns config_missing if first-ever run)+ * 1. Check .impeccable/live/config.json (returns config_missing if first-ever run)* 2. Start the live server in the background (or reuse a running one)* 3. Inject the browser script tag into the project's entry file- * 4. Read .impeccable.md for design context (if present)+ * 4. Read PRODUCT.md / DESIGN.md for project context* 5. Print a single JSON blob with everything the agent needs** After this, the agent's only remaining steps are:@@ -23,9 +23,9 @@ import path from 'node:path';import { fileURLToPath } from 'node:url';import { loadContext } from './load-context.mjs';import { resolveFiles } from './live-inject.mjs';+import { readLiveServerInfo } from './impeccable-paths.mjs';const __dirname = path.dirname(fileURLToPath(import.meta.url));-const PID_FILE = path.join(process.cwd(), '.impeccable-live.json');async function liveCli() {const args = process.argv.slice(2);@@ -34,10 +34,10 @@ async function liveCli() {console.log(`Usage: node live.mjsPrepare everything for live variant mode in a single command:- - Checks scripts/config.json (required, created once per project)+ - Checks .impeccable/live/config.json (required, created once per project)- Starts (or reuses) the live server in the background- Injects the browser script tag- - Reads .impeccable.md for design context+ - Reads PRODUCT.md / DESIGN.md for project contextOn success, prints a JSON blob with:{ ok, serverPort, serverToken, pageFile, hasContext, context }@@ -223,7 +223,7 @@ function safeParse(out) {function ensureServerRunning() {// Try to reuse an existing servertry {- const existing = JSON.parse(fs.readFileSync(PID_FILE, 'utf-8'));+ const existing = readLiveServerInfo(process.cwd())?.info;if (existing && existing.pid) {try {process.kill(existing.pid, 0); // throws if deaddiff --git a/.gemini/skills/impeccable/scripts/load-context.mjs b/.gemini/skills/impeccable/scripts/load-context.mjsindex dca23c1f8..dc340bf16 100644--- a/.gemini/skills/impeccable/scripts/load-context.mjs+++ b/.gemini/skills/impeccable/scripts/load-context.mjs@@ -39,7 +39,7 @@ const LEGACY_NAMES = ['.impeccable.md'];const FALLBACK_DIRS = ['.agents/context', 'docs'];/**- * Resolve the directory that holds PRODUCT.md / DESIGN.md / DESIGN.json for+ * Resolve the directory that holds PRODUCT.md / DESIGN.md for* this project. Exported so other scripts (e.g. live-server.mjs) can read the* design files from the same location the loader uses.*/diff --git a/.github/skills/impeccable/reference/document.md b/.github/skills/impeccable/reference/document.mdindex 39afbd2ba..d27533278 100644--- a/.github/skills/impeccable/reference/document.md+++ b/.github/skills/impeccable/reference/document.md@@ -237,11 +237,11 @@ Concrete, forceful guardrails. Lead each with "Do" or "Don't". Be specific: incl- **Don't** [...]```-### Step 4b: Write DESIGN.json sidecar (extensions only)+### Step 4b: Write .impeccable/design.json sidecar (extensions only)-The frontmatter owns token primitives (colors, typography, rounded, spacing, components). The sidecar at `DESIGN.json` carries **what Stitch's schema can't hold**: tonal ramps per color, shadow/elevation tokens, motion tokens, breakpoints, full component HTML/CSS snippets (the panel renders these into a shadow DOM), and narrative (north star, rules, do's/don'ts). It extends the frontmatter, it doesn't duplicate it.+The frontmatter owns token primitives (colors, typography, rounded, spacing, components). The sidecar at `.impeccable/design.json` carries **what Stitch's schema can't hold**: tonal ramps per color, shadow/elevation tokens, motion tokens, breakpoints, full component HTML/CSS snippets (the panel renders these into a shadow DOM), and narrative (north star, rules, do's/don'ts). It extends the frontmatter, it doesn't duplicate it.-Regenerate the sidecar whenever you regenerate DESIGN.md. If the user only asks to refresh the sidecar (e.g., from the live panel's stale-hint), preserve DESIGN.md and write only DESIGN.json.+Regenerate the sidecar whenever you regenerate root `DESIGN.md`. If the user only asks to refresh the sidecar (e.g., from the live panel's stale-hint), preserve `DESIGN.md` and write only `.impeccable/design.json`.#### Schema@@ -310,7 +310,7 @@ Aim for a tight set of **5-10 components** that best represent the visual system- **Signature components (include if distinctive):** hero CTA, featured card, filter pill, any custom pattern the user mentioned as important in PRODUCT.md.- **Skip the rest.** Utility components, form building blocks, wrapper layouts: not worth documenting unless visually distinctive.-If the project has **no component library yet** (bare landing page, new project), synthesize canonical primitives from the tokens using best-practice defaults consistent with the DESIGN.md's rules. Every DESIGN.json has *something* to render, even on day zero.+If the project has **no component library yet** (bare landing page, new project), synthesize canonical primitives from the tokens using best-practice defaults consistent with the DESIGN.md's rules. Every `.impeccable/design.json` has *something* to render, even on day zero.#### Tonal ramps@@ -331,7 +331,7 @@ Do not reword. The panel shows these as secondary collapsible context; the same### Step 5: Confirm, refine, and refresh session cache1. Show the user the full DESIGN.md you wrote. Briefly highlight the non-obvious creative choices (descriptive color names, atmosphere language, named rules).-2. Mention that `DESIGN.json` was also written alongside; the live panel will now render this project's actual button/input/nav primitives instead of generic approximations.+2. Mention that `.impeccable/design.json` was also written alongside; the live panel will now render this project's actual button/input/nav primitives instead of generic approximations.3. Offer to refine any section: "Want me to revise a section, add component patterns I missed, or adjust the atmosphere language?"4. **Refresh the session cache.** Run `node .github/skills/impeccable/scripts/load-context.mjs` one final time so the newly-written DESIGN.md lands in conversation. Subsequent commands in this session will use the fresh version automatically without re-reading.@@ -392,7 +392,7 @@ Per-section guidance in seed mode:- **Components**: omit entirely; no components exist yet.- **Do's and Don'ts**: carry PRODUCT.md's anti-references directly plus the anti-reference named in Q5.-Seed mode writes a minimal frontmatter with `name` and `description` only; no colors, typography, rounded, spacing, or components yet. Real tokens land on the next Scan-mode run. Skip the `DESIGN.json` sidecar in seed mode for the same reason: nothing to render.+Seed mode writes a minimal frontmatter with `name` and `description` only; no colors, typography, rounded, spacing, or components yet. Real tokens land on the next Scan-mode run. Skip the `.impeccable/design.json` sidecar in seed mode for the same reason: nothing to render.### Step 4: Confirm and refresh session cachediff --git a/.github/skills/impeccable/reference/live.md b/.github/skills/impeccable/reference/live.mdindex 5d3c4293a..c71d361fb 100644--- a/.github/skills/impeccable/reference/live.md+++ b/.github/skills/impeccable/reference/live.md@@ -12,8 +12,9 @@ Execute in order. No step skipped, no step reordered.2. Navigate to the URL that serves `pageFile` (infer from `package.json`, docs, terminal output, or an open tab). If you can't infer it confidently, tell the user once to open their dev/preview URL. Never use `serverPort` as that URL; it's the helper, not the app.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=`.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.-5. On `accept` / `discard`: the poll script already cleaned up; just poll again.-6. On `exit`: run the cleanup at the bottom.+5. 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. If interrupted, run `live-status.mjs` or `live-resume.mjs` before guessing. The durable journal replays unacknowledged work after helper restart.+7. 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.@@ -43,13 +44,31 @@ LOOP:Read JSON; dispatch on "type""generate" → Handle Generate; reply done; LOOP- "accept" → Handle Accept; LOOP+ "accept" → Handle Accept; complete carbonize cleanup if required; LOOP"discard" → Handle Discard; LOOP"prefetch" → Handle Prefetch; LOOP"timeout" → LOOP"exit" → break → Cleanup```+## Recovery commands++The live helper persists an append-only journal under `.impeccable/live/sessions/`. Browser checkpoints are advisory but durable; the journal is canonical. This is local durable recovery state, not project source.++Use these commands when the chat was interrupted, polling was missed, the helper restarted, or the browser reloaded:++```bash+node .github/skills/impeccable/scripts/live-status.mjs+node .github/skills/impeccable/scripts/live-resume.mjs --id SESSION_ID+node .github/skills/impeccable/scripts/live-complete.mjs --id SESSION_ID+```++- `live-status.mjs` prints connected helper state, active durable sessions, and queued pending events. It works even when the helper is down by reading the journal directly.+- `live-resume.mjs` prints the active snapshot, pending event, checkpoint phase, visible variant, parameter values, and the next safe agent action.+- `live-complete.mjs` is the canonical manual final acknowledgement. Use it after carbonize/manual cleanup is verified and no further poll acknowledgement will happen automatically.++Server restart rule: start `live-server.mjs` again, then poll. Startup requeues unacknowledged pending events from the journal, so do not ask the user to click Go again unless `live-resume.mjs` says no active session exists.+## Handle `generate`Event: `{id, action, freeformPrompt?, count, pageUrl, element, screenshotPath?, comments?, strokes?}`.@@ -88,7 +107,14 @@ The helper searches ID first, then classes, then tag + class combo. If `event.paIf `--text` matches multiple candidates equally well, wrap exits with `{ error: "element_ambiguous", candidates: [...] }` and `fallback: "agent-driven"`: read the candidate line ranges, decide which one matches the picked element from page context, and write the wrapper manually per the fallback flow.-Output on success: `{ file, insertLine, commentSyntax }`.+Output on success: `{ file, insertLine, commentSyntax, styleMode, styleTag, cssSelectorPrefixExamples, cssAuthoring }`.++`styleMode` controls how preview CSS must be authored. Treat it as a detected capability mode, not a framework guess:++- `scoped`: use `@scope ([data-impeccable-variant="N"])` rules.+- `astro-global-prefixed`: use explicit `[data-impeccable-variant="N"]` selector prefixes and the exact `styleTag` returned by the tool.++Use `cssAuthoring` as the source of truth for the current file. It includes the exact `styleTag`, selector strategy, selector examples, requirements, and forbidden patterns. Do not apply a framework-specific exception unless the returned `styleMode` / `cssAuthoring.mode` says to.**Fallback errors.** Wrap only writes into files it judges to be source (tracked by git, not marked GENERATED, not listed in config's `generatedFiles`). If it can't land on a source file, it errors without writing; accepting a variant into a generated file is silent data loss. Three shapes:@@ -208,13 +234,14 @@ When the prompt and PRODUCT.md anti-references conflict (the prompt asks for X,Complete 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 scoped 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).+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).++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:```html<!-- Variants: insert below this line --><style data-impeccable-css="SESSION_ID">- @scope ([data-impeccable-variant="1"]) { ... }- @scope ([data-impeccable-variant="2"]) { ... }+ /* rules matching cssAuthoring.rulePattern */</style><div data-impeccable-variant="1"><!-- variant 1: full element replacement (single top-level element) -->@@ -229,11 +256,11 @@ Write CSS + all variants in ONE edit at the `insertLine` reported by `wrap`. Col**Each variant div contains exactly one top-level element: the full replacement for the original.** Use the same tag as the original (e.g. `<section>` if the user picked a `<section>`). Loose siblings (heading + paragraph + div as direct children of the variant div) break the outline tracking and the accept flow, which both assume one child.-The first variant has no `display: none` (visible by default). All others do. If variants use only inline styles and no scoped CSS, omit the `<style>` tag entirely. Use `@scope` for CSS isolation (Chrome 118+ / Firefox 128+ / Safari 17.4+).+The 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.-**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 rule starts `:scope > ...`.+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 > ...`.**JSX / TSX target files.** Wrap `<style>` content in a template literal so the CSS `{` / `}` aren't parsed as JSX expressions, and use `className=` / `style={{…}}` on every variant element. Keep `data-impeccable-*` attributes as-is; they're plain strings:@@ -369,10 +396,11 @@ Remove the wrapper you inserted in Step 2. Nothing else to do.## Handle `accept`-Event: `{id, variantId, _acceptResult}`. The poll script already ran `live-accept.mjs` to handle the file operation deterministically; the browser DOM is already updated.+Event: `{id, variantId, _acceptResult, _completionAck}`. The poll script already ran `live-accept.mjs` to handle the file operation deterministically, then acknowledged event delivery to the helper. The browser DOM is already updated.+- `_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 and a stderr banner both list the steps explicitly; neither is decorative.+- `_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: 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` without `mode`: manual cleanup: read file, find markers, edit.@@ -388,13 +416,13 @@ Do these five steps in the current thread, synchronously, before the next poll.4. **Unwrap the accepted content.** Delete the `<div data-impeccable-variant="N" style="display: contents">` that wraps it. Drop `data-impeccable-params` and any `data-p-*` attributes from it; 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.-Then poll again.+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.## Handle `discard`-Event: `{id, _acceptResult}`. The poll script already restored the original and removed all variant markers. Nothing to do. Poll again.+Event: `{id, _acceptResult, _completionAck}`. The poll script already restored the original, removed all variant markers, and acknowledged `discarded` durable completion. Nothing to do unless `_completionAck.ok !== true`; in that case run `live-complete.mjs --id EVENT_ID --discarded`, then poll again.## Handle `prefetch`@@ -424,7 +452,7 @@ When the poll returns `exit`, proceed to cleanup. If the poll is still running anode .github/skills/impeccable/scripts/live-server.mjs stop```-Stops the HTTP server and runs `live-inject.mjs --remove` to strip `localhost:…/live.js` from the HTML entry. To stop the server but keep the inject tag (for a quick restart), use `stop --keep-inject`. `config.json` persists for future sessions.+Stops the HTTP server and runs `live-inject.mjs --remove` to strip `localhost:…/live.js` from the HTML entry. To stop the server but keep the inject tag (for a quick restart), use `stop --keep-inject`. `.impeccable/live/config.json` persists as project config for future sessions.Then:- Remove any leftover variant wrappers (search for `impeccable-variants-start` markers).@@ -432,7 +460,7 @@ Then:## First-time setup (config missing or invalid)-If `live.mjs` outputs `{ ok: false, error: "config_missing" | "config_invalid", path }`, write `config.json` at the reported path.+If `live.mjs` outputs `{ ok: false, error: "config_missing" | "config_invalid", path }`, write the live config at the reported path. By default this is `.impeccable/live/config.json`.Schema:@@ -512,7 +540,7 @@ node .github/skills/impeccable/scripts/detect-csp.mjsOutput: `{ shape, signals }` where `shape` is one of `append-arrays`, `append-string`, `middleware`, `meta-tag`, or `null`. The shape is named by *patch mechanism*, so one template covers many frameworks.-- **`null`**: no CSP; skip to writing `config.json` with `cspChecked: true`.+- **`null`**: no CSP; skip to writing `.impeccable/live/config.json` with `cspChecked: true`.- **`append-arrays`**: CSP defined as structured directive arrays. Auto-patchable. See *append-arrays* below. Covers:- Monorepo helpers with `additionalScriptSrc` / `additionalConnectSrc` options (Next.js + shared config package)- SvelteKit `kit.csp.directives`@@ -589,6 +617,6 @@ Reference outputs:### Troubleshooting-If a user says "no" to the CSP patch at setup time and later complains that live doesn't work: their dev CSP blocks `http://localhost:8400`. Fix: delete `cspChecked` from `config.json` and re-run `live.mjs`: setup will ask again.+If a user says "no" to the CSP patch at setup time and later complains that live doesn't work: their dev CSP blocks `http://localhost:8400`. Fix: delete `cspChecked` from `.impeccable/live/config.json` and re-run `live.mjs`: setup will ask again.Then re-run `live.mjs`.diff --git a/.github/skills/impeccable/reference/teach.md b/.github/skills/impeccable/reference/teach.mdindex 724c6a98f..003e436e3 100644--- a/.github/skills/impeccable/reference/teach.md+++ b/.github/skills/impeccable/reference/teach.md@@ -2,8 +2,8 @@Gathers design context for a project and writes two complementary files at the project root:-- **PRODUCT.md** (strategic): register, target users, product purpose, brand personality, anti-references, strategic design principles. Answers "who/what/why".-- **DESIGN.md** (visual): visual theme, color palette, typography, components, layout. Follows the [Google Stitch DESIGN.md format](https://stitch.withgoogle.com/docs/design-md/format/). Answers "how it looks".+- **PRODUCT.md** (strategic): root project file for register, target users, product purpose, brand personality, anti-references, strategic design principles. Answers "who/what/why".+- **DESIGN.md** (visual): root project file for visual theme, color palette, typography, components, layout. Follows the [Google Stitch DESIGN.md format](https://stitch.withgoogle.com/docs/design-md/format/). Answers "how it looks".Every other impeccable command reads these files before doing any work.diff --git a/.github/skills/impeccable/scripts/impeccable-paths.mjs b/.github/skills/impeccable/scripts/impeccable-paths.mjsnew file mode 100644index 000000000..ba852bae9--- /dev/null+++ b/.github/skills/impeccable/scripts/impeccable-paths.mjs@@ -0,0 +1,105 @@+import fs from 'node:fs';+import path from 'node:path';++export const IMPECCABLE_DIR = '.impeccable';+export const LIVE_DIR = 'live';++export function getImpeccableDir(cwd = process.cwd()) {+ return path.join(cwd, IMPECCABLE_DIR);+}++export function getDesignSidecarPath(cwd = process.cwd()) {+ return path.join(getImpeccableDir(cwd), 'design.json');+}++export function getDesignSidecarCandidates(cwd = process.cwd(), contextDir = cwd) {+ const candidates = [+ getDesignSidecarPath(cwd),+ path.join(cwd, 'DESIGN.json'),+ ];+ const contextLegacy = path.join(contextDir, 'DESIGN.json');+ if (!candidates.includes(contextLegacy)) candidates.push(contextLegacy);+ return candidates;+}++export function resolveDesignSidecarPath(cwd = process.cwd(), contextDir = cwd) {+ return firstExisting(getDesignSidecarCandidates(cwd, contextDir));+}++export function getLiveDir(cwd = process.cwd()) {+ return path.join(getImpeccableDir(cwd), LIVE_DIR);+}++export function getLiveConfigPath(cwd = process.cwd()) {+ return path.join(getLiveDir(cwd), 'config.json');+}++export function getLegacyLiveConfigPath(scriptsDir) {+ return path.join(scriptsDir, 'config.json');+}++export function resolveLiveConfigPath({ cwd = process.cwd(), scriptsDir, env = process.env } = {}) {+ if (env.IMPECCABLE_LIVE_CONFIG && env.IMPECCABLE_LIVE_CONFIG.trim()) {+ const configured = env.IMPECCABLE_LIVE_CONFIG.trim();+ return path.isAbsolute(configured) ? configured : path.resolve(cwd, configured);+ }+ const primary = getLiveConfigPath(cwd);+ if (fs.existsSync(primary)) return primary;+ if (scriptsDir) {+ const legacy = getLegacyLiveConfigPath(scriptsDir);+ if (fs.existsSync(legacy)) return legacy;+ }+ return primary;+}++export function getLiveServerPath(cwd = process.cwd()) {+ return path.join(getLiveDir(cwd), 'server.json');+}++export function getLegacyLiveServerPath(cwd = process.cwd()) {+ return path.join(cwd, '.impeccable-live.json');+}++export function readLiveServerInfo(cwd = process.cwd()) {+ for (const filePath of [getLiveServerPath(cwd), getLegacyLiveServerPath(cwd)]) {+ try {+ return { info: JSON.parse(fs.readFileSync(filePath, 'utf-8')), path: filePath };+ } catch {+ /* try next */+ }+ }+ return null;+}++export function writeLiveServerInfo(cwd = process.cwd(), info) {+ const filePath = getLiveServerPath(cwd);+ fs.mkdirSync(path.dirname(filePath), { recursive: true });+ fs.writeFileSync(filePath, JSON.stringify(info));+ return filePath;+}++export function removeLiveServerInfo(cwd = process.cwd()) {+ for (const filePath of [getLiveServerPath(cwd), getLegacyLiveServerPath(cwd)]) {+ try { fs.unlinkSync(filePath); } catch {}+ }+}++export function getLiveSessionsDir(cwd = process.cwd()) {+ return path.join(getLiveDir(cwd), 'sessions');+}++export function getLegacyLiveSessionsDir(cwd = process.cwd()) {+ return path.join(cwd, '.impeccable-live', 'sessions');+}++export function getLiveAnnotationsDir(cwd = process.cwd()) {+ return path.join(getLiveDir(cwd), 'annotations');+}++export function getLegacyLiveAnnotationsDir(cwd = process.cwd()) {+ return path.join(cwd, '.impeccable-live', 'annotations');+}++function firstExisting(paths) {+ return paths.find((filePath) => fs.existsSync(filePath)) || null;+}diff --git a/.github/skills/impeccable/scripts/live-browser-session.js b/.github/skills/impeccable/scripts/live-browser-session.jsnew file mode 100644index 000000000..0e362d6be--- /dev/null+++ b/.github/skills/impeccable/scripts/live-browser-session.js@@ -0,0 +1,123 @@+/**+ * Browser-side durable session helpers for Impeccable live mode.+ *+ * Kept separate from live-browser.js so recovery state can be tested without+ * booting the full overlay UI. Served before live-browser.js and attached to+ * window.__IMPECCABLE_LIVE_SESSION__.+ */+(function (root) {+ 'use strict';++ function createLiveBrowserSessionState({ prefix, storage, idFactory }) {+ if (!prefix) throw new Error('prefix required');+ const store = storage || root.localStorage;+ const makeId = idFactory || function () { return Math.random().toString(16).slice(2, 10); };+ const sessionKey = prefix + '-session';+ const handledKey = sessionKey + '-handled';+ const scrollKey = sessionKey + '-scroll';+ let checkpointRevision = 0;+ const owner = makeId();++ function safeRead(key) {+ try { return store.getItem(key); } catch { return null; }+ }++ function safeWrite(key, value) {+ try { store.setItem(key, value); } catch { /* quota exceeded or private mode */ }+ }++ function safeRemove(key) {+ try { store.removeItem(key); } catch { /* unavailable storage */ }+ }++ function loadSession() {+ try {+ const raw = safeRead(sessionKey);+ if (!raw) return null;+ const parsed = JSON.parse(raw);+ if (Number.isInteger(parsed.checkpointRevision)) {+ checkpointRevision = Math.max(checkpointRevision, parsed.checkpointRevision);+ }+ return parsed;+ } catch { return null; }+ }++ function saveSession(session) {+ if (!session || !session.id) return;+ const payload = {+ ...session,+ checkpointRevision,+ };+ safeWrite(sessionKey, JSON.stringify(payload));+ }++ function clearSession() {+ safeRemove(sessionKey);+ }++ function nextCheckpointRevision() {+ checkpointRevision += 1;+ const existing = loadSession();+ if (existing?.id) saveSession(existing);+ return checkpointRevision;+ }++ function seedCheckpointRevision(value) {+ if (Number.isInteger(value)) checkpointRevision = Math.max(checkpointRevision, value);+ return checkpointRevision;+ }++ function currentCheckpointRevision() {+ return checkpointRevision;+ }++ function markHandled(id) {+ if (!id) return;+ safeWrite(handledKey, id);+ }++ function isHandled(id) {+ return !!id && safeRead(handledKey) === id;+ }++ function clearHandled() {+ safeRemove(handledKey);+ }++ function writeScrollY(y) {+ safeWrite(scrollKey, String(y));+ }++ function readScrollY() {+ const raw = safeRead(scrollKey);+ if (raw == null) return null;+ const n = parseFloat(raw);+ return isFinite(n) ? n : null;+ }++ function clearScrollY() {+ safeRemove(scrollKey);+ }++ return {+ owner,+ sessionKey,+ handledKey,+ scrollKey,+ saveSession,+ loadSession,+ clearSession,+ nextCheckpointRevision,+ seedCheckpointRevision,+ currentCheckpointRevision,+ markHandled,+ isHandled,+ clearHandled,+ writeScrollY,+ readScrollY,+ clearScrollY,+ };+ }++ root.__IMPECCABLE_LIVE_SESSION__ = { createLiveBrowserSessionState };+})(typeof window !== 'undefined' ? window : globalThis);diff --git a/.github/skills/impeccable/scripts/live-browser.js b/.github/skills/impeccable/scripts/live-browser.jsindex 3da76bb96..e67cd01ed 100644--- a/.github/skills/impeccable/scripts/live-browser.js+++ b/.github/skills/impeccable/scripts/live-browser.js@@ -50,6 +50,16 @@const Z = { highlight: 100001, bar: 100005, picker: 100007, toast: 100010 };const EASE = 'cubic-bezier(0.22, 1, 0.36, 1)'; // ease-out-quintconst PREFIX = 'impeccable-live';+ const sessionState = window.__IMPECCABLE_LIVE_SESSION__?.createLiveBrowserSessionState({+ prefix: PREFIX,+ storage: localStorage,+ idFactory: () => crypto.randomUUID().replace(/-/g, '').slice(0, 8),+ });+ if (!sessionState) {+ console.error('[impeccable] live-browser-session.js was not loaded. Live mode cannot start safely.');+ window.__IMPECCABLE_LIVE_INIT__ = false;+ return;+ }const HIGHLIGHT_TRANSITION ='top 140ms ' + EASE +', left 140ms ' + EASE +@@ -112,6 +122,8 @@let hasProjectContext = false;let selectedAction = 'impeccable';let selectedCount = 3;+ const browserOwner = sessionState.owner;+ let checkpointTimer = null;// Scroll lock — holds window.scrollY at a fixed value while the session is// active, so HMR DOM patches and variant swaps can't drift the page. See@@ -126,21 +138,9 @@// (Previously: saveSession wrote scrollY alongside state, so every call// during resume overwrote the pre-reload value with whatever the browser// had landed on, typically 0.)- const SCROLL_KEY_SUFFIX = '-scroll';- function writeScrollY(y) {- try { localStorage.setItem(LS_KEY + SCROLL_KEY_SUFFIX, String(y)); } catch {}- }- function readScrollY() {- try {- const raw = localStorage.getItem(LS_KEY + SCROLL_KEY_SUFFIX);- if (raw == null) return null;- const n = parseFloat(raw);- return isFinite(n) ? n : null;- } catch { return null; }- }- function clearScrollY() {- try { localStorage.removeItem(LS_KEY + SCROLL_KEY_SUFFIX); } catch {}- }+ function writeScrollY(y) { sessionState.writeScrollY(y); }+ function readScrollY() { return sessionState.readScrollY(); }+ function clearScrollY() { sessionState.clearScrollY(); }// Pre-empt the browser: apply manual scroll restoration and jump to the// saved scrollY at script-parse time. Retries on fonts.ready and load@@ -1585,6 +1585,7 @@paramsCurrentValues[p.id] = v;readout.textContent = formatRangeValue(input);applyParamValue(variantEl, p, v);+ queueCheckpoint('param_changed');});row.appendChild(input);} else if (p.kind === 'toggle') {@@ -1615,6 +1616,7 @@knob.style.left = next ? '18px' : '2px';readout.textContent = next ? 'On' : 'Off';applyParamValue(variantEl, p, next);+ queueCheckpoint('param_changed');});row.appendChild(track);} else if (p.kind === 'steps') {@@ -1651,6 +1653,7 @@btn.style.color = on ? 'oklch(98% 0 0)' : P.text;});applyParamValue(variantEl, p, o.value);+ queueCheckpoint('param_changed');});segRow.appendChild(b);segBtns.push({ btn: b, val: o.value });@@ -1872,19 +1875,26 @@return;}+ const previousVisibleVariant = currentSessionId === sessionId ? visibleVariant : 0;+// Replace the live element with the full wrapper from sourceconst wrapper = srcWrapper.cloneNode(true);liveEl.parentElement.replaceChild(wrapper, liveEl);- // Update state: count variants, show the first one+ // Update state: count variants, preserving the user's current variant+ // when a late HMR/source reinjection lands after they have cycled.const variants = wrapper.querySelectorAll('[data-impeccable-variant]:not([data-impeccable-variant="original"])');arrivedVariants = variants.length;expectedVariants = parseInt(wrapper.dataset.impeccableVariantCount || arrivedVariants);- visibleVariant = 1;- showVariantInDOM(sessionId, 1);+ const saved = loadSession();+ const savedVisibleVariant = saved && saved.id === sessionId ? saved.visible : 0;+ visibleVariant = previousVisibleVariant > 0 && previousVisibleVariant <= arrivedVariants+ ? previousVisibleVariant+ : (savedVisibleVariant > 0 && savedVisibleVariant <= arrivedVariants ? savedVisibleVariant : 1);+ showVariantInDOM(sessionId, visibleVariant);// Update selectedElement to the visible variant's content- selectedElement = pickVariantContent(wrapper, 1) || wrapper.parentElement;+ selectedElement = pickVariantContent(wrapper, visibleVariant) || wrapper.parentElement;state = 'CYCLING';hideShaderOverlay();@@ -1907,6 +1917,7 @@updateSelectedElement();updateBarContent('cycling');saveSession();+ queueCheckpoint('variant_changed');}function updateSelectedElement() {@@ -1917,6 +1928,18 @@if (visEl) selectedElement = visEl;}+ function readVisibleVariantFromDOM(sessionId) {+ const wrapper = document.querySelector('[data-impeccable-variants="' + sessionId + '"]');+ if (!wrapper) return 0;+ const variants = wrapper.querySelectorAll('[data-impeccable-variant]:not([data-impeccable-variant="original"])');+ for (const variant of variants) {+ if (variant.style.display === 'none') continue;+ const idx = parseInt(variant.dataset.impeccableVariant || '0', 10);+ if (idx > 0) return idx;+ }+ return 0;+ }+// Resolve the element that represents the variant's visible content.// Contract: each variant div should contain exactly one top-level element// (the full replacement). In practice a model may ship loose siblings or@@ -2107,8 +2130,10 @@updating = true;arrivedVariants = count;if (visibleVariant === 0 && arrivedVariants > 0) {- visibleVariant = 1;- showVariantInDOM(sessionId, 1);+ const saved = loadSession();+ const savedVisibleVariant = saved && saved.id === sessionId ? saved.visible : 0;+ visibleVariant = savedVisibleVariant > 0 && savedVisibleVariant <= arrivedVariants ? savedVisibleVariant : 1;+ showVariantInDOM(sessionId, visibleVariant);// showVariantInDOM hid the original (display:none); if we were still// anchored to the original's content, its boundingRect is now zero// and the bar snaps to (0,0). Re-point at the visible variant instead.@@ -2128,6 +2153,7 @@updateBarContent('generating');}saveSession();+ queueCheckpoint(state === 'CYCLING' ? 'variants_ready' : 'variants_progress');updating = false;});@@ -2236,6 +2262,7 @@/** Server died or became unreachable. Reset UI to a clean state. */function handleServerLost() {+ const recoveryState = currentSessionId ? state : 'IDLE';if (state === 'GENERATING' || state === 'CYCLING' || state === 'SAVING') {showToast('Live server disconnected. Session ended.', 5000);}@@ -2246,21 +2273,61 @@stopScrollTracking();if (variantObserver) { variantObserver.disconnect(); variantObserver = null; }stopScrollLock();- clearScrollY();- clearSession();+ // Preserve local session state on server loss. The durable journal is the+ // source of truth, but localStorage plus the variant wrapper lets the UI+ // resume after a helper restart or page reload instead of treating a+ // transient disconnect as an explicit discard.selectedElement = null;- currentSessionId = null;selectedAction = 'impeccable';- state = 'IDLE';+ state = recoveryState;+ if (currentSessionId) saveSession();}- function sendEvent(msg) {+ function sendEvent(msg, opts) {msg.token = TOKEN;- fetch('http://localhost:' + PORT + '/events', {+ function handleFailure(err) {+ console.error('[impeccable] Failed to send event:', err);+ if (opts && opts.throwOnError) throw err;+ return null;+ }+ return fetch('http://localhost:' + PORT + '/events', {method: 'POST',headers: { 'Content-Type': 'application/json' },body: JSON.stringify(msg),- }).catch(err => console.error('[impeccable] Failed to send event:', err));+ }).then(res => {+ if (res.ok) return res;+ return handleFailure(new Error('HTTP ' + res.status + ' ' + res.statusText));+ }).catch(handleFailure);+ }++ function checkpointPayload(reason) {+ return {+ type: 'checkpoint',+ id: currentSessionId,+ revision: sessionState.nextCheckpointRevision(),+ owner: browserOwner,+ phase: String(state || '').toLowerCase(),+ reason,+ pageUrl: location.pathname,+ expectedVariants,+ arrivedVariants,+ visibleVariant,+ paramValues: { ...paramsCurrentValues },+ };+ }++ function sendCheckpoint(reason) {+ if (!currentSessionId) return Promise.resolve(null);+ return sendEvent(checkpointPayload(reason)).catch(() => null);+ }++ function queueCheckpoint(reason) {+ if (!currentSessionId) return;+ if (checkpointTimer) clearTimeout(checkpointTimer);+ checkpointTimer = setTimeout(() => {+ checkpointTimer = null;+ sendCheckpoint(reason);+ }, 120);}// ---------------------------------------------------------------------------@@ -2496,6 +2563,7 @@state = 'GENERATING';showBar('generating');saveSession();+ sendCheckpoint('generate_started');writeScrollY(window.scrollY);if (variantObserver) variantObserver.disconnect();variantObserver = startVariantObserver(currentSessionId);@@ -2920,13 +2988,12 @@ void main() {function handleAccept() {if (!currentSessionId || arrivedVariants === 0) return;+ const domVisibleVariant = readVisibleVariantFromDOM(currentSessionId);+ if (domVisibleVariant > 0) visibleVariant = domVisibleVariant;const acceptPayload = { type: 'accept', id: currentSessionId, variantId: String(visibleVariant) };if (Object.keys(paramsCurrentValues).length > 0) {acceptPayload.paramValues = { ...paramsCurrentValues };}- sendEvent(acceptPayload);- markSessionHandled();-// The accepted variant is already the only visible child of the wrapper// (all other variants are display:none). HMR from the source rewrite will// replace the wrapper imminently. Don't eagerly replaceChild here — React@@ -2936,9 +3003,28 @@ void main() {const acceptedSessionId = currentSessionId;const acceptedVariant = visibleVariant;- state = 'CONFIRMED';- updateBarContent('confirmed');- setTimeout(function() {+ state = 'SAVING';+ updateBarContent('saving');++ sendEvent(acceptPayload, { throwOnError: true })+ .then(() => {+ markSessionHandled();+ confirmAcceptAfterReceipt();+ })+ .catch(() => {+ state = 'CYCLING';+ updateBarContent('cycling');+ showToast('Could not confirm accept with the live server. Session kept for recovery; try Accept again.', 5000);+ });++ function confirmAcceptAfterReceipt() {+ state = 'CONFIRMED';+ updateBarContent('confirmed');+ scheduleAcceptCleanup();+ }++ function scheduleAcceptCleanup() {+ setTimeout(function() {hideBar();hideHighlight();stopScrollTracking();@@ -2967,50 +3053,46 @@ void main() {accepted.style.display = 'contents';parent.replaceChild(accepted, wrapper);}- }, 2000);+ }, 2000);+ }}function handleDiscard() {if (!currentSessionId) return;- sendEvent({ type: 'discard', id: currentSessionId });- markSessionHandled();- // Instant DOM restore + fire-and-forget (script handles file cleanup)- cleanup();+ sendEvent({ type: 'discard', id: currentSessionId }, { throwOnError: true })+ .then(() => {+ markSessionHandled();+ cleanup();+ })+ .catch(() => showToast('Could not confirm discard with the live server. Session kept for recovery.', 5000));}// ---------------------------------------------------------------------------- // Session persistence via localStorage+ // Session persistence via live-browser-session.js// ---------------------------------------------------------------------------// Survives page reloads, browser close/reopen, HMR, and accidental refreshes.- const LS_KEY = PREFIX + '-session';-function saveSession() {if (!currentSessionId) return;// NOTE: scrollY is stored under a separate key (writeScrollY). Storing// it here would overwrite the Go-time value every time state changes.- try {- localStorage.setItem(LS_KEY, JSON.stringify({- id: currentSessionId,- state: state,- action: selectedAction,- count: selectedCount,- expected: expectedVariants,- arrived: arrivedVariants,- visible: visibleVariant,- }));- } catch { /* quota exceeded or private mode */ }+ sessionState.saveSession({+ id: currentSessionId,+ state,+ action: selectedAction,+ count: selectedCount,+ expected: expectedVariants,+ arrived: arrivedVariants,+ visible: visibleVariant,+ });}function loadSession() {- try {- const raw = localStorage.getItem(LS_KEY);- return raw ? JSON.parse(raw) : null;- } catch { return null; }+ return sessionState.loadSession();}function clearSession() {- try { localStorage.removeItem(LS_KEY); } catch {}+ sessionState.clearSession();}/** Mark session as handled (accepted/discarded). The agent will clean up@@ -3018,19 +3100,15 @@ void main() {* prevents resumeSession from picking it up again after reload. */function markSessionHandled() {if (!currentSessionId) return;- try {- localStorage.setItem(LS_KEY + '-handled', currentSessionId);- } catch {}+ sessionState.markHandled(currentSessionId);}function isSessionHandled(id) {- try {- return localStorage.getItem(LS_KEY + '-handled') === id;- } catch { return false; }+ return sessionState.isHandled(id);}function clearHandled() {- try { localStorage.removeItem(LS_KEY + '-handled'); } catch {}+ sessionState.clearHandled();}function cleanup() {@@ -3161,6 +3239,7 @@ void main() {// hid. Now that state is CYCLING, re-fire.if (state === 'CYCLING') refreshParamsPanel();saveSession();+ queueCheckpoint('browser_resumed');// Start observing for more variants AFTER initial setupif (variantObserver) variantObserver.disconnect();@@ -3617,7 +3696,7 @@ void main() {}// ---------------------------------------------------------------------------- // Design System Panel — visualizes the project's DESIGN.json sidecar+ // Design System Panel — visualizes the project's .impeccable/design.json sidecar// ---------------------------------------------------------------------------const DESIGN_PREFS_KEY = 'impeccable-live-design-panel';@@ -3629,7 +3708,7 @@ void main() {open: false,tab: 'visual', // 'visual' | 'raw'parsed: null, // parseDesignMd output (frontmatter + body sections)- sidecar: null, // DESIGN.json v2 payload (extensions + components + narrative)+ sidecar: null, // .impeccable/design.json v2 payload (extensions + components + narrative)hasMd: false,hasSidecar: false,present: null, // true/false once fetch resolves@@ -4130,7 +4209,7 @@ void main() {box.className = 'stale';box.innerHTML = `<span class="stale-dot"></span>- <span class="stale-text"><strong>DESIGN.md is newer than DESIGN.json.</strong> Run <code>/impeccable document</code> to refresh the sidecar.</span>+ <span class="stale-text"><strong>DESIGN.md is newer than .impeccable/design.json.</strong> Run <code>/impeccable document</code> to refresh the sidecar.</span>`;return box;}@@ -4138,7 +4217,7 @@ void main() {function renderParsedMdCta() {const box = document.createElement('div');box.className = 'parsed-md-cta';- box.innerHTML = `<strong>Basic view</strong>This panel reads the tokens in your <code>DESIGN.md</code> frontmatter. Running <code>/impeccable document</code> also generates a <code>DESIGN.json</code> sidecar with your project's actual component snippets (button, input, nav) and tonal ramps, rendered live below the tokens.`;+ box.innerHTML = `<strong>Basic view</strong>This panel reads the tokens in your <code>DESIGN.md</code> frontmatter. Running <code>/impeccable document</code> also generates a <code>.impeccable/design.json</code> sidecar with your project's actual component snippets (button, input, nav) and tonal ramps, rendered live below the tokens.`;return box;}@@ -4598,7 +4677,7 @@ void main() {function cssSafe(v) {// Strip anything outside valid CSS value chars to prevent injection via- // DESIGN.json values rendered into inline style strings.+ // .impeccable/design.json values rendered into inline style strings.return String(v).replace(/[<>"'`\n]/g, '');}diff --git a/.github/skills/impeccable/scripts/live-complete.mjs b/.github/skills/impeccable/scripts/live-complete.mjsnew file mode 100644index 000000000..78155af85--- /dev/null+++ b/.github/skills/impeccable/scripts/live-complete.mjs@@ -0,0 +1,75 @@+#!/usr/bin/env node+/**+ * Canonical durable completion acknowledgement for Impeccable live sessions.+ */++import { createLiveSessionStore } from './live-session-store.mjs';+import { readLiveServerInfo } from './impeccable-paths.mjs';++function parseArgs(argv) {+ const out = { status: 'complete' };+ for (let i = 0; i < argv.length; i++) {+ const arg = argv[i];+ if (arg === '--id') out.id = argv[++i];+ else if (arg.startsWith('--id=')) out.id = arg.slice('--id='.length);+ else if (arg === '--discarded' || arg === '--discard') out.status = 'discarded';+ else if (arg === '--error') { out.status = 'agent_error'; out.message = argv[++i] || 'unknown error'; }+ else if (arg.startsWith('--error=')) { out.status = 'agent_error'; out.message = arg.slice('--error='.length); }+ else if (arg === '--help' || arg === '-h') out.help = true;+ }+ return out;+}++export async function completeCli() {+ const args = parseArgs(process.argv.slice(2));+ if (args.help || !args.id) {+ console.log(`Usage: node live-complete.mjs --id SESSION_ID [--discarded|--error MESSAGE]\n\nAppend the final durable session acknowledgement. Use after accept/discard cleanup is verified.`);+ process.exit(args.help ? 0 : 1);+ }++ const serverInfo = readServerInfo();+ const serverResult = serverInfo ? await completeThroughServer(serverInfo, args) : null;+ if (serverResult?.ok) {+ const store = createLiveSessionStore({ cwd: process.cwd(), sessionId: args.id });+ const snapshot = store.getSnapshot(args.id, { includeCompleted: true });+ console.log(JSON.stringify({ ok: true, id: args.id, phase: snapshot?.phase || args.status, snapshot }, null, 2));+ return;+ }++ const store = createLiveSessionStore({ cwd: process.cwd(), sessionId: args.id });+ const event = args.status === 'discarded'+ ? { type: 'discarded', id: args.id }+ : args.status === 'agent_error'+ ? { type: 'agent_error', id: args.id, message: args.message || 'unknown error' }+ : { type: 'complete', id: args.id };+ const snapshot = store.appendEvent(event);+ console.log(JSON.stringify({ ok: true, id: args.id, phase: snapshot.phase, snapshot }, null, 2));+}++function readServerInfo() {+ return readLiveServerInfo(process.cwd())?.info || null;+}++async function completeThroughServer(info, args) {+ const type = args.status === 'discarded'+ ? 'discarded'+ : args.status === 'agent_error'+ ? 'error'+ : 'complete';+ try {+ const res = await fetch(`http://localhost:${info.port}/poll`, {+ method: 'POST',+ headers: { 'Content-Type': 'application/json' },+ body: JSON.stringify({ token: info.token, id: args.id, type, message: args.message }),+ });+ if (!res.ok) return null;+ return await res.json();+ } catch {+ return null;+ }+}++const _running = process.argv[1];+if (_running?.endsWith('live-complete.mjs') || _running?.endsWith('live-complete.mjs/')) {+ completeCli();+}diff --git a/.github/skills/impeccable/scripts/live-completion.mjs b/.github/skills/impeccable/scripts/live-completion.mjsnew file mode 100644index 000000000..86b637fff--- /dev/null+++ b/.github/skills/impeccable/scripts/live-completion.mjs@@ -0,0 +1,18 @@+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';+ return 'agent_done';+}++export function completionAckForAcceptResult(eventId, completionType, acceptResult) {+ const ack = { ok: true, type: completionType };+ if (acceptResult?.handled === true && acceptResult?.carbonize === true) {+ ack.final = false;+ ack.requiresComplete = true;+ ack.nextCommand = `live-complete.mjs --id ${eventId}`;+ ack.message = 'Carbonize cleanup must be verified, then the session must be completed explicitly before polling again.';+ }+ return ack;+}diff --git a/.github/skills/impeccable/scripts/live-inject.mjs b/.github/skills/impeccable/scripts/live-inject.mjsindex 1d2ae12f7..555c3a36a 100644--- a/.github/skills/impeccable/scripts/live-inject.mjs+++ b/.github/skills/impeccable/scripts/live-inject.mjs@@ -2,23 +2,24 @@* CLI helper: insert/remove the live variant mode script tag in the project's* main HTML entry point.*- * On first live run, the agent generates `config.json` in this script's- * directory with the project's insertion target (framework-specific). On+ * On first live run, the agent generates `.impeccable/live/config.json`+ * with the project's insertion target (framework-specific). On* every subsequent run, this script handles insert/remove deterministically* with zero LLM involvement.** Usage:* node live-inject.mjs --port PORT # Insert the live script tag* node live-inject.mjs --remove # Remove the live script tag- * node live-inject.mjs --check # Check whether config.json exists+ * node live-inject.mjs --check # Check whether live config exists*/import fs from 'node:fs';import path from 'node:path';import { fileURLToPath } from 'node:url';+import { resolveLiveConfigPath } from './impeccable-paths.mjs';const __dirname = path.dirname(fileURLToPath(import.meta.url));-const CONFIG_PATH = process.env.IMPECCABLE_LIVE_CONFIG || path.join(__dirname, 'config.json');+const CONFIG_PATH = resolveLiveConfigPath({ cwd: process.cwd(), scriptsDir: __dirname });const MARKER_OPEN_TEXT = 'impeccable-live-start';const MARKER_CLOSE_TEXT = 'impeccable-live-end';@@ -39,12 +40,12 @@ export async function injectCli() {console.log(`Usage: node live-inject.mjs [options]Insert or remove the live mode script tag in the project's HTML entry point.-Reads configuration from config.json (in this same directory).+Reads configuration from .impeccable/live/config.json.Modes:--port PORT Insert script tag pointing at http://localhost:PORT/live.js--remove Remove the script tag (if present)- --check Print whether config.json exists and its content+ --check Print whether .impeccable/live/config.json exists and its contentOutput (JSON):{ ok, file, inserted|removed, config? }`);diff --git a/.github/skills/impeccable/scripts/live-poll.mjs b/.github/skills/impeccable/scripts/live-poll.mjsindex eb8f1586a..10d452491 100644--- a/.github/skills/impeccable/scripts/live-poll.mjs+++ b/.github/skills/impeccable/scripts/live-poll.mjs@@ -9,10 +9,10 @@*/import { execFileSync } from 'node:child_process';-import fs from 'node:fs';import path from 'node:path';-import os from 'node:os';import { fileURLToPath } from 'node:url';+import { completionAckForAcceptResult, completionTypeForAcceptResult } from './live-completion.mjs';+import { readLiveServerInfo } from './impeccable-paths.mjs';// Node's built-in fetch (undici under the hood) enforces a 300s headers// timeout that can't be lowered per-request. We cap each request below@@ -20,15 +20,29 @@ import { fileURLToPath } from 'node:url';// depending on the standalone undici package.const PER_REQUEST_TIMEOUT_MS = 270_000;-const LIVE_PID_FILE = path.join(process.cwd(), '.impeccable-live.json');-function readServerInfo() {- try {- return JSON.parse(fs.readFileSync(LIVE_PID_FILE, 'utf-8'));- } catch {+ const record = readLiveServerInfo(process.cwd());+ if (!record) {console.error('No running live server found. Start one with: npx impeccable live');process.exit(1);}+ return record.info;+}++export function buildPollReplyPayload(token, { id, type, message, file, data }) {+ return { token, id, type, message, file, data };+}++async function postReply(base, token, reply) {+ const res = await fetch(`${base}/poll`, {+ method: 'POST',+ headers: { 'Content-Type': 'application/json' },+ body: JSON.stringify(buildPollReplyPayload(token, reply)),+ });+ if (!res.ok) {+ const body = await res.json().catch(() => ({}));+ throw new Error(body.error || res.statusText);+ }}export async function pollCli() {@@ -69,23 +83,7 @@ Options:}try {- const res = await fetch(`${base}/poll`, {- method: 'POST',- headers: { 'Content-Type': 'application/json' },- body: JSON.stringify({- token: info.token,- id,- type: status,- message,- file: filePath,- }),- });-- if (!res.ok) {- const body = await res.json().catch(() => ({}));- console.error(`Reply failed (${res.status}):`, body.error || res.statusText);- process.exit(1);- }+ await postReply(base, info.token, { id, type: status, message, file: filePath });// Success — silent exit (agent doesn't need output for replies)} catch (err) {@@ -156,7 +154,23 @@ Options:);event._acceptResult = JSON.parse(out.trim());} catch (err) {- event._acceptResult = { handled: false, error: err.message };+ event._acceptResult = { handled: false, mode: 'error', error: err.message };+ }++ const completionType = completionTypeForAcceptResult(event.type, event._acceptResult);+ try {+ await postReply(base, info.token, {+ id: event.id,+ type: completionType,+ message: event._acceptResult?.error,+ file: event._acceptResult?.file,+ data: event._acceptResult?.carbonize === true ? { carbonize: true } : undefined,+ });+ } catch (err) {+ event._completionAck = { ok: false, error: err.message };+ }+ if (!event._completionAck) {+ event._completionAck = completionAckForAcceptResult(event.id, completionType, event._acceptResult);}}@@ -164,7 +178,7 @@ Options:// JSON but skips nested fields. One line is enough — the full checklist// is in reference/live.md.if (event._acceptResult?.carbonize === true) {- process.stderr.write('\n⚠ Carbonize cleanup REQUIRED before next poll. See reference/live.md "Required after accept".\n\n');+ process.stderr.write('\n⚠ Carbonize cleanup REQUIRED before next poll. After cleanup, run live-complete.mjs --id ' + event.id + '. See reference/live.md "Required after accept".\n\n');}// Print the event as JSON — the agent reads this from stdoutdiff --git a/.github/skills/impeccable/scripts/live-resume.mjs b/.github/skills/impeccable/scripts/live-resume.mjsnew file mode 100644index 000000000..a3465c9b5--- /dev/null+++ b/.github/skills/impeccable/scripts/live-resume.mjs@@ -0,0 +1,48 @@+#!/usr/bin/env node+/**+ * Recover the next agent action from the durable live-session journal.+ */++import { createLiveSessionStore } from './live-session-store.mjs';++function parseArgs(argv) {+ const out = { id: null };+ for (let i = 0; i < argv.length; i++) {+ const arg = argv[i];+ if (arg === '--id') out.id = argv[++i];+ else if (arg.startsWith('--id=')) out.id = arg.slice('--id='.length);+ else if (arg === '--help' || arg === '-h') out.help = true;+ }+ return out;+}++export async function resumeCli() {+ const args = parseArgs(process.argv.slice(2));+ if (args.help) {+ console.log(`Usage: node live-resume.mjs [--id SESSION_ID]\n\nPrint the active durable session checkpoint and the next safe agent action.`);+ return;+ }++ const store = createLiveSessionStore({ cwd: process.cwd(), sessionId: args.id || undefined });+ const snapshot = args.id ? store.getSnapshot(args.id) : store.listActiveSessions()[0] || null;+ if (!snapshot) {+ console.log(JSON.stringify({ active: false, nextAction: 'No active durable live session found.' }, null, 2));+ return;+ }++ const pending = snapshot.pendingEvent || null;+ const nextAction = pending+ ? `Run live-poll.mjs, handle ${pending.type} ${pending.id}, then acknowledge with live-poll.mjs --reply ${pending.id} done.`+ : snapshot.phase === 'carbonize_required'+ ? `Finish carbonize cleanup${snapshot.sourceFile ? ` in ${snapshot.sourceFile}` : ''}, then run live-complete.mjs --id ${snapshot.id}.`+ : snapshot.phase === 'accept_requested'+ ? `Run live-complete.mjs --id ${snapshot.id} after verifying the accepted variant is written.`+ : `Inspect ${snapshot.id}; no pending agent event is currently queued.`;++ console.log(JSON.stringify({ active: true, snapshot, pendingEvent: pending, nextAction }, null, 2));+}++const _running = process.argv[1];+if (_running?.endsWith('live-resume.mjs') || _running?.endsWith('live-resume.mjs/')) {+ resumeCli();+}diff --git a/.github/skills/impeccable/scripts/live-server.mjs b/.github/skills/impeccable/scripts/live-server.mjsindex 90614fbf7..53d8f21cb 100644--- a/.github/skills/impeccable/scripts/live-server.mjs+++ b/.github/skills/impeccable/scripts/live-server.mjs@@ -22,14 +22,20 @@ import net from 'node:net';import { fileURLToPath } from 'node:url';import { parseDesignMd } from './design-parser.mjs';import { resolveContextDir } from './load-context.mjs';+import { createLiveSessionStore } from './live-session-store.mjs';+import {+ getDesignSidecarPath,+ getLiveAnnotationsDir,+ readLiveServerInfo,+ removeLiveServerInfo,+ resolveDesignSidecarPath,+ writeLiveServerInfo,+} from './impeccable-paths.mjs';const __dirname = path.dirname(fileURLToPath(import.meta.url));-// PID file in the project root so both the server and agent can find it-// predictably (os.tmpdir() varies across platforms).-const LIVE_PID_FILE = path.join(process.cwd(), '.impeccable-live.json');-// PRODUCT.md / DESIGN.md / DESIGN.json live wherever load-context.mjs resolves.-// Keeps live-server in sync with the loader when users keep the docs in-// .agents/context/, docs/, or a path set via IMPECCABLE_CONTEXT_DIR.+// PRODUCT.md / DESIGN.md live wherever load-context.mjs resolves. The generated+// DESIGN sidecar is project-local at .impeccable/design.json, with legacy+// DESIGN.json fallback for existing projects.const CONTEXT_DIR = resolveContextDir(process.cwd());const DEFAULT_POLL_TIMEOUT = 600_000; // 10 min — agent re-polls on timeout anywayconst SSE_HEARTBEAT_INTERVAL = 30_000; // keepalive ping every 30s@@ -57,10 +63,12 @@ const state = {token: null,port: null,sseClients: new Set(), // SSE response objects (server→browser push)- pendingEvents: [], // browser events waiting for agent poll+ pendingEvents: [], // browser events waiting for agent ack ({ event, leaseUntil })pendingPolls: [], // agent poll callbacks waiting for browser eventsexitTimer: null,sessionDir: null, // per-session tmp dir for annotation screenshots+ sessionStore: null,+ leaseTimer: null,};// Cap per-annotation upload size. A full 1920×1080 PNG is typically <1 MB;@@ -68,11 +76,70 @@ const state = {const MAX_ANNOTATION_BYTES = 10 * 1024 * 1024;function enqueueEvent(event) {- if (state.pendingPolls.length > 0) {- state.pendingPolls.shift()(event);- } else {- state.pendingEvents.push(event);+ if (!event || (event.id && state.pendingEvents.some((entry) => entry.event?.id === event.id && entry.event?.type === event.type))) return;+ state.pendingEvents.push({ event, leaseUntil: 0 });+ flushPendingPolls();+}++function restorePendingEventsFromStore() {+ if (!state.sessionStore) return;+ for (const snapshot of state.sessionStore.listActiveSessions()) {+ if (snapshot.pendingEvent) enqueueEvent(snapshot.pendingEvent);+ }+}++function findAvailablePendingEvent(now = Date.now()) {+ return state.pendingEvents.find((entry) => !entry.leaseUntil || entry.leaseUntil <= now);+}++function leaseEvent(entry, leaseMs) {+ if (!entry.event?.id) {+ const idx = state.pendingEvents.indexOf(entry);+ if (idx !== -1) state.pendingEvents.splice(idx, 1);+ return entry.event;}+ entry.leaseUntil = Date.now() + leaseMs;+ return entry.event;+}++function acknowledgePendingEvent(id) {+ if (!id) return false;+ const idx = state.pendingEvents.findIndex((entry) => entry.event?.id === id);+ if (idx === -1) return false;+ state.pendingEvents.splice(idx, 1);+ scheduleLeaseFlush();+ return true;+}++function scheduleLeaseFlush() {+ if (state.leaseTimer) {+ clearTimeout(state.leaseTimer);+ state.leaseTimer = null;+ }+ if (state.pendingPolls.length === 0) return;+ const now = Date.now();+ const nextLeaseUntil = state.pendingEvents+ .map((entry) => entry.leaseUntil || 0)+ .filter((leaseUntil) => leaseUntil > now)+ .sort((a, b) => a - b)[0];+ if (!nextLeaseUntil) return;+ state.leaseTimer = setTimeout(() => {+ state.leaseTimer = null;+ flushPendingPolls();+ }, Math.max(0, nextLeaseUntil - now));+}++function flushPendingPolls() {+ while (state.pendingPolls.length > 0) {+ const entry = findAvailablePendingEvent();+ if (!entry) {+ scheduleLeaseFlush();+ return;+ }+ const poll = state.pendingPolls.shift();+ poll.resolve(leaseEvent(entry, poll.leaseMs));+ }+ scheduleLeaseFlush();}/** Push a message to all connected SSE clients. */@@ -103,13 +170,16 @@ function loadBrowserScripts() {// live-browser.js: DO NOT cache. Return the path so the /live.js handler// can re-read on every request. Editing the browser script during iteration// should land on the next tab reload, not require a server restart.+ const sessionPath = path.join(__dirname, 'live-browser-session.js');const livePath = path.join(__dirname, 'live-browser.js');- if (!fs.existsSync(livePath)) {- process.stderr.write('Error: live-browser.js not found at ' + livePath + '\n');- process.exit(1);+ for (const p of [sessionPath, livePath]) {+ if (!fs.existsSync(p)) {+ process.stderr.write('Error: live browser script not found at ' + p + '\n');+ process.exit(1);+ }}- return { detectScript, livePath };+ return { detectScript, sessionPath, livePath };}function hasProjectContext() {@@ -170,6 +240,13 @@ function validateEvent(msg) {return null;case 'discard':return isValidId(msg.id) ? null : 'discard: missing or malformed id';+ case 'checkpoint':+ if (!isValidId(msg.id)) return 'checkpoint: missing or malformed id';+ if (!Number.isInteger(msg.revision) || msg.revision < 0) return 'checkpoint: revision must be a non-negative integer';+ if (msg.paramValues !== undefined && (typeof msg.paramValues !== 'object' || msg.paramValues === null || Array.isArray(msg.paramValues))) {+ return 'checkpoint: paramValues must be an object';+ }+ return null;case 'exit':return null;case 'prefetch':@@ -184,7 +261,7 @@ function validateEvent(msg) {// HTTP request handler// ----------------------------------------------------------------------------function createRequestHandler({ detectScript, livePath }) {+function createRequestHandler({ detectScript, sessionPath, livePath }) {return (req, res) => {const url = new URL(req.url, `http://localhost:${state.port}`);res.setHeader('Access-Control-Allow-Origin', '*');@@ -200,17 +277,20 @@ function createRequestHandler({ detectScript, livePath }) {// the next tab reload. No-store headers prevent browser caching across// sessions — during iteration, a cached old script silently breaks// every subsequent session.+ let sessionScript;let liveScript;try {+ sessionScript = fs.readFileSync(sessionPath, 'utf-8');liveScript = fs.readFileSync(livePath, 'utf-8');} catch (err) {res.writeHead(500, { 'Content-Type': 'text/plain' });- res.end('Error reading live-browser.js: ' + err.message);+ res.end('Error reading live browser scripts: ' + err.message);return;}const body =`window.__IMPECCABLE_TOKEN__ = '${state.token}';\n` +`window.__IMPECCABLE_PORT__ = ${state.port};\n` ++ sessionScript + '\n' +liveScript;res.writeHead(200, {'Content-Type': 'application/javascript',@@ -305,6 +385,26 @@ function createRequestHandler({ detectScript, livePath }) {}// --- Health ---+ if (p === '/status') {+ const token = url.searchParams.get('token');+ if (token !== state.token) { res.writeHead(401, { 'Content-Type': 'application/json' }); res.end(JSON.stringify({ error: 'Unauthorized' })); return; }+ const sessions = state.sessionStore ? state.sessionStore.listActiveSessions() : [];+ res.writeHead(200, { 'Content-Type': 'application/json' });+ res.end(JSON.stringify({+ status: 'ok',+ port: state.port,+ connectedClients: state.sseClients.size,+ pendingEvents: state.pendingEvents.map((entry) => ({+ id: entry.event?.id,+ type: entry.event?.type,+ leased: !!(entry.leaseUntil && entry.leaseUntil > Date.now()),+ leaseUntil: entry.leaseUntil || null,+ })),+ activeSessions: sessions,+ }));+ return;+ }+if (p === '/health') {res.writeHead(200, { 'Content-Type': 'application/json' });res.end(JSON.stringify({@@ -316,13 +416,13 @@ function createRequestHandler({ detectScript, livePath }) {}// --- Design system (unified v2 response) + raw ---- // /design-system.json returns both parsed DESIGN.md and DESIGN.json+ // /design-system.json returns both parsed DESIGN.md and .impeccable/design.json// sidecar when present. Panel merges them:// { present, parsed, sidecar, hasMd, hasSidecar,// mdNewerThanJson, parseError?, sidecarError? }// - parsed: output of parseDesignMd (frontmatter// + six canonical sections) when DESIGN.md exists.- // - sidecar: DESIGN.json contents when present.+ // - sidecar: .impeccable/design.json contents when present.// Expected shape: schemaVersion 2, carrying// extensions + components + narrative.// /design-system/raw returns DESIGN.md markdown verbatim@@ -331,7 +431,7 @@ function createRequestHandler({ detectScript, livePath }) {if (token !== state.token) { res.writeHead(401); res.end('Unauthorized'); return; }const mdPath = path.join(CONTEXT_DIR, 'DESIGN.md');- const jsonPath = path.join(CONTEXT_DIR, 'DESIGN.json');+ const jsonPath = resolveDesignSidecarPath(process.cwd(), CONTEXT_DIR) || getDesignSidecarPath(process.cwd());const mdStat = statOrNull(mdPath);const jsonStat = statOrNull(jsonPath);@@ -367,7 +467,7 @@ function createRequestHandler({ detectScript, livePath }) {try {response.sidecar = JSON.parse(fs.readFileSync(jsonPath, 'utf-8'));} catch (err) {- response.sidecarError = 'Failed to parse DESIGN.json: ' + err.message;+ response.sidecarError = 'Failed to parse .impeccable/design.json: ' + err.message;}}@@ -449,7 +549,16 @@ function createRequestHandler({ detectScript, livePath }) {res.end(JSON.stringify({ error }));return;}- enqueueEvent(msg);+ if (state.sessionStore && msg.id) {+ try {+ state.sessionStore.appendEvent(msg);+ } catch (err) {+ res.writeHead(500, { 'Content-Type': 'application/json' });+ res.end(JSON.stringify({ error: 'session_store_append_failed', message: err.message }));+ return;+ }+ }+ if (msg.type !== 'checkpoint') enqueueEvent(msg);res.writeHead(200, { 'Content-Type': 'application/json' });res.end(JSON.stringify({ ok: true }));});@@ -492,13 +601,16 @@ function handlePollGet(req, res, url) {return;}const timeout = parseInt(url.searchParams.get('timeout') || DEFAULT_POLL_TIMEOUT, 10);- if (state.pendingEvents.length > 0) {+ const leaseMs = parseInt(url.searchParams.get('leaseMs') || '30000', 10);+ const available = findAvailablePendingEvent();+ if (available) {res.writeHead(200, { 'Content-Type': 'application/json' });- res.end(JSON.stringify(state.pendingEvents.shift()));+ res.end(JSON.stringify(leaseEvent(available, leaseMs)));return;}+ const poll = { resolve, leaseMs };const timer = setTimeout(() => {- const idx = state.pendingPolls.indexOf(resolve);+ const idx = state.pendingPolls.indexOf(poll);if (idx !== -1) state.pendingPolls.splice(idx, 1);res.writeHead(200, { 'Content-Type': 'application/json' });res.end(JSON.stringify({ type: 'timeout' }));@@ -508,10 +620,11 @@ function handlePollGet(req, res, url) {res.writeHead(200, { 'Content-Type': 'application/json' });res.end(JSON.stringify(event));}- state.pendingPolls.push(resolve);+ state.pendingPolls.push(poll);+ scheduleLeaseFlush();req.on('close', () => {clearTimeout(timer);- const idx = state.pendingPolls.indexOf(resolve);+ const idx = state.pendingPolls.indexOf(poll);if (idx !== -1) state.pendingPolls.splice(idx, 1);});}@@ -531,6 +644,26 @@ function handlePollPost(req, res) {res.end(JSON.stringify({ error: 'Unauthorized' }));return;}+ acknowledgePendingEvent(msg.id);+ if (state.sessionStore && msg.id) {+ try {+ const eventType = msg.type === 'discard' || msg.type === 'discarded'+ ? 'discarded'+ : msg.type === 'complete'+ ? 'complete'+ : msg.type === 'error'+ ? 'agent_error'+ : 'agent_done';+ state.sessionStore.appendEvent({+ type: eventType,+ id: msg.id,+ file: msg.file,+ message: msg.message,+ carbonize: msg.data?.carbonize === true,+ });+ } catch { /* keep reply path best-effort; browser still needs SSE */ }+ }+ flushPendingPolls();// Forward the reply to the browser via SSEbroadcast({ type: msg.type || 'done', id: msg.id, message: msg.message, file: msg.file, data: msg.data });res.writeHead(200, { 'Content-Type': 'application/json' });@@ -545,13 +678,15 @@ function handlePollPost(req, res) {let httpServer = null;function shutdown() {- try { fs.unlinkSync(LIVE_PID_FILE); } catch {}+ removeLiveServerInfo(process.cwd());+ if (state.leaseTimer) clearTimeout(state.leaseTimer);+ state.leaseTimer = null;if (state.sessionDir) {try { fs.rmSync(state.sessionDir, { recursive: true, force: true }); } catch {}}for (const res of state.sseClients) { try { res.end(); } catch {} }state.sseClients.clear();- for (const resolve of state.pendingPolls) resolve({ type: 'exit' });+ for (const poll of state.pendingPolls) poll.resolve({ type: 'exit' });state.pendingPolls.length = 0;if (httpServer) httpServer.close();process.exit(0);@@ -587,6 +722,7 @@ Endpoints:/events SSE stream (server→browser) + POST (browser→server)/poll Long-poll for agent CLI/source Raw source file reader (no-HMR fallback)+ /status Durable recovery status (token-protected)/health Health check`);process.exit(0);}@@ -594,7 +730,7 @@ Endpoints:if (args.includes('stop')) {const keepInject = args.includes('--keep-inject');try {- const info = JSON.parse(fs.readFileSync(LIVE_PID_FILE, 'utf-8'));+ const { info } = readLiveServerInfo(process.cwd()) || {};const res = await fetch(`http://localhost:${info.port}/stop?token=${info.token}`);if (res.ok) console.log(`Stopped live server on port ${info.port}.`);} catch {@@ -645,7 +781,7 @@ if (args.includes('--background')) {const deadline = Date.now() + 10_000;while (Date.now() < deadline) {try {- const info = JSON.parse(fs.readFileSync(LIVE_PID_FILE, 'utf-8'));+ const { info } = readLiveServerInfo(process.cwd()) || {};if (info.pid !== process.pid) {// Output JSON so the agent can read port + token from stdout.console.log(JSON.stringify(info));@@ -659,30 +795,36 @@ if (args.includes('--background')) {}// Check for existing session-try {- const existing = JSON.parse(fs.readFileSync(LIVE_PID_FILE, 'utf-8'));- try { process.kill(existing.pid, 0);+const existingRecord = readLiveServerInfo(process.cwd());+if (existingRecord?.info) {+ const existing = existingRecord.info;+ try {+ process.kill(existing.pid, 0);console.error(`Live server already running on port ${existing.port} (pid ${existing.pid}).`);console.error('Stop it first with: node ' + path.basename(fileURLToPath(import.meta.url)) + ' stop');process.exit(1);- } catch { fs.unlinkSync(LIVE_PID_FILE); }-} catch {}+ } catch {+ try { fs.unlinkSync(existingRecord.path); } catch {}+ }+}state.token = randomUUID();+state.sessionStore = createLiveSessionStore({ cwd: process.cwd() });+restorePendingEventsFromStore();const portArg = args.find(a => a.startsWith('--port='));state.port = portArg ? parseInt(portArg.split('=')[1], 10) : await findOpenPort();// Annotation screenshots live in the project root so the agent's Read tool// doesn't trip a per-file permission prompt. Sessioned by token so concurrent// projects (or quick restarts) don't collide.-const annotRoot = path.join(process.cwd(), '.impeccable-live', 'annotations');+const annotRoot = getLiveAnnotationsDir(process.cwd());fs.mkdirSync(annotRoot, { recursive: true });state.sessionDir = fs.mkdtempSync(path.join(annotRoot, 'session-'));-const { detectScript, livePath } = loadBrowserScripts();-httpServer = http.createServer(createRequestHandler({ detectScript, livePath }));+const { detectScript, sessionPath, livePath } = loadBrowserScripts();+httpServer = http.createServer(createRequestHandler({ detectScript, sessionPath, livePath }));httpServer.listen(state.port, '127.0.0.1', () => {- fs.writeFileSync(LIVE_PID_FILE, JSON.stringify({ pid: process.pid, port: state.port, token: state.token }));+ writeLiveServerInfo(process.cwd(), { pid: process.pid, port: state.port, token: state.token });const url = `http://localhost:${state.port}`;console.log(`\nImpeccable live server running on ${url}`);console.log(`Token: ${state.token}\n`);diff --git a/.github/skills/impeccable/scripts/live-session-store.mjs b/.github/skills/impeccable/scripts/live-session-store.mjsnew file mode 100644index 000000000..d55ed2d3a--- /dev/null+++ b/.github/skills/impeccable/scripts/live-session-store.mjs@@ -0,0 +1,254 @@+import fs from 'node:fs';+import path from 'node:path';+import { getLegacyLiveSessionsDir, getLiveSessionsDir } from './impeccable-paths.mjs';++const COMPLETED_PHASES = new Set(['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;+ }++ function getReadableJournalPath(id) {+ const primary = getJournalPath(rootDir, id);+ if (fs.existsSync(primary)) return primary;+ const legacy = getJournalPath(legacyRootDir, id);+ if (fs.existsSync(legacy)) return legacy;+ return primary;+ }++ return {+ rootDir,+ legacyRootDir,+ appendEvent(event) {+ const normalized = normalizeEvent(event, sessionId);+ const journalPath = getJournalPath(rootDir, normalized.id);+ const snapshotPath = getSnapshotPath(rootDir, normalized.id);+ const legacyJournalPath = getJournalPath(legacyRootDir, normalized.id);+ if (!fs.existsSync(journalPath) && fs.existsSync(legacyJournalPath)) {+ fs.copyFileSync(legacyJournalPath, journalPath);+ }+ const prior = loadCachedOrRebuild(normalized.id);+ const seq = prior.nextSeq;+ const entry = {+ seq,+ id: normalized.id,+ type: normalized.type,+ ts: new Date().toISOString(),+ event: normalized,+ };+ 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;+ },+ getSnapshot(id = sessionId, opts = {}) {+ if (!id) throw new Error('session id required');+ 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;+ },+ listActiveSessions() {+ const ids = new Set();+ for (const dir of [legacyRootDir, rootDir]) {+ if (!fs.existsSync(dir)) continue;+ for (const name of fs.readdirSync(dir)) {+ if (name.endsWith('.jsonl')) ids.add(name.slice(0, -'.jsonl'.length));+ }+ }+ return [...ids]+ .sort()+ .map((id) => this.getSnapshot(id))+ .filter(Boolean);+ },+ };+}++function normalizeEvent(event, fallbackId) {+ if (!event || typeof event !== 'object') throw new Error('event object required');+ const id = event.id || fallbackId;+ if (!id || typeof id !== 'string') throw new Error('event id required');+ if (!event.type || typeof event.type !== 'string') throw new Error('event type required');+ return { ...event, id };+}++function getJournalPath(rootDir, id) {+ return path.join(rootDir, safeSessionId(id) + '.jsonl');+}++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,+ phase: 'new',+ pageUrl: null,+ sourceFile: null,+ expectedVariants: 0,+ arrivedVariants: 0,+ visibleVariant: null,+ paramValues: {},+ pendingEventSeq: null,+ pendingEvent: null,+ deliveryLease: null,+ checkpointRevision: 0,+ activeOwner: null,+ sourceMarkers: {},+ fallbackMode: null,+ annotationArtifacts: [],+ diagnostics: [],+ updatedAt: null,+ };+}++function rebuildSnapshotFromJournal(journalPath, id) {+ let snapshot = baseSnapshot(id);+ const diagnostics = [];+ let nextSeq = 1;+ if (!fs.existsSync(journalPath)) return { snapshot, diagnostics, nextSeq };++ const lines = fs.readFileSync(journalPath, 'utf-8').split('\n');+ for (let i = 0; i < lines.length; i++) {+ const line = lines[i];+ if (!line.trim()) continue;+ try {+ const entry = JSON.parse(line);+ if (!entry || typeof entry !== 'object') throw new Error('entry is not object');+ if (Number.isInteger(entry.seq)) nextSeq = Math.max(nextSeq, entry.seq + 1);+ snapshot = applyEvent(snapshot, entry);+ } catch (err) {+ diagnostics.push({+ error: 'journal_parse_failed',+ line: i + 1,+ message: err.message,+ });+ }+ }+ snapshot.diagnostics = [...snapshot.diagnostics, ...diagnostics];+ return { snapshot, diagnostics, nextSeq };+}++function applyEvent(snapshot, entry, inheritedDiagnostics = []) {+ const event = entry.event || entry;+ const next = {+ ...snapshot,+ paramValues: { ...(snapshot.paramValues || {}) },+ sourceMarkers: { ...(snapshot.sourceMarkers || {}) },+ annotationArtifacts: [...(snapshot.annotationArtifacts || [])],+ diagnostics: [...(snapshot.diagnostics || [])],+ updatedAt: entry.ts || new Date().toISOString(),+ };++ if (inheritedDiagnostics.length && next.diagnostics.length === 0) {+ next.diagnostics = [...inheritedDiagnostics];+ }++ switch (event.type) {+ case 'generate':+ next.phase = 'generate_requested';+ next.pageUrl = event.pageUrl ?? next.pageUrl;+ next.expectedVariants = event.count ?? next.expectedVariants;+ next.pendingEventSeq = entry.seq ?? next.pendingEventSeq;+ next.pendingEvent = toPendingEvent(event);+ if (event.screenshotPath) upsertArtifact(next.annotationArtifacts, { type: 'screenshot', path: event.screenshotPath });+ break;+ case 'variants_ready':+ case 'agent_done':+ next.phase = event.carbonize === true ? 'carbonize_required' : 'variants_ready';+ next.sourceFile = event.file ?? next.sourceFile;+ next.arrivedVariants = event.arrivedVariants ?? (next.arrivedVariants ?? next.expectedVariants);+ next.pendingEventSeq = null;+ next.pendingEvent = null;+ if (event.carbonize === true) {+ next.diagnostics.push({+ error: 'carbonize_cleanup_required',+ file: event.file || null,+ message: 'Accepted variant still has carbonize markers that must be folded into source CSS.',+ });+ }+ break;+ case 'checkpoint':+ 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;+ if (event.paramValues) next.paramValues = { ...event.paramValues };+ } else {+ next.diagnostics.push({ error: 'stale_checkpoint_ignored', revision: event.revision });+ }+ break;+ case 'accept':+ case 'accept_intent':+ next.phase = 'accept_requested';+ next.visibleVariant = Number(event.variantId ?? next.visibleVariant);+ if (event.paramValues) next.paramValues = { ...event.paramValues };+ next.pendingEventSeq = entry.seq ?? next.pendingEventSeq;+ next.pendingEvent = toPendingEvent(event);+ break;+ case 'discard':+ next.phase = 'discard_requested';+ next.pendingEventSeq = entry.seq ?? next.pendingEventSeq;+ next.pendingEvent = toPendingEvent(event);+ break;+ case 'discarded':+ next.phase = 'discarded';+ next.pendingEventSeq = null;+ next.pendingEvent = null;+ break;+ case 'complete':+ next.phase = 'completed';+ next.pendingEventSeq = null;+ next.pendingEvent = null;+ break;+ case 'agent_error':+ next.phase = 'agent_error';+ next.pendingEventSeq = null;+ next.pendingEvent = null;+ next.diagnostics.push({ error: 'agent_error', message: event.message || 'unknown agent error' });+ break;+ default:+ next.diagnostics.push({ error: 'unknown_event_type', type: event.type });+ break;+ }+ return next;+}++function toPendingEvent(event) {+ const pending = { ...event };+ delete pending.token;+ return pending;+}++function upsertArtifact(artifacts, artifact) {+ if (!artifacts.some((existing) => existing.path === artifact.path && existing.type === artifact.type)) {+ artifacts.push(artifact);+ }+}++function writeSnapshot(snapshotPath, snapshot) {+ fs.writeFileSync(snapshotPath, JSON.stringify(snapshot, null, 2) + '\n');+}diff --git a/.github/skills/impeccable/scripts/live-status.mjs b/.github/skills/impeccable/scripts/live-status.mjsnew file mode 100644index 000000000..dce1fbca2--- /dev/null+++ b/.github/skills/impeccable/scripts/live-status.mjs@@ -0,0 +1,47 @@+#!/usr/bin/env node+/**+ * Print durable recovery status for Impeccable live sessions.+ */++import { createLiveSessionStore } from './live-session-store.mjs';+import { readLiveServerInfo } from './impeccable-paths.mjs';++function readServerInfo() {+ return readLiveServerInfo(process.cwd())?.info || null;+}++async function fetchServerStatus(info) {+ if (!info) return null;+ try {+ const res = await fetch(`http://localhost:${info.port}/status?token=${info.token}`);+ if (!res.ok) return null;+ return await res.json();+ } catch {+ return null;+ }+}++export async function statusCli() {+ const info = readServerInfo();+ const server = await fetchServerStatus(info);+ const store = createLiveSessionStore({ cwd: process.cwd() });+ const activeSessions = store.listActiveSessions();+ const payload = {+ liveServer: server ? {+ status: server.status,+ port: server.port,+ connectedClients: server.connectedClients,+ pendingEvents: server.pendingEvents,+ } : null,+ activeSessions: server?.activeSessions || activeSessions,+ recoveryHint: 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.',+ };+ console.log(JSON.stringify(payload, null, 2));+}++const _running = process.argv[1];+if (_running?.endsWith('live-status.mjs') || _running?.endsWith('live-status.mjs/')) {+ statusCli();+}diff --git a/.github/skills/impeccable/scripts/live-wrap.mjs b/.github/skills/impeccable/scripts/live-wrap.mjsindex a5769a50a..d46328b9f 100644--- a/.github/skills/impeccable/scripts/live-wrap.mjs+++ b/.github/skills/impeccable/scripts/live-wrap.mjs@@ -185,6 +185,7 @@ The agent should insert variant HTML at insertLine.`);const { startLine, endLine } = match;const commentSyntax = detectCommentSyntax(targetFile);+ const styleMode = detectStyleMode(targetFile);const isJsx = commentSyntax.open === '{/*';const indent = lines[startLine].match(/^(\s*)/)[1];@@ -269,6 +270,10 @@ The agent should insert variant HTML at insertLine.`);endLine: startLine + wrapperLines.length + (originalLines.length - 1), // 1-indexedinsertLine: insertLine + 1, // 1-indexed: where variants gocommentSyntax: commentSyntax,+ styleMode: styleMode.mode,+ styleTag: styleMode.styleTag,+ cssSelectorPrefixExamples: buildCssSelectorPrefixExamples(styleMode.mode, count),+ cssAuthoring: buildCssAuthoring(styleMode, count),originalLineCount: originalLines.length,}));}@@ -335,6 +340,62 @@ function detectCommentSyntax(filePath) {return { open: '<!--', close: '-->' };}+function detectStyleMode(filePath) {+ const ext = path.extname(filePath).toLowerCase();+ if (ext === '.astro') {+ return {+ mode: 'astro-global-prefixed',+ styleTag: '<style is:inline data-impeccable-css="SESSION_ID">',+ };+ }+ return {+ mode: 'scoped',+ styleTag: '<style data-impeccable-css="SESSION_ID">',+ };+}++function buildCssSelectorPrefixExamples(styleMode, count) {+ if (styleMode !== 'astro-global-prefixed') return [];+ return Array.from({ length: count }, (_, i) => `[data-impeccable-variant="${i + 1}"]`);+}++function buildCssAuthoring(styleMode, count) {+ const variantNumbers = Array.from({ length: count }, (_, i) => i + 1);+ if (styleMode.mode === 'astro-global-prefixed') {+ return {+ mode: styleMode.mode,+ styleTag: styleMode.styleTag,+ strategy: 'global-prefixed',+ rulePattern: '[data-impeccable-variant="N"] > .variant-class { ... }',+ selectorExamples: variantNumbers.map((n) => `[data-impeccable-variant="${n}"] > .variant-class`),+ requirements: [+ 'Use the styleTag exactly; the is:inline attribute is required for this file.',+ 'Prefix every preview selector with the matching [data-impeccable-variant="N"] selector.',+ 'Keep selectors anchored to the generated variant wrapper; do not rely on component CSS scoping for preview rules.',+ ],+ forbidden: [+ 'Do not use @scope for this styleMode.',+ ],+ };+ }+ return {+ mode: styleMode.mode,+ styleTag: styleMode.styleTag,+ strategy: 'scope-rule',+ rulePattern: '@scope ([data-impeccable-variant="N"]) { :scope > .variant-class { ... } }',+ selectorExamples: variantNumbers.map((n) => `@scope ([data-impeccable-variant="${n}"]) { :scope > .variant-class { ... } }`),+ requirements: [+ 'Use @scope blocks keyed to each [data-impeccable-variant="N"] wrapper.',+ 'Inside each @scope block, make :scope rules step into the replacement element with a descendant combinator.',+ 'Use the styleTag exactly; do not add framework-specific style attributes unless this object says to.',+ ],+ forbidden: [+ 'Do not use global [data-impeccable-variant="N"] selector prefixes for this styleMode.',+ 'Do not add is:inline to the style tag for this styleMode.',+ ],+ };+}+/*** Search project files for the query string (class name, ID, etc.)* Returns the first matching file path, or null.diff --git a/.github/skills/impeccable/scripts/live.mjs b/.github/skills/impeccable/scripts/live.mjsindex befbdb8ed..cafb0eca9 100644--- a/.github/skills/impeccable/scripts/live.mjs+++ b/.github/skills/impeccable/scripts/live.mjs@@ -2,10 +2,10 @@* CLI entry point: prepare everything needed to enter the live variant poll loop.** Does (all in one command):- * 1. Check config.json (returns config_missing if first-ever run)+ * 1. Check .impeccable/live/config.json (returns config_missing if first-ever run)* 2. Start the live server in the background (or reuse a running one)* 3. Inject the browser script tag into the project's entry file- * 4. Read .impeccable.md for design context (if present)+ * 4. Read PRODUCT.md / DESIGN.md for project context* 5. Print a single JSON blob with everything the agent needs** After this, the agent's only remaining steps are:@@ -23,9 +23,9 @@ import path from 'node:path';import { fileURLToPath } from 'node:url';import { loadContext } from './load-context.mjs';import { resolveFiles } from './live-inject.mjs';+import { readLiveServerInfo } from './impeccable-paths.mjs';const __dirname = path.dirname(fileURLToPath(import.meta.url));-const PID_FILE = path.join(process.cwd(), '.impeccable-live.json');async function liveCli() {const args = process.argv.slice(2);@@ -34,10 +34,10 @@ async function liveCli() {console.log(`Usage: node live.mjsPrepare everything for live variant mode in a single command:- - Checks scripts/config.json (required, created once per project)+ - Checks .impeccable/live/config.json (required, created once per project)- Starts (or reuses) the live server in the background- Injects the browser script tag- - Reads .impeccable.md for design context+ - Reads PRODUCT.md / DESIGN.md for project contextOn success, prints a JSON blob with:{ ok, serverPort, serverToken, pageFile, hasContext, context }@@ -223,7 +223,7 @@ function safeParse(out) {function ensureServerRunning() {// Try to reuse an existing servertry {- const existing = JSON.parse(fs.readFileSync(PID_FILE, 'utf-8'));+ const existing = readLiveServerInfo(process.cwd())?.info;if (existing && existing.pid) {try {process.kill(existing.pid, 0); // throws if deaddiff --git a/.github/skills/impeccable/scripts/load-context.mjs b/.github/skills/impeccable/scripts/load-context.mjsindex dca23c1f8..dc340bf16 100644--- a/.github/skills/impeccable/scripts/load-context.mjs+++ b/.github/skills/impeccable/scripts/load-context.mjs@@ -39,7 +39,7 @@ const LEGACY_NAMES = ['.impeccable.md'];const FALLBACK_DIRS = ['.agents/context', 'docs'];/**- * Resolve the directory that holds PRODUCT.md / DESIGN.md / DESIGN.json for+ * Resolve the directory that holds PRODUCT.md / DESIGN.md for* this project. Exported so other scripts (e.g. live-server.mjs) can read the* design files from the same location the loader uses.*/diff --git a/.gitignore b/.gitignoreindex d895f5001..9755513f5 100644--- a/.gitignore+++ b/.gitignore@@ -37,12 +37,20 @@ Thumbs.db# Cloudflare.wrangler/-# Live mode session file + annotation screenshots (cleaned up on server stop)+# Impeccable-owned project files are split: generated sidecars/config may be+# tracked, but runtime recovery state and local assets should stay local.+.impeccable/live/server.json+.impeccable/live/sessions/+.impeccable/live/annotations/+.impeccable/live/cache/+.impeccable/history/++# Legacy live mode session file + annotation screenshots.impeccable-live.json.impeccable-live/-# Per-project live mode injection config (generated once per project by the-# skill; wiped on skill update, regenerated on next live run)+# Legacy per-project live mode injection config. New installs use+# .impeccable/live/config.json in the project root instead.**/skills/impeccable/scripts/config.json# Extension build artifactsdiff --git a/DESIGN.json b/.impeccable/design.jsonsimilarity index 100%rename from DESIGN.jsonrename to .impeccable/design.jsondiff --git a/.kiro/skills/impeccable/reference/document.md b/.kiro/skills/impeccable/reference/document.mdindex a16302712..f9f04356d 100644--- a/.kiro/skills/impeccable/reference/document.md+++ b/.kiro/skills/impeccable/reference/document.md@@ -237,11 +237,11 @@ Concrete, forceful guardrails. Lead each with "Do" or "Don't". Be specific: incl- **Don't** [...]```-### Step 4b: Write DESIGN.json sidecar (extensions only)+### Step 4b: Write .impeccable/design.json sidecar (extensions only)-The frontmatter owns token primitives (colors, typography, rounded, spacing, components). The sidecar at `DESIGN.json` carries **what Stitch's schema can't hold**: tonal ramps per color, shadow/elevation tokens, motion tokens, breakpoints, full component HTML/CSS snippets (the panel renders these into a shadow DOM), and narrative (north star, rules, do's/don'ts). It extends the frontmatter, it doesn't duplicate it.+The frontmatter owns token primitives (colors, typography, rounded, spacing, components). The sidecar at `.impeccable/design.json` carries **what Stitch's schema can't hold**: tonal ramps per color, shadow/elevation tokens, motion tokens, breakpoints, full component HTML/CSS snippets (the panel renders these into a shadow DOM), and narrative (north star, rules, do's/don'ts). It extends the frontmatter, it doesn't duplicate it.-Regenerate the sidecar whenever you regenerate DESIGN.md. If the user only asks to refresh the sidecar (e.g., from the live panel's stale-hint), preserve DESIGN.md and write only DESIGN.json.+Regenerate the sidecar whenever you regenerate root `DESIGN.md`. If the user only asks to refresh the sidecar (e.g., from the live panel's stale-hint), preserve `DESIGN.md` and write only `.impeccable/design.json`.#### Schema@@ -310,7 +310,7 @@ Aim for a tight set of **5-10 components** that best represent the visual system- **Signature components (include if distinctive):** hero CTA, featured card, filter pill, any custom pattern the user mentioned as important in PRODUCT.md.- **Skip the rest.** Utility components, form building blocks, wrapper layouts: not worth documenting unless visually distinctive.-If the project has **no component library yet** (bare landing page, new project), synthesize canonical primitives from the tokens using best-practice defaults consistent with the DESIGN.md's rules. Every DESIGN.json has *something* to render, even on day zero.+If the project has **no component library yet** (bare landing page, new project), synthesize canonical primitives from the tokens using best-practice defaults consistent with the DESIGN.md's rules. Every `.impeccable/design.json` has *something* to render, even on day zero.#### Tonal ramps@@ -331,7 +331,7 @@ Do not reword. The panel shows these as secondary collapsible context; the same### Step 5: Confirm, refine, and refresh session cache1. Show the user the full DESIGN.md you wrote. Briefly highlight the non-obvious creative choices (descriptive color names, atmosphere language, named rules).-2. Mention that `DESIGN.json` was also written alongside; the live panel will now render this project's actual button/input/nav primitives instead of generic approximations.+2. Mention that `.impeccable/design.json` was also written alongside; the live panel will now render this project's actual button/input/nav primitives instead of generic approximations.3. Offer to refine any section: "Want me to revise a section, add component patterns I missed, or adjust the atmosphere language?"4. **Refresh the session cache.** Run `node .kiro/skills/impeccable/scripts/load-context.mjs` one final time so the newly-written DESIGN.md lands in conversation. Subsequent commands in this session will use the fresh version automatically without re-reading.@@ -392,7 +392,7 @@ Per-section guidance in seed mode:- **Components**: omit entirely; no components exist yet.- **Do's and Don'ts**: carry PRODUCT.md's anti-references directly plus the anti-reference named in Q5.-Seed mode writes a minimal frontmatter with `name` and `description` only; no colors, typography, rounded, spacing, or components yet. Real tokens land on the next Scan-mode run. Skip the `DESIGN.json` sidecar in seed mode for the same reason: nothing to render.+Seed mode writes a minimal frontmatter with `name` and `description` only; no colors, typography, rounded, spacing, or components yet. Real tokens land on the next Scan-mode run. Skip the `.impeccable/design.json` sidecar in seed mode for the same reason: nothing to render.### Step 4: Confirm and refresh session cachediff --git a/.kiro/skills/impeccable/reference/live.md b/.kiro/skills/impeccable/reference/live.mdindex 26e87d240..2be415d47 100644--- a/.kiro/skills/impeccable/reference/live.md+++ b/.kiro/skills/impeccable/reference/live.md@@ -12,8 +12,9 @@ Execute in order. No step skipped, no step reordered.2. Navigate to the URL that serves `pageFile` (infer from `package.json`, docs, terminal output, or an open tab). If you can't infer it confidently, tell the user once to open their dev/preview URL. Never use `serverPort` as that URL; it's the helper, not the app.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=`.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.-5. On `accept` / `discard`: the poll script already cleaned up; just poll again.-6. On `exit`: run the cleanup at the bottom.+5. 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. If interrupted, run `live-status.mjs` or `live-resume.mjs` before guessing. The durable journal replays unacknowledged work after helper restart.+7. 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.@@ -43,13 +44,31 @@ LOOP:Read JSON; dispatch on "type""generate" → Handle Generate; reply done; LOOP- "accept" → Handle Accept; LOOP+ "accept" → Handle Accept; complete carbonize cleanup if required; LOOP"discard" → Handle Discard; LOOP"prefetch" → Handle Prefetch; LOOP"timeout" → LOOP"exit" → break → Cleanup```+## Recovery commands++The live helper persists an append-only journal under `.impeccable/live/sessions/`. Browser checkpoints are advisory but durable; the journal is canonical. This is local durable recovery state, not project source.++Use these commands when the chat was interrupted, polling was missed, the helper restarted, or the browser reloaded:++```bash+node .kiro/skills/impeccable/scripts/live-status.mjs+node .kiro/skills/impeccable/scripts/live-resume.mjs --id SESSION_ID+node .kiro/skills/impeccable/scripts/live-complete.mjs --id SESSION_ID+```++- `live-status.mjs` prints connected helper state, active durable sessions, and queued pending events. It works even when the helper is down by reading the journal directly.+- `live-resume.mjs` prints the active snapshot, pending event, checkpoint phase, visible variant, parameter values, and the next safe agent action.+- `live-complete.mjs` is the canonical manual final acknowledgement. Use it after carbonize/manual cleanup is verified and no further poll acknowledgement will happen automatically.++Server restart rule: start `live-server.mjs` again, then poll. Startup requeues unacknowledged pending events from the journal, so do not ask the user to click Go again unless `live-resume.mjs` says no active session exists.+## Handle `generate`Event: `{id, action, freeformPrompt?, count, pageUrl, element, screenshotPath?, comments?, strokes?}`.@@ -88,7 +107,14 @@ The helper searches ID first, then classes, then tag + class combo. If `event.paIf `--text` matches multiple candidates equally well, wrap exits with `{ error: "element_ambiguous", candidates: [...] }` and `fallback: "agent-driven"`: read the candidate line ranges, decide which one matches the picked element from page context, and write the wrapper manually per the fallback flow.-Output on success: `{ file, insertLine, commentSyntax }`.+Output on success: `{ file, insertLine, commentSyntax, styleMode, styleTag, cssSelectorPrefixExamples, cssAuthoring }`.++`styleMode` controls how preview CSS must be authored. Treat it as a detected capability mode, not a framework guess:++- `scoped`: use `@scope ([data-impeccable-variant="N"])` rules.+- `astro-global-prefixed`: use explicit `[data-impeccable-variant="N"]` selector prefixes and the exact `styleTag` returned by the tool.++Use `cssAuthoring` as the source of truth for the current file. It includes the exact `styleTag`, selector strategy, selector examples, requirements, and forbidden patterns. Do not apply a framework-specific exception unless the returned `styleMode` / `cssAuthoring.mode` says to.**Fallback errors.** Wrap only writes into files it judges to be source (tracked by git, not marked GENERATED, not listed in config's `generatedFiles`). If it can't land on a source file, it errors without writing; accepting a variant into a generated file is silent data loss. Three shapes:@@ -208,13 +234,14 @@ When the prompt and PRODUCT.md anti-references conflict (the prompt asks for X,Complete 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 scoped 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).+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).++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:```html<!-- Variants: insert below this line --><style data-impeccable-css="SESSION_ID">- @scope ([data-impeccable-variant="1"]) { ... }- @scope ([data-impeccable-variant="2"]) { ... }+ /* rules matching cssAuthoring.rulePattern */</style><div data-impeccable-variant="1"><!-- variant 1: full element replacement (single top-level element) -->@@ -229,11 +256,11 @@ Write CSS + all variants in ONE edit at the `insertLine` reported by `wrap`. Col**Each variant div contains exactly one top-level element: the full replacement for the original.** Use the same tag as the original (e.g. `<section>` if the user picked a `<section>`). Loose siblings (heading + paragraph + div as direct children of the variant div) break the outline tracking and the accept flow, which both assume one child.-The first variant has no `display: none` (visible by default). All others do. If variants use only inline styles and no scoped CSS, omit the `<style>` tag entirely. Use `@scope` for CSS isolation (Chrome 118+ / Firefox 128+ / Safari 17.4+).+The 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.-**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 rule starts `:scope > ...`.+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 > ...`.**JSX / TSX target files.** Wrap `<style>` content in a template literal so the CSS `{` / `}` aren't parsed as JSX expressions, and use `className=` / `style={{…}}` on every variant element. Keep `data-impeccable-*` attributes as-is; they're plain strings:@@ -369,10 +396,11 @@ Remove the wrapper you inserted in Step 2. Nothing else to do.## Handle `accept`-Event: `{id, variantId, _acceptResult}`. The poll script already ran `live-accept.mjs` to handle the file operation deterministically; the browser DOM is already updated.+Event: `{id, variantId, _acceptResult, _completionAck}`. The poll script already ran `live-accept.mjs` to handle the file operation deterministically, then acknowledged event delivery to the helper. The browser DOM is already updated.+- `_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 and a stderr banner both list the steps explicitly; neither is decorative.+- `_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: 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` without `mode`: manual cleanup: read file, find markers, edit.@@ -388,13 +416,13 @@ Do these five steps in the current thread, synchronously, before the next poll.4. **Unwrap the accepted content.** Delete the `<div data-impeccable-variant="N" style="display: contents">` that wraps it. Drop `data-impeccable-params` and any `data-p-*` attributes from it; 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.-Then poll again.+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.## Handle `discard`-Event: `{id, _acceptResult}`. The poll script already restored the original and removed all variant markers. Nothing to do. Poll again.+Event: `{id, _acceptResult, _completionAck}`. The poll script already restored the original, removed all variant markers, and acknowledged `discarded` durable completion. Nothing to do unless `_completionAck.ok !== true`; in that case run `live-complete.mjs --id EVENT_ID --discarded`, then poll again.## Handle `prefetch`@@ -424,7 +452,7 @@ When the poll returns `exit`, proceed to cleanup. If the poll is still running anode .kiro/skills/impeccable/scripts/live-server.mjs stop```-Stops the HTTP server and runs `live-inject.mjs --remove` to strip `localhost:…/live.js` from the HTML entry. To stop the server but keep the inject tag (for a quick restart), use `stop --keep-inject`. `config.json` persists for future sessions.+Stops the HTTP server and runs `live-inject.mjs --remove` to strip `localhost:…/live.js` from the HTML entry. To stop the server but keep the inject tag (for a quick restart), use `stop --keep-inject`. `.impeccable/live/config.json` persists as project config for future sessions.Then:- Remove any leftover variant wrappers (search for `impeccable-variants-start` markers).@@ -432,7 +460,7 @@ Then:## First-time setup (config missing or invalid)-If `live.mjs` outputs `{ ok: false, error: "config_missing" | "config_invalid", path }`, write `config.json` at the reported path.+If `live.mjs` outputs `{ ok: false, error: "config_missing" | "config_invalid", path }`, write the live config at the reported path. By default this is `.impeccable/live/config.json`.Schema:@@ -512,7 +540,7 @@ node .kiro/skills/impeccable/scripts/detect-csp.mjsOutput: `{ shape, signals }` where `shape` is one of `append-arrays`, `append-string`, `middleware`, `meta-tag`, or `null`. The shape is named by *patch mechanism*, so one template covers many frameworks.-- **`null`**: no CSP; skip to writing `config.json` with `cspChecked: true`.+- **`null`**: no CSP; skip to writing `.impeccable/live/config.json` with `cspChecked: true`.- **`append-arrays`**: CSP defined as structured directive arrays. Auto-patchable. See *append-arrays* below. Covers:- Monorepo helpers with `additionalScriptSrc` / `additionalConnectSrc` options (Next.js + shared config package)- SvelteKit `kit.csp.directives`@@ -589,6 +617,6 @@ Reference outputs:### Troubleshooting-If a user says "no" to the CSP patch at setup time and later complains that live doesn't work: their dev CSP blocks `http://localhost:8400`. Fix: delete `cspChecked` from `config.json` and re-run `live.mjs`: setup will ask again.+If a user says "no" to the CSP patch at setup time and later complains that live doesn't work: their dev CSP blocks `http://localhost:8400`. Fix: delete `cspChecked` from `.impeccable/live/config.json` and re-run `live.mjs`: setup will ask again.Then re-run `live.mjs`.diff --git a/.kiro/skills/impeccable/reference/teach.md b/.kiro/skills/impeccable/reference/teach.mdindex b17d6615c..81949a89e 100644--- a/.kiro/skills/impeccable/reference/teach.md+++ b/.kiro/skills/impeccable/reference/teach.md@@ -2,8 +2,8 @@Gathers design context for a project and writes two complementary files at the project root:-- **PRODUCT.md** (strategic): register, target users, product purpose, brand personality, anti-references, strategic design principles. Answers "who/what/why".-- **DESIGN.md** (visual): visual theme, color palette, typography, components, layout. Follows the [Google Stitch DESIGN.md format](https://stitch.withgoogle.com/docs/design-md/format/). Answers "how it looks".+- **PRODUCT.md** (strategic): root project file for register, target users, product purpose, brand personality, anti-references, strategic design principles. Answers "who/what/why".+- **DESIGN.md** (visual): root project file for visual theme, color palette, typography, components, layout. Follows the [Google Stitch DESIGN.md format](https://stitch.withgoogle.com/docs/design-md/format/). Answers "how it looks".Every other impeccable command reads these files before doing any work.diff --git a/.kiro/skills/impeccable/scripts/impeccable-paths.mjs b/.kiro/skills/impeccable/scripts/impeccable-paths.mjsnew file mode 100644index 000000000..ba852bae9--- /dev/null+++ b/.kiro/skills/impeccable/scripts/impeccable-paths.mjs@@ -0,0 +1,105 @@+import fs from 'node:fs';+import path from 'node:path';++export const IMPECCABLE_DIR = '.impeccable';+export const LIVE_DIR = 'live';++export function getImpeccableDir(cwd = process.cwd()) {+ return path.join(cwd, IMPECCABLE_DIR);+}++export function getDesignSidecarPath(cwd = process.cwd()) {+ return path.join(getImpeccableDir(cwd), 'design.json');+}++export function getDesignSidecarCandidates(cwd = process.cwd(), contextDir = cwd) {+ const candidates = [+ getDesignSidecarPath(cwd),+ path.join(cwd, 'DESIGN.json'),+ ];+ const contextLegacy = path.join(contextDir, 'DESIGN.json');+ if (!candidates.includes(contextLegacy)) candidates.push(contextLegacy);+ return candidates;+}++export function resolveDesignSidecarPath(cwd = process.cwd(), contextDir = cwd) {+ return firstExisting(getDesignSidecarCandidates(cwd, contextDir));+}++export function getLiveDir(cwd = process.cwd()) {+ return path.join(getImpeccableDir(cwd), LIVE_DIR);+}++export function getLiveConfigPath(cwd = process.cwd()) {+ return path.join(getLiveDir(cwd), 'config.json');+}++export function getLegacyLiveConfigPath(scriptsDir) {+ return path.join(scriptsDir, 'config.json');+}++export function resolveLiveConfigPath({ cwd = process.cwd(), scriptsDir, env = process.env } = {}) {+ if (env.IMPECCABLE_LIVE_CONFIG && env.IMPECCABLE_LIVE_CONFIG.trim()) {+ const configured = env.IMPECCABLE_LIVE_CONFIG.trim();+ return path.isAbsolute(configured) ? configured : path.resolve(cwd, configured);+ }+ const primary = getLiveConfigPath(cwd);+ if (fs.existsSync(primary)) return primary;+ if (scriptsDir) {+ const legacy = getLegacyLiveConfigPath(scriptsDir);+ if (fs.existsSync(legacy)) return legacy;+ }+ return primary;+}++export function getLiveServerPath(cwd = process.cwd()) {+ return path.join(getLiveDir(cwd), 'server.json');+}++export function getLegacyLiveServerPath(cwd = process.cwd()) {+ return path.join(cwd, '.impeccable-live.json');+}++export function readLiveServerInfo(cwd = process.cwd()) {+ for (const filePath of [getLiveServerPath(cwd), getLegacyLiveServerPath(cwd)]) {+ try {+ return { info: JSON.parse(fs.readFileSync(filePath, 'utf-8')), path: filePath };+ } catch {+ /* try next */+ }+ }+ return null;+}++export function writeLiveServerInfo(cwd = process.cwd(), info) {+ const filePath = getLiveServerPath(cwd);+ fs.mkdirSync(path.dirname(filePath), { recursive: true });+ fs.writeFileSync(filePath, JSON.stringify(info));+ return filePath;+}++export function removeLiveServerInfo(cwd = process.cwd()) {+ for (const filePath of [getLiveServerPath(cwd), getLegacyLiveServerPath(cwd)]) {+ try { fs.unlinkSync(filePath); } catch {}+ }+}++export function getLiveSessionsDir(cwd = process.cwd()) {+ return path.join(getLiveDir(cwd), 'sessions');+}++export function getLegacyLiveSessionsDir(cwd = process.cwd()) {+ return path.join(cwd, '.impeccable-live', 'sessions');+}++export function getLiveAnnotationsDir(cwd = process.cwd()) {+ return path.join(getLiveDir(cwd), 'annotations');+}++export function getLegacyLiveAnnotationsDir(cwd = process.cwd()) {+ return path.join(cwd, '.impeccable-live', 'annotations');+}++function firstExisting(paths) {+ return paths.find((filePath) => fs.existsSync(filePath)) || null;+}diff --git a/.kiro/skills/impeccable/scripts/live-browser-session.js b/.kiro/skills/impeccable/scripts/live-browser-session.jsnew file mode 100644index 000000000..0e362d6be--- /dev/null+++ b/.kiro/skills/impeccable/scripts/live-browser-session.js@@ -0,0 +1,123 @@+/**+ * Browser-side durable session helpers for Impeccable live mode.+ *+ * Kept separate from live-browser.js so recovery state can be tested without+ * booting the full overlay UI. Served before live-browser.js and attached to+ * window.__IMPECCABLE_LIVE_SESSION__.+ */+(function (root) {+ 'use strict';++ function createLiveBrowserSessionState({ prefix, storage, idFactory }) {+ if (!prefix) throw new Error('prefix required');+ const store = storage || root.localStorage;+ const makeId = idFactory || function () { return Math.random().toString(16).slice(2, 10); };+ const sessionKey = prefix + '-session';+ const handledKey = sessionKey + '-handled';+ const scrollKey = sessionKey + '-scroll';+ let checkpointRevision = 0;+ const owner = makeId();++ function safeRead(key) {+ try { return store.getItem(key); } catch { return null; }+ }++ function safeWrite(key, value) {+ try { store.setItem(key, value); } catch { /* quota exceeded or private mode */ }+ }++ function safeRemove(key) {+ try { store.removeItem(key); } catch { /* unavailable storage */ }+ }++ function loadSession() {+ try {+ const raw = safeRead(sessionKey);+ if (!raw) return null;+ const parsed = JSON.parse(raw);+ if (Number.isInteger(parsed.checkpointRevision)) {+ checkpointRevision = Math.max(checkpointRevision, parsed.checkpointRevision);+ }+ return parsed;+ } catch { return null; }+ }++ function saveSession(session) {+ if (!session || !session.id) return;+ const payload = {+ ...session,+ checkpointRevision,+ };+ safeWrite(sessionKey, JSON.stringify(payload));+ }++ function clearSession() {+ safeRemove(sessionKey);+ }++ function nextCheckpointRevision() {+ checkpointRevision += 1;+ const existing = loadSession();+ if (existing?.id) saveSession(existing);+ return checkpointRevision;+ }++ function seedCheckpointRevision(value) {+ if (Number.isInteger(value)) checkpointRevision = Math.max(checkpointRevision, value);+ return checkpointRevision;+ }++ function currentCheckpointRevision() {+ return checkpointRevision;+ }++ function markHandled(id) {+ if (!id) return;+ safeWrite(handledKey, id);+ }++ function isHandled(id) {+ return !!id && safeRead(handledKey) === id;+ }++ function clearHandled() {+ safeRemove(handledKey);+ }++ function writeScrollY(y) {+ safeWrite(scrollKey, String(y));+ }++ function readScrollY() {+ const raw = safeRead(scrollKey);+ if (raw == null) return null;+ const n = parseFloat(raw);+ return isFinite(n) ? n : null;+ }++ function clearScrollY() {+ safeRemove(scrollKey);+ }++ return {+ owner,+ sessionKey,+ handledKey,+ scrollKey,+ saveSession,+ loadSession,+ clearSession,+ nextCheckpointRevision,+ seedCheckpointRevision,+ currentCheckpointRevision,+ markHandled,+ isHandled,+ clearHandled,+ writeScrollY,+ readScrollY,+ clearScrollY,+ };+ }++ root.__IMPECCABLE_LIVE_SESSION__ = { createLiveBrowserSessionState };+})(typeof window !== 'undefined' ? window : globalThis);diff --git a/.kiro/skills/impeccable/scripts/live-browser.js b/.kiro/skills/impeccable/scripts/live-browser.jsindex 3da76bb96..e67cd01ed 100644--- a/.kiro/skills/impeccable/scripts/live-browser.js+++ b/.kiro/skills/impeccable/scripts/live-browser.js@@ -50,6 +50,16 @@const Z = { highlight: 100001, bar: 100005, picker: 100007, toast: 100010 };const EASE = 'cubic-bezier(0.22, 1, 0.36, 1)'; // ease-out-quintconst PREFIX = 'impeccable-live';+ const sessionState = window.__IMPECCABLE_LIVE_SESSION__?.createLiveBrowserSessionState({+ prefix: PREFIX,+ storage: localStorage,+ idFactory: () => crypto.randomUUID().replace(/-/g, '').slice(0, 8),+ });+ if (!sessionState) {+ console.error('[impeccable] live-browser-session.js was not loaded. Live mode cannot start safely.');+ window.__IMPECCABLE_LIVE_INIT__ = false;+ return;+ }const HIGHLIGHT_TRANSITION ='top 140ms ' + EASE +', left 140ms ' + EASE +@@ -112,6 +122,8 @@let hasProjectContext = false;let selectedAction = 'impeccable';let selectedCount = 3;+ const browserOwner = sessionState.owner;+ let checkpointTimer = null;// Scroll lock — holds window.scrollY at a fixed value while the session is// active, so HMR DOM patches and variant swaps can't drift the page. See@@ -126,21 +138,9 @@// (Previously: saveSession wrote scrollY alongside state, so every call// during resume overwrote the pre-reload value with whatever the browser// had landed on, typically 0.)- const SCROLL_KEY_SUFFIX = '-scroll';- function writeScrollY(y) {- try { localStorage.setItem(LS_KEY + SCROLL_KEY_SUFFIX, String(y)); } catch {}- }- function readScrollY() {- try {- const raw = localStorage.getItem(LS_KEY + SCROLL_KEY_SUFFIX);- if (raw == null) return null;- const n = parseFloat(raw);- return isFinite(n) ? n : null;- } catch { return null; }- }- function clearScrollY() {- try { localStorage.removeItem(LS_KEY + SCROLL_KEY_SUFFIX); } catch {}- }+ function writeScrollY(y) { sessionState.writeScrollY(y); }+ function readScrollY() { return sessionState.readScrollY(); }+ function clearScrollY() { sessionState.clearScrollY(); }// Pre-empt the browser: apply manual scroll restoration and jump to the// saved scrollY at script-parse time. Retries on fonts.ready and load@@ -1585,6 +1585,7 @@paramsCurrentValues[p.id] = v;readout.textContent = formatRangeValue(input);applyParamValue(variantEl, p, v);+ queueCheckpoint('param_changed');});row.appendChild(input);} else if (p.kind === 'toggle') {@@ -1615,6 +1616,7 @@knob.style.left = next ? '18px' : '2px';readout.textContent = next ? 'On' : 'Off';applyParamValue(variantEl, p, next);+ queueCheckpoint('param_changed');});row.appendChild(track);} else if (p.kind === 'steps') {@@ -1651,6 +1653,7 @@btn.style.color = on ? 'oklch(98% 0 0)' : P.text;});applyParamValue(variantEl, p, o.value);+ queueCheckpoint('param_changed');});segRow.appendChild(b);segBtns.push({ btn: b, val: o.value });@@ -1872,19 +1875,26 @@return;}+ const previousVisibleVariant = currentSessionId === sessionId ? visibleVariant : 0;+// Replace the live element with the full wrapper from sourceconst wrapper = srcWrapper.cloneNode(true);liveEl.parentElement.replaceChild(wrapper, liveEl);- // Update state: count variants, show the first one+ // Update state: count variants, preserving the user's current variant+ // when a late HMR/source reinjection lands after they have cycled.const variants = wrapper.querySelectorAll('[data-impeccable-variant]:not([data-impeccable-variant="original"])');arrivedVariants = variants.length;expectedVariants = parseInt(wrapper.dataset.impeccableVariantCount || arrivedVariants);- visibleVariant = 1;- showVariantInDOM(sessionId, 1);+ const saved = loadSession();+ const savedVisibleVariant = saved && saved.id === sessionId ? saved.visible : 0;+ visibleVariant = previousVisibleVariant > 0 && previousVisibleVariant <= arrivedVariants+ ? previousVisibleVariant+ : (savedVisibleVariant > 0 && savedVisibleVariant <= arrivedVariants ? savedVisibleVariant : 1);+ showVariantInDOM(sessionId, visibleVariant);// Update selectedElement to the visible variant's content- selectedElement = pickVariantContent(wrapper, 1) || wrapper.parentElement;+ selectedElement = pickVariantContent(wrapper, visibleVariant) || wrapper.parentElement;state = 'CYCLING';hideShaderOverlay();@@ -1907,6 +1917,7 @@updateSelectedElement();updateBarContent('cycling');saveSession();+ queueCheckpoint('variant_changed');}function updateSelectedElement() {@@ -1917,6 +1928,18 @@if (visEl) selectedElement = visEl;}+ function readVisibleVariantFromDOM(sessionId) {+ const wrapper = document.querySelector('[data-impeccable-variants="' + sessionId + '"]');+ if (!wrapper) return 0;+ const variants = wrapper.querySelectorAll('[data-impeccable-variant]:not([data-impeccable-variant="original"])');+ for (const variant of variants) {+ if (variant.style.display === 'none') continue;+ const idx = parseInt(variant.dataset.impeccableVariant || '0', 10);+ if (idx > 0) return idx;+ }+ return 0;+ }+// Resolve the element that represents the variant's visible content.// Contract: each variant div should contain exactly one top-level element// (the full replacement). In practice a model may ship loose siblings or@@ -2107,8 +2130,10 @@updating = true;arrivedVariants = count;if (visibleVariant === 0 && arrivedVariants > 0) {- visibleVariant = 1;- showVariantInDOM(sessionId, 1);+ const saved = loadSession();+ const savedVisibleVariant = saved && saved.id === sessionId ? saved.visible : 0;+ visibleVariant = savedVisibleVariant > 0 && savedVisibleVariant <= arrivedVariants ? savedVisibleVariant : 1;+ showVariantInDOM(sessionId, visibleVariant);// showVariantInDOM hid the original (display:none); if we were still// anchored to the original's content, its boundingRect is now zero// and the bar snaps to (0,0). Re-point at the visible variant instead.@@ -2128,6 +2153,7 @@updateBarContent('generating');}saveSession();+ queueCheckpoint(state === 'CYCLING' ? 'variants_ready' : 'variants_progress');updating = false;});@@ -2236,6 +2262,7 @@/** Server died or became unreachable. Reset UI to a clean state. */function handleServerLost() {+ const recoveryState = currentSessionId ? state : 'IDLE';if (state === 'GENERATING' || state === 'CYCLING' || state === 'SAVING') {showToast('Live server disconnected. Session ended.', 5000);}@@ -2246,21 +2273,61 @@stopScrollTracking();if (variantObserver) { variantObserver.disconnect(); variantObserver = null; }stopScrollLock();- clearScrollY();- clearSession();+ // Preserve local session state on server loss. The durable journal is the+ // source of truth, but localStorage plus the variant wrapper lets the UI+ // resume after a helper restart or page reload instead of treating a+ // transient disconnect as an explicit discard.selectedElement = null;- currentSessionId = null;selectedAction = 'impeccable';- state = 'IDLE';+ state = recoveryState;+ if (currentSessionId) saveSession();}- function sendEvent(msg) {+ function sendEvent(msg, opts) {msg.token = TOKEN;- fetch('http://localhost:' + PORT + '/events', {+ function handleFailure(err) {+ console.error('[impeccable] Failed to send event:', err);+ if (opts && opts.throwOnError) throw err;+ return null;+ }+ return fetch('http://localhost:' + PORT + '/events', {method: 'POST',headers: { 'Content-Type': 'application/json' },body: JSON.stringify(msg),- }).catch(err => console.error('[impeccable] Failed to send event:', err));+ }).then(res => {+ if (res.ok) return res;+ return handleFailure(new Error('HTTP ' + res.status + ' ' + res.statusText));+ }).catch(handleFailure);+ }++ function checkpointPayload(reason) {+ return {+ type: 'checkpoint',+ id: currentSessionId,+ revision: sessionState.nextCheckpointRevision(),+ owner: browserOwner,+ phase: String(state || '').toLowerCase(),+ reason,+ pageUrl: location.pathname,+ expectedVariants,+ arrivedVariants,+ visibleVariant,+ paramValues: { ...paramsCurrentValues },+ };+ }++ function sendCheckpoint(reason) {+ if (!currentSessionId) return Promise.resolve(null);+ return sendEvent(checkpointPayload(reason)).catch(() => null);+ }++ function queueCheckpoint(reason) {+ if (!currentSessionId) return;+ if (checkpointTimer) clearTimeout(checkpointTimer);+ checkpointTimer = setTimeout(() => {+ checkpointTimer = null;+ sendCheckpoint(reason);+ }, 120);}// ---------------------------------------------------------------------------@@ -2496,6 +2563,7 @@state = 'GENERATING';showBar('generating');saveSession();+ sendCheckpoint('generate_started');writeScrollY(window.scrollY);if (variantObserver) variantObserver.disconnect();variantObserver = startVariantObserver(currentSessionId);@@ -2920,13 +2988,12 @@ void main() {function handleAccept() {if (!currentSessionId || arrivedVariants === 0) return;+ const domVisibleVariant = readVisibleVariantFromDOM(currentSessionId);+ if (domVisibleVariant > 0) visibleVariant = domVisibleVariant;const acceptPayload = { type: 'accept', id: currentSessionId, variantId: String(visibleVariant) };if (Object.keys(paramsCurrentValues).length > 0) {acceptPayload.paramValues = { ...paramsCurrentValues };}- sendEvent(acceptPayload);- markSessionHandled();-// The accepted variant is already the only visible child of the wrapper// (all other variants are display:none). HMR from the source rewrite will// replace the wrapper imminently. Don't eagerly replaceChild here — React@@ -2936,9 +3003,28 @@ void main() {const acceptedSessionId = currentSessionId;const acceptedVariant = visibleVariant;- state = 'CONFIRMED';- updateBarContent('confirmed');- setTimeout(function() {+ state = 'SAVING';+ updateBarContent('saving');++ sendEvent(acceptPayload, { throwOnError: true })+ .then(() => {+ markSessionHandled();+ confirmAcceptAfterReceipt();+ })+ .catch(() => {+ state = 'CYCLING';+ updateBarContent('cycling');+ showToast('Could not confirm accept with the live server. Session kept for recovery; try Accept again.', 5000);+ });++ function confirmAcceptAfterReceipt() {+ state = 'CONFIRMED';+ updateBarContent('confirmed');+ scheduleAcceptCleanup();+ }++ function scheduleAcceptCleanup() {+ setTimeout(function() {hideBar();hideHighlight();stopScrollTracking();@@ -2967,50 +3053,46 @@ void main() {accepted.style.display = 'contents';parent.replaceChild(accepted, wrapper);}- }, 2000);+ }, 2000);+ }}function handleDiscard() {if (!currentSessionId) return;- sendEvent({ type: 'discard', id: currentSessionId });- markSessionHandled();- // Instant DOM restore + fire-and-forget (script handles file cleanup)- cleanup();+ sendEvent({ type: 'discard', id: currentSessionId }, { throwOnError: true })+ .then(() => {+ markSessionHandled();+ cleanup();+ })+ .catch(() => showToast('Could not confirm discard with the live server. Session kept for recovery.', 5000));}// ---------------------------------------------------------------------------- // Session persistence via localStorage+ // Session persistence via live-browser-session.js// ---------------------------------------------------------------------------// Survives page reloads, browser close/reopen, HMR, and accidental refreshes.- const LS_KEY = PREFIX + '-session';-function saveSession() {if (!currentSessionId) return;// NOTE: scrollY is stored under a separate key (writeScrollY). Storing// it here would overwrite the Go-time value every time state changes.- try {- localStorage.setItem(LS_KEY, JSON.stringify({- id: currentSessionId,- state: state,- action: selectedAction,- count: selectedCount,- expected: expectedVariants,- arrived: arrivedVariants,- visible: visibleVariant,- }));- } catch { /* quota exceeded or private mode */ }+ sessionState.saveSession({+ id: currentSessionId,+ state,+ action: selectedAction,+ count: selectedCount,+ expected: expectedVariants,+ arrived: arrivedVariants,+ visible: visibleVariant,+ });}function loadSession() {- try {- const raw = localStorage.getItem(LS_KEY);- return raw ? JSON.parse(raw) : null;- } catch { return null; }+ return sessionState.loadSession();}function clearSession() {- try { localStorage.removeItem(LS_KEY); } catch {}+ sessionState.clearSession();}/** Mark session as handled (accepted/discarded). The agent will clean up@@ -3018,19 +3100,15 @@ void main() {* prevents resumeSession from picking it up again after reload. */function markSessionHandled() {if (!currentSessionId) return;- try {- localStorage.setItem(LS_KEY + '-handled', currentSessionId);- } catch {}+ sessionState.markHandled(currentSessionId);}function isSessionHandled(id) {- try {- return localStorage.getItem(LS_KEY + '-handled') === id;- } catch { return false; }+ return sessionState.isHandled(id);}function clearHandled() {- try { localStorage.removeItem(LS_KEY + '-handled'); } catch {}+ sessionState.clearHandled();}function cleanup() {@@ -3161,6 +3239,7 @@ void main() {// hid. Now that state is CYCLING, re-fire.if (state === 'CYCLING') refreshParamsPanel();saveSession();+ queueCheckpoint('browser_resumed');// Start observing for more variants AFTER initial setupif (variantObserver) variantObserver.disconnect();@@ -3617,7 +3696,7 @@ void main() {}// ---------------------------------------------------------------------------- // Design System Panel — visualizes the project's DESIGN.json sidecar+ // Design System Panel — visualizes the project's .impeccable/design.json sidecar// ---------------------------------------------------------------------------const DESIGN_PREFS_KEY = 'impeccable-live-design-panel';@@ -3629,7 +3708,7 @@ void main() {open: false,tab: 'visual', // 'visual' | 'raw'parsed: null, // parseDesignMd output (frontmatter + body sections)- sidecar: null, // DESIGN.json v2 payload (extensions + components + narrative)+ sidecar: null, // .impeccable/design.json v2 payload (extensions + components + narrative)hasMd: false,hasSidecar: false,present: null, // true/false once fetch resolves@@ -4130,7 +4209,7 @@ void main() {box.className = 'stale';box.innerHTML = `<span class="stale-dot"></span>- <span class="stale-text"><strong>DESIGN.md is newer than DESIGN.json.</strong> Run <code>/impeccable document</code> to refresh the sidecar.</span>+ <span class="stale-text"><strong>DESIGN.md is newer than .impeccable/design.json.</strong> Run <code>/impeccable document</code> to refresh the sidecar.</span>`;return box;}@@ -4138,7 +4217,7 @@ void main() {function renderParsedMdCta() {const box = document.createElement('div');box.className = 'parsed-md-cta';- box.innerHTML = `<strong>Basic view</strong>This panel reads the tokens in your <code>DESIGN.md</code> frontmatter. Running <code>/impeccable document</code> also generates a <code>DESIGN.json</code> sidecar with your project's actual component snippets (button, input, nav) and tonal ramps, rendered live below the tokens.`;+ box.innerHTML = `<strong>Basic view</strong>This panel reads the tokens in your <code>DESIGN.md</code> frontmatter. Running <code>/impeccable document</code> also generates a <code>.impeccable/design.json</code> sidecar with your project's actual component snippets (button, input, nav) and tonal ramps, rendered live below the tokens.`;return box;}@@ -4598,7 +4677,7 @@ void main() {function cssSafe(v) {// Strip anything outside valid CSS value chars to prevent injection via- // DESIGN.json values rendered into inline style strings.+ // .impeccable/design.json values rendered into inline style strings.return String(v).replace(/[<>"'`\n]/g, '');}diff --git a/.kiro/skills/impeccable/scripts/live-complete.mjs b/.kiro/skills/impeccable/scripts/live-complete.mjsnew file mode 100644index 000000000..78155af85--- /dev/null+++ b/.kiro/skills/impeccable/scripts/live-complete.mjs@@ -0,0 +1,75 @@+#!/usr/bin/env node+/**+ * Canonical durable completion acknowledgement for Impeccable live sessions.+ */++import { createLiveSessionStore } from './live-session-store.mjs';+import { readLiveServerInfo } from './impeccable-paths.mjs';++function parseArgs(argv) {+ const out = { status: 'complete' };+ for (let i = 0; i < argv.length; i++) {+ const arg = argv[i];+ if (arg === '--id') out.id = argv[++i];+ else if (arg.startsWith('--id=')) out.id = arg.slice('--id='.length);+ else if (arg === '--discarded' || arg === '--discard') out.status = 'discarded';+ else if (arg === '--error') { out.status = 'agent_error'; out.message = argv[++i] || 'unknown error'; }+ else if (arg.startsWith('--error=')) { out.status = 'agent_error'; out.message = arg.slice('--error='.length); }+ else if (arg === '--help' || arg === '-h') out.help = true;+ }+ return out;+}++export async function completeCli() {+ const args = parseArgs(process.argv.slice(2));+ if (args.help || !args.id) {+ console.log(`Usage: node live-complete.mjs --id SESSION_ID [--discarded|--error MESSAGE]\n\nAppend the final durable session acknowledgement. Use after accept/discard cleanup is verified.`);+ process.exit(args.help ? 0 : 1);+ }++ const serverInfo = readServerInfo();+ const serverResult = serverInfo ? await completeThroughServer(serverInfo, args) : null;+ if (serverResult?.ok) {+ const store = createLiveSessionStore({ cwd: process.cwd(), sessionId: args.id });+ const snapshot = store.getSnapshot(args.id, { includeCompleted: true });+ console.log(JSON.stringify({ ok: true, id: args.id, phase: snapshot?.phase || args.status, snapshot }, null, 2));+ return;+ }++ const store = createLiveSessionStore({ cwd: process.cwd(), sessionId: args.id });+ const event = args.status === 'discarded'+ ? { type: 'discarded', id: args.id }+ : args.status === 'agent_error'+ ? { type: 'agent_error', id: args.id, message: args.message || 'unknown error' }+ : { type: 'complete', id: args.id };+ const snapshot = store.appendEvent(event);+ console.log(JSON.stringify({ ok: true, id: args.id, phase: snapshot.phase, snapshot }, null, 2));+}++function readServerInfo() {+ return readLiveServerInfo(process.cwd())?.info || null;+}++async function completeThroughServer(info, args) {+ const type = args.status === 'discarded'+ ? 'discarded'+ : args.status === 'agent_error'+ ? 'error'+ : 'complete';+ try {+ const res = await fetch(`http://localhost:${info.port}/poll`, {+ method: 'POST',+ headers: { 'Content-Type': 'application/json' },+ body: JSON.stringify({ token: info.token, id: args.id, type, message: args.message }),+ });+ if (!res.ok) return null;+ return await res.json();+ } catch {+ return null;+ }+}++const _running = process.argv[1];+if (_running?.endsWith('live-complete.mjs') || _running?.endsWith('live-complete.mjs/')) {+ completeCli();+}diff --git a/.kiro/skills/impeccable/scripts/live-completion.mjs b/.kiro/skills/impeccable/scripts/live-completion.mjsnew file mode 100644index 000000000..86b637fff--- /dev/null+++ b/.kiro/skills/impeccable/scripts/live-completion.mjs@@ -0,0 +1,18 @@+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';+ return 'agent_done';+}++export function completionAckForAcceptResult(eventId, completionType, acceptResult) {+ const ack = { ok: true, type: completionType };+ if (acceptResult?.handled === true && acceptResult?.carbonize === true) {+ ack.final = false;+ ack.requiresComplete = true;+ ack.nextCommand = `live-complete.mjs --id ${eventId}`;+ ack.message = 'Carbonize cleanup must be verified, then the session must be completed explicitly before polling again.';+ }+ return ack;+}diff --git a/.kiro/skills/impeccable/scripts/live-inject.mjs b/.kiro/skills/impeccable/scripts/live-inject.mjsindex 1d2ae12f7..555c3a36a 100644--- a/.kiro/skills/impeccable/scripts/live-inject.mjs+++ b/.kiro/skills/impeccable/scripts/live-inject.mjs@@ -2,23 +2,24 @@* CLI helper: insert/remove the live variant mode script tag in the project's* main HTML entry point.*- * On first live run, the agent generates `config.json` in this script's- * directory with the project's insertion target (framework-specific). On+ * On first live run, the agent generates `.impeccable/live/config.json`+ * with the project's insertion target (framework-specific). On* every subsequent run, this script handles insert/remove deterministically* with zero LLM involvement.** Usage:* node live-inject.mjs --port PORT # Insert the live script tag* node live-inject.mjs --remove # Remove the live script tag- * node live-inject.mjs --check # Check whether config.json exists+ * node live-inject.mjs --check # Check whether live config exists*/import fs from 'node:fs';import path from 'node:path';import { fileURLToPath } from 'node:url';+import { resolveLiveConfigPath } from './impeccable-paths.mjs';const __dirname = path.dirname(fileURLToPath(import.meta.url));-const CONFIG_PATH = process.env.IMPECCABLE_LIVE_CONFIG || path.join(__dirname, 'config.json');+const CONFIG_PATH = resolveLiveConfigPath({ cwd: process.cwd(), scriptsDir: __dirname });const MARKER_OPEN_TEXT = 'impeccable-live-start';const MARKER_CLOSE_TEXT = 'impeccable-live-end';@@ -39,12 +40,12 @@ export async function injectCli() {console.log(`Usage: node live-inject.mjs [options]Insert or remove the live mode script tag in the project's HTML entry point.-Reads configuration from config.json (in this same directory).+Reads configuration from .impeccable/live/config.json.Modes:--port PORT Insert script tag pointing at http://localhost:PORT/live.js--remove Remove the script tag (if present)- --check Print whether config.json exists and its content+ --check Print whether .impeccable/live/config.json exists and its contentOutput (JSON):{ ok, file, inserted|removed, config? }`);diff --git a/.kiro/skills/impeccable/scripts/live-poll.mjs b/.kiro/skills/impeccable/scripts/live-poll.mjsindex eb8f1586a..10d452491 100644--- a/.kiro/skills/impeccable/scripts/live-poll.mjs+++ b/.kiro/skills/impeccable/scripts/live-poll.mjs@@ -9,10 +9,10 @@*/import { execFileSync } from 'node:child_process';-import fs from 'node:fs';import path from 'node:path';-import os from 'node:os';import { fileURLToPath } from 'node:url';+import { completionAckForAcceptResult, completionTypeForAcceptResult } from './live-completion.mjs';+import { readLiveServerInfo } from './impeccable-paths.mjs';// Node's built-in fetch (undici under the hood) enforces a 300s headers// timeout that can't be lowered per-request. We cap each request below@@ -20,15 +20,29 @@ import { fileURLToPath } from 'node:url';// depending on the standalone undici package.const PER_REQUEST_TIMEOUT_MS = 270_000;-const LIVE_PID_FILE = path.join(process.cwd(), '.impeccable-live.json');-function readServerInfo() {- try {- return JSON.parse(fs.readFileSync(LIVE_PID_FILE, 'utf-8'));- } catch {+ const record = readLiveServerInfo(process.cwd());+ if (!record) {console.error('No running live server found. Start one with: npx impeccable live');process.exit(1);}+ return record.info;+}++export function buildPollReplyPayload(token, { id, type, message, file, data }) {+ return { token, id, type, message, file, data };+}++async function postReply(base, token, reply) {+ const res = await fetch(`${base}/poll`, {+ method: 'POST',+ headers: { 'Content-Type': 'application/json' },+ body: JSON.stringify(buildPollReplyPayload(token, reply)),+ });+ if (!res.ok) {+ const body = await res.json().catch(() => ({}));+ throw new Error(body.error || res.statusText);+ }}export async function pollCli() {@@ -69,23 +83,7 @@ Options:}try {- const res = await fetch(`${base}/poll`, {- method: 'POST',- headers: { 'Content-Type': 'application/json' },- body: JSON.stringify({- token: info.token,- id,- type: status,- message,- file: filePath,- }),- });-- if (!res.ok) {- const body = await res.json().catch(() => ({}));- console.error(`Reply failed (${res.status}):`, body.error || res.statusText);- process.exit(1);- }+ await postReply(base, info.token, { id, type: status, message, file: filePath });// Success — silent exit (agent doesn't need output for replies)} catch (err) {@@ -156,7 +154,23 @@ Options:);event._acceptResult = JSON.parse(out.trim());} catch (err) {- event._acceptResult = { handled: false, error: err.message };+ event._acceptResult = { handled: false, mode: 'error', error: err.message };+ }++ const completionType = completionTypeForAcceptResult(event.type, event._acceptResult);+ try {+ await postReply(base, info.token, {+ id: event.id,+ type: completionType,+ message: event._acceptResult?.error,+ file: event._acceptResult?.file,+ data: event._acceptResult?.carbonize === true ? { carbonize: true } : undefined,+ });+ } catch (err) {+ event._completionAck = { ok: false, error: err.message };+ }+ if (!event._completionAck) {+ event._completionAck = completionAckForAcceptResult(event.id, completionType, event._acceptResult);}}@@ -164,7 +178,7 @@ Options:// JSON but skips nested fields. One line is enough — the full checklist// is in reference/live.md.if (event._acceptResult?.carbonize === true) {- process.stderr.write('\n⚠ Carbonize cleanup REQUIRED before next poll. See reference/live.md "Required after accept".\n\n');+ process.stderr.write('\n⚠ Carbonize cleanup REQUIRED before next poll. After cleanup, run live-complete.mjs --id ' + event.id + '. See reference/live.md "Required after accept".\n\n');}// Print the event as JSON — the agent reads this from stdoutdiff --git a/.kiro/skills/impeccable/scripts/live-resume.mjs b/.kiro/skills/impeccable/scripts/live-resume.mjsnew file mode 100644index 000000000..a3465c9b5--- /dev/null+++ b/.kiro/skills/impeccable/scripts/live-resume.mjs@@ -0,0 +1,48 @@+#!/usr/bin/env node+/**+ * Recover the next agent action from the durable live-session journal.+ */++import { createLiveSessionStore } from './live-session-store.mjs';++function parseArgs(argv) {+ const out = { id: null };+ for (let i = 0; i < argv.length; i++) {+ const arg = argv[i];+ if (arg === '--id') out.id = argv[++i];+ else if (arg.startsWith('--id=')) out.id = arg.slice('--id='.length);+ else if (arg === '--help' || arg === '-h') out.help = true;+ }+ return out;+}++export async function resumeCli() {+ const args = parseArgs(process.argv.slice(2));+ if (args.help) {+ console.log(`Usage: node live-resume.mjs [--id SESSION_ID]\n\nPrint the active durable session checkpoint and the next safe agent action.`);+ return;+ }++ const store = createLiveSessionStore({ cwd: process.cwd(), sessionId: args.id || undefined });+ const snapshot = args.id ? store.getSnapshot(args.id) : store.listActiveSessions()[0] || null;+ if (!snapshot) {+ console.log(JSON.stringify({ active: false, nextAction: 'No active durable live session found.' }, null, 2));+ return;+ }++ const pending = snapshot.pendingEvent || null;+ const nextAction = pending+ ? `Run live-poll.mjs, handle ${pending.type} ${pending.id}, then acknowledge with live-poll.mjs --reply ${pending.id} done.`+ : snapshot.phase === 'carbonize_required'+ ? `Finish carbonize cleanup${snapshot.sourceFile ? ` in ${snapshot.sourceFile}` : ''}, then run live-complete.mjs --id ${snapshot.id}.`+ : snapshot.phase === 'accept_requested'+ ? `Run live-complete.mjs --id ${snapshot.id} after verifying the accepted variant is written.`+ : `Inspect ${snapshot.id}; no pending agent event is currently queued.`;++ console.log(JSON.stringify({ active: true, snapshot, pendingEvent: pending, nextAction }, null, 2));+}++const _running = process.argv[1];+if (_running?.endsWith('live-resume.mjs') || _running?.endsWith('live-resume.mjs/')) {+ resumeCli();+}diff --git a/.kiro/skills/impeccable/scripts/live-server.mjs b/.kiro/skills/impeccable/scripts/live-server.mjsindex 90614fbf7..53d8f21cb 100644--- a/.kiro/skills/impeccable/scripts/live-server.mjs+++ b/.kiro/skills/impeccable/scripts/live-server.mjs@@ -22,14 +22,20 @@ import net from 'node:net';import { fileURLToPath } from 'node:url';import { parseDesignMd } from './design-parser.mjs';import { resolveContextDir } from './load-context.mjs';+import { createLiveSessionStore } from './live-session-store.mjs';+import {+ getDesignSidecarPath,+ getLiveAnnotationsDir,+ readLiveServerInfo,+ removeLiveServerInfo,+ resolveDesignSidecarPath,+ writeLiveServerInfo,+} from './impeccable-paths.mjs';const __dirname = path.dirname(fileURLToPath(import.meta.url));-// PID file in the project root so both the server and agent can find it-// predictably (os.tmpdir() varies across platforms).-const LIVE_PID_FILE = path.join(process.cwd(), '.impeccable-live.json');-// PRODUCT.md / DESIGN.md / DESIGN.json live wherever load-context.mjs resolves.-// Keeps live-server in sync with the loader when users keep the docs in-// .agents/context/, docs/, or a path set via IMPECCABLE_CONTEXT_DIR.+// PRODUCT.md / DESIGN.md live wherever load-context.mjs resolves. The generated+// DESIGN sidecar is project-local at .impeccable/design.json, with legacy+// DESIGN.json fallback for existing projects.const CONTEXT_DIR = resolveContextDir(process.cwd());const DEFAULT_POLL_TIMEOUT = 600_000; // 10 min — agent re-polls on timeout anywayconst SSE_HEARTBEAT_INTERVAL = 30_000; // keepalive ping every 30s@@ -57,10 +63,12 @@ const state = {token: null,port: null,sseClients: new Set(), // SSE response objects (server→browser push)- pendingEvents: [], // browser events waiting for agent poll+ pendingEvents: [], // browser events waiting for agent ack ({ event, leaseUntil })pendingPolls: [], // agent poll callbacks waiting for browser eventsexitTimer: null,sessionDir: null, // per-session tmp dir for annotation screenshots+ sessionStore: null,+ leaseTimer: null,};// Cap per-annotation upload size. A full 1920×1080 PNG is typically <1 MB;@@ -68,11 +76,70 @@ const state = {const MAX_ANNOTATION_BYTES = 10 * 1024 * 1024;function enqueueEvent(event) {- if (state.pendingPolls.length > 0) {- state.pendingPolls.shift()(event);- } else {- state.pendingEvents.push(event);+ if (!event || (event.id && state.pendingEvents.some((entry) => entry.event?.id === event.id && entry.event?.type === event.type))) return;+ state.pendingEvents.push({ event, leaseUntil: 0 });+ flushPendingPolls();+}++function restorePendingEventsFromStore() {+ if (!state.sessionStore) return;+ for (const snapshot of state.sessionStore.listActiveSessions()) {+ if (snapshot.pendingEvent) enqueueEvent(snapshot.pendingEvent);+ }+}++function findAvailablePendingEvent(now = Date.now()) {+ return state.pendingEvents.find((entry) => !entry.leaseUntil || entry.leaseUntil <= now);+}++function leaseEvent(entry, leaseMs) {+ if (!entry.event?.id) {+ const idx = state.pendingEvents.indexOf(entry);+ if (idx !== -1) state.pendingEvents.splice(idx, 1);+ return entry.event;}+ entry.leaseUntil = Date.now() + leaseMs;+ return entry.event;+}++function acknowledgePendingEvent(id) {+ if (!id) return false;+ const idx = state.pendingEvents.findIndex((entry) => entry.event?.id === id);+ if (idx === -1) return false;+ state.pendingEvents.splice(idx, 1);+ scheduleLeaseFlush();+ return true;+}++function scheduleLeaseFlush() {+ if (state.leaseTimer) {+ clearTimeout(state.leaseTimer);+ state.leaseTimer = null;+ }+ if (state.pendingPolls.length === 0) return;+ const now = Date.now();+ const nextLeaseUntil = state.pendingEvents+ .map((entry) => entry.leaseUntil || 0)+ .filter((leaseUntil) => leaseUntil > now)+ .sort((a, b) => a - b)[0];+ if (!nextLeaseUntil) return;+ state.leaseTimer = setTimeout(() => {+ state.leaseTimer = null;+ flushPendingPolls();+ }, Math.max(0, nextLeaseUntil - now));+}++function flushPendingPolls() {+ while (state.pendingPolls.length > 0) {+ const entry = findAvailablePendingEvent();+ if (!entry) {+ scheduleLeaseFlush();+ return;+ }+ const poll = state.pendingPolls.shift();+ poll.resolve(leaseEvent(entry, poll.leaseMs));+ }+ scheduleLeaseFlush();}/** Push a message to all connected SSE clients. */@@ -103,13 +170,16 @@ function loadBrowserScripts() {// live-browser.js: DO NOT cache. Return the path so the /live.js handler// can re-read on every request. Editing the browser script during iteration// should land on the next tab reload, not require a server restart.+ const sessionPath = path.join(__dirname, 'live-browser-session.js');const livePath = path.join(__dirname, 'live-browser.js');- if (!fs.existsSync(livePath)) {- process.stderr.write('Error: live-browser.js not found at ' + livePath + '\n');- process.exit(1);+ for (const p of [sessionPath, livePath]) {+ if (!fs.existsSync(p)) {+ process.stderr.write('Error: live browser script not found at ' + p + '\n');+ process.exit(1);+ }}- return { detectScript, livePath };+ return { detectScript, sessionPath, livePath };}function hasProjectContext() {@@ -170,6 +240,13 @@ function validateEvent(msg) {return null;case 'discard':return isValidId(msg.id) ? null : 'discard: missing or malformed id';+ case 'checkpoint':+ if (!isValidId(msg.id)) return 'checkpoint: missing or malformed id';+ if (!Number.isInteger(msg.revision) || msg.revision < 0) return 'checkpoint: revision must be a non-negative integer';+ if (msg.paramValues !== undefined && (typeof msg.paramValues !== 'object' || msg.paramValues === null || Array.isArray(msg.paramValues))) {+ return 'checkpoint: paramValues must be an object';+ }+ return null;case 'exit':return null;case 'prefetch':@@ -184,7 +261,7 @@ function validateEvent(msg) {// HTTP request handler// ----------------------------------------------------------------------------function createRequestHandler({ detectScript, livePath }) {+function createRequestHandler({ detectScript, sessionPath, livePath }) {return (req, res) => {const url = new URL(req.url, `http://localhost:${state.port}`);res.setHeader('Access-Control-Allow-Origin', '*');@@ -200,17 +277,20 @@ function createRequestHandler({ detectScript, livePath }) {// the next tab reload. No-store headers prevent browser caching across// sessions — during iteration, a cached old script silently breaks// every subsequent session.+ let sessionScript;let liveScript;try {+ sessionScript = fs.readFileSync(sessionPath, 'utf-8');liveScript = fs.readFileSync(livePath, 'utf-8');} catch (err) {res.writeHead(500, { 'Content-Type': 'text/plain' });- res.end('Error reading live-browser.js: ' + err.message);+ res.end('Error reading live browser scripts: ' + err.message);return;}const body =`window.__IMPECCABLE_TOKEN__ = '${state.token}';\n` +`window.__IMPECCABLE_PORT__ = ${state.port};\n` ++ sessionScript + '\n' +liveScript;res.writeHead(200, {'Content-Type': 'application/javascript',@@ -305,6 +385,26 @@ function createRequestHandler({ detectScript, livePath }) {}// --- Health ---+ if (p === '/status') {+ const token = url.searchParams.get('token');+ if (token !== state.token) { res.writeHead(401, { 'Content-Type': 'application/json' }); res.end(JSON.stringify({ error: 'Unauthorized' })); return; }+ const sessions = state.sessionStore ? state.sessionStore.listActiveSessions() : [];+ res.writeHead(200, { 'Content-Type': 'application/json' });+ res.end(JSON.stringify({+ status: 'ok',+ port: state.port,+ connectedClients: state.sseClients.size,+ pendingEvents: state.pendingEvents.map((entry) => ({+ id: entry.event?.id,+ type: entry.event?.type,+ leased: !!(entry.leaseUntil && entry.leaseUntil > Date.now()),+ leaseUntil: entry.leaseUntil || null,+ })),+ activeSessions: sessions,+ }));+ return;+ }+if (p === '/health') {res.writeHead(200, { 'Content-Type': 'application/json' });res.end(JSON.stringify({@@ -316,13 +416,13 @@ function createRequestHandler({ detectScript, livePath }) {}// --- Design system (unified v2 response) + raw ---- // /design-system.json returns both parsed DESIGN.md and DESIGN.json+ // /design-system.json returns both parsed DESIGN.md and .impeccable/design.json// sidecar when present. Panel merges them:// { present, parsed, sidecar, hasMd, hasSidecar,// mdNewerThanJson, parseError?, sidecarError? }// - parsed: output of parseDesignMd (frontmatter// + six canonical sections) when DESIGN.md exists.- // - sidecar: DESIGN.json contents when present.+ // - sidecar: .impeccable/design.json contents when present.// Expected shape: schemaVersion 2, carrying// extensions + components + narrative.// /design-system/raw returns DESIGN.md markdown verbatim@@ -331,7 +431,7 @@ function createRequestHandler({ detectScript, livePath }) {if (token !== state.token) { res.writeHead(401); res.end('Unauthorized'); return; }const mdPath = path.join(CONTEXT_DIR, 'DESIGN.md');- const jsonPath = path.join(CONTEXT_DIR, 'DESIGN.json');+ const jsonPath = resolveDesignSidecarPath(process.cwd(), CONTEXT_DIR) || getDesignSidecarPath(process.cwd());const mdStat = statOrNull(mdPath);const jsonStat = statOrNull(jsonPath);@@ -367,7 +467,7 @@ function createRequestHandler({ detectScript, livePath }) {try {response.sidecar = JSON.parse(fs.readFileSync(jsonPath, 'utf-8'));} catch (err) {- response.sidecarError = 'Failed to parse DESIGN.json: ' + err.message;+ response.sidecarError = 'Failed to parse .impeccable/design.json: ' + err.message;}}@@ -449,7 +549,16 @@ function createRequestHandler({ detectScript, livePath }) {res.end(JSON.stringify({ error }));return;}- enqueueEvent(msg);+ if (state.sessionStore && msg.id) {+ try {+ state.sessionStore.appendEvent(msg);+ } catch (err) {+ res.writeHead(500, { 'Content-Type': 'application/json' });+ res.end(JSON.stringify({ error: 'session_store_append_failed', message: err.message }));+ return;+ }+ }+ if (msg.type !== 'checkpoint') enqueueEvent(msg);res.writeHead(200, { 'Content-Type': 'application/json' });res.end(JSON.stringify({ ok: true }));});@@ -492,13 +601,16 @@ function handlePollGet(req, res, url) {return;}const timeout = parseInt(url.searchParams.get('timeout') || DEFAULT_POLL_TIMEOUT, 10);- if (state.pendingEvents.length > 0) {+ const leaseMs = parseInt(url.searchParams.get('leaseMs') || '30000', 10);+ const available = findAvailablePendingEvent();+ if (available) {res.writeHead(200, { 'Content-Type': 'application/json' });- res.end(JSON.stringify(state.pendingEvents.shift()));+ res.end(JSON.stringify(leaseEvent(available, leaseMs)));return;}+ const poll = { resolve, leaseMs };const timer = setTimeout(() => {- const idx = state.pendingPolls.indexOf(resolve);+ const idx = state.pendingPolls.indexOf(poll);if (idx !== -1) state.pendingPolls.splice(idx, 1);res.writeHead(200, { 'Content-Type': 'application/json' });res.end(JSON.stringify({ type: 'timeout' }));@@ -508,10 +620,11 @@ function handlePollGet(req, res, url) {res.writeHead(200, { 'Content-Type': 'application/json' });res.end(JSON.stringify(event));}- state.pendingPolls.push(resolve);+ state.pendingPolls.push(poll);+ scheduleLeaseFlush();req.on('close', () => {clearTimeout(timer);- const idx = state.pendingPolls.indexOf(resolve);+ const idx = state.pendingPolls.indexOf(poll);if (idx !== -1) state.pendingPolls.splice(idx, 1);});}@@ -531,6 +644,26 @@ function handlePollPost(req, res) {res.end(JSON.stringify({ error: 'Unauthorized' }));return;}+ acknowledgePendingEvent(msg.id);+ if (state.sessionStore && msg.id) {+ try {+ const eventType = msg.type === 'discard' || msg.type === 'discarded'+ ? 'discarded'+ : msg.type === 'complete'+ ? 'complete'+ : msg.type === 'error'+ ? 'agent_error'+ : 'agent_done';+ state.sessionStore.appendEvent({+ type: eventType,+ id: msg.id,+ file: msg.file,+ message: msg.message,+ carbonize: msg.data?.carbonize === true,+ });+ } catch { /* keep reply path best-effort; browser still needs SSE */ }+ }+ flushPendingPolls();// Forward the reply to the browser via SSEbroadcast({ type: msg.type || 'done', id: msg.id, message: msg.message, file: msg.file, data: msg.data });res.writeHead(200, { 'Content-Type': 'application/json' });@@ -545,13 +678,15 @@ function handlePollPost(req, res) {let httpServer = null;function shutdown() {- try { fs.unlinkSync(LIVE_PID_FILE); } catch {}+ removeLiveServerInfo(process.cwd());+ if (state.leaseTimer) clearTimeout(state.leaseTimer);+ state.leaseTimer = null;if (state.sessionDir) {try { fs.rmSync(state.sessionDir, { recursive: true, force: true }); } catch {}}for (const res of state.sseClients) { try { res.end(); } catch {} }state.sseClients.clear();- for (const resolve of state.pendingPolls) resolve({ type: 'exit' });+ for (const poll of state.pendingPolls) poll.resolve({ type: 'exit' });state.pendingPolls.length = 0;if (httpServer) httpServer.close();process.exit(0);@@ -587,6 +722,7 @@ Endpoints:/events SSE stream (server→browser) + POST (browser→server)/poll Long-poll for agent CLI/source Raw source file reader (no-HMR fallback)+ /status Durable recovery status (token-protected)/health Health check`);process.exit(0);}@@ -594,7 +730,7 @@ Endpoints:if (args.includes('stop')) {const keepInject = args.includes('--keep-inject');try {- const info = JSON.parse(fs.readFileSync(LIVE_PID_FILE, 'utf-8'));+ const { info } = readLiveServerInfo(process.cwd()) || {};const res = await fetch(`http://localhost:${info.port}/stop?token=${info.token}`);if (res.ok) console.log(`Stopped live server on port ${info.port}.`);} catch {@@ -645,7 +781,7 @@ if (args.includes('--background')) {const deadline = Date.now() + 10_000;while (Date.now() < deadline) {try {- const info = JSON.parse(fs.readFileSync(LIVE_PID_FILE, 'utf-8'));+ const { info } = readLiveServerInfo(process.cwd()) || {};if (info.pid !== process.pid) {// Output JSON so the agent can read port + token from stdout.console.log(JSON.stringify(info));@@ -659,30 +795,36 @@ if (args.includes('--background')) {}// Check for existing session-try {- const existing = JSON.parse(fs.readFileSync(LIVE_PID_FILE, 'utf-8'));- try { process.kill(existing.pid, 0);+const existingRecord = readLiveServerInfo(process.cwd());+if (existingRecord?.info) {+ const existing = existingRecord.info;+ try {+ process.kill(existing.pid, 0);console.error(`Live server already running on port ${existing.port} (pid ${existing.pid}).`);console.error('Stop it first with: node ' + path.basename(fileURLToPath(import.meta.url)) + ' stop');process.exit(1);- } catch { fs.unlinkSync(LIVE_PID_FILE); }-} catch {}+ } catch {+ try { fs.unlinkSync(existingRecord.path); } catch {}+ }+}state.token = randomUUID();+state.sessionStore = createLiveSessionStore({ cwd: process.cwd() });+restorePendingEventsFromStore();const portArg = args.find(a => a.startsWith('--port='));state.port = portArg ? parseInt(portArg.split('=')[1], 10) : await findOpenPort();// Annotation screenshots live in the project root so the agent's Read tool// doesn't trip a per-file permission prompt. Sessioned by token so concurrent// projects (or quick restarts) don't collide.-const annotRoot = path.join(process.cwd(), '.impeccable-live', 'annotations');+const annotRoot = getLiveAnnotationsDir(process.cwd());fs.mkdirSync(annotRoot, { recursive: true });state.sessionDir = fs.mkdtempSync(path.join(annotRoot, 'session-'));-const { detectScript, livePath } = loadBrowserScripts();-httpServer = http.createServer(createRequestHandler({ detectScript, livePath }));+const { detectScript, sessionPath, livePath } = loadBrowserScripts();+httpServer = http.createServer(createRequestHandler({ detectScript, sessionPath, livePath }));httpServer.listen(state.port, '127.0.0.1', () => {- fs.writeFileSync(LIVE_PID_FILE, JSON.stringify({ pid: process.pid, port: state.port, token: state.token }));+ writeLiveServerInfo(process.cwd(), { pid: process.pid, port: state.port, token: state.token });const url = `http://localhost:${state.port}`;console.log(`\nImpeccable live server running on ${url}`);console.log(`Token: ${state.token}\n`);diff --git a/.kiro/skills/impeccable/scripts/live-session-store.mjs b/.kiro/skills/impeccable/scripts/live-session-store.mjsnew file mode 100644index 000000000..d55ed2d3a--- /dev/null+++ b/.kiro/skills/impeccable/scripts/live-session-store.mjs@@ -0,0 +1,254 @@+import fs from 'node:fs';+import path from 'node:path';+import { getLegacyLiveSessionsDir, getLiveSessionsDir } from './impeccable-paths.mjs';++const COMPLETED_PHASES = new Set(['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;+ }++ function getReadableJournalPath(id) {+ const primary = getJournalPath(rootDir, id);+ if (fs.existsSync(primary)) return primary;+ const legacy = getJournalPath(legacyRootDir, id);+ if (fs.existsSync(legacy)) return legacy;+ return primary;+ }++ return {+ rootDir,+ legacyRootDir,+ appendEvent(event) {+ const normalized = normalizeEvent(event, sessionId);+ const journalPath = getJournalPath(rootDir, normalized.id);+ const snapshotPath = getSnapshotPath(rootDir, normalized.id);+ const legacyJournalPath = getJournalPath(legacyRootDir, normalized.id);+ if (!fs.existsSync(journalPath) && fs.existsSync(legacyJournalPath)) {+ fs.copyFileSync(legacyJournalPath, journalPath);+ }+ const prior = loadCachedOrRebuild(normalized.id);+ const seq = prior.nextSeq;+ const entry = {+ seq,+ id: normalized.id,+ type: normalized.type,+ ts: new Date().toISOString(),+ event: normalized,+ };+ 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;+ },+ getSnapshot(id = sessionId, opts = {}) {+ if (!id) throw new Error('session id required');+ 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;+ },+ listActiveSessions() {+ const ids = new Set();+ for (const dir of [legacyRootDir, rootDir]) {+ if (!fs.existsSync(dir)) continue;+ for (const name of fs.readdirSync(dir)) {+ if (name.endsWith('.jsonl')) ids.add(name.slice(0, -'.jsonl'.length));+ }+ }+ return [...ids]+ .sort()+ .map((id) => this.getSnapshot(id))+ .filter(Boolean);+ },+ };+}++function normalizeEvent(event, fallbackId) {+ if (!event || typeof event !== 'object') throw new Error('event object required');+ const id = event.id || fallbackId;+ if (!id || typeof id !== 'string') throw new Error('event id required');+ if (!event.type || typeof event.type !== 'string') throw new Error('event type required');+ return { ...event, id };+}++function getJournalPath(rootDir, id) {+ return path.join(rootDir, safeSessionId(id) + '.jsonl');+}++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,+ phase: 'new',+ pageUrl: null,+ sourceFile: null,+ expectedVariants: 0,+ arrivedVariants: 0,+ visibleVariant: null,+ paramValues: {},+ pendingEventSeq: null,+ pendingEvent: null,+ deliveryLease: null,+ checkpointRevision: 0,+ activeOwner: null,+ sourceMarkers: {},+ fallbackMode: null,+ annotationArtifacts: [],+ diagnostics: [],+ updatedAt: null,+ };+}++function rebuildSnapshotFromJournal(journalPath, id) {+ let snapshot = baseSnapshot(id);+ const diagnostics = [];+ let nextSeq = 1;+ if (!fs.existsSync(journalPath)) return { snapshot, diagnostics, nextSeq };++ const lines = fs.readFileSync(journalPath, 'utf-8').split('\n');+ for (let i = 0; i < lines.length; i++) {+ const line = lines[i];+ if (!line.trim()) continue;+ try {+ const entry = JSON.parse(line);+ if (!entry || typeof entry !== 'object') throw new Error('entry is not object');+ if (Number.isInteger(entry.seq)) nextSeq = Math.max(nextSeq, entry.seq + 1);+ snapshot = applyEvent(snapshot, entry);+ } catch (err) {+ diagnostics.push({+ error: 'journal_parse_failed',+ line: i + 1,+ message: err.message,+ });+ }+ }+ snapshot.diagnostics = [...snapshot.diagnostics, ...diagnostics];+ return { snapshot, diagnostics, nextSeq };+}++function applyEvent(snapshot, entry, inheritedDiagnostics = []) {+ const event = entry.event || entry;+ const next = {+ ...snapshot,+ paramValues: { ...(snapshot.paramValues || {}) },+ sourceMarkers: { ...(snapshot.sourceMarkers || {}) },+ annotationArtifacts: [...(snapshot.annotationArtifacts || [])],+ diagnostics: [...(snapshot.diagnostics || [])],+ updatedAt: entry.ts || new Date().toISOString(),+ };++ if (inheritedDiagnostics.length && next.diagnostics.length === 0) {+ next.diagnostics = [...inheritedDiagnostics];+ }++ switch (event.type) {+ case 'generate':+ next.phase = 'generate_requested';+ next.pageUrl = event.pageUrl ?? next.pageUrl;+ next.expectedVariants = event.count ?? next.expectedVariants;+ next.pendingEventSeq = entry.seq ?? next.pendingEventSeq;+ next.pendingEvent = toPendingEvent(event);+ if (event.screenshotPath) upsertArtifact(next.annotationArtifacts, { type: 'screenshot', path: event.screenshotPath });+ break;+ case 'variants_ready':+ case 'agent_done':+ next.phase = event.carbonize === true ? 'carbonize_required' : 'variants_ready';+ next.sourceFile = event.file ?? next.sourceFile;+ next.arrivedVariants = event.arrivedVariants ?? (next.arrivedVariants ?? next.expectedVariants);+ next.pendingEventSeq = null;+ next.pendingEvent = null;+ if (event.carbonize === true) {+ next.diagnostics.push({+ error: 'carbonize_cleanup_required',+ file: event.file || null,+ message: 'Accepted variant still has carbonize markers that must be folded into source CSS.',+ });+ }+ break;+ case 'checkpoint':+ 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;+ if (event.paramValues) next.paramValues = { ...event.paramValues };+ } else {+ next.diagnostics.push({ error: 'stale_checkpoint_ignored', revision: event.revision });+ }+ break;+ case 'accept':+ case 'accept_intent':+ next.phase = 'accept_requested';+ next.visibleVariant = Number(event.variantId ?? next.visibleVariant);+ if (event.paramValues) next.paramValues = { ...event.paramValues };+ next.pendingEventSeq = entry.seq ?? next.pendingEventSeq;+ next.pendingEvent = toPendingEvent(event);+ break;+ case 'discard':+ next.phase = 'discard_requested';+ next.pendingEventSeq = entry.seq ?? next.pendingEventSeq;+ next.pendingEvent = toPendingEvent(event);+ break;+ case 'discarded':+ next.phase = 'discarded';+ next.pendingEventSeq = null;+ next.pendingEvent = null;+ break;+ case 'complete':+ next.phase = 'completed';+ next.pendingEventSeq = null;+ next.pendingEvent = null;+ break;+ case 'agent_error':+ next.phase = 'agent_error';+ next.pendingEventSeq = null;+ next.pendingEvent = null;+ next.diagnostics.push({ error: 'agent_error', message: event.message || 'unknown agent error' });+ break;+ default:+ next.diagnostics.push({ error: 'unknown_event_type', type: event.type });+ break;+ }+ return next;+}++function toPendingEvent(event) {+ const pending = { ...event };+ delete pending.token;+ return pending;+}++function upsertArtifact(artifacts, artifact) {+ if (!artifacts.some((existing) => existing.path === artifact.path && existing.type === artifact.type)) {+ artifacts.push(artifact);+ }+}++function writeSnapshot(snapshotPath, snapshot) {+ fs.writeFileSync(snapshotPath, JSON.stringify(snapshot, null, 2) + '\n');+}diff --git a/.kiro/skills/impeccable/scripts/live-status.mjs b/.kiro/skills/impeccable/scripts/live-status.mjsnew file mode 100644index 000000000..dce1fbca2--- /dev/null+++ b/.kiro/skills/impeccable/scripts/live-status.mjs@@ -0,0 +1,47 @@+#!/usr/bin/env node+/**+ * Print durable recovery status for Impeccable live sessions.+ */++import { createLiveSessionStore } from './live-session-store.mjs';+import { readLiveServerInfo } from './impeccable-paths.mjs';++function readServerInfo() {+ return readLiveServerInfo(process.cwd())?.info || null;+}++async function fetchServerStatus(info) {+ if (!info) return null;+ try {+ const res = await fetch(`http://localhost:${info.port}/status?token=${info.token}`);+ if (!res.ok) return null;+ return await res.json();+ } catch {+ return null;+ }+}++export async function statusCli() {+ const info = readServerInfo();+ const server = await fetchServerStatus(info);+ const store = createLiveSessionStore({ cwd: process.cwd() });+ const activeSessions = store.listActiveSessions();+ const payload = {+ liveServer: server ? {+ status: server.status,+ port: server.port,+ connectedClients: server.connectedClients,+ pendingEvents: server.pendingEvents,+ } : null,+ activeSessions: server?.activeSessions || activeSessions,+ recoveryHint: 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.',+ };+ console.log(JSON.stringify(payload, null, 2));+}++const _running = process.argv[1];+if (_running?.endsWith('live-status.mjs') || _running?.endsWith('live-status.mjs/')) {+ statusCli();+}diff --git a/.kiro/skills/impeccable/scripts/live-wrap.mjs b/.kiro/skills/impeccable/scripts/live-wrap.mjsindex a5769a50a..d46328b9f 100644--- a/.kiro/skills/impeccable/scripts/live-wrap.mjs+++ b/.kiro/skills/impeccable/scripts/live-wrap.mjs@@ -185,6 +185,7 @@ The agent should insert variant HTML at insertLine.`);const { startLine, endLine } = match;const commentSyntax = detectCommentSyntax(targetFile);+ const styleMode = detectStyleMode(targetFile);const isJsx = commentSyntax.open === '{/*';const indent = lines[startLine].match(/^(\s*)/)[1];@@ -269,6 +270,10 @@ The agent should insert variant HTML at insertLine.`);endLine: startLine + wrapperLines.length + (originalLines.length - 1), // 1-indexedinsertLine: insertLine + 1, // 1-indexed: where variants gocommentSyntax: commentSyntax,+ styleMode: styleMode.mode,+ styleTag: styleMode.styleTag,+ cssSelectorPrefixExamples: buildCssSelectorPrefixExamples(styleMode.mode, count),+ cssAuthoring: buildCssAuthoring(styleMode, count),originalLineCount: originalLines.length,}));}@@ -335,6 +340,62 @@ function detectCommentSyntax(filePath) {return { open: '<!--', close: '-->' };}+function detectStyleMode(filePath) {+ const ext = path.extname(filePath).toLowerCase();+ if (ext === '.astro') {+ return {+ mode: 'astro-global-prefixed',+ styleTag: '<style is:inline data-impeccable-css="SESSION_ID">',+ };+ }+ return {+ mode: 'scoped',+ styleTag: '<style data-impeccable-css="SESSION_ID">',+ };+}++function buildCssSelectorPrefixExamples(styleMode, count) {+ if (styleMode !== 'astro-global-prefixed') return [];+ return Array.from({ length: count }, (_, i) => `[data-impeccable-variant="${i + 1}"]`);+}++function buildCssAuthoring(styleMode, count) {+ const variantNumbers = Array.from({ length: count }, (_, i) => i + 1);+ if (styleMode.mode === 'astro-global-prefixed') {+ return {+ mode: styleMode.mode,+ styleTag: styleMode.styleTag,+ strategy: 'global-prefixed',+ rulePattern: '[data-impeccable-variant="N"] > .variant-class { ... }',+ selectorExamples: variantNumbers.map((n) => `[data-impeccable-variant="${n}"] > .variant-class`),+ requirements: [+ 'Use the styleTag exactly; the is:inline attribute is required for this file.',+ 'Prefix every preview selector with the matching [data-impeccable-variant="N"] selector.',+ 'Keep selectors anchored to the generated variant wrapper; do not rely on component CSS scoping for preview rules.',+ ],+ forbidden: [+ 'Do not use @scope for this styleMode.',+ ],+ };+ }+ return {+ mode: styleMode.mode,+ styleTag: styleMode.styleTag,+ strategy: 'scope-rule',+ rulePattern: '@scope ([data-impeccable-variant="N"]) { :scope > .variant-class { ... } }',+ selectorExamples: variantNumbers.map((n) => `@scope ([data-impeccable-variant="${n}"]) { :scope > .variant-class { ... } }`),+ requirements: [+ 'Use @scope blocks keyed to each [data-impeccable-variant="N"] wrapper.',+ 'Inside each @scope block, make :scope rules step into the replacement element with a descendant combinator.',+ 'Use the styleTag exactly; do not add framework-specific style attributes unless this object says to.',+ ],+ forbidden: [+ 'Do not use global [data-impeccable-variant="N"] selector prefixes for this styleMode.',+ 'Do not add is:inline to the style tag for this styleMode.',+ ],+ };+}+/*** Search project files for the query string (class name, ID, etc.)* Returns the first matching file path, or null.diff --git a/.kiro/skills/impeccable/scripts/live.mjs b/.kiro/skills/impeccable/scripts/live.mjsindex befbdb8ed..cafb0eca9 100644--- a/.kiro/skills/impeccable/scripts/live.mjs+++ b/.kiro/skills/impeccable/scripts/live.mjs@@ -2,10 +2,10 @@* CLI entry point: prepare everything needed to enter the live variant poll loop.** Does (all in one command):- * 1. Check config.json (returns config_missing if first-ever run)+ * 1. Check .impeccable/live/config.json (returns config_missing if first-ever run)* 2. Start the live server in the background (or reuse a running one)* 3. Inject the browser script tag into the project's entry file- * 4. Read .impeccable.md for design context (if present)+ * 4. Read PRODUCT.md / DESIGN.md for project context* 5. Print a single JSON blob with everything the agent needs** After this, the agent's only remaining steps are:@@ -23,9 +23,9 @@ import path from 'node:path';import { fileURLToPath } from 'node:url';import { loadContext } from './load-context.mjs';import { resolveFiles } from './live-inject.mjs';+import { readLiveServerInfo } from './impeccable-paths.mjs';const __dirname = path.dirname(fileURLToPath(import.meta.url));-const PID_FILE = path.join(process.cwd(), '.impeccable-live.json');async function liveCli() {const args = process.argv.slice(2);@@ -34,10 +34,10 @@ async function liveCli() {console.log(`Usage: node live.mjsPrepare everything for live variant mode in a single command:- - Checks scripts/config.json (required, created once per project)+ - Checks .impeccable/live/config.json (required, created once per project)- Starts (or reuses) the live server in the background- Injects the browser script tag- - Reads .impeccable.md for design context+ - Reads PRODUCT.md / DESIGN.md for project contextOn success, prints a JSON blob with:{ ok, serverPort, serverToken, pageFile, hasContext, context }@@ -223,7 +223,7 @@ function safeParse(out) {function ensureServerRunning() {// Try to reuse an existing servertry {- const existing = JSON.parse(fs.readFileSync(PID_FILE, 'utf-8'));+ const existing = readLiveServerInfo(process.cwd())?.info;if (existing && existing.pid) {try {process.kill(existing.pid, 0); // throws if deaddiff --git a/.kiro/skills/impeccable/scripts/load-context.mjs b/.kiro/skills/impeccable/scripts/load-context.mjsindex dca23c1f8..dc340bf16 100644--- a/.kiro/skills/impeccable/scripts/load-context.mjs+++ b/.kiro/skills/impeccable/scripts/load-context.mjs@@ -39,7 +39,7 @@ const LEGACY_NAMES = ['.impeccable.md'];const FALLBACK_DIRS = ['.agents/context', 'docs'];/**- * Resolve the directory that holds PRODUCT.md / DESIGN.md / DESIGN.json for+ * Resolve the directory that holds PRODUCT.md / DESIGN.md for* this project. Exported so other scripts (e.g. live-server.mjs) can read the* design files from the same location the loader uses.*/diff --git a/.opencode/skills/impeccable/reference/document.md b/.opencode/skills/impeccable/reference/document.mdindex 1787c6699..ad09f87cb 100644--- a/.opencode/skills/impeccable/reference/document.md+++ b/.opencode/skills/impeccable/reference/document.md@@ -237,11 +237,11 @@ Concrete, forceful guardrails. Lead each with "Do" or "Don't". Be specific: incl- **Don't** [...]```-### Step 4b: Write DESIGN.json sidecar (extensions only)+### Step 4b: Write .impeccable/design.json sidecar (extensions only)-The frontmatter owns token primitives (colors, typography, rounded, spacing, components). The sidecar at `DESIGN.json` carries **what Stitch's schema can't hold**: tonal ramps per color, shadow/elevation tokens, motion tokens, breakpoints, full component HTML/CSS snippets (the panel renders these into a shadow DOM), and narrative (north star, rules, do's/don'ts). It extends the frontmatter, it doesn't duplicate it.+The frontmatter owns token primitives (colors, typography, rounded, spacing, components). The sidecar at `.impeccable/design.json` carries **what Stitch's schema can't hold**: tonal ramps per color, shadow/elevation tokens, motion tokens, breakpoints, full component HTML/CSS snippets (the panel renders these into a shadow DOM), and narrative (north star, rules, do's/don'ts). It extends the frontmatter, it doesn't duplicate it.-Regenerate the sidecar whenever you regenerate DESIGN.md. If the user only asks to refresh the sidecar (e.g., from the live panel's stale-hint), preserve DESIGN.md and write only DESIGN.json.+Regenerate the sidecar whenever you regenerate root `DESIGN.md`. If the user only asks to refresh the sidecar (e.g., from the live panel's stale-hint), preserve `DESIGN.md` and write only `.impeccable/design.json`.#### Schema@@ -310,7 +310,7 @@ Aim for a tight set of **5-10 components** that best represent the visual system- **Signature components (include if distinctive):** hero CTA, featured card, filter pill, any custom pattern the user mentioned as important in PRODUCT.md.- **Skip the rest.** Utility components, form building blocks, wrapper layouts: not worth documenting unless visually distinctive.-If the project has **no component library yet** (bare landing page, new project), synthesize canonical primitives from the tokens using best-practice defaults consistent with the DESIGN.md's rules. Every DESIGN.json has *something* to render, even on day zero.+If the project has **no component library yet** (bare landing page, new project), synthesize canonical primitives from the tokens using best-practice defaults consistent with the DESIGN.md's rules. Every `.impeccable/design.json` has *something* to render, even on day zero.#### Tonal ramps@@ -331,7 +331,7 @@ Do not reword. The panel shows these as secondary collapsible context; the same### Step 5: Confirm, refine, and refresh session cache1. Show the user the full DESIGN.md you wrote. Briefly highlight the non-obvious creative choices (descriptive color names, atmosphere language, named rules).-2. Mention that `DESIGN.json` was also written alongside; the live panel will now render this project's actual button/input/nav primitives instead of generic approximations.+2. Mention that `.impeccable/design.json` was also written alongside; the live panel will now render this project's actual button/input/nav primitives instead of generic approximations.3. Offer to refine any section: "Want me to revise a section, add component patterns I missed, or adjust the atmosphere language?"4. **Refresh the session cache.** Run `node .opencode/skills/impeccable/scripts/load-context.mjs` one final time so the newly-written DESIGN.md lands in conversation. Subsequent commands in this session will use the fresh version automatically without re-reading.@@ -392,7 +392,7 @@ Per-section guidance in seed mode:- **Components**: omit entirely; no components exist yet.- **Do's and Don'ts**: carry PRODUCT.md's anti-references directly plus the anti-reference named in Q5.-Seed mode writes a minimal frontmatter with `name` and `description` only; no colors, typography, rounded, spacing, or components yet. Real tokens land on the next Scan-mode run. Skip the `DESIGN.json` sidecar in seed mode for the same reason: nothing to render.+Seed mode writes a minimal frontmatter with `name` and `description` only; no colors, typography, rounded, spacing, or components yet. Real tokens land on the next Scan-mode run. Skip the `.impeccable/design.json` sidecar in seed mode for the same reason: nothing to render.### Step 4: Confirm and refresh session cachediff --git a/.opencode/skills/impeccable/reference/live.md b/.opencode/skills/impeccable/reference/live.mdindex 041aa91ea..f2b188f26 100644--- a/.opencode/skills/impeccable/reference/live.md+++ b/.opencode/skills/impeccable/reference/live.md@@ -12,8 +12,9 @@ Execute in order. No step skipped, no step reordered.2. Navigate to the URL that serves `pageFile` (infer from `package.json`, docs, terminal output, or an open tab). If you can't infer it confidently, tell the user once to open their dev/preview URL. Never use `serverPort` as that URL; it's the helper, not the app.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=`.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.-5. On `accept` / `discard`: the poll script already cleaned up; just poll again.-6. On `exit`: run the cleanup at the bottom.+5. 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. If interrupted, run `live-status.mjs` or `live-resume.mjs` before guessing. The durable journal replays unacknowledged work after helper restart.+7. 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.@@ -43,13 +44,31 @@ LOOP:Read JSON; dispatch on "type""generate" → Handle Generate; reply done; LOOP- "accept" → Handle Accept; LOOP+ "accept" → Handle Accept; complete carbonize cleanup if required; LOOP"discard" → Handle Discard; LOOP"prefetch" → Handle Prefetch; LOOP"timeout" → LOOP"exit" → break → Cleanup```+## Recovery commands++The live helper persists an append-only journal under `.impeccable/live/sessions/`. Browser checkpoints are advisory but durable; the journal is canonical. This is local durable recovery state, not project source.++Use these commands when the chat was interrupted, polling was missed, the helper restarted, or the browser reloaded:++```bash+node .opencode/skills/impeccable/scripts/live-status.mjs+node .opencode/skills/impeccable/scripts/live-resume.mjs --id SESSION_ID+node .opencode/skills/impeccable/scripts/live-complete.mjs --id SESSION_ID+```++- `live-status.mjs` prints connected helper state, active durable sessions, and queued pending events. It works even when the helper is down by reading the journal directly.+- `live-resume.mjs` prints the active snapshot, pending event, checkpoint phase, visible variant, parameter values, and the next safe agent action.+- `live-complete.mjs` is the canonical manual final acknowledgement. Use it after carbonize/manual cleanup is verified and no further poll acknowledgement will happen automatically.++Server restart rule: start `live-server.mjs` again, then poll. Startup requeues unacknowledged pending events from the journal, so do not ask the user to click Go again unless `live-resume.mjs` says no active session exists.+## Handle `generate`Event: `{id, action, freeformPrompt?, count, pageUrl, element, screenshotPath?, comments?, strokes?}`.@@ -88,7 +107,14 @@ The helper searches ID first, then classes, then tag + class combo. If `event.paIf `--text` matches multiple candidates equally well, wrap exits with `{ error: "element_ambiguous", candidates: [...] }` and `fallback: "agent-driven"`: read the candidate line ranges, decide which one matches the picked element from page context, and write the wrapper manually per the fallback flow.-Output on success: `{ file, insertLine, commentSyntax }`.+Output on success: `{ file, insertLine, commentSyntax, styleMode, styleTag, cssSelectorPrefixExamples, cssAuthoring }`.++`styleMode` controls how preview CSS must be authored. Treat it as a detected capability mode, not a framework guess:++- `scoped`: use `@scope ([data-impeccable-variant="N"])` rules.+- `astro-global-prefixed`: use explicit `[data-impeccable-variant="N"]` selector prefixes and the exact `styleTag` returned by the tool.++Use `cssAuthoring` as the source of truth for the current file. It includes the exact `styleTag`, selector strategy, selector examples, requirements, and forbidden patterns. Do not apply a framework-specific exception unless the returned `styleMode` / `cssAuthoring.mode` says to.**Fallback errors.** Wrap only writes into files it judges to be source (tracked by git, not marked GENERATED, not listed in config's `generatedFiles`). If it can't land on a source file, it errors without writing; accepting a variant into a generated file is silent data loss. Three shapes:@@ -208,13 +234,14 @@ When the prompt and PRODUCT.md anti-references conflict (the prompt asks for X,Complete 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 scoped 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).+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).++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:```html<!-- Variants: insert below this line --><style data-impeccable-css="SESSION_ID">- @scope ([data-impeccable-variant="1"]) { ... }- @scope ([data-impeccable-variant="2"]) { ... }+ /* rules matching cssAuthoring.rulePattern */</style><div data-impeccable-variant="1"><!-- variant 1: full element replacement (single top-level element) -->@@ -229,11 +256,11 @@ Write CSS + all variants in ONE edit at the `insertLine` reported by `wrap`. Col**Each variant div contains exactly one top-level element: the full replacement for the original.** Use the same tag as the original (e.g. `<section>` if the user picked a `<section>`). Loose siblings (heading + paragraph + div as direct children of the variant div) break the outline tracking and the accept flow, which both assume one child.-The first variant has no `display: none` (visible by default). All others do. If variants use only inline styles and no scoped CSS, omit the `<style>` tag entirely. Use `@scope` for CSS isolation (Chrome 118+ / Firefox 128+ / Safari 17.4+).+The 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.-**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 rule starts `:scope > ...`.+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 > ...`.**JSX / TSX target files.** Wrap `<style>` content in a template literal so the CSS `{` / `}` aren't parsed as JSX expressions, and use `className=` / `style={{…}}` on every variant element. Keep `data-impeccable-*` attributes as-is; they're plain strings:@@ -369,10 +396,11 @@ Remove the wrapper you inserted in Step 2. Nothing else to do.## Handle `accept`-Event: `{id, variantId, _acceptResult}`. The poll script already ran `live-accept.mjs` to handle the file operation deterministically; the browser DOM is already updated.+Event: `{id, variantId, _acceptResult, _completionAck}`. The poll script already ran `live-accept.mjs` to handle the file operation deterministically, then acknowledged event delivery to the helper. The browser DOM is already updated.+- `_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 and a stderr banner both list the steps explicitly; neither is decorative.+- `_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: 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` without `mode`: manual cleanup: read file, find markers, edit.@@ -388,13 +416,13 @@ Do these five steps in the current thread, synchronously, before the next poll.4. **Unwrap the accepted content.** Delete the `<div data-impeccable-variant="N" style="display: contents">` that wraps it. Drop `data-impeccable-params` and any `data-p-*` attributes from it; 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.-Then poll again.+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.## Handle `discard`-Event: `{id, _acceptResult}`. The poll script already restored the original and removed all variant markers. Nothing to do. Poll again.+Event: `{id, _acceptResult, _completionAck}`. The poll script already restored the original, removed all variant markers, and acknowledged `discarded` durable completion. Nothing to do unless `_completionAck.ok !== true`; in that case run `live-complete.mjs --id EVENT_ID --discarded`, then poll again.## Handle `prefetch`@@ -424,7 +452,7 @@ When the poll returns `exit`, proceed to cleanup. If the poll is still running anode .opencode/skills/impeccable/scripts/live-server.mjs stop```-Stops the HTTP server and runs `live-inject.mjs --remove` to strip `localhost:…/live.js` from the HTML entry. To stop the server but keep the inject tag (for a quick restart), use `stop --keep-inject`. `config.json` persists for future sessions.+Stops the HTTP server and runs `live-inject.mjs --remove` to strip `localhost:…/live.js` from the HTML entry. To stop the server but keep the inject tag (for a quick restart), use `stop --keep-inject`. `.impeccable/live/config.json` persists as project config for future sessions.Then:- Remove any leftover variant wrappers (search for `impeccable-variants-start` markers).@@ -432,7 +460,7 @@ Then:## First-time setup (config missing or invalid)-If `live.mjs` outputs `{ ok: false, error: "config_missing" | "config_invalid", path }`, write `config.json` at the reported path.+If `live.mjs` outputs `{ ok: false, error: "config_missing" | "config_invalid", path }`, write the live config at the reported path. By default this is `.impeccable/live/config.json`.Schema:@@ -512,7 +540,7 @@ node .opencode/skills/impeccable/scripts/detect-csp.mjsOutput: `{ shape, signals }` where `shape` is one of `append-arrays`, `append-string`, `middleware`, `meta-tag`, or `null`. The shape is named by *patch mechanism*, so one template covers many frameworks.-- **`null`**: no CSP; skip to writing `config.json` with `cspChecked: true`.+- **`null`**: no CSP; skip to writing `.impeccable/live/config.json` with `cspChecked: true`.- **`append-arrays`**: CSP defined as structured directive arrays. Auto-patchable. See *append-arrays* below. Covers:- Monorepo helpers with `additionalScriptSrc` / `additionalConnectSrc` options (Next.js + shared config package)- SvelteKit `kit.csp.directives`@@ -589,6 +617,6 @@ Reference outputs:### Troubleshooting-If a user says "no" to the CSP patch at setup time and later complains that live doesn't work: their dev CSP blocks `http://localhost:8400`. Fix: delete `cspChecked` from `config.json` and re-run `live.mjs`: setup will ask again.+If a user says "no" to the CSP patch at setup time and later complains that live doesn't work: their dev CSP blocks `http://localhost:8400`. Fix: delete `cspChecked` from `.impeccable/live/config.json` and re-run `live.mjs`: setup will ask again.Then re-run `live.mjs`.diff --git a/.opencode/skills/impeccable/reference/teach.md b/.opencode/skills/impeccable/reference/teach.mdindex c3f3294b7..93c2a74f0 100644--- a/.opencode/skills/impeccable/reference/teach.md+++ b/.opencode/skills/impeccable/reference/teach.md@@ -2,8 +2,8 @@Gathers design context for a project and writes two complementary files at the project root:-- **PRODUCT.md** (strategic): register, target users, product purpose, brand personality, anti-references, strategic design principles. Answers "who/what/why".-- **DESIGN.md** (visual): visual theme, color palette, typography, components, layout. Follows the [Google Stitch DESIGN.md format](https://stitch.withgoogle.com/docs/design-md/format/). Answers "how it looks".+- **PRODUCT.md** (strategic): root project file for register, target users, product purpose, brand personality, anti-references, strategic design principles. Answers "who/what/why".+- **DESIGN.md** (visual): root project file for visual theme, color palette, typography, components, layout. Follows the [Google Stitch DESIGN.md format](https://stitch.withgoogle.com/docs/design-md/format/). Answers "how it looks".Every other impeccable command reads these files before doing any work.diff --git a/.opencode/skills/impeccable/scripts/impeccable-paths.mjs b/.opencode/skills/impeccable/scripts/impeccable-paths.mjsnew file mode 100644index 000000000..ba852bae9--- /dev/null+++ b/.opencode/skills/impeccable/scripts/impeccable-paths.mjs@@ -0,0 +1,105 @@+import fs from 'node:fs';+import path from 'node:path';++export const IMPECCABLE_DIR = '.impeccable';+export const LIVE_DIR = 'live';++export function getImpeccableDir(cwd = process.cwd()) {+ return path.join(cwd, IMPECCABLE_DIR);+}++export function getDesignSidecarPath(cwd = process.cwd()) {+ return path.join(getImpeccableDir(cwd), 'design.json');+}++export function getDesignSidecarCandidates(cwd = process.cwd(), contextDir = cwd) {+ const candidates = [+ getDesignSidecarPath(cwd),+ path.join(cwd, 'DESIGN.json'),+ ];+ const contextLegacy = path.join(contextDir, 'DESIGN.json');+ if (!candidates.includes(contextLegacy)) candidates.push(contextLegacy);+ return candidates;+}++export function resolveDesignSidecarPath(cwd = process.cwd(), contextDir = cwd) {+ return firstExisting(getDesignSidecarCandidates(cwd, contextDir));+}++export function getLiveDir(cwd = process.cwd()) {+ return path.join(getImpeccableDir(cwd), LIVE_DIR);+}++export function getLiveConfigPath(cwd = process.cwd()) {+ return path.join(getLiveDir(cwd), 'config.json');+}++export function getLegacyLiveConfigPath(scriptsDir) {+ return path.join(scriptsDir, 'config.json');+}++export function resolveLiveConfigPath({ cwd = process.cwd(), scriptsDir, env = process.env } = {}) {+ if (env.IMPECCABLE_LIVE_CONFIG && env.IMPECCABLE_LIVE_CONFIG.trim()) {+ const configured = env.IMPECCABLE_LIVE_CONFIG.trim();+ return path.isAbsolute(configured) ? configured : path.resolve(cwd, configured);+ }+ const primary = getLiveConfigPath(cwd);+ if (fs.existsSync(primary)) return primary;+ if (scriptsDir) {+ const legacy = getLegacyLiveConfigPath(scriptsDir);+ if (fs.existsSync(legacy)) return legacy;+ }+ return primary;+}++export function getLiveServerPath(cwd = process.cwd()) {+ return path.join(getLiveDir(cwd), 'server.json');+}++export function getLegacyLiveServerPath(cwd = process.cwd()) {+ return path.join(cwd, '.impeccable-live.json');+}++export function readLiveServerInfo(cwd = process.cwd()) {+ for (const filePath of [getLiveServerPath(cwd), getLegacyLiveServerPath(cwd)]) {+ try {+ return { info: JSON.parse(fs.readFileSync(filePath, 'utf-8')), path: filePath };+ } catch {+ /* try next */+ }+ }+ return null;+}++export function writeLiveServerInfo(cwd = process.cwd(), info) {+ const filePath = getLiveServerPath(cwd);+ fs.mkdirSync(path.dirname(filePath), { recursive: true });+ fs.writeFileSync(filePath, JSON.stringify(info));+ return filePath;+}++export function removeLiveServerInfo(cwd = process.cwd()) {+ for (const filePath of [getLiveServerPath(cwd), getLegacyLiveServerPath(cwd)]) {+ try { fs.unlinkSync(filePath); } catch {}+ }+}++export function getLiveSessionsDir(cwd = process.cwd()) {+ return path.join(getLiveDir(cwd), 'sessions');+}++export function getLegacyLiveSessionsDir(cwd = process.cwd()) {+ return path.join(cwd, '.impeccable-live', 'sessions');+}++export function getLiveAnnotationsDir(cwd = process.cwd()) {+ return path.join(getLiveDir(cwd), 'annotations');+}++export function getLegacyLiveAnnotationsDir(cwd = process.cwd()) {+ return path.join(cwd, '.impeccable-live', 'annotations');+}++function firstExisting(paths) {+ return paths.find((filePath) => fs.existsSync(filePath)) || null;+}diff --git a/.opencode/skills/impeccable/scripts/live-browser-session.js b/.opencode/skills/impeccable/scripts/live-browser-session.jsnew file mode 100644index 000000000..0e362d6be--- /dev/null+++ b/.opencode/skills/impeccable/scripts/live-browser-session.js@@ -0,0 +1,123 @@+/**+ * Browser-side durable session helpers for Impeccable live mode.+ *+ * Kept separate from live-browser.js so recovery state can be tested without+ * booting the full overlay UI. Served before live-browser.js and attached to+ * window.__IMPECCABLE_LIVE_SESSION__.+ */+(function (root) {+ 'use strict';++ function createLiveBrowserSessionState({ prefix, storage, idFactory }) {+ if (!prefix) throw new Error('prefix required');+ const store = storage || root.localStorage;+ const makeId = idFactory || function () { return Math.random().toString(16).slice(2, 10); };+ const sessionKey = prefix + '-session';+ const handledKey = sessionKey + '-handled';+ const scrollKey = sessionKey + '-scroll';+ let checkpointRevision = 0;+ const owner = makeId();++ function safeRead(key) {+ try { return store.getItem(key); } catch { return null; }+ }++ function safeWrite(key, value) {+ try { store.setItem(key, value); } catch { /* quota exceeded or private mode */ }+ }++ function safeRemove(key) {+ try { store.removeItem(key); } catch { /* unavailable storage */ }+ }++ function loadSession() {+ try {+ const raw = safeRead(sessionKey);+ if (!raw) return null;+ const parsed = JSON.parse(raw);+ if (Number.isInteger(parsed.checkpointRevision)) {+ checkpointRevision = Math.max(checkpointRevision, parsed.checkpointRevision);+ }+ return parsed;+ } catch { return null; }+ }++ function saveSession(session) {+ if (!session || !session.id) return;+ const payload = {+ ...session,+ checkpointRevision,+ };+ safeWrite(sessionKey, JSON.stringify(payload));+ }++ function clearSession() {+ safeRemove(sessionKey);+ }++ function nextCheckpointRevision() {+ checkpointRevision += 1;+ const existing = loadSession();+ if (existing?.id) saveSession(existing);+ return checkpointRevision;+ }++ function seedCheckpointRevision(value) {+ if (Number.isInteger(value)) checkpointRevision = Math.max(checkpointRevision, value);+ return checkpointRevision;+ }++ function currentCheckpointRevision() {+ return checkpointRevision;+ }++ function markHandled(id) {+ if (!id) return;+ safeWrite(handledKey, id);+ }++ function isHandled(id) {+ return !!id && safeRead(handledKey) === id;+ }++ function clearHandled() {+ safeRemove(handledKey);+ }++ function writeScrollY(y) {+ safeWrite(scrollKey, String(y));+ }++ function readScrollY() {+ const raw = safeRead(scrollKey);+ if (raw == null) return null;+ const n = parseFloat(raw);+ return isFinite(n) ? n : null;+ }++ function clearScrollY() {+ safeRemove(scrollKey);+ }++ return {+ owner,+ sessionKey,+ handledKey,+ scrollKey,+ saveSession,+ loadSession,+ clearSession,+ nextCheckpointRevision,+ seedCheckpointRevision,+ currentCheckpointRevision,+ markHandled,+ isHandled,+ clearHandled,+ writeScrollY,+ readScrollY,+ clearScrollY,+ };+ }++ root.__IMPECCABLE_LIVE_SESSION__ = { createLiveBrowserSessionState };+})(typeof window !== 'undefined' ? window : globalThis);diff --git a/.opencode/skills/impeccable/scripts/live-browser.js b/.opencode/skills/impeccable/scripts/live-browser.jsindex 3da76bb96..e67cd01ed 100644--- a/.opencode/skills/impeccable/scripts/live-browser.js+++ b/.opencode/skills/impeccable/scripts/live-browser.js@@ -50,6 +50,16 @@const Z = { highlight: 100001, bar: 100005, picker: 100007, toast: 100010 };const EASE = 'cubic-bezier(0.22, 1, 0.36, 1)'; // ease-out-quintconst PREFIX = 'impeccable-live';+ const sessionState = window.__IMPECCABLE_LIVE_SESSION__?.createLiveBrowserSessionState({+ prefix: PREFIX,+ storage: localStorage,+ idFactory: () => crypto.randomUUID().replace(/-/g, '').slice(0, 8),+ });+ if (!sessionState) {+ console.error('[impeccable] live-browser-session.js was not loaded. Live mode cannot start safely.');+ window.__IMPECCABLE_LIVE_INIT__ = false;+ return;+ }const HIGHLIGHT_TRANSITION ='top 140ms ' + EASE +', left 140ms ' + EASE +@@ -112,6 +122,8 @@let hasProjectContext = false;let selectedAction = 'impeccable';let selectedCount = 3;+ const browserOwner = sessionState.owner;+ let checkpointTimer = null;// Scroll lock — holds window.scrollY at a fixed value while the session is// active, so HMR DOM patches and variant swaps can't drift the page. See@@ -126,21 +138,9 @@// (Previously: saveSession wrote scrollY alongside state, so every call// during resume overwrote the pre-reload value with whatever the browser// had landed on, typically 0.)- const SCROLL_KEY_SUFFIX = '-scroll';- function writeScrollY(y) {- try { localStorage.setItem(LS_KEY + SCROLL_KEY_SUFFIX, String(y)); } catch {}- }- function readScrollY() {- try {- const raw = localStorage.getItem(LS_KEY + SCROLL_KEY_SUFFIX);- if (raw == null) return null;- const n = parseFloat(raw);- return isFinite(n) ? n : null;- } catch { return null; }- }- function clearScrollY() {- try { localStorage.removeItem(LS_KEY + SCROLL_KEY_SUFFIX); } catch {}- }+ function writeScrollY(y) { sessionState.writeScrollY(y); }+ function readScrollY() { return sessionState.readScrollY(); }+ function clearScrollY() { sessionState.clearScrollY(); }// Pre-empt the browser: apply manual scroll restoration and jump to the// saved scrollY at script-parse time. Retries on fonts.ready and load@@ -1585,6 +1585,7 @@paramsCurrentValues[p.id] = v;readout.textContent = formatRangeValue(input);applyParamValue(variantEl, p, v);+ queueCheckpoint('param_changed');});row.appendChild(input);} else if (p.kind === 'toggle') {@@ -1615,6 +1616,7 @@knob.style.left = next ? '18px' : '2px';readout.textContent = next ? 'On' : 'Off';applyParamValue(variantEl, p, next);+ queueCheckpoint('param_changed');});row.appendChild(track);} else if (p.kind === 'steps') {@@ -1651,6 +1653,7 @@btn.style.color = on ? 'oklch(98% 0 0)' : P.text;});applyParamValue(variantEl, p, o.value);+ queueCheckpoint('param_changed');});segRow.appendChild(b);segBtns.push({ btn: b, val: o.value });@@ -1872,19 +1875,26 @@return;}+ const previousVisibleVariant = currentSessionId === sessionId ? visibleVariant : 0;+// Replace the live element with the full wrapper from sourceconst wrapper = srcWrapper.cloneNode(true);liveEl.parentElement.replaceChild(wrapper, liveEl);- // Update state: count variants, show the first one+ // Update state: count variants, preserving the user's current variant+ // when a late HMR/source reinjection lands after they have cycled.const variants = wrapper.querySelectorAll('[data-impeccable-variant]:not([data-impeccable-variant="original"])');arrivedVariants = variants.length;expectedVariants = parseInt(wrapper.dataset.impeccableVariantCount || arrivedVariants);- visibleVariant = 1;- showVariantInDOM(sessionId, 1);+ const saved = loadSession();+ const savedVisibleVariant = saved && saved.id === sessionId ? saved.visible : 0;+ visibleVariant = previousVisibleVariant > 0 && previousVisibleVariant <= arrivedVariants+ ? previousVisibleVariant+ : (savedVisibleVariant > 0 && savedVisibleVariant <= arrivedVariants ? savedVisibleVariant : 1);+ showVariantInDOM(sessionId, visibleVariant);// Update selectedElement to the visible variant's content- selectedElement = pickVariantContent(wrapper, 1) || wrapper.parentElement;+ selectedElement = pickVariantContent(wrapper, visibleVariant) || wrapper.parentElement;state = 'CYCLING';hideShaderOverlay();@@ -1907,6 +1917,7 @@updateSelectedElement();updateBarContent('cycling');saveSession();+ queueCheckpoint('variant_changed');}function updateSelectedElement() {@@ -1917,6 +1928,18 @@if (visEl) selectedElement = visEl;}+ function readVisibleVariantFromDOM(sessionId) {+ const wrapper = document.querySelector('[data-impeccable-variants="' + sessionId + '"]');+ if (!wrapper) return 0;+ const variants = wrapper.querySelectorAll('[data-impeccable-variant]:not([data-impeccable-variant="original"])');+ for (const variant of variants) {+ if (variant.style.display === 'none') continue;+ const idx = parseInt(variant.dataset.impeccableVariant || '0', 10);+ if (idx > 0) return idx;+ }+ return 0;+ }+// Resolve the element that represents the variant's visible content.// Contract: each variant div should contain exactly one top-level element// (the full replacement). In practice a model may ship loose siblings or@@ -2107,8 +2130,10 @@updating = true;arrivedVariants = count;if (visibleVariant === 0 && arrivedVariants > 0) {- visibleVariant = 1;- showVariantInDOM(sessionId, 1);+ const saved = loadSession();+ const savedVisibleVariant = saved && saved.id === sessionId ? saved.visible : 0;+ visibleVariant = savedVisibleVariant > 0 && savedVisibleVariant <= arrivedVariants ? savedVisibleVariant : 1;+ showVariantInDOM(sessionId, visibleVariant);// showVariantInDOM hid the original (display:none); if we were still// anchored to the original's content, its boundingRect is now zero// and the bar snaps to (0,0). Re-point at the visible variant instead.@@ -2128,6 +2153,7 @@updateBarContent('generating');}saveSession();+ queueCheckpoint(state === 'CYCLING' ? 'variants_ready' : 'variants_progress');updating = false;});@@ -2236,6 +2262,7 @@/** Server died or became unreachable. Reset UI to a clean state. */function handleServerLost() {+ const recoveryState = currentSessionId ? state : 'IDLE';if (state === 'GENERATING' || state === 'CYCLING' || state === 'SAVING') {showToast('Live server disconnected. Session ended.', 5000);}@@ -2246,21 +2273,61 @@stopScrollTracking();if (variantObserver) { variantObserver.disconnect(); variantObserver = null; }stopScrollLock();- clearScrollY();- clearSession();+ // Preserve local session state on server loss. The durable journal is the+ // source of truth, but localStorage plus the variant wrapper lets the UI+ // resume after a helper restart or page reload instead of treating a+ // transient disconnect as an explicit discard.selectedElement = null;- currentSessionId = null;selectedAction = 'impeccable';- state = 'IDLE';+ state = recoveryState;+ if (currentSessionId) saveSession();}- function sendEvent(msg) {+ function sendEvent(msg, opts) {msg.token = TOKEN;- fetch('http://localhost:' + PORT + '/events', {+ function handleFailure(err) {+ console.error('[impeccable] Failed to send event:', err);+ if (opts && opts.throwOnError) throw err;+ return null;+ }+ return fetch('http://localhost:' + PORT + '/events', {method: 'POST',headers: { 'Content-Type': 'application/json' },body: JSON.stringify(msg),- }).catch(err => console.error('[impeccable] Failed to send event:', err));+ }).then(res => {+ if (res.ok) return res;+ return handleFailure(new Error('HTTP ' + res.status + ' ' + res.statusText));+ }).catch(handleFailure);+ }++ function checkpointPayload(reason) {+ return {+ type: 'checkpoint',+ id: currentSessionId,+ revision: sessionState.nextCheckpointRevision(),+ owner: browserOwner,+ phase: String(state || '').toLowerCase(),+ reason,+ pageUrl: location.pathname,+ expectedVariants,+ arrivedVariants,+ visibleVariant,+ paramValues: { ...paramsCurrentValues },+ };+ }++ function sendCheckpoint(reason) {+ if (!currentSessionId) return Promise.resolve(null);+ return sendEvent(checkpointPayload(reason)).catch(() => null);+ }++ function queueCheckpoint(reason) {+ if (!currentSessionId) return;+ if (checkpointTimer) clearTimeout(checkpointTimer);+ checkpointTimer = setTimeout(() => {+ checkpointTimer = null;+ sendCheckpoint(reason);+ }, 120);}// ---------------------------------------------------------------------------@@ -2496,6 +2563,7 @@state = 'GENERATING';showBar('generating');saveSession();+ sendCheckpoint('generate_started');writeScrollY(window.scrollY);if (variantObserver) variantObserver.disconnect();variantObserver = startVariantObserver(currentSessionId);@@ -2920,13 +2988,12 @@ void main() {function handleAccept() {if (!currentSessionId || arrivedVariants === 0) return;+ const domVisibleVariant = readVisibleVariantFromDOM(currentSessionId);+ if (domVisibleVariant > 0) visibleVariant = domVisibleVariant;const acceptPayload = { type: 'accept', id: currentSessionId, variantId: String(visibleVariant) };if (Object.keys(paramsCurrentValues).length > 0) {acceptPayload.paramValues = { ...paramsCurrentValues };}- sendEvent(acceptPayload);- markSessionHandled();-// The accepted variant is already the only visible child of the wrapper// (all other variants are display:none). HMR from the source rewrite will// replace the wrapper imminently. Don't eagerly replaceChild here — React@@ -2936,9 +3003,28 @@ void main() {const acceptedSessionId = currentSessionId;const acceptedVariant = visibleVariant;- state = 'CONFIRMED';- updateBarContent('confirmed');- setTimeout(function() {+ state = 'SAVING';+ updateBarContent('saving');++ sendEvent(acceptPayload, { throwOnError: true })+ .then(() => {+ markSessionHandled();+ confirmAcceptAfterReceipt();+ })+ .catch(() => {+ state = 'CYCLING';+ updateBarContent('cycling');+ showToast('Could not confirm accept with the live server. Session kept for recovery; try Accept again.', 5000);+ });++ function confirmAcceptAfterReceipt() {+ state = 'CONFIRMED';+ updateBarContent('confirmed');+ scheduleAcceptCleanup();+ }++ function scheduleAcceptCleanup() {+ setTimeout(function() {hideBar();hideHighlight();stopScrollTracking();@@ -2967,50 +3053,46 @@ void main() {accepted.style.display = 'contents';parent.replaceChild(accepted, wrapper);}- }, 2000);+ }, 2000);+ }}function handleDiscard() {if (!currentSessionId) return;- sendEvent({ type: 'discard', id: currentSessionId });- markSessionHandled();- // Instant DOM restore + fire-and-forget (script handles file cleanup)- cleanup();+ sendEvent({ type: 'discard', id: currentSessionId }, { throwOnError: true })+ .then(() => {+ markSessionHandled();+ cleanup();+ })+ .catch(() => showToast('Could not confirm discard with the live server. Session kept for recovery.', 5000));}// ---------------------------------------------------------------------------- // Session persistence via localStorage+ // Session persistence via live-browser-session.js// ---------------------------------------------------------------------------// Survives page reloads, browser close/reopen, HMR, and accidental refreshes.- const LS_KEY = PREFIX + '-session';-function saveSession() {if (!currentSessionId) return;// NOTE: scrollY is stored under a separate key (writeScrollY). Storing// it here would overwrite the Go-time value every time state changes.- try {- localStorage.setItem(LS_KEY, JSON.stringify({- id: currentSessionId,- state: state,- action: selectedAction,- count: selectedCount,- expected: expectedVariants,- arrived: arrivedVariants,- visible: visibleVariant,- }));- } catch { /* quota exceeded or private mode */ }+ sessionState.saveSession({+ id: currentSessionId,+ state,+ action: selectedAction,+ count: selectedCount,+ expected: expectedVariants,+ arrived: arrivedVariants,+ visible: visibleVariant,+ });}function loadSession() {- try {- const raw = localStorage.getItem(LS_KEY);- return raw ? JSON.parse(raw) : null;- } catch { return null; }+ return sessionState.loadSession();}function clearSession() {- try { localStorage.removeItem(LS_KEY); } catch {}+ sessionState.clearSession();}/** Mark session as handled (accepted/discarded). The agent will clean up@@ -3018,19 +3100,15 @@ void main() {* prevents resumeSession from picking it up again after reload. */function markSessionHandled() {if (!currentSessionId) return;- try {- localStorage.setItem(LS_KEY + '-handled', currentSessionId);- } catch {}+ sessionState.markHandled(currentSessionId);}function isSessionHandled(id) {- try {- return localStorage.getItem(LS_KEY + '-handled') === id;- } catch { return false; }+ return sessionState.isHandled(id);}function clearHandled() {- try { localStorage.removeItem(LS_KEY + '-handled'); } catch {}+ sessionState.clearHandled();}function cleanup() {@@ -3161,6 +3239,7 @@ void main() {// hid. Now that state is CYCLING, re-fire.if (state === 'CYCLING') refreshParamsPanel();saveSession();+ queueCheckpoint('browser_resumed');// Start observing for more variants AFTER initial setupif (variantObserver) variantObserver.disconnect();@@ -3617,7 +3696,7 @@ void main() {}// ---------------------------------------------------------------------------- // Design System Panel — visualizes the project's DESIGN.json sidecar+ // Design System Panel — visualizes the project's .impeccable/design.json sidecar// ---------------------------------------------------------------------------const DESIGN_PREFS_KEY = 'impeccable-live-design-panel';@@ -3629,7 +3708,7 @@ void main() {open: false,tab: 'visual', // 'visual' | 'raw'parsed: null, // parseDesignMd output (frontmatter + body sections)- sidecar: null, // DESIGN.json v2 payload (extensions + components + narrative)+ sidecar: null, // .impeccable/design.json v2 payload (extensions + components + narrative)hasMd: false,hasSidecar: false,present: null, // true/false once fetch resolves@@ -4130,7 +4209,7 @@ void main() {box.className = 'stale';box.innerHTML = `<span class="stale-dot"></span>- <span class="stale-text"><strong>DESIGN.md is newer than DESIGN.json.</strong> Run <code>/impeccable document</code> to refresh the sidecar.</span>+ <span class="stale-text"><strong>DESIGN.md is newer than .impeccable/design.json.</strong> Run <code>/impeccable document</code> to refresh the sidecar.</span>`;return box;}@@ -4138,7 +4217,7 @@ void main() {function renderParsedMdCta() {const box = document.createElement('div');box.className = 'parsed-md-cta';- box.innerHTML = `<strong>Basic view</strong>This panel reads the tokens in your <code>DESIGN.md</code> frontmatter. Running <code>/impeccable document</code> also generates a <code>DESIGN.json</code> sidecar with your project's actual component snippets (button, input, nav) and tonal ramps, rendered live below the tokens.`;+ box.innerHTML = `<strong>Basic view</strong>This panel reads the tokens in your <code>DESIGN.md</code> frontmatter. Running <code>/impeccable document</code> also generates a <code>.impeccable/design.json</code> sidecar with your project's actual component snippets (button, input, nav) and tonal ramps, rendered live below the tokens.`;return box;}@@ -4598,7 +4677,7 @@ void main() {function cssSafe(v) {// Strip anything outside valid CSS value chars to prevent injection via- // DESIGN.json values rendered into inline style strings.+ // .impeccable/design.json values rendered into inline style strings.return String(v).replace(/[<>"'`\n]/g, '');}diff --git a/.opencode/skills/impeccable/scripts/live-complete.mjs b/.opencode/skills/impeccable/scripts/live-complete.mjsnew file mode 100644index 000000000..78155af85--- /dev/null+++ b/.opencode/skills/impeccable/scripts/live-complete.mjs@@ -0,0 +1,75 @@+#!/usr/bin/env node+/**+ * Canonical durable completion acknowledgement for Impeccable live sessions.+ */++import { createLiveSessionStore } from './live-session-store.mjs';+import { readLiveServerInfo } from './impeccable-paths.mjs';++function parseArgs(argv) {+ const out = { status: 'complete' };+ for (let i = 0; i < argv.length; i++) {+ const arg = argv[i];+ if (arg === '--id') out.id = argv[++i];+ else if (arg.startsWith('--id=')) out.id = arg.slice('--id='.length);+ else if (arg === '--discarded' || arg === '--discard') out.status = 'discarded';+ else if (arg === '--error') { out.status = 'agent_error'; out.message = argv[++i] || 'unknown error'; }+ else if (arg.startsWith('--error=')) { out.status = 'agent_error'; out.message = arg.slice('--error='.length); }+ else if (arg === '--help' || arg === '-h') out.help = true;+ }+ return out;+}++export async function completeCli() {+ const args = parseArgs(process.argv.slice(2));+ if (args.help || !args.id) {+ console.log(`Usage: node live-complete.mjs --id SESSION_ID [--discarded|--error MESSAGE]\n\nAppend the final durable session acknowledgement. Use after accept/discard cleanup is verified.`);+ process.exit(args.help ? 0 : 1);+ }++ const serverInfo = readServerInfo();+ const serverResult = serverInfo ? await completeThroughServer(serverInfo, args) : null;+ if (serverResult?.ok) {+ const store = createLiveSessionStore({ cwd: process.cwd(), sessionId: args.id });+ const snapshot = store.getSnapshot(args.id, { includeCompleted: true });+ console.log(JSON.stringify({ ok: true, id: args.id, phase: snapshot?.phase || args.status, snapshot }, null, 2));+ return;+ }++ const store = createLiveSessionStore({ cwd: process.cwd(), sessionId: args.id });+ const event = args.status === 'discarded'+ ? { type: 'discarded', id: args.id }+ : args.status === 'agent_error'+ ? { type: 'agent_error', id: args.id, message: args.message || 'unknown error' }+ : { type: 'complete', id: args.id };+ const snapshot = store.appendEvent(event);+ console.log(JSON.stringify({ ok: true, id: args.id, phase: snapshot.phase, snapshot }, null, 2));+}++function readServerInfo() {+ return readLiveServerInfo(process.cwd())?.info || null;+}++async function completeThroughServer(info, args) {+ const type = args.status === 'discarded'+ ? 'discarded'+ : args.status === 'agent_error'+ ? 'error'+ : 'complete';+ try {+ const res = await fetch(`http://localhost:${info.port}/poll`, {+ method: 'POST',+ headers: { 'Content-Type': 'application/json' },+ body: JSON.stringify({ token: info.token, id: args.id, type, message: args.message }),+ });+ if (!res.ok) return null;+ return await res.json();+ } catch {+ return null;+ }+}++const _running = process.argv[1];+if (_running?.endsWith('live-complete.mjs') || _running?.endsWith('live-complete.mjs/')) {+ completeCli();+}diff --git a/.opencode/skills/impeccable/scripts/live-completion.mjs b/.opencode/skills/impeccable/scripts/live-completion.mjsnew file mode 100644index 000000000..86b637fff--- /dev/null+++ b/.opencode/skills/impeccable/scripts/live-completion.mjs@@ -0,0 +1,18 @@+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';+ return 'agent_done';+}++export function completionAckForAcceptResult(eventId, completionType, acceptResult) {+ const ack = { ok: true, type: completionType };+ if (acceptResult?.handled === true && acceptResult?.carbonize === true) {+ ack.final = false;+ ack.requiresComplete = true;+ ack.nextCommand = `live-complete.mjs --id ${eventId}`;+ ack.message = 'Carbonize cleanup must be verified, then the session must be completed explicitly before polling again.';+ }+ return ack;+}diff --git a/.opencode/skills/impeccable/scripts/live-inject.mjs b/.opencode/skills/impeccable/scripts/live-inject.mjsindex 1d2ae12f7..555c3a36a 100644--- a/.opencode/skills/impeccable/scripts/live-inject.mjs+++ b/.opencode/skills/impeccable/scripts/live-inject.mjs@@ -2,23 +2,24 @@* CLI helper: insert/remove the live variant mode script tag in the project's* main HTML entry point.*- * On first live run, the agent generates `config.json` in this script's- * directory with the project's insertion target (framework-specific). On+ * On first live run, the agent generates `.impeccable/live/config.json`+ * with the project's insertion target (framework-specific). On* every subsequent run, this script handles insert/remove deterministically* with zero LLM involvement.** Usage:* node live-inject.mjs --port PORT # Insert the live script tag* node live-inject.mjs --remove # Remove the live script tag- * node live-inject.mjs --check # Check whether config.json exists+ * node live-inject.mjs --check # Check whether live config exists*/import fs from 'node:fs';import path from 'node:path';import { fileURLToPath } from 'node:url';+import { resolveLiveConfigPath } from './impeccable-paths.mjs';const __dirname = path.dirname(fileURLToPath(import.meta.url));-const CONFIG_PATH = process.env.IMPECCABLE_LIVE_CONFIG || path.join(__dirname, 'config.json');+const CONFIG_PATH = resolveLiveConfigPath({ cwd: process.cwd(), scriptsDir: __dirname });const MARKER_OPEN_TEXT = 'impeccable-live-start';const MARKER_CLOSE_TEXT = 'impeccable-live-end';@@ -39,12 +40,12 @@ export async function injectCli() {console.log(`Usage: node live-inject.mjs [options]Insert or remove the live mode script tag in the project's HTML entry point.-Reads configuration from config.json (in this same directory).+Reads configuration from .impeccable/live/config.json.Modes:--port PORT Insert script tag pointing at http://localhost:PORT/live.js--remove Remove the script tag (if present)- --check Print whether config.json exists and its content+ --check Print whether .impeccable/live/config.json exists and its contentOutput (JSON):{ ok, file, inserted|removed, config? }`);diff --git a/.opencode/skills/impeccable/scripts/live-poll.mjs b/.opencode/skills/impeccable/scripts/live-poll.mjsindex eb8f1586a..10d452491 100644--- a/.opencode/skills/impeccable/scripts/live-poll.mjs+++ b/.opencode/skills/impeccable/scripts/live-poll.mjs@@ -9,10 +9,10 @@*/import { execFileSync } from 'node:child_process';-import fs from 'node:fs';import path from 'node:path';-import os from 'node:os';import { fileURLToPath } from 'node:url';+import { completionAckForAcceptResult, completionTypeForAcceptResult } from './live-completion.mjs';+import { readLiveServerInfo } from './impeccable-paths.mjs';// Node's built-in fetch (undici under the hood) enforces a 300s headers// timeout that can't be lowered per-request. We cap each request below@@ -20,15 +20,29 @@ import { fileURLToPath } from 'node:url';// depending on the standalone undici package.const PER_REQUEST_TIMEOUT_MS = 270_000;-const LIVE_PID_FILE = path.join(process.cwd(), '.impeccable-live.json');-function readServerInfo() {- try {- return JSON.parse(fs.readFileSync(LIVE_PID_FILE, 'utf-8'));- } catch {+ const record = readLiveServerInfo(process.cwd());+ if (!record) {console.error('No running live server found. Start one with: npx impeccable live');process.exit(1);}+ return record.info;+}++export function buildPollReplyPayload(token, { id, type, message, file, data }) {+ return { token, id, type, message, file, data };+}++async function postReply(base, token, reply) {+ const res = await fetch(`${base}/poll`, {+ method: 'POST',+ headers: { 'Content-Type': 'application/json' },+ body: JSON.stringify(buildPollReplyPayload(token, reply)),+ });+ if (!res.ok) {+ const body = await res.json().catch(() => ({}));+ throw new Error(body.error || res.statusText);+ }}export async function pollCli() {@@ -69,23 +83,7 @@ Options:}try {- const res = await fetch(`${base}/poll`, {- method: 'POST',- headers: { 'Content-Type': 'application/json' },- body: JSON.stringify({- token: info.token,- id,- type: status,- message,- file: filePath,- }),- });-- if (!res.ok) {- const body = await res.json().catch(() => ({}));- console.error(`Reply failed (${res.status}):`, body.error || res.statusText);- process.exit(1);- }+ await postReply(base, info.token, { id, type: status, message, file: filePath });// Success — silent exit (agent doesn't need output for replies)} catch (err) {@@ -156,7 +154,23 @@ Options:);event._acceptResult = JSON.parse(out.trim());} catch (err) {- event._acceptResult = { handled: false, error: err.message };+ event._acceptResult = { handled: false, mode: 'error', error: err.message };+ }++ const completionType = completionTypeForAcceptResult(event.type, event._acceptResult);+ try {+ await postReply(base, info.token, {+ id: event.id,+ type: completionType,+ message: event._acceptResult?.error,+ file: event._acceptResult?.file,+ data: event._acceptResult?.carbonize === true ? { carbonize: true } : undefined,+ });+ } catch (err) {+ event._completionAck = { ok: false, error: err.message };+ }+ if (!event._completionAck) {+ event._completionAck = completionAckForAcceptResult(event.id, completionType, event._acceptResult);}}@@ -164,7 +178,7 @@ Options:// JSON but skips nested fields. One line is enough — the full checklist// is in reference/live.md.if (event._acceptResult?.carbonize === true) {- process.stderr.write('\n⚠ Carbonize cleanup REQUIRED before next poll. See reference/live.md "Required after accept".\n\n');+ process.stderr.write('\n⚠ Carbonize cleanup REQUIRED before next poll. After cleanup, run live-complete.mjs --id ' + event.id + '. See reference/live.md "Required after accept".\n\n');}// Print the event as JSON — the agent reads this from stdoutdiff --git a/.opencode/skills/impeccable/scripts/live-resume.mjs b/.opencode/skills/impeccable/scripts/live-resume.mjsnew file mode 100644index 000000000..a3465c9b5--- /dev/null+++ b/.opencode/skills/impeccable/scripts/live-resume.mjs@@ -0,0 +1,48 @@+#!/usr/bin/env node+/**+ * Recover the next agent action from the durable live-session journal.+ */++import { createLiveSessionStore } from './live-session-store.mjs';++function parseArgs(argv) {+ const out = { id: null };+ for (let i = 0; i < argv.length; i++) {+ const arg = argv[i];+ if (arg === '--id') out.id = argv[++i];+ else if (arg.startsWith('--id=')) out.id = arg.slice('--id='.length);+ else if (arg === '--help' || arg === '-h') out.help = true;+ }+ return out;+}++export async function resumeCli() {+ const args = parseArgs(process.argv.slice(2));+ if (args.help) {+ console.log(`Usage: node live-resume.mjs [--id SESSION_ID]\n\nPrint the active durable session checkpoint and the next safe agent action.`);+ return;+ }++ const store = createLiveSessionStore({ cwd: process.cwd(), sessionId: args.id || undefined });+ const snapshot = args.id ? store.getSnapshot(args.id) : store.listActiveSessions()[0] || null;+ if (!snapshot) {+ console.log(JSON.stringify({ active: false, nextAction: 'No active durable live session found.' }, null, 2));+ return;+ }++ const pending = snapshot.pendingEvent || null;+ const nextAction = pending+ ? `Run live-poll.mjs, handle ${pending.type} ${pending.id}, then acknowledge with live-poll.mjs --reply ${pending.id} done.`+ : snapshot.phase === 'carbonize_required'+ ? `Finish carbonize cleanup${snapshot.sourceFile ? ` in ${snapshot.sourceFile}` : ''}, then run live-complete.mjs --id ${snapshot.id}.`+ : snapshot.phase === 'accept_requested'+ ? `Run live-complete.mjs --id ${snapshot.id} after verifying the accepted variant is written.`+ : `Inspect ${snapshot.id}; no pending agent event is currently queued.`;++ console.log(JSON.stringify({ active: true, snapshot, pendingEvent: pending, nextAction }, null, 2));+}++const _running = process.argv[1];+if (_running?.endsWith('live-resume.mjs') || _running?.endsWith('live-resume.mjs/')) {+ resumeCli();+}diff --git a/.opencode/skills/impeccable/scripts/live-server.mjs b/.opencode/skills/impeccable/scripts/live-server.mjsindex 90614fbf7..53d8f21cb 100644--- a/.opencode/skills/impeccable/scripts/live-server.mjs+++ b/.opencode/skills/impeccable/scripts/live-server.mjs@@ -22,14 +22,20 @@ import net from 'node:net';import { fileURLToPath } from 'node:url';import { parseDesignMd } from './design-parser.mjs';import { resolveContextDir } from './load-context.mjs';+import { createLiveSessionStore } from './live-session-store.mjs';+import {+ getDesignSidecarPath,+ getLiveAnnotationsDir,+ readLiveServerInfo,+ removeLiveServerInfo,+ resolveDesignSidecarPath,+ writeLiveServerInfo,+} from './impeccable-paths.mjs';const __dirname = path.dirname(fileURLToPath(import.meta.url));-// PID file in the project root so both the server and agent can find it-// predictably (os.tmpdir() varies across platforms).-const LIVE_PID_FILE = path.join(process.cwd(), '.impeccable-live.json');-// PRODUCT.md / DESIGN.md / DESIGN.json live wherever load-context.mjs resolves.-// Keeps live-server in sync with the loader when users keep the docs in-// .agents/context/, docs/, or a path set via IMPECCABLE_CONTEXT_DIR.+// PRODUCT.md / DESIGN.md live wherever load-context.mjs resolves. The generated+// DESIGN sidecar is project-local at .impeccable/design.json, with legacy+// DESIGN.json fallback for existing projects.const CONTEXT_DIR = resolveContextDir(process.cwd());const DEFAULT_POLL_TIMEOUT = 600_000; // 10 min — agent re-polls on timeout anywayconst SSE_HEARTBEAT_INTERVAL = 30_000; // keepalive ping every 30s@@ -57,10 +63,12 @@ const state = {token: null,port: null,sseClients: new Set(), // SSE response objects (server→browser push)- pendingEvents: [], // browser events waiting for agent poll+ pendingEvents: [], // browser events waiting for agent ack ({ event, leaseUntil })pendingPolls: [], // agent poll callbacks waiting for browser eventsexitTimer: null,sessionDir: null, // per-session tmp dir for annotation screenshots+ sessionStore: null,+ leaseTimer: null,};// Cap per-annotation upload size. A full 1920×1080 PNG is typically <1 MB;@@ -68,11 +76,70 @@ const state = {const MAX_ANNOTATION_BYTES = 10 * 1024 * 1024;function enqueueEvent(event) {- if (state.pendingPolls.length > 0) {- state.pendingPolls.shift()(event);- } else {- state.pendingEvents.push(event);+ if (!event || (event.id && state.pendingEvents.some((entry) => entry.event?.id === event.id && entry.event?.type === event.type))) return;+ state.pendingEvents.push({ event, leaseUntil: 0 });+ flushPendingPolls();+}++function restorePendingEventsFromStore() {+ if (!state.sessionStore) return;+ for (const snapshot of state.sessionStore.listActiveSessions()) {+ if (snapshot.pendingEvent) enqueueEvent(snapshot.pendingEvent);+ }+}++function findAvailablePendingEvent(now = Date.now()) {+ return state.pendingEvents.find((entry) => !entry.leaseUntil || entry.leaseUntil <= now);+}++function leaseEvent(entry, leaseMs) {+ if (!entry.event?.id) {+ const idx = state.pendingEvents.indexOf(entry);+ if (idx !== -1) state.pendingEvents.splice(idx, 1);+ return entry.event;}+ entry.leaseUntil = Date.now() + leaseMs;+ return entry.event;+}++function acknowledgePendingEvent(id) {+ if (!id) return false;+ const idx = state.pendingEvents.findIndex((entry) => entry.event?.id === id);+ if (idx === -1) return false;+ state.pendingEvents.splice(idx, 1);+ scheduleLeaseFlush();+ return true;+}++function scheduleLeaseFlush() {+ if (state.leaseTimer) {+ clearTimeout(state.leaseTimer);+ state.leaseTimer = null;+ }+ if (state.pendingPolls.length === 0) return;+ const now = Date.now();+ const nextLeaseUntil = state.pendingEvents+ .map((entry) => entry.leaseUntil || 0)+ .filter((leaseUntil) => leaseUntil > now)+ .sort((a, b) => a - b)[0];+ if (!nextLeaseUntil) return;+ state.leaseTimer = setTimeout(() => {+ state.leaseTimer = null;+ flushPendingPolls();+ }, Math.max(0, nextLeaseUntil - now));+}++function flushPendingPolls() {+ while (state.pendingPolls.length > 0) {+ const entry = findAvailablePendingEvent();+ if (!entry) {+ scheduleLeaseFlush();+ return;+ }+ const poll = state.pendingPolls.shift();+ poll.resolve(leaseEvent(entry, poll.leaseMs));+ }+ scheduleLeaseFlush();}/** Push a message to all connected SSE clients. */@@ -103,13 +170,16 @@ function loadBrowserScripts() {// live-browser.js: DO NOT cache. Return the path so the /live.js handler// can re-read on every request. Editing the browser script during iteration// should land on the next tab reload, not require a server restart.+ const sessionPath = path.join(__dirname, 'live-browser-session.js');const livePath = path.join(__dirname, 'live-browser.js');- if (!fs.existsSync(livePath)) {- process.stderr.write('Error: live-browser.js not found at ' + livePath + '\n');- process.exit(1);+ for (const p of [sessionPath, livePath]) {+ if (!fs.existsSync(p)) {+ process.stderr.write('Error: live browser script not found at ' + p + '\n');+ process.exit(1);+ }}- return { detectScript, livePath };+ return { detectScript, sessionPath, livePath };}function hasProjectContext() {@@ -170,6 +240,13 @@ function validateEvent(msg) {return null;case 'discard':return isValidId(msg.id) ? null : 'discard: missing or malformed id';+ case 'checkpoint':+ if (!isValidId(msg.id)) return 'checkpoint: missing or malformed id';+ if (!Number.isInteger(msg.revision) || msg.revision < 0) return 'checkpoint: revision must be a non-negative integer';+ if (msg.paramValues !== undefined && (typeof msg.paramValues !== 'object' || msg.paramValues === null || Array.isArray(msg.paramValues))) {+ return 'checkpoint: paramValues must be an object';+ }+ return null;case 'exit':return null;case 'prefetch':@@ -184,7 +261,7 @@ function validateEvent(msg) {// HTTP request handler// ----------------------------------------------------------------------------function createRequestHandler({ detectScript, livePath }) {+function createRequestHandler({ detectScript, sessionPath, livePath }) {return (req, res) => {const url = new URL(req.url, `http://localhost:${state.port}`);res.setHeader('Access-Control-Allow-Origin', '*');@@ -200,17 +277,20 @@ function createRequestHandler({ detectScript, livePath }) {// the next tab reload. No-store headers prevent browser caching across// sessions — during iteration, a cached old script silently breaks// every subsequent session.+ let sessionScript;let liveScript;try {+ sessionScript = fs.readFileSync(sessionPath, 'utf-8');liveScript = fs.readFileSync(livePath, 'utf-8');} catch (err) {res.writeHead(500, { 'Content-Type': 'text/plain' });- res.end('Error reading live-browser.js: ' + err.message);+ res.end('Error reading live browser scripts: ' + err.message);return;}const body =`window.__IMPECCABLE_TOKEN__ = '${state.token}';\n` +`window.__IMPECCABLE_PORT__ = ${state.port};\n` ++ sessionScript + '\n' +liveScript;res.writeHead(200, {'Content-Type': 'application/javascript',@@ -305,6 +385,26 @@ function createRequestHandler({ detectScript, livePath }) {}// --- Health ---+ if (p === '/status') {+ const token = url.searchParams.get('token');+ if (token !== state.token) { res.writeHead(401, { 'Content-Type': 'application/json' }); res.end(JSON.stringify({ error: 'Unauthorized' })); return; }+ const sessions = state.sessionStore ? state.sessionStore.listActiveSessions() : [];+ res.writeHead(200, { 'Content-Type': 'application/json' });+ res.end(JSON.stringify({+ status: 'ok',+ port: state.port,+ connectedClients: state.sseClients.size,+ pendingEvents: state.pendingEvents.map((entry) => ({+ id: entry.event?.id,+ type: entry.event?.type,+ leased: !!(entry.leaseUntil && entry.leaseUntil > Date.now()),+ leaseUntil: entry.leaseUntil || null,+ })),+ activeSessions: sessions,+ }));+ return;+ }+if (p === '/health') {res.writeHead(200, { 'Content-Type': 'application/json' });res.end(JSON.stringify({@@ -316,13 +416,13 @@ function createRequestHandler({ detectScript, livePath }) {}// --- Design system (unified v2 response) + raw ---- // /design-system.json returns both parsed DESIGN.md and DESIGN.json+ // /design-system.json returns both parsed DESIGN.md and .impeccable/design.json// sidecar when present. Panel merges them:// { present, parsed, sidecar, hasMd, hasSidecar,// mdNewerThanJson, parseError?, sidecarError? }// - parsed: output of parseDesignMd (frontmatter// + six canonical sections) when DESIGN.md exists.- // - sidecar: DESIGN.json contents when present.+ // - sidecar: .impeccable/design.json contents when present.// Expected shape: schemaVersion 2, carrying// extensions + components + narrative.// /design-system/raw returns DESIGN.md markdown verbatim@@ -331,7 +431,7 @@ function createRequestHandler({ detectScript, livePath }) {if (token !== state.token) { res.writeHead(401); res.end('Unauthorized'); return; }const mdPath = path.join(CONTEXT_DIR, 'DESIGN.md');- const jsonPath = path.join(CONTEXT_DIR, 'DESIGN.json');+ const jsonPath = resolveDesignSidecarPath(process.cwd(), CONTEXT_DIR) || getDesignSidecarPath(process.cwd());const mdStat = statOrNull(mdPath);const jsonStat = statOrNull(jsonPath);@@ -367,7 +467,7 @@ function createRequestHandler({ detectScript, livePath }) {try {response.sidecar = JSON.parse(fs.readFileSync(jsonPath, 'utf-8'));} catch (err) {- response.sidecarError = 'Failed to parse DESIGN.json: ' + err.message;+ response.sidecarError = 'Failed to parse .impeccable/design.json: ' + err.message;}}@@ -449,7 +549,16 @@ function createRequestHandler({ detectScript, livePath }) {res.end(JSON.stringify({ error }));return;}- enqueueEvent(msg);+ if (state.sessionStore && msg.id) {+ try {+ state.sessionStore.appendEvent(msg);+ } catch (err) {+ res.writeHead(500, { 'Content-Type': 'application/json' });+ res.end(JSON.stringify({ error: 'session_store_append_failed', message: err.message }));+ return;+ }+ }+ if (msg.type !== 'checkpoint') enqueueEvent(msg);res.writeHead(200, { 'Content-Type': 'application/json' });res.end(JSON.stringify({ ok: true }));});@@ -492,13 +601,16 @@ function handlePollGet(req, res, url) {return;}const timeout = parseInt(url.searchParams.get('timeout') || DEFAULT_POLL_TIMEOUT, 10);- if (state.pendingEvents.length > 0) {+ const leaseMs = parseInt(url.searchParams.get('leaseMs') || '30000', 10);+ const available = findAvailablePendingEvent();+ if (available) {res.writeHead(200, { 'Content-Type': 'application/json' });- res.end(JSON.stringify(state.pendingEvents.shift()));+ res.end(JSON.stringify(leaseEvent(available, leaseMs)));return;}+ const poll = { resolve, leaseMs };const timer = setTimeout(() => {- const idx = state.pendingPolls.indexOf(resolve);+ const idx = state.pendingPolls.indexOf(poll);if (idx !== -1) state.pendingPolls.splice(idx, 1);res.writeHead(200, { 'Content-Type': 'application/json' });res.end(JSON.stringify({ type: 'timeout' }));@@ -508,10 +620,11 @@ function handlePollGet(req, res, url) {res.writeHead(200, { 'Content-Type': 'application/json' });res.end(JSON.stringify(event));}- state.pendingPolls.push(resolve);+ state.pendingPolls.push(poll);+ scheduleLeaseFlush();req.on('close', () => {clearTimeout(timer);- const idx = state.pendingPolls.indexOf(resolve);+ const idx = state.pendingPolls.indexOf(poll);if (idx !== -1) state.pendingPolls.splice(idx, 1);});}@@ -531,6 +644,26 @@ function handlePollPost(req, res) {res.end(JSON.stringify({ error: 'Unauthorized' }));return;}+ acknowledgePendingEvent(msg.id);+ if (state.sessionStore && msg.id) {+ try {+ const eventType = msg.type === 'discard' || msg.type === 'discarded'+ ? 'discarded'+ : msg.type === 'complete'+ ? 'complete'+ : msg.type === 'error'+ ? 'agent_error'+ : 'agent_done';+ state.sessionStore.appendEvent({+ type: eventType,+ id: msg.id,+ file: msg.file,+ message: msg.message,+ carbonize: msg.data?.carbonize === true,+ });+ } catch { /* keep reply path best-effort; browser still needs SSE */ }+ }+ flushPendingPolls();// Forward the reply to the browser via SSEbroadcast({ type: msg.type || 'done', id: msg.id, message: msg.message, file: msg.file, data: msg.data });res.writeHead(200, { 'Content-Type': 'application/json' });@@ -545,13 +678,15 @@ function handlePollPost(req, res) {let httpServer = null;function shutdown() {- try { fs.unlinkSync(LIVE_PID_FILE); } catch {}+ removeLiveServerInfo(process.cwd());+ if (state.leaseTimer) clearTimeout(state.leaseTimer);+ state.leaseTimer = null;if (state.sessionDir) {try { fs.rmSync(state.sessionDir, { recursive: true, force: true }); } catch {}}for (const res of state.sseClients) { try { res.end(); } catch {} }state.sseClients.clear();- for (const resolve of state.pendingPolls) resolve({ type: 'exit' });+ for (const poll of state.pendingPolls) poll.resolve({ type: 'exit' });state.pendingPolls.length = 0;if (httpServer) httpServer.close();process.exit(0);@@ -587,6 +722,7 @@ Endpoints:/events SSE stream (server→browser) + POST (browser→server)/poll Long-poll for agent CLI/source Raw source file reader (no-HMR fallback)+ /status Durable recovery status (token-protected)/health Health check`);process.exit(0);}@@ -594,7 +730,7 @@ Endpoints:if (args.includes('stop')) {const keepInject = args.includes('--keep-inject');try {- const info = JSON.parse(fs.readFileSync(LIVE_PID_FILE, 'utf-8'));+ const { info } = readLiveServerInfo(process.cwd()) || {};const res = await fetch(`http://localhost:${info.port}/stop?token=${info.token}`);if (res.ok) console.log(`Stopped live server on port ${info.port}.`);} catch {@@ -645,7 +781,7 @@ if (args.includes('--background')) {const deadline = Date.now() + 10_000;while (Date.now() < deadline) {try {- const info = JSON.parse(fs.readFileSync(LIVE_PID_FILE, 'utf-8'));+ const { info } = readLiveServerInfo(process.cwd()) || {};if (info.pid !== process.pid) {// Output JSON so the agent can read port + token from stdout.console.log(JSON.stringify(info));@@ -659,30 +795,36 @@ if (args.includes('--background')) {}// Check for existing session-try {- const existing = JSON.parse(fs.readFileSync(LIVE_PID_FILE, 'utf-8'));- try { process.kill(existing.pid, 0);+const existingRecord = readLiveServerInfo(process.cwd());+if (existingRecord?.info) {+ const existing = existingRecord.info;+ try {+ process.kill(existing.pid, 0);console.error(`Live server already running on port ${existing.port} (pid ${existing.pid}).`);console.error('Stop it first with: node ' + path.basename(fileURLToPath(import.meta.url)) + ' stop');process.exit(1);- } catch { fs.unlinkSync(LIVE_PID_FILE); }-} catch {}+ } catch {+ try { fs.unlinkSync(existingRecord.path); } catch {}+ }+}state.token = randomUUID();+state.sessionStore = createLiveSessionStore({ cwd: process.cwd() });+restorePendingEventsFromStore();const portArg = args.find(a => a.startsWith('--port='));state.port = portArg ? parseInt(portArg.split('=')[1], 10) : await findOpenPort();// Annotation screenshots live in the project root so the agent's Read tool// doesn't trip a per-file permission prompt. Sessioned by token so concurrent// projects (or quick restarts) don't collide.-const annotRoot = path.join(process.cwd(), '.impeccable-live', 'annotations');+const annotRoot = getLiveAnnotationsDir(process.cwd());fs.mkdirSync(annotRoot, { recursive: true });state.sessionDir = fs.mkdtempSync(path.join(annotRoot, 'session-'));-const { detectScript, livePath } = loadBrowserScripts();-httpServer = http.createServer(createRequestHandler({ detectScript, livePath }));+const { detectScript, sessionPath, livePath } = loadBrowserScripts();+httpServer = http.createServer(createRequestHandler({ detectScript, sessionPath, livePath }));httpServer.listen(state.port, '127.0.0.1', () => {- fs.writeFileSync(LIVE_PID_FILE, JSON.stringify({ pid: process.pid, port: state.port, token: state.token }));+ writeLiveServerInfo(process.cwd(), { pid: process.pid, port: state.port, token: state.token });const url = `http://localhost:${state.port}`;console.log(`\nImpeccable live server running on ${url}`);console.log(`Token: ${state.token}\n`);diff --git a/.opencode/skills/impeccable/scripts/live-session-store.mjs b/.opencode/skills/impeccable/scripts/live-session-store.mjsnew file mode 100644index 000000000..d55ed2d3a--- /dev/null+++ b/.opencode/skills/impeccable/scripts/live-session-store.mjs@@ -0,0 +1,254 @@+import fs from 'node:fs';+import path from 'node:path';+import { getLegacyLiveSessionsDir, getLiveSessionsDir } from './impeccable-paths.mjs';++const COMPLETED_PHASES = new Set(['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;+ }++ function getReadableJournalPath(id) {+ const primary = getJournalPath(rootDir, id);+ if (fs.existsSync(primary)) return primary;+ const legacy = getJournalPath(legacyRootDir, id);+ if (fs.existsSync(legacy)) return legacy;+ return primary;+ }++ return {+ rootDir,+ legacyRootDir,+ appendEvent(event) {+ const normalized = normalizeEvent(event, sessionId);+ const journalPath = getJournalPath(rootDir, normalized.id);+ const snapshotPath = getSnapshotPath(rootDir, normalized.id);+ const legacyJournalPath = getJournalPath(legacyRootDir, normalized.id);+ if (!fs.existsSync(journalPath) && fs.existsSync(legacyJournalPath)) {+ fs.copyFileSync(legacyJournalPath, journalPath);+ }+ const prior = loadCachedOrRebuild(normalized.id);+ const seq = prior.nextSeq;+ const entry = {+ seq,+ id: normalized.id,+ type: normalized.type,+ ts: new Date().toISOString(),+ event: normalized,+ };+ 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;+ },+ getSnapshot(id = sessionId, opts = {}) {+ if (!id) throw new Error('session id required');+ 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;+ },+ listActiveSessions() {+ const ids = new Set();+ for (const dir of [legacyRootDir, rootDir]) {+ if (!fs.existsSync(dir)) continue;+ for (const name of fs.readdirSync(dir)) {+ if (name.endsWith('.jsonl')) ids.add(name.slice(0, -'.jsonl'.length));+ }+ }+ return [...ids]+ .sort()+ .map((id) => this.getSnapshot(id))+ .filter(Boolean);+ },+ };+}++function normalizeEvent(event, fallbackId) {+ if (!event || typeof event !== 'object') throw new Error('event object required');+ const id = event.id || fallbackId;+ if (!id || typeof id !== 'string') throw new Error('event id required');+ if (!event.type || typeof event.type !== 'string') throw new Error('event type required');+ return { ...event, id };+}++function getJournalPath(rootDir, id) {+ return path.join(rootDir, safeSessionId(id) + '.jsonl');+}++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,+ phase: 'new',+ pageUrl: null,+ sourceFile: null,+ expectedVariants: 0,+ arrivedVariants: 0,+ visibleVariant: null,+ paramValues: {},+ pendingEventSeq: null,+ pendingEvent: null,+ deliveryLease: null,+ checkpointRevision: 0,+ activeOwner: null,+ sourceMarkers: {},+ fallbackMode: null,+ annotationArtifacts: [],+ diagnostics: [],+ updatedAt: null,+ };+}++function rebuildSnapshotFromJournal(journalPath, id) {+ let snapshot = baseSnapshot(id);+ const diagnostics = [];+ let nextSeq = 1;+ if (!fs.existsSync(journalPath)) return { snapshot, diagnostics, nextSeq };++ const lines = fs.readFileSync(journalPath, 'utf-8').split('\n');+ for (let i = 0; i < lines.length; i++) {+ const line = lines[i];+ if (!line.trim()) continue;+ try {+ const entry = JSON.parse(line);+ if (!entry || typeof entry !== 'object') throw new Error('entry is not object');+ if (Number.isInteger(entry.seq)) nextSeq = Math.max(nextSeq, entry.seq + 1);+ snapshot = applyEvent(snapshot, entry);+ } catch (err) {+ diagnostics.push({+ error: 'journal_parse_failed',+ line: i + 1,+ message: err.message,+ });+ }+ }+ snapshot.diagnostics = [...snapshot.diagnostics, ...diagnostics];+ return { snapshot, diagnostics, nextSeq };+}++function applyEvent(snapshot, entry, inheritedDiagnostics = []) {+ const event = entry.event || entry;+ const next = {+ ...snapshot,+ paramValues: { ...(snapshot.paramValues || {}) },+ sourceMarkers: { ...(snapshot.sourceMarkers || {}) },+ annotationArtifacts: [...(snapshot.annotationArtifacts || [])],+ diagnostics: [...(snapshot.diagnostics || [])],+ updatedAt: entry.ts || new Date().toISOString(),+ };++ if (inheritedDiagnostics.length && next.diagnostics.length === 0) {+ next.diagnostics = [...inheritedDiagnostics];+ }++ switch (event.type) {+ case 'generate':+ next.phase = 'generate_requested';+ next.pageUrl = event.pageUrl ?? next.pageUrl;+ next.expectedVariants = event.count ?? next.expectedVariants;+ next.pendingEventSeq = entry.seq ?? next.pendingEventSeq;+ next.pendingEvent = toPendingEvent(event);+ if (event.screenshotPath) upsertArtifact(next.annotationArtifacts, { type: 'screenshot', path: event.screenshotPath });+ break;+ case 'variants_ready':+ case 'agent_done':+ next.phase = event.carbonize === true ? 'carbonize_required' : 'variants_ready';+ next.sourceFile = event.file ?? next.sourceFile;+ next.arrivedVariants = event.arrivedVariants ?? (next.arrivedVariants ?? next.expectedVariants);+ next.pendingEventSeq = null;+ next.pendingEvent = null;+ if (event.carbonize === true) {+ next.diagnostics.push({+ error: 'carbonize_cleanup_required',+ file: event.file || null,+ message: 'Accepted variant still has carbonize markers that must be folded into source CSS.',+ });+ }+ break;+ case 'checkpoint':+ 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;+ if (event.paramValues) next.paramValues = { ...event.paramValues };+ } else {+ next.diagnostics.push({ error: 'stale_checkpoint_ignored', revision: event.revision });+ }+ break;+ case 'accept':+ case 'accept_intent':+ next.phase = 'accept_requested';+ next.visibleVariant = Number(event.variantId ?? next.visibleVariant);+ if (event.paramValues) next.paramValues = { ...event.paramValues };+ next.pendingEventSeq = entry.seq ?? next.pendingEventSeq;+ next.pendingEvent = toPendingEvent(event);+ break;+ case 'discard':+ next.phase = 'discard_requested';+ next.pendingEventSeq = entry.seq ?? next.pendingEventSeq;+ next.pendingEvent = toPendingEvent(event);+ break;+ case 'discarded':+ next.phase = 'discarded';+ next.pendingEventSeq = null;+ next.pendingEvent = null;+ break;+ case 'complete':+ next.phase = 'completed';+ next.pendingEventSeq = null;+ next.pendingEvent = null;+ break;+ case 'agent_error':+ next.phase = 'agent_error';+ next.pendingEventSeq = null;+ next.pendingEvent = null;+ next.diagnostics.push({ error: 'agent_error', message: event.message || 'unknown agent error' });+ break;+ default:+ next.diagnostics.push({ error: 'unknown_event_type', type: event.type });+ break;+ }+ return next;+}++function toPendingEvent(event) {+ const pending = { ...event };+ delete pending.token;+ return pending;+}++function upsertArtifact(artifacts, artifact) {+ if (!artifacts.some((existing) => existing.path === artifact.path && existing.type === artifact.type)) {+ artifacts.push(artifact);+ }+}++function writeSnapshot(snapshotPath, snapshot) {+ fs.writeFileSync(snapshotPath, JSON.stringify(snapshot, null, 2) + '\n');+}diff --git a/.opencode/skills/impeccable/scripts/live-status.mjs b/.opencode/skills/impeccable/scripts/live-status.mjsnew file mode 100644index 000000000..dce1fbca2--- /dev/null+++ b/.opencode/skills/impeccable/scripts/live-status.mjs@@ -0,0 +1,47 @@+#!/usr/bin/env node+/**+ * Print durable recovery status for Impeccable live sessions.+ */++import { createLiveSessionStore } from './live-session-store.mjs';+import { readLiveServerInfo } from './impeccable-paths.mjs';++function readServerInfo() {+ return readLiveServerInfo(process.cwd())?.info || null;+}++async function fetchServerStatus(info) {+ if (!info) return null;+ try {+ const res = await fetch(`http://localhost:${info.port}/status?token=${info.token}`);+ if (!res.ok) return null;+ return await res.json();+ } catch {+ return null;+ }+}++export async function statusCli() {+ const info = readServerInfo();+ const server = await fetchServerStatus(info);+ const store = createLiveSessionStore({ cwd: process.cwd() });+ const activeSessions = store.listActiveSessions();+ const payload = {+ liveServer: server ? {+ status: server.status,+ port: server.port,+ connectedClients: server.connectedClients,+ pendingEvents: server.pendingEvents,+ } : null,+ activeSessions: server?.activeSessions || activeSessions,+ recoveryHint: 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.',+ };+ console.log(JSON.stringify(payload, null, 2));+}++const _running = process.argv[1];+if (_running?.endsWith('live-status.mjs') || _running?.endsWith('live-status.mjs/')) {+ statusCli();+}diff --git a/.opencode/skills/impeccable/scripts/live-wrap.mjs b/.opencode/skills/impeccable/scripts/live-wrap.mjsindex a5769a50a..d46328b9f 100644--- a/.opencode/skills/impeccable/scripts/live-wrap.mjs+++ b/.opencode/skills/impeccable/scripts/live-wrap.mjs@@ -185,6 +185,7 @@ The agent should insert variant HTML at insertLine.`);const { startLine, endLine } = match;const commentSyntax = detectCommentSyntax(targetFile);+ const styleMode = detectStyleMode(targetFile);const isJsx = commentSyntax.open === '{/*';const indent = lines[startLine].match(/^(\s*)/)[1];@@ -269,6 +270,10 @@ The agent should insert variant HTML at insertLine.`);endLine: startLine + wrapperLines.length + (originalLines.length - 1), // 1-indexedinsertLine: insertLine + 1, // 1-indexed: where variants gocommentSyntax: commentSyntax,+ styleMode: styleMode.mode,+ styleTag: styleMode.styleTag,+ cssSelectorPrefixExamples: buildCssSelectorPrefixExamples(styleMode.mode, count),+ cssAuthoring: buildCssAuthoring(styleMode, count),originalLineCount: originalLines.length,}));}@@ -335,6 +340,62 @@ function detectCommentSyntax(filePath) {return { open: '<!--', close: '-->' };}+function detectStyleMode(filePath) {+ const ext = path.extname(filePath).toLowerCase();+ if (ext === '.astro') {+ return {+ mode: 'astro-global-prefixed',+ styleTag: '<style is:inline data-impeccable-css="SESSION_ID">',+ };+ }+ return {+ mode: 'scoped',+ styleTag: '<style data-impeccable-css="SESSION_ID">',+ };+}++function buildCssSelectorPrefixExamples(styleMode, count) {+ if (styleMode !== 'astro-global-prefixed') return [];+ return Array.from({ length: count }, (_, i) => `[data-impeccable-variant="${i + 1}"]`);+}++function buildCssAuthoring(styleMode, count) {+ const variantNumbers = Array.from({ length: count }, (_, i) => i + 1);+ if (styleMode.mode === 'astro-global-prefixed') {+ return {+ mode: styleMode.mode,+ styleTag: styleMode.styleTag,+ strategy: 'global-prefixed',+ rulePattern: '[data-impeccable-variant="N"] > .variant-class { ... }',+ selectorExamples: variantNumbers.map((n) => `[data-impeccable-variant="${n}"] > .variant-class`),+ requirements: [+ 'Use the styleTag exactly; the is:inline attribute is required for this file.',+ 'Prefix every preview selector with the matching [data-impeccable-variant="N"] selector.',+ 'Keep selectors anchored to the generated variant wrapper; do not rely on component CSS scoping for preview rules.',+ ],+ forbidden: [+ 'Do not use @scope for this styleMode.',+ ],+ };+ }+ return {+ mode: styleMode.mode,+ styleTag: styleMode.styleTag,+ strategy: 'scope-rule',+ rulePattern: '@scope ([data-impeccable-variant="N"]) { :scope > .variant-class { ... } }',+ selectorExamples: variantNumbers.map((n) => `@scope ([data-impeccable-variant="${n}"]) { :scope > .variant-class { ... } }`),+ requirements: [+ 'Use @scope blocks keyed to each [data-impeccable-variant="N"] wrapper.',+ 'Inside each @scope block, make :scope rules step into the replacement element with a descendant combinator.',+ 'Use the styleTag exactly; do not add framework-specific style attributes unless this object says to.',+ ],+ forbidden: [+ 'Do not use global [data-impeccable-variant="N"] selector prefixes for this styleMode.',+ 'Do not add is:inline to the style tag for this styleMode.',+ ],+ };+}+/*** Search project files for the query string (class name, ID, etc.)* Returns the first matching file path, or null.diff --git a/.opencode/skills/impeccable/scripts/live.mjs b/.opencode/skills/impeccable/scripts/live.mjsindex befbdb8ed..cafb0eca9 100644--- a/.opencode/skills/impeccable/scripts/live.mjs+++ b/.opencode/skills/impeccable/scripts/live.mjs@@ -2,10 +2,10 @@* CLI entry point: prepare everything needed to enter the live variant poll loop.** Does (all in one command):- * 1. Check config.json (returns config_missing if first-ever run)+ * 1. Check .impeccable/live/config.json (returns config_missing if first-ever run)* 2. Start the live server in the background (or reuse a running one)* 3. Inject the browser script tag into the project's entry file- * 4. Read .impeccable.md for design context (if present)+ * 4. Read PRODUCT.md / DESIGN.md for project context* 5. Print a single JSON blob with everything the agent needs** After this, the agent's only remaining steps are:@@ -23,9 +23,9 @@ import path from 'node:path';import { fileURLToPath } from 'node:url';import { loadContext } from './load-context.mjs';import { resolveFiles } from './live-inject.mjs';+import { readLiveServerInfo } from './impeccable-paths.mjs';const __dirname = path.dirname(fileURLToPath(import.meta.url));-const PID_FILE = path.join(process.cwd(), '.impeccable-live.json');async function liveCli() {const args = process.argv.slice(2);@@ -34,10 +34,10 @@ async function liveCli() {console.log(`Usage: node live.mjsPrepare everything for live variant mode in a single command:- - Checks scripts/config.json (required, created once per project)+ - Checks .impeccable/live/config.json (required, created once per project)- Starts (or reuses) the live server in the background- Injects the browser script tag- - Reads .impeccable.md for design context+ - Reads PRODUCT.md / DESIGN.md for project contextOn success, prints a JSON blob with:{ ok, serverPort, serverToken, pageFile, hasContext, context }@@ -223,7 +223,7 @@ function safeParse(out) {function ensureServerRunning() {// Try to reuse an existing servertry {- const existing = JSON.parse(fs.readFileSync(PID_FILE, 'utf-8'));+ const existing = readLiveServerInfo(process.cwd())?.info;if (existing && existing.pid) {try {process.kill(existing.pid, 0); // throws if deaddiff --git a/.opencode/skills/impeccable/scripts/load-context.mjs b/.opencode/skills/impeccable/scripts/load-context.mjsindex dca23c1f8..dc340bf16 100644--- a/.opencode/skills/impeccable/scripts/load-context.mjs+++ b/.opencode/skills/impeccable/scripts/load-context.mjs@@ -39,7 +39,7 @@ const LEGACY_NAMES = ['.impeccable.md'];const FALLBACK_DIRS = ['.agents/context', 'docs'];/**- * Resolve the directory that holds PRODUCT.md / DESIGN.md / DESIGN.json for+ * Resolve the directory that holds PRODUCT.md / DESIGN.md for* this project. Exported so other scripts (e.g. live-server.mjs) can read the* design files from the same location the loader uses.*/diff --git a/.pi/skills/impeccable/reference/document.md b/.pi/skills/impeccable/reference/document.mdindex 7430f2bf3..e5488c074 100644--- a/.pi/skills/impeccable/reference/document.md+++ b/.pi/skills/impeccable/reference/document.md@@ -237,11 +237,11 @@ Concrete, forceful guardrails. Lead each with "Do" or "Don't". Be specific: incl- **Don't** [...]```-### Step 4b: Write DESIGN.json sidecar (extensions only)+### Step 4b: Write .impeccable/design.json sidecar (extensions only)-The frontmatter owns token primitives (colors, typography, rounded, spacing, components). The sidecar at `DESIGN.json` carries **what Stitch's schema can't hold**: tonal ramps per color, shadow/elevation tokens, motion tokens, breakpoints, full component HTML/CSS snippets (the panel renders these into a shadow DOM), and narrative (north star, rules, do's/don'ts). It extends the frontmatter, it doesn't duplicate it.+The frontmatter owns token primitives (colors, typography, rounded, spacing, components). The sidecar at `.impeccable/design.json` carries **what Stitch's schema can't hold**: tonal ramps per color, shadow/elevation tokens, motion tokens, breakpoints, full component HTML/CSS snippets (the panel renders these into a shadow DOM), and narrative (north star, rules, do's/don'ts). It extends the frontmatter, it doesn't duplicate it.-Regenerate the sidecar whenever you regenerate DESIGN.md. If the user only asks to refresh the sidecar (e.g., from the live panel's stale-hint), preserve DESIGN.md and write only DESIGN.json.+Regenerate the sidecar whenever you regenerate root `DESIGN.md`. If the user only asks to refresh the sidecar (e.g., from the live panel's stale-hint), preserve `DESIGN.md` and write only `.impeccable/design.json`.#### Schema@@ -310,7 +310,7 @@ Aim for a tight set of **5-10 components** that best represent the visual system- **Signature components (include if distinctive):** hero CTA, featured card, filter pill, any custom pattern the user mentioned as important in PRODUCT.md.- **Skip the rest.** Utility components, form building blocks, wrapper layouts: not worth documenting unless visually distinctive.-If the project has **no component library yet** (bare landing page, new project), synthesize canonical primitives from the tokens using best-practice defaults consistent with the DESIGN.md's rules. Every DESIGN.json has *something* to render, even on day zero.+If the project has **no component library yet** (bare landing page, new project), synthesize canonical primitives from the tokens using best-practice defaults consistent with the DESIGN.md's rules. Every `.impeccable/design.json` has *something* to render, even on day zero.#### Tonal ramps@@ -331,7 +331,7 @@ Do not reword. The panel shows these as secondary collapsible context; the same### Step 5: Confirm, refine, and refresh session cache1. Show the user the full DESIGN.md you wrote. Briefly highlight the non-obvious creative choices (descriptive color names, atmosphere language, named rules).-2. Mention that `DESIGN.json` was also written alongside; the live panel will now render this project's actual button/input/nav primitives instead of generic approximations.+2. Mention that `.impeccable/design.json` was also written alongside; the live panel will now render this project's actual button/input/nav primitives instead of generic approximations.3. Offer to refine any section: "Want me to revise a section, add component patterns I missed, or adjust the atmosphere language?"4. **Refresh the session cache.** Run `node .pi/skills/impeccable/scripts/load-context.mjs` one final time so the newly-written DESIGN.md lands in conversation. Subsequent commands in this session will use the fresh version automatically without re-reading.@@ -392,7 +392,7 @@ Per-section guidance in seed mode:- **Components**: omit entirely; no components exist yet.- **Do's and Don'ts**: carry PRODUCT.md's anti-references directly plus the anti-reference named in Q5.-Seed mode writes a minimal frontmatter with `name` and `description` only; no colors, typography, rounded, spacing, or components yet. Real tokens land on the next Scan-mode run. Skip the `DESIGN.json` sidecar in seed mode for the same reason: nothing to render.+Seed mode writes a minimal frontmatter with `name` and `description` only; no colors, typography, rounded, spacing, or components yet. Real tokens land on the next Scan-mode run. Skip the `.impeccable/design.json` sidecar in seed mode for the same reason: nothing to render.### Step 4: Confirm and refresh session cachediff --git a/.pi/skills/impeccable/reference/live.md b/.pi/skills/impeccable/reference/live.mdindex 70083ed90..59028a1dc 100644--- a/.pi/skills/impeccable/reference/live.md+++ b/.pi/skills/impeccable/reference/live.md@@ -12,8 +12,9 @@ Execute in order. No step skipped, no step reordered.2. Navigate to the URL that serves `pageFile` (infer from `package.json`, docs, terminal output, or an open tab). If you can't infer it confidently, tell the user once to open their dev/preview URL. Never use `serverPort` as that URL; it's the helper, not the app.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=`.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.-5. On `accept` / `discard`: the poll script already cleaned up; just poll again.-6. On `exit`: run the cleanup at the bottom.+5. 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. If interrupted, run `live-status.mjs` or `live-resume.mjs` before guessing. The durable journal replays unacknowledged work after helper restart.+7. 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.@@ -43,13 +44,31 @@ LOOP:Read JSON; dispatch on "type""generate" → Handle Generate; reply done; LOOP- "accept" → Handle Accept; LOOP+ "accept" → Handle Accept; complete carbonize cleanup if required; LOOP"discard" → Handle Discard; LOOP"prefetch" → Handle Prefetch; LOOP"timeout" → LOOP"exit" → break → Cleanup```+## Recovery commands++The live helper persists an append-only journal under `.impeccable/live/sessions/`. Browser checkpoints are advisory but durable; the journal is canonical. This is local durable recovery state, not project source.++Use these commands when the chat was interrupted, polling was missed, the helper restarted, or the browser reloaded:++```bash+node .pi/skills/impeccable/scripts/live-status.mjs+node .pi/skills/impeccable/scripts/live-resume.mjs --id SESSION_ID+node .pi/skills/impeccable/scripts/live-complete.mjs --id SESSION_ID+```++- `live-status.mjs` prints connected helper state, active durable sessions, and queued pending events. It works even when the helper is down by reading the journal directly.+- `live-resume.mjs` prints the active snapshot, pending event, checkpoint phase, visible variant, parameter values, and the next safe agent action.+- `live-complete.mjs` is the canonical manual final acknowledgement. Use it after carbonize/manual cleanup is verified and no further poll acknowledgement will happen automatically.++Server restart rule: start `live-server.mjs` again, then poll. Startup requeues unacknowledged pending events from the journal, so do not ask the user to click Go again unless `live-resume.mjs` says no active session exists.+## Handle `generate`Event: `{id, action, freeformPrompt?, count, pageUrl, element, screenshotPath?, comments?, strokes?}`.@@ -88,7 +107,14 @@ The helper searches ID first, then classes, then tag + class combo. If `event.paIf `--text` matches multiple candidates equally well, wrap exits with `{ error: "element_ambiguous", candidates: [...] }` and `fallback: "agent-driven"`: read the candidate line ranges, decide which one matches the picked element from page context, and write the wrapper manually per the fallback flow.-Output on success: `{ file, insertLine, commentSyntax }`.+Output on success: `{ file, insertLine, commentSyntax, styleMode, styleTag, cssSelectorPrefixExamples, cssAuthoring }`.++`styleMode` controls how preview CSS must be authored. Treat it as a detected capability mode, not a framework guess:++- `scoped`: use `@scope ([data-impeccable-variant="N"])` rules.+- `astro-global-prefixed`: use explicit `[data-impeccable-variant="N"]` selector prefixes and the exact `styleTag` returned by the tool.++Use `cssAuthoring` as the source of truth for the current file. It includes the exact `styleTag`, selector strategy, selector examples, requirements, and forbidden patterns. Do not apply a framework-specific exception unless the returned `styleMode` / `cssAuthoring.mode` says to.**Fallback errors.** Wrap only writes into files it judges to be source (tracked by git, not marked GENERATED, not listed in config's `generatedFiles`). If it can't land on a source file, it errors without writing; accepting a variant into a generated file is silent data loss. Three shapes:@@ -208,13 +234,14 @@ When the prompt and PRODUCT.md anti-references conflict (the prompt asks for X,Complete 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 scoped 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).+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).++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:```html<!-- Variants: insert below this line --><style data-impeccable-css="SESSION_ID">- @scope ([data-impeccable-variant="1"]) { ... }- @scope ([data-impeccable-variant="2"]) { ... }+ /* rules matching cssAuthoring.rulePattern */</style><div data-impeccable-variant="1"><!-- variant 1: full element replacement (single top-level element) -->@@ -229,11 +256,11 @@ Write CSS + all variants in ONE edit at the `insertLine` reported by `wrap`. Col**Each variant div contains exactly one top-level element: the full replacement for the original.** Use the same tag as the original (e.g. `<section>` if the user picked a `<section>`). Loose siblings (heading + paragraph + div as direct children of the variant div) break the outline tracking and the accept flow, which both assume one child.-The first variant has no `display: none` (visible by default). All others do. If variants use only inline styles and no scoped CSS, omit the `<style>` tag entirely. Use `@scope` for CSS isolation (Chrome 118+ / Firefox 128+ / Safari 17.4+).+The 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.-**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 rule starts `:scope > ...`.+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 > ...`.**JSX / TSX target files.** Wrap `<style>` content in a template literal so the CSS `{` / `}` aren't parsed as JSX expressions, and use `className=` / `style={{…}}` on every variant element. Keep `data-impeccable-*` attributes as-is; they're plain strings:@@ -369,10 +396,11 @@ Remove the wrapper you inserted in Step 2. Nothing else to do.## Handle `accept`-Event: `{id, variantId, _acceptResult}`. The poll script already ran `live-accept.mjs` to handle the file operation deterministically; the browser DOM is already updated.+Event: `{id, variantId, _acceptResult, _completionAck}`. The poll script already ran `live-accept.mjs` to handle the file operation deterministically, then acknowledged event delivery to the helper. The browser DOM is already updated.+- `_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 and a stderr banner both list the steps explicitly; neither is decorative.+- `_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: 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` without `mode`: manual cleanup: read file, find markers, edit.@@ -388,13 +416,13 @@ Do these five steps in the current thread, synchronously, before the next poll.4. **Unwrap the accepted content.** Delete the `<div data-impeccable-variant="N" style="display: contents">` that wraps it. Drop `data-impeccable-params` and any `data-p-*` attributes from it; 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.-Then poll again.+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.## Handle `discard`-Event: `{id, _acceptResult}`. The poll script already restored the original and removed all variant markers. Nothing to do. Poll again.+Event: `{id, _acceptResult, _completionAck}`. The poll script already restored the original, removed all variant markers, and acknowledged `discarded` durable completion. Nothing to do unless `_completionAck.ok !== true`; in that case run `live-complete.mjs --id EVENT_ID --discarded`, then poll again.## Handle `prefetch`@@ -424,7 +452,7 @@ When the poll returns `exit`, proceed to cleanup. If the poll is still running anode .pi/skills/impeccable/scripts/live-server.mjs stop```-Stops the HTTP server and runs `live-inject.mjs --remove` to strip `localhost:…/live.js` from the HTML entry. To stop the server but keep the inject tag (for a quick restart), use `stop --keep-inject`. `config.json` persists for future sessions.+Stops the HTTP server and runs `live-inject.mjs --remove` to strip `localhost:…/live.js` from the HTML entry. To stop the server but keep the inject tag (for a quick restart), use `stop --keep-inject`. `.impeccable/live/config.json` persists as project config for future sessions.Then:- Remove any leftover variant wrappers (search for `impeccable-variants-start` markers).@@ -432,7 +460,7 @@ Then:## First-time setup (config missing or invalid)-If `live.mjs` outputs `{ ok: false, error: "config_missing" | "config_invalid", path }`, write `config.json` at the reported path.+If `live.mjs` outputs `{ ok: false, error: "config_missing" | "config_invalid", path }`, write the live config at the reported path. By default this is `.impeccable/live/config.json`.Schema:@@ -512,7 +540,7 @@ node .pi/skills/impeccable/scripts/detect-csp.mjsOutput: `{ shape, signals }` where `shape` is one of `append-arrays`, `append-string`, `middleware`, `meta-tag`, or `null`. The shape is named by *patch mechanism*, so one template covers many frameworks.-- **`null`**: no CSP; skip to writing `config.json` with `cspChecked: true`.+- **`null`**: no CSP; skip to writing `.impeccable/live/config.json` with `cspChecked: true`.- **`append-arrays`**: CSP defined as structured directive arrays. Auto-patchable. See *append-arrays* below. Covers:- Monorepo helpers with `additionalScriptSrc` / `additionalConnectSrc` options (Next.js + shared config package)- SvelteKit `kit.csp.directives`@@ -589,6 +617,6 @@ Reference outputs:### Troubleshooting-If a user says "no" to the CSP patch at setup time and later complains that live doesn't work: their dev CSP blocks `http://localhost:8400`. Fix: delete `cspChecked` from `config.json` and re-run `live.mjs`: setup will ask again.+If a user says "no" to the CSP patch at setup time and later complains that live doesn't work: their dev CSP blocks `http://localhost:8400`. Fix: delete `cspChecked` from `.impeccable/live/config.json` and re-run `live.mjs`: setup will ask again.Then re-run `live.mjs`.diff --git a/.pi/skills/impeccable/reference/teach.md b/.pi/skills/impeccable/reference/teach.mdindex 9d14cfdd8..9da9cffd6 100644--- a/.pi/skills/impeccable/reference/teach.md+++ b/.pi/skills/impeccable/reference/teach.md@@ -2,8 +2,8 @@Gathers design context for a project and writes two complementary files at the project root:-- **PRODUCT.md** (strategic): register, target users, product purpose, brand personality, anti-references, strategic design principles. Answers "who/what/why".-- **DESIGN.md** (visual): visual theme, color palette, typography, components, layout. Follows the [Google Stitch DESIGN.md format](https://stitch.withgoogle.com/docs/design-md/format/). Answers "how it looks".+- **PRODUCT.md** (strategic): root project file for register, target users, product purpose, brand personality, anti-references, strategic design principles. Answers "who/what/why".+- **DESIGN.md** (visual): root project file for visual theme, color palette, typography, components, layout. Follows the [Google Stitch DESIGN.md format](https://stitch.withgoogle.com/docs/design-md/format/). Answers "how it looks".Every other impeccable command reads these files before doing any work.diff --git a/.pi/skills/impeccable/scripts/impeccable-paths.mjs b/.pi/skills/impeccable/scripts/impeccable-paths.mjsnew file mode 100644index 000000000..ba852bae9--- /dev/null+++ b/.pi/skills/impeccable/scripts/impeccable-paths.mjs@@ -0,0 +1,105 @@+import fs from 'node:fs';+import path from 'node:path';++export const IMPECCABLE_DIR = '.impeccable';+export const LIVE_DIR = 'live';++export function getImpeccableDir(cwd = process.cwd()) {+ return path.join(cwd, IMPECCABLE_DIR);+}++export function getDesignSidecarPath(cwd = process.cwd()) {+ return path.join(getImpeccableDir(cwd), 'design.json');+}++export function getDesignSidecarCandidates(cwd = process.cwd(), contextDir = cwd) {+ const candidates = [+ getDesignSidecarPath(cwd),+ path.join(cwd, 'DESIGN.json'),+ ];+ const contextLegacy = path.join(contextDir, 'DESIGN.json');+ if (!candidates.includes(contextLegacy)) candidates.push(contextLegacy);+ return candidates;+}++export function resolveDesignSidecarPath(cwd = process.cwd(), contextDir = cwd) {+ return firstExisting(getDesignSidecarCandidates(cwd, contextDir));+}++export function getLiveDir(cwd = process.cwd()) {+ return path.join(getImpeccableDir(cwd), LIVE_DIR);+}++export function getLiveConfigPath(cwd = process.cwd()) {+ return path.join(getLiveDir(cwd), 'config.json');+}++export function getLegacyLiveConfigPath(scriptsDir) {+ return path.join(scriptsDir, 'config.json');+}++export function resolveLiveConfigPath({ cwd = process.cwd(), scriptsDir, env = process.env } = {}) {+ if (env.IMPECCABLE_LIVE_CONFIG && env.IMPECCABLE_LIVE_CONFIG.trim()) {+ const configured = env.IMPECCABLE_LIVE_CONFIG.trim();+ return path.isAbsolute(configured) ? configured : path.resolve(cwd, configured);+ }+ const primary = getLiveConfigPath(cwd);+ if (fs.existsSync(primary)) return primary;+ if (scriptsDir) {+ const legacy = getLegacyLiveConfigPath(scriptsDir);+ if (fs.existsSync(legacy)) return legacy;+ }+ return primary;+}++export function getLiveServerPath(cwd = process.cwd()) {+ return path.join(getLiveDir(cwd), 'server.json');+}++export function getLegacyLiveServerPath(cwd = process.cwd()) {+ return path.join(cwd, '.impeccable-live.json');+}++export function readLiveServerInfo(cwd = process.cwd()) {+ for (const filePath of [getLiveServerPath(cwd), getLegacyLiveServerPath(cwd)]) {+ try {+ return { info: JSON.parse(fs.readFileSync(filePath, 'utf-8')), path: filePath };+ } catch {+ /* try next */+ }+ }+ return null;+}++export function writeLiveServerInfo(cwd = process.cwd(), info) {+ const filePath = getLiveServerPath(cwd);+ fs.mkdirSync(path.dirname(filePath), { recursive: true });+ fs.writeFileSync(filePath, JSON.stringify(info));+ return filePath;+}++export function removeLiveServerInfo(cwd = process.cwd()) {+ for (const filePath of [getLiveServerPath(cwd), getLegacyLiveServerPath(cwd)]) {+ try { fs.unlinkSync(filePath); } catch {}+ }+}++export function getLiveSessionsDir(cwd = process.cwd()) {+ return path.join(getLiveDir(cwd), 'sessions');+}++export function getLegacyLiveSessionsDir(cwd = process.cwd()) {+ return path.join(cwd, '.impeccable-live', 'sessions');+}++export function getLiveAnnotationsDir(cwd = process.cwd()) {+ return path.join(getLiveDir(cwd), 'annotations');+}++export function getLegacyLiveAnnotationsDir(cwd = process.cwd()) {+ return path.join(cwd, '.impeccable-live', 'annotations');+}++function firstExisting(paths) {+ return paths.find((filePath) => fs.existsSync(filePath)) || null;+}diff --git a/.pi/skills/impeccable/scripts/live-browser-session.js b/.pi/skills/impeccable/scripts/live-browser-session.jsnew file mode 100644index 000000000..0e362d6be--- /dev/null+++ b/.pi/skills/impeccable/scripts/live-browser-session.js@@ -0,0 +1,123 @@+/**+ * Browser-side durable session helpers for Impeccable live mode.+ *+ * Kept separate from live-browser.js so recovery state can be tested without+ * booting the full overlay UI. Served before live-browser.js and attached to+ * window.__IMPECCABLE_LIVE_SESSION__.+ */+(function (root) {+ 'use strict';++ function createLiveBrowserSessionState({ prefix, storage, idFactory }) {+ if (!prefix) throw new Error('prefix required');+ const store = storage || root.localStorage;+ const makeId = idFactory || function () { return Math.random().toString(16).slice(2, 10); };+ const sessionKey = prefix + '-session';+ const handledKey = sessionKey + '-handled';+ const scrollKey = sessionKey + '-scroll';+ let checkpointRevision = 0;+ const owner = makeId();++ function safeRead(key) {+ try { return store.getItem(key); } catch { return null; }+ }++ function safeWrite(key, value) {+ try { store.setItem(key, value); } catch { /* quota exceeded or private mode */ }+ }++ function safeRemove(key) {+ try { store.removeItem(key); } catch { /* unavailable storage */ }+ }++ function loadSession() {+ try {+ const raw = safeRead(sessionKey);+ if (!raw) return null;+ const parsed = JSON.parse(raw);+ if (Number.isInteger(parsed.checkpointRevision)) {+ checkpointRevision = Math.max(checkpointRevision, parsed.checkpointRevision);+ }+ return parsed;+ } catch { return null; }+ }++ function saveSession(session) {+ if (!session || !session.id) return;+ const payload = {+ ...session,+ checkpointRevision,+ };+ safeWrite(sessionKey, JSON.stringify(payload));+ }++ function clearSession() {+ safeRemove(sessionKey);+ }++ function nextCheckpointRevision() {+ checkpointRevision += 1;+ const existing = loadSession();+ if (existing?.id) saveSession(existing);+ return checkpointRevision;+ }++ function seedCheckpointRevision(value) {+ if (Number.isInteger(value)) checkpointRevision = Math.max(checkpointRevision, value);+ return checkpointRevision;+ }++ function currentCheckpointRevision() {+ return checkpointRevision;+ }++ function markHandled(id) {+ if (!id) return;+ safeWrite(handledKey, id);+ }++ function isHandled(id) {+ return !!id && safeRead(handledKey) === id;+ }++ function clearHandled() {+ safeRemove(handledKey);+ }++ function writeScrollY(y) {+ safeWrite(scrollKey, String(y));+ }++ function readScrollY() {+ const raw = safeRead(scrollKey);+ if (raw == null) return null;+ const n = parseFloat(raw);+ return isFinite(n) ? n : null;+ }++ function clearScrollY() {+ safeRemove(scrollKey);+ }++ return {+ owner,+ sessionKey,+ handledKey,+ scrollKey,+ saveSession,+ loadSession,+ clearSession,+ nextCheckpointRevision,+ seedCheckpointRevision,+ currentCheckpointRevision,+ markHandled,+ isHandled,+ clearHandled,+ writeScrollY,+ readScrollY,+ clearScrollY,+ };+ }++ root.__IMPECCABLE_LIVE_SESSION__ = { createLiveBrowserSessionState };+})(typeof window !== 'undefined' ? window : globalThis);diff --git a/.pi/skills/impeccable/scripts/live-browser.js b/.pi/skills/impeccable/scripts/live-browser.jsindex 3da76bb96..e67cd01ed 100644--- a/.pi/skills/impeccable/scripts/live-browser.js+++ b/.pi/skills/impeccable/scripts/live-browser.js@@ -50,6 +50,16 @@const Z = { highlight: 100001, bar: 100005, picker: 100007, toast: 100010 };const EASE = 'cubic-bezier(0.22, 1, 0.36, 1)'; // ease-out-quintconst PREFIX = 'impeccable-live';+ const sessionState = window.__IMPECCABLE_LIVE_SESSION__?.createLiveBrowserSessionState({+ prefix: PREFIX,+ storage: localStorage,+ idFactory: () => crypto.randomUUID().replace(/-/g, '').slice(0, 8),+ });+ if (!sessionState) {+ console.error('[impeccable] live-browser-session.js was not loaded. Live mode cannot start safely.');+ window.__IMPECCABLE_LIVE_INIT__ = false;+ return;+ }const HIGHLIGHT_TRANSITION ='top 140ms ' + EASE +', left 140ms ' + EASE +@@ -112,6 +122,8 @@let hasProjectContext = false;let selectedAction = 'impeccable';let selectedCount = 3;+ const browserOwner = sessionState.owner;+ let checkpointTimer = null;// Scroll lock — holds window.scrollY at a fixed value while the session is// active, so HMR DOM patches and variant swaps can't drift the page. See@@ -126,21 +138,9 @@// (Previously: saveSession wrote scrollY alongside state, so every call// during resume overwrote the pre-reload value with whatever the browser// had landed on, typically 0.)- const SCROLL_KEY_SUFFIX = '-scroll';- function writeScrollY(y) {- try { localStorage.setItem(LS_KEY + SCROLL_KEY_SUFFIX, String(y)); } catch {}- }- function readScrollY() {- try {- const raw = localStorage.getItem(LS_KEY + SCROLL_KEY_SUFFIX);- if (raw == null) return null;- const n = parseFloat(raw);- return isFinite(n) ? n : null;- } catch { return null; }- }- function clearScrollY() {- try { localStorage.removeItem(LS_KEY + SCROLL_KEY_SUFFIX); } catch {}- }+ function writeScrollY(y) { sessionState.writeScrollY(y); }+ function readScrollY() { return sessionState.readScrollY(); }+ function clearScrollY() { sessionState.clearScrollY(); }// Pre-empt the browser: apply manual scroll restoration and jump to the// saved scrollY at script-parse time. Retries on fonts.ready and load@@ -1585,6 +1585,7 @@paramsCurrentValues[p.id] = v;readout.textContent = formatRangeValue(input);applyParamValue(variantEl, p, v);+ queueCheckpoint('param_changed');});row.appendChild(input);} else if (p.kind === 'toggle') {@@ -1615,6 +1616,7 @@knob.style.left = next ? '18px' : '2px';readout.textContent = next ? 'On' : 'Off';applyParamValue(variantEl, p, next);+ queueCheckpoint('param_changed');});row.appendChild(track);} else if (p.kind === 'steps') {@@ -1651,6 +1653,7 @@btn.style.color = on ? 'oklch(98% 0 0)' : P.text;});applyParamValue(variantEl, p, o.value);+ queueCheckpoint('param_changed');});segRow.appendChild(b);segBtns.push({ btn: b, val: o.value });@@ -1872,19 +1875,26 @@return;}+ const previousVisibleVariant = currentSessionId === sessionId ? visibleVariant : 0;+// Replace the live element with the full wrapper from sourceconst wrapper = srcWrapper.cloneNode(true);liveEl.parentElement.replaceChild(wrapper, liveEl);- // Update state: count variants, show the first one+ // Update state: count variants, preserving the user's current variant+ // when a late HMR/source reinjection lands after they have cycled.const variants = wrapper.querySelectorAll('[data-impeccable-variant]:not([data-impeccable-variant="original"])');arrivedVariants = variants.length;expectedVariants = parseInt(wrapper.dataset.impeccableVariantCount || arrivedVariants);- visibleVariant = 1;- showVariantInDOM(sessionId, 1);+ const saved = loadSession();+ const savedVisibleVariant = saved && saved.id === sessionId ? saved.visible : 0;+ visibleVariant = previousVisibleVariant > 0 && previousVisibleVariant <= arrivedVariants+ ? previousVisibleVariant+ : (savedVisibleVariant > 0 && savedVisibleVariant <= arrivedVariants ? savedVisibleVariant : 1);+ showVariantInDOM(sessionId, visibleVariant);// Update selectedElement to the visible variant's content- selectedElement = pickVariantContent(wrapper, 1) || wrapper.parentElement;+ selectedElement = pickVariantContent(wrapper, visibleVariant) || wrapper.parentElement;state = 'CYCLING';hideShaderOverlay();@@ -1907,6 +1917,7 @@updateSelectedElement();updateBarContent('cycling');saveSession();+ queueCheckpoint('variant_changed');}function updateSelectedElement() {@@ -1917,6 +1928,18 @@if (visEl) selectedElement = visEl;}+ function readVisibleVariantFromDOM(sessionId) {+ const wrapper = document.querySelector('[data-impeccable-variants="' + sessionId + '"]');+ if (!wrapper) return 0;+ const variants = wrapper.querySelectorAll('[data-impeccable-variant]:not([data-impeccable-variant="original"])');+ for (const variant of variants) {+ if (variant.style.display === 'none') continue;+ const idx = parseInt(variant.dataset.impeccableVariant || '0', 10);+ if (idx > 0) return idx;+ }+ return 0;+ }+// Resolve the element that represents the variant's visible content.// Contract: each variant div should contain exactly one top-level element// (the full replacement). In practice a model may ship loose siblings or@@ -2107,8 +2130,10 @@updating = true;arrivedVariants = count;if (visibleVariant === 0 && arrivedVariants > 0) {- visibleVariant = 1;- showVariantInDOM(sessionId, 1);+ const saved = loadSession();+ const savedVisibleVariant = saved && saved.id === sessionId ? saved.visible : 0;+ visibleVariant = savedVisibleVariant > 0 && savedVisibleVariant <= arrivedVariants ? savedVisibleVariant : 1;+ showVariantInDOM(sessionId, visibleVariant);// showVariantInDOM hid the original (display:none); if we were still// anchored to the original's content, its boundingRect is now zero// and the bar snaps to (0,0). Re-point at the visible variant instead.@@ -2128,6 +2153,7 @@updateBarContent('generating');}saveSession();+ queueCheckpoint(state === 'CYCLING' ? 'variants_ready' : 'variants_progress');updating = false;});@@ -2236,6 +2262,7 @@/** Server died or became unreachable. Reset UI to a clean state. */function handleServerLost() {+ const recoveryState = currentSessionId ? state : 'IDLE';if (state === 'GENERATING' || state === 'CYCLING' || state === 'SAVING') {showToast('Live server disconnected. Session ended.', 5000);}@@ -2246,21 +2273,61 @@stopScrollTracking();if (variantObserver) { variantObserver.disconnect(); variantObserver = null; }stopScrollLock();- clearScrollY();- clearSession();+ // Preserve local session state on server loss. The durable journal is the+ // source of truth, but localStorage plus the variant wrapper lets the UI+ // resume after a helper restart or page reload instead of treating a+ // transient disconnect as an explicit discard.selectedElement = null;- currentSessionId = null;selectedAction = 'impeccable';- state = 'IDLE';+ state = recoveryState;+ if (currentSessionId) saveSession();}- function sendEvent(msg) {+ function sendEvent(msg, opts) {msg.token = TOKEN;- fetch('http://localhost:' + PORT + '/events', {+ function handleFailure(err) {+ console.error('[impeccable] Failed to send event:', err);+ if (opts && opts.throwOnError) throw err;+ return null;+ }+ return fetch('http://localhost:' + PORT + '/events', {method: 'POST',headers: { 'Content-Type': 'application/json' },body: JSON.stringify(msg),- }).catch(err => console.error('[impeccable] Failed to send event:', err));+ }).then(res => {+ if (res.ok) return res;+ return handleFailure(new Error('HTTP ' + res.status + ' ' + res.statusText));+ }).catch(handleFailure);+ }++ function checkpointPayload(reason) {+ return {+ type: 'checkpoint',+ id: currentSessionId,+ revision: sessionState.nextCheckpointRevision(),+ owner: browserOwner,+ phase: String(state || '').toLowerCase(),+ reason,+ pageUrl: location.pathname,+ expectedVariants,+ arrivedVariants,+ visibleVariant,+ paramValues: { ...paramsCurrentValues },+ };+ }++ function sendCheckpoint(reason) {+ if (!currentSessionId) return Promise.resolve(null);+ return sendEvent(checkpointPayload(reason)).catch(() => null);+ }++ function queueCheckpoint(reason) {+ if (!currentSessionId) return;+ if (checkpointTimer) clearTimeout(checkpointTimer);+ checkpointTimer = setTimeout(() => {+ checkpointTimer = null;+ sendCheckpoint(reason);+ }, 120);}// ---------------------------------------------------------------------------@@ -2496,6 +2563,7 @@state = 'GENERATING';showBar('generating');saveSession();+ sendCheckpoint('generate_started');writeScrollY(window.scrollY);if (variantObserver) variantObserver.disconnect();variantObserver = startVariantObserver(currentSessionId);@@ -2920,13 +2988,12 @@ void main() {function handleAccept() {if (!currentSessionId || arrivedVariants === 0) return;+ const domVisibleVariant = readVisibleVariantFromDOM(currentSessionId);+ if (domVisibleVariant > 0) visibleVariant = domVisibleVariant;const acceptPayload = { type: 'accept', id: currentSessionId, variantId: String(visibleVariant) };if (Object.keys(paramsCurrentValues).length > 0) {acceptPayload.paramValues = { ...paramsCurrentValues };}- sendEvent(acceptPayload);- markSessionHandled();-// The accepted variant is already the only visible child of the wrapper// (all other variants are display:none). HMR from the source rewrite will// replace the wrapper imminently. Don't eagerly replaceChild here — React@@ -2936,9 +3003,28 @@ void main() {const acceptedSessionId = currentSessionId;const acceptedVariant = visibleVariant;- state = 'CONFIRMED';- updateBarContent('confirmed');- setTimeout(function() {+ state = 'SAVING';+ updateBarContent('saving');++ sendEvent(acceptPayload, { throwOnError: true })+ .then(() => {+ markSessionHandled();+ confirmAcceptAfterReceipt();+ })+ .catch(() => {+ state = 'CYCLING';+ updateBarContent('cycling');+ showToast('Could not confirm accept with the live server. Session kept for recovery; try Accept again.', 5000);+ });++ function confirmAcceptAfterReceipt() {+ state = 'CONFIRMED';+ updateBarContent('confirmed');+ scheduleAcceptCleanup();+ }++ function scheduleAcceptCleanup() {+ setTimeout(function() {hideBar();hideHighlight();stopScrollTracking();@@ -2967,50 +3053,46 @@ void main() {accepted.style.display = 'contents';parent.replaceChild(accepted, wrapper);}- }, 2000);+ }, 2000);+ }}function handleDiscard() {if (!currentSessionId) return;- sendEvent({ type: 'discard', id: currentSessionId });- markSessionHandled();- // Instant DOM restore + fire-and-forget (script handles file cleanup)- cleanup();+ sendEvent({ type: 'discard', id: currentSessionId }, { throwOnError: true })+ .then(() => {+ markSessionHandled();+ cleanup();+ })+ .catch(() => showToast('Could not confirm discard with the live server. Session kept for recovery.', 5000));}// ---------------------------------------------------------------------------- // Session persistence via localStorage+ // Session persistence via live-browser-session.js// ---------------------------------------------------------------------------// Survives page reloads, browser close/reopen, HMR, and accidental refreshes.- const LS_KEY = PREFIX + '-session';-function saveSession() {if (!currentSessionId) return;// NOTE: scrollY is stored under a separate key (writeScrollY). Storing// it here would overwrite the Go-time value every time state changes.- try {- localStorage.setItem(LS_KEY, JSON.stringify({- id: currentSessionId,- state: state,- action: selectedAction,- count: selectedCount,- expected: expectedVariants,- arrived: arrivedVariants,- visible: visibleVariant,- }));- } catch { /* quota exceeded or private mode */ }+ sessionState.saveSession({+ id: currentSessionId,+ state,+ action: selectedAction,+ count: selectedCount,+ expected: expectedVariants,+ arrived: arrivedVariants,+ visible: visibleVariant,+ });}function loadSession() {- try {- const raw = localStorage.getItem(LS_KEY);- return raw ? JSON.parse(raw) : null;- } catch { return null; }+ return sessionState.loadSession();}function clearSession() {- try { localStorage.removeItem(LS_KEY); } catch {}+ sessionState.clearSession();}/** Mark session as handled (accepted/discarded). The agent will clean up@@ -3018,19 +3100,15 @@ void main() {* prevents resumeSession from picking it up again after reload. */function markSessionHandled() {if (!currentSessionId) return;- try {- localStorage.setItem(LS_KEY + '-handled', currentSessionId);- } catch {}+ sessionState.markHandled(currentSessionId);}function isSessionHandled(id) {- try {- return localStorage.getItem(LS_KEY + '-handled') === id;- } catch { return false; }+ return sessionState.isHandled(id);}function clearHandled() {- try { localStorage.removeItem(LS_KEY + '-handled'); } catch {}+ sessionState.clearHandled();}function cleanup() {@@ -3161,6 +3239,7 @@ void main() {// hid. Now that state is CYCLING, re-fire.if (state === 'CYCLING') refreshParamsPanel();saveSession();+ queueCheckpoint('browser_resumed');// Start observing for more variants AFTER initial setupif (variantObserver) variantObserver.disconnect();@@ -3617,7 +3696,7 @@ void main() {}// ---------------------------------------------------------------------------- // Design System Panel — visualizes the project's DESIGN.json sidecar+ // Design System Panel — visualizes the project's .impeccable/design.json sidecar// ---------------------------------------------------------------------------const DESIGN_PREFS_KEY = 'impeccable-live-design-panel';@@ -3629,7 +3708,7 @@ void main() {open: false,tab: 'visual', // 'visual' | 'raw'parsed: null, // parseDesignMd output (frontmatter + body sections)- sidecar: null, // DESIGN.json v2 payload (extensions + components + narrative)+ sidecar: null, // .impeccable/design.json v2 payload (extensions + components + narrative)hasMd: false,hasSidecar: false,present: null, // true/false once fetch resolves@@ -4130,7 +4209,7 @@ void main() {box.className = 'stale';box.innerHTML = `<span class="stale-dot"></span>- <span class="stale-text"><strong>DESIGN.md is newer than DESIGN.json.</strong> Run <code>/impeccable document</code> to refresh the sidecar.</span>+ <span class="stale-text"><strong>DESIGN.md is newer than .impeccable/design.json.</strong> Run <code>/impeccable document</code> to refresh the sidecar.</span>`;return box;}@@ -4138,7 +4217,7 @@ void main() {function renderParsedMdCta() {const box = document.createElement('div');box.className = 'parsed-md-cta';- box.innerHTML = `<strong>Basic view</strong>This panel reads the tokens in your <code>DESIGN.md</code> frontmatter. Running <code>/impeccable document</code> also generates a <code>DESIGN.json</code> sidecar with your project's actual component snippets (button, input, nav) and tonal ramps, rendered live below the tokens.`;+ box.innerHTML = `<strong>Basic view</strong>This panel reads the tokens in your <code>DESIGN.md</code> frontmatter. Running <code>/impeccable document</code> also generates a <code>.impeccable/design.json</code> sidecar with your project's actual component snippets (button, input, nav) and tonal ramps, rendered live below the tokens.`;return box;}@@ -4598,7 +4677,7 @@ void main() {function cssSafe(v) {// Strip anything outside valid CSS value chars to prevent injection via- // DESIGN.json values rendered into inline style strings.+ // .impeccable/design.json values rendered into inline style strings.return String(v).replace(/[<>"'`\n]/g, '');}diff --git a/.pi/skills/impeccable/scripts/live-complete.mjs b/.pi/skills/impeccable/scripts/live-complete.mjsnew file mode 100644index 000000000..78155af85--- /dev/null+++ b/.pi/skills/impeccable/scripts/live-complete.mjs@@ -0,0 +1,75 @@+#!/usr/bin/env node+/**+ * Canonical durable completion acknowledgement for Impeccable live sessions.+ */++import { createLiveSessionStore } from './live-session-store.mjs';+import { readLiveServerInfo } from './impeccable-paths.mjs';++function parseArgs(argv) {+ const out = { status: 'complete' };+ for (let i = 0; i < argv.length; i++) {+ const arg = argv[i];+ if (arg === '--id') out.id = argv[++i];+ else if (arg.startsWith('--id=')) out.id = arg.slice('--id='.length);+ else if (arg === '--discarded' || arg === '--discard') out.status = 'discarded';+ else if (arg === '--error') { out.status = 'agent_error'; out.message = argv[++i] || 'unknown error'; }+ else if (arg.startsWith('--error=')) { out.status = 'agent_error'; out.message = arg.slice('--error='.length); }+ else if (arg === '--help' || arg === '-h') out.help = true;+ }+ return out;+}++export async function completeCli() {+ const args = parseArgs(process.argv.slice(2));+ if (args.help || !args.id) {+ console.log(`Usage: node live-complete.mjs --id SESSION_ID [--discarded|--error MESSAGE]\n\nAppend the final durable session acknowledgement. Use after accept/discard cleanup is verified.`);+ process.exit(args.help ? 0 : 1);+ }++ const serverInfo = readServerInfo();+ const serverResult = serverInfo ? await completeThroughServer(serverInfo, args) : null;+ if (serverResult?.ok) {+ const store = createLiveSessionStore({ cwd: process.cwd(), sessionId: args.id });+ const snapshot = store.getSnapshot(args.id, { includeCompleted: true });+ console.log(JSON.stringify({ ok: true, id: args.id, phase: snapshot?.phase || args.status, snapshot }, null, 2));+ return;+ }++ const store = createLiveSessionStore({ cwd: process.cwd(), sessionId: args.id });+ const event = args.status === 'discarded'+ ? { type: 'discarded', id: args.id }+ : args.status === 'agent_error'+ ? { type: 'agent_error', id: args.id, message: args.message || 'unknown error' }+ : { type: 'complete', id: args.id };+ const snapshot = store.appendEvent(event);+ console.log(JSON.stringify({ ok: true, id: args.id, phase: snapshot.phase, snapshot }, null, 2));+}++function readServerInfo() {+ return readLiveServerInfo(process.cwd())?.info || null;+}++async function completeThroughServer(info, args) {+ const type = args.status === 'discarded'+ ? 'discarded'+ : args.status === 'agent_error'+ ? 'error'+ : 'complete';+ try {+ const res = await fetch(`http://localhost:${info.port}/poll`, {+ method: 'POST',+ headers: { 'Content-Type': 'application/json' },+ body: JSON.stringify({ token: info.token, id: args.id, type, message: args.message }),+ });+ if (!res.ok) return null;+ return await res.json();+ } catch {+ return null;+ }+}++const _running = process.argv[1];+if (_running?.endsWith('live-complete.mjs') || _running?.endsWith('live-complete.mjs/')) {+ completeCli();+}diff --git a/.pi/skills/impeccable/scripts/live-completion.mjs b/.pi/skills/impeccable/scripts/live-completion.mjsnew file mode 100644index 000000000..86b637fff--- /dev/null+++ b/.pi/skills/impeccable/scripts/live-completion.mjs@@ -0,0 +1,18 @@+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';+ return 'agent_done';+}++export function completionAckForAcceptResult(eventId, completionType, acceptResult) {+ const ack = { ok: true, type: completionType };+ if (acceptResult?.handled === true && acceptResult?.carbonize === true) {+ ack.final = false;+ ack.requiresComplete = true;+ ack.nextCommand = `live-complete.mjs --id ${eventId}`;+ ack.message = 'Carbonize cleanup must be verified, then the session must be completed explicitly before polling again.';+ }+ return ack;+}diff --git a/.pi/skills/impeccable/scripts/live-inject.mjs b/.pi/skills/impeccable/scripts/live-inject.mjsindex 1d2ae12f7..555c3a36a 100644--- a/.pi/skills/impeccable/scripts/live-inject.mjs+++ b/.pi/skills/impeccable/scripts/live-inject.mjs@@ -2,23 +2,24 @@* CLI helper: insert/remove the live variant mode script tag in the project's* main HTML entry point.*- * On first live run, the agent generates `config.json` in this script's- * directory with the project's insertion target (framework-specific). On+ * On first live run, the agent generates `.impeccable/live/config.json`+ * with the project's insertion target (framework-specific). On* every subsequent run, this script handles insert/remove deterministically* with zero LLM involvement.** Usage:* node live-inject.mjs --port PORT # Insert the live script tag* node live-inject.mjs --remove # Remove the live script tag- * node live-inject.mjs --check # Check whether config.json exists+ * node live-inject.mjs --check # Check whether live config exists*/import fs from 'node:fs';import path from 'node:path';import { fileURLToPath } from 'node:url';+import { resolveLiveConfigPath } from './impeccable-paths.mjs';const __dirname = path.dirname(fileURLToPath(import.meta.url));-const CONFIG_PATH = process.env.IMPECCABLE_LIVE_CONFIG || path.join(__dirname, 'config.json');+const CONFIG_PATH = resolveLiveConfigPath({ cwd: process.cwd(), scriptsDir: __dirname });const MARKER_OPEN_TEXT = 'impeccable-live-start';const MARKER_CLOSE_TEXT = 'impeccable-live-end';@@ -39,12 +40,12 @@ export async function injectCli() {console.log(`Usage: node live-inject.mjs [options]Insert or remove the live mode script tag in the project's HTML entry point.-Reads configuration from config.json (in this same directory).+Reads configuration from .impeccable/live/config.json.Modes:--port PORT Insert script tag pointing at http://localhost:PORT/live.js--remove Remove the script tag (if present)- --check Print whether config.json exists and its content+ --check Print whether .impeccable/live/config.json exists and its contentOutput (JSON):{ ok, file, inserted|removed, config? }`);diff --git a/.pi/skills/impeccable/scripts/live-poll.mjs b/.pi/skills/impeccable/scripts/live-poll.mjsindex eb8f1586a..10d452491 100644--- a/.pi/skills/impeccable/scripts/live-poll.mjs+++ b/.pi/skills/impeccable/scripts/live-poll.mjs@@ -9,10 +9,10 @@*/import { execFileSync } from 'node:child_process';-import fs from 'node:fs';import path from 'node:path';-import os from 'node:os';import { fileURLToPath } from 'node:url';+import { completionAckForAcceptResult, completionTypeForAcceptResult } from './live-completion.mjs';+import { readLiveServerInfo } from './impeccable-paths.mjs';// Node's built-in fetch (undici under the hood) enforces a 300s headers// timeout that can't be lowered per-request. We cap each request below@@ -20,15 +20,29 @@ import { fileURLToPath } from 'node:url';// depending on the standalone undici package.const PER_REQUEST_TIMEOUT_MS = 270_000;-const LIVE_PID_FILE = path.join(process.cwd(), '.impeccable-live.json');-function readServerInfo() {- try {- return JSON.parse(fs.readFileSync(LIVE_PID_FILE, 'utf-8'));- } catch {+ const record = readLiveServerInfo(process.cwd());+ if (!record) {console.error('No running live server found. Start one with: npx impeccable live');process.exit(1);}+ return record.info;+}++export function buildPollReplyPayload(token, { id, type, message, file, data }) {+ return { token, id, type, message, file, data };+}++async function postReply(base, token, reply) {+ const res = await fetch(`${base}/poll`, {+ method: 'POST',+ headers: { 'Content-Type': 'application/json' },+ body: JSON.stringify(buildPollReplyPayload(token, reply)),+ });+ if (!res.ok) {+ const body = await res.json().catch(() => ({}));+ throw new Error(body.error || res.statusText);+ }}export async function pollCli() {@@ -69,23 +83,7 @@ Options:}try {- const res = await fetch(`${base}/poll`, {- method: 'POST',- headers: { 'Content-Type': 'application/json' },- body: JSON.stringify({- token: info.token,- id,- type: status,- message,- file: filePath,- }),- });-- if (!res.ok) {- const body = await res.json().catch(() => ({}));- console.error(`Reply failed (${res.status}):`, body.error || res.statusText);- process.exit(1);- }+ await postReply(base, info.token, { id, type: status, message, file: filePath });// Success — silent exit (agent doesn't need output for replies)} catch (err) {@@ -156,7 +154,23 @@ Options:);event._acceptResult = JSON.parse(out.trim());} catch (err) {- event._acceptResult = { handled: false, error: err.message };+ event._acceptResult = { handled: false, mode: 'error', error: err.message };+ }++ const completionType = completionTypeForAcceptResult(event.type, event._acceptResult);+ try {+ await postReply(base, info.token, {+ id: event.id,+ type: completionType,+ message: event._acceptResult?.error,+ file: event._acceptResult?.file,+ data: event._acceptResult?.carbonize === true ? { carbonize: true } : undefined,+ });+ } catch (err) {+ event._completionAck = { ok: false, error: err.message };+ }+ if (!event._completionAck) {+ event._completionAck = completionAckForAcceptResult(event.id, completionType, event._acceptResult);}}@@ -164,7 +178,7 @@ Options:// JSON but skips nested fields. One line is enough — the full checklist// is in reference/live.md.if (event._acceptResult?.carbonize === true) {- process.stderr.write('\n⚠ Carbonize cleanup REQUIRED before next poll. See reference/live.md "Required after accept".\n\n');+ process.stderr.write('\n⚠ Carbonize cleanup REQUIRED before next poll. After cleanup, run live-complete.mjs --id ' + event.id + '. See reference/live.md "Required after accept".\n\n');}// Print the event as JSON — the agent reads this from stdoutdiff --git a/.pi/skills/impeccable/scripts/live-resume.mjs b/.pi/skills/impeccable/scripts/live-resume.mjsnew file mode 100644index 000000000..a3465c9b5--- /dev/null+++ b/.pi/skills/impeccable/scripts/live-resume.mjs@@ -0,0 +1,48 @@+#!/usr/bin/env node+/**+ * Recover the next agent action from the durable live-session journal.+ */++import { createLiveSessionStore } from './live-session-store.mjs';++function parseArgs(argv) {+ const out = { id: null };+ for (let i = 0; i < argv.length; i++) {+ const arg = argv[i];+ if (arg === '--id') out.id = argv[++i];+ else if (arg.startsWith('--id=')) out.id = arg.slice('--id='.length);+ else if (arg === '--help' || arg === '-h') out.help = true;+ }+ return out;+}++export async function resumeCli() {+ const args = parseArgs(process.argv.slice(2));+ if (args.help) {+ console.log(`Usage: node live-resume.mjs [--id SESSION_ID]\n\nPrint the active durable session checkpoint and the next safe agent action.`);+ return;+ }++ const store = createLiveSessionStore({ cwd: process.cwd(), sessionId: args.id || undefined });+ const snapshot = args.id ? store.getSnapshot(args.id) : store.listActiveSessions()[0] || null;+ if (!snapshot) {+ console.log(JSON.stringify({ active: false, nextAction: 'No active durable live session found.' }, null, 2));+ return;+ }++ const pending = snapshot.pendingEvent || null;+ const nextAction = pending+ ? `Run live-poll.mjs, handle ${pending.type} ${pending.id}, then acknowledge with live-poll.mjs --reply ${pending.id} done.`+ : snapshot.phase === 'carbonize_required'+ ? `Finish carbonize cleanup${snapshot.sourceFile ? ` in ${snapshot.sourceFile}` : ''}, then run live-complete.mjs --id ${snapshot.id}.`+ : snapshot.phase === 'accept_requested'+ ? `Run live-complete.mjs --id ${snapshot.id} after verifying the accepted variant is written.`+ : `Inspect ${snapshot.id}; no pending agent event is currently queued.`;++ console.log(JSON.stringify({ active: true, snapshot, pendingEvent: pending, nextAction }, null, 2));+}++const _running = process.argv[1];+if (_running?.endsWith('live-resume.mjs') || _running?.endsWith('live-resume.mjs/')) {+ resumeCli();+}diff --git a/.pi/skills/impeccable/scripts/live-server.mjs b/.pi/skills/impeccable/scripts/live-server.mjsindex 90614fbf7..53d8f21cb 100644--- a/.pi/skills/impeccable/scripts/live-server.mjs+++ b/.pi/skills/impeccable/scripts/live-server.mjs@@ -22,14 +22,20 @@ import net from 'node:net';import { fileURLToPath } from 'node:url';import { parseDesignMd } from './design-parser.mjs';import { resolveContextDir } from './load-context.mjs';+import { createLiveSessionStore } from './live-session-store.mjs';+import {+ getDesignSidecarPath,+ getLiveAnnotationsDir,+ readLiveServerInfo,+ removeLiveServerInfo,+ resolveDesignSidecarPath,+ writeLiveServerInfo,+} from './impeccable-paths.mjs';const __dirname = path.dirname(fileURLToPath(import.meta.url));-// PID file in the project root so both the server and agent can find it-// predictably (os.tmpdir() varies across platforms).-const LIVE_PID_FILE = path.join(process.cwd(), '.impeccable-live.json');-// PRODUCT.md / DESIGN.md / DESIGN.json live wherever load-context.mjs resolves.-// Keeps live-server in sync with the loader when users keep the docs in-// .agents/context/, docs/, or a path set via IMPECCABLE_CONTEXT_DIR.+// PRODUCT.md / DESIGN.md live wherever load-context.mjs resolves. The generated+// DESIGN sidecar is project-local at .impeccable/design.json, with legacy+// DESIGN.json fallback for existing projects.const CONTEXT_DIR = resolveContextDir(process.cwd());const DEFAULT_POLL_TIMEOUT = 600_000; // 10 min — agent re-polls on timeout anywayconst SSE_HEARTBEAT_INTERVAL = 30_000; // keepalive ping every 30s@@ -57,10 +63,12 @@ const state = {token: null,port: null,sseClients: new Set(), // SSE response objects (server→browser push)- pendingEvents: [], // browser events waiting for agent poll+ pendingEvents: [], // browser events waiting for agent ack ({ event, leaseUntil })pendingPolls: [], // agent poll callbacks waiting for browser eventsexitTimer: null,sessionDir: null, // per-session tmp dir for annotation screenshots+ sessionStore: null,+ leaseTimer: null,};// Cap per-annotation upload size. A full 1920×1080 PNG is typically <1 MB;@@ -68,11 +76,70 @@ const state = {const MAX_ANNOTATION_BYTES = 10 * 1024 * 1024;function enqueueEvent(event) {- if (state.pendingPolls.length > 0) {- state.pendingPolls.shift()(event);- } else {- state.pendingEvents.push(event);+ if (!event || (event.id && state.pendingEvents.some((entry) => entry.event?.id === event.id && entry.event?.type === event.type))) return;+ state.pendingEvents.push({ event, leaseUntil: 0 });+ flushPendingPolls();+}++function restorePendingEventsFromStore() {+ if (!state.sessionStore) return;+ for (const snapshot of state.sessionStore.listActiveSessions()) {+ if (snapshot.pendingEvent) enqueueEvent(snapshot.pendingEvent);+ }+}++function findAvailablePendingEvent(now = Date.now()) {+ return state.pendingEvents.find((entry) => !entry.leaseUntil || entry.leaseUntil <= now);+}++function leaseEvent(entry, leaseMs) {+ if (!entry.event?.id) {+ const idx = state.pendingEvents.indexOf(entry);+ if (idx !== -1) state.pendingEvents.splice(idx, 1);+ return entry.event;}+ entry.leaseUntil = Date.now() + leaseMs;+ return entry.event;+}++function acknowledgePendingEvent(id) {+ if (!id) return false;+ const idx = state.pendingEvents.findIndex((entry) => entry.event?.id === id);+ if (idx === -1) return false;+ state.pendingEvents.splice(idx, 1);+ scheduleLeaseFlush();+ return true;+}++function scheduleLeaseFlush() {+ if (state.leaseTimer) {+ clearTimeout(state.leaseTimer);+ state.leaseTimer = null;+ }+ if (state.pendingPolls.length === 0) return;+ const now = Date.now();+ const nextLeaseUntil = state.pendingEvents+ .map((entry) => entry.leaseUntil || 0)+ .filter((leaseUntil) => leaseUntil > now)+ .sort((a, b) => a - b)[0];+ if (!nextLeaseUntil) return;+ state.leaseTimer = setTimeout(() => {+ state.leaseTimer = null;+ flushPendingPolls();+ }, Math.max(0, nextLeaseUntil - now));+}++function flushPendingPolls() {+ while (state.pendingPolls.length > 0) {+ const entry = findAvailablePendingEvent();+ if (!entry) {+ scheduleLeaseFlush();+ return;+ }+ const poll = state.pendingPolls.shift();+ poll.resolve(leaseEvent(entry, poll.leaseMs));+ }+ scheduleLeaseFlush();}/** Push a message to all connected SSE clients. */@@ -103,13 +170,16 @@ function loadBrowserScripts() {// live-browser.js: DO NOT cache. Return the path so the /live.js handler// can re-read on every request. Editing the browser script during iteration// should land on the next tab reload, not require a server restart.+ const sessionPath = path.join(__dirname, 'live-browser-session.js');const livePath = path.join(__dirname, 'live-browser.js');- if (!fs.existsSync(livePath)) {- process.stderr.write('Error: live-browser.js not found at ' + livePath + '\n');- process.exit(1);+ for (const p of [sessionPath, livePath]) {+ if (!fs.existsSync(p)) {+ process.stderr.write('Error: live browser script not found at ' + p + '\n');+ process.exit(1);+ }}- return { detectScript, livePath };+ return { detectScript, sessionPath, livePath };}function hasProjectContext() {@@ -170,6 +240,13 @@ function validateEvent(msg) {return null;case 'discard':return isValidId(msg.id) ? null : 'discard: missing or malformed id';+ case 'checkpoint':+ if (!isValidId(msg.id)) return 'checkpoint: missing or malformed id';+ if (!Number.isInteger(msg.revision) || msg.revision < 0) return 'checkpoint: revision must be a non-negative integer';+ if (msg.paramValues !== undefined && (typeof msg.paramValues !== 'object' || msg.paramValues === null || Array.isArray(msg.paramValues))) {+ return 'checkpoint: paramValues must be an object';+ }+ return null;case 'exit':return null;case 'prefetch':@@ -184,7 +261,7 @@ function validateEvent(msg) {// HTTP request handler// ----------------------------------------------------------------------------function createRequestHandler({ detectScript, livePath }) {+function createRequestHandler({ detectScript, sessionPath, livePath }) {return (req, res) => {const url = new URL(req.url, `http://localhost:${state.port}`);res.setHeader('Access-Control-Allow-Origin', '*');@@ -200,17 +277,20 @@ function createRequestHandler({ detectScript, livePath }) {// the next tab reload. No-store headers prevent browser caching across// sessions — during iteration, a cached old script silently breaks// every subsequent session.+ let sessionScript;let liveScript;try {+ sessionScript = fs.readFileSync(sessionPath, 'utf-8');liveScript = fs.readFileSync(livePath, 'utf-8');} catch (err) {res.writeHead(500, { 'Content-Type': 'text/plain' });- res.end('Error reading live-browser.js: ' + err.message);+ res.end('Error reading live browser scripts: ' + err.message);return;}const body =`window.__IMPECCABLE_TOKEN__ = '${state.token}';\n` +`window.__IMPECCABLE_PORT__ = ${state.port};\n` ++ sessionScript + '\n' +liveScript;res.writeHead(200, {'Content-Type': 'application/javascript',@@ -305,6 +385,26 @@ function createRequestHandler({ detectScript, livePath }) {}// --- Health ---+ if (p === '/status') {+ const token = url.searchParams.get('token');+ if (token !== state.token) { res.writeHead(401, { 'Content-Type': 'application/json' }); res.end(JSON.stringify({ error: 'Unauthorized' })); return; }+ const sessions = state.sessionStore ? state.sessionStore.listActiveSessions() : [];+ res.writeHead(200, { 'Content-Type': 'application/json' });+ res.end(JSON.stringify({+ status: 'ok',+ port: state.port,+ connectedClients: state.sseClients.size,+ pendingEvents: state.pendingEvents.map((entry) => ({+ id: entry.event?.id,+ type: entry.event?.type,+ leased: !!(entry.leaseUntil && entry.leaseUntil > Date.now()),+ leaseUntil: entry.leaseUntil || null,+ })),+ activeSessions: sessions,+ }));+ return;+ }+if (p === '/health') {res.writeHead(200, { 'Content-Type': 'application/json' });res.end(JSON.stringify({@@ -316,13 +416,13 @@ function createRequestHandler({ detectScript, livePath }) {}// --- Design system (unified v2 response) + raw ---- // /design-system.json returns both parsed DESIGN.md and DESIGN.json+ // /design-system.json returns both parsed DESIGN.md and .impeccable/design.json// sidecar when present. Panel merges them:// { present, parsed, sidecar, hasMd, hasSidecar,// mdNewerThanJson, parseError?, sidecarError? }// - parsed: output of parseDesignMd (frontmatter// + six canonical sections) when DESIGN.md exists.- // - sidecar: DESIGN.json contents when present.+ // - sidecar: .impeccable/design.json contents when present.// Expected shape: schemaVersion 2, carrying// extensions + components + narrative.// /design-system/raw returns DESIGN.md markdown verbatim@@ -331,7 +431,7 @@ function createRequestHandler({ detectScript, livePath }) {if (token !== state.token) { res.writeHead(401); res.end('Unauthorized'); return; }const mdPath = path.join(CONTEXT_DIR, 'DESIGN.md');- const jsonPath = path.join(CONTEXT_DIR, 'DESIGN.json');+ const jsonPath = resolveDesignSidecarPath(process.cwd(), CONTEXT_DIR) || getDesignSidecarPath(process.cwd());const mdStat = statOrNull(mdPath);const jsonStat = statOrNull(jsonPath);@@ -367,7 +467,7 @@ function createRequestHandler({ detectScript, livePath }) {try {response.sidecar = JSON.parse(fs.readFileSync(jsonPath, 'utf-8'));} catch (err) {- response.sidecarError = 'Failed to parse DESIGN.json: ' + err.message;+ response.sidecarError = 'Failed to parse .impeccable/design.json: ' + err.message;}}@@ -449,7 +549,16 @@ function createRequestHandler({ detectScript, livePath }) {res.end(JSON.stringify({ error }));return;}- enqueueEvent(msg);+ if (state.sessionStore && msg.id) {+ try {+ state.sessionStore.appendEvent(msg);+ } catch (err) {+ res.writeHead(500, { 'Content-Type': 'application/json' });+ res.end(JSON.stringify({ error: 'session_store_append_failed', message: err.message }));+ return;+ }+ }+ if (msg.type !== 'checkpoint') enqueueEvent(msg);res.writeHead(200, { 'Content-Type': 'application/json' });res.end(JSON.stringify({ ok: true }));});@@ -492,13 +601,16 @@ function handlePollGet(req, res, url) {return;}const timeout = parseInt(url.searchParams.get('timeout') || DEFAULT_POLL_TIMEOUT, 10);- if (state.pendingEvents.length > 0) {+ const leaseMs = parseInt(url.searchParams.get('leaseMs') || '30000', 10);+ const available = findAvailablePendingEvent();+ if (available) {res.writeHead(200, { 'Content-Type': 'application/json' });- res.end(JSON.stringify(state.pendingEvents.shift()));+ res.end(JSON.stringify(leaseEvent(available, leaseMs)));return;}+ const poll = { resolve, leaseMs };const timer = setTimeout(() => {- const idx = state.pendingPolls.indexOf(resolve);+ const idx = state.pendingPolls.indexOf(poll);if (idx !== -1) state.pendingPolls.splice(idx, 1);res.writeHead(200, { 'Content-Type': 'application/json' });res.end(JSON.stringify({ type: 'timeout' }));@@ -508,10 +620,11 @@ function handlePollGet(req, res, url) {res.writeHead(200, { 'Content-Type': 'application/json' });res.end(JSON.stringify(event));}- state.pendingPolls.push(resolve);+ state.pendingPolls.push(poll);+ scheduleLeaseFlush();req.on('close', () => {clearTimeout(timer);- const idx = state.pendingPolls.indexOf(resolve);+ const idx = state.pendingPolls.indexOf(poll);if (idx !== -1) state.pendingPolls.splice(idx, 1);});}@@ -531,6 +644,26 @@ function handlePollPost(req, res) {res.end(JSON.stringify({ error: 'Unauthorized' }));return;}+ acknowledgePendingEvent(msg.id);+ if (state.sessionStore && msg.id) {+ try {+ const eventType = msg.type === 'discard' || msg.type === 'discarded'+ ? 'discarded'+ : msg.type === 'complete'+ ? 'complete'+ : msg.type === 'error'+ ? 'agent_error'+ : 'agent_done';+ state.sessionStore.appendEvent({+ type: eventType,+ id: msg.id,+ file: msg.file,+ message: msg.message,+ carbonize: msg.data?.carbonize === true,+ });+ } catch { /* keep reply path best-effort; browser still needs SSE */ }+ }+ flushPendingPolls();// Forward the reply to the browser via SSEbroadcast({ type: msg.type || 'done', id: msg.id, message: msg.message, file: msg.file, data: msg.data });res.writeHead(200, { 'Content-Type': 'application/json' });@@ -545,13 +678,15 @@ function handlePollPost(req, res) {let httpServer = null;function shutdown() {- try { fs.unlinkSync(LIVE_PID_FILE); } catch {}+ removeLiveServerInfo(process.cwd());+ if (state.leaseTimer) clearTimeout(state.leaseTimer);+ state.leaseTimer = null;if (state.sessionDir) {try { fs.rmSync(state.sessionDir, { recursive: true, force: true }); } catch {}}for (const res of state.sseClients) { try { res.end(); } catch {} }state.sseClients.clear();- for (const resolve of state.pendingPolls) resolve({ type: 'exit' });+ for (const poll of state.pendingPolls) poll.resolve({ type: 'exit' });state.pendingPolls.length = 0;if (httpServer) httpServer.close();process.exit(0);@@ -587,6 +722,7 @@ Endpoints:/events SSE stream (server→browser) + POST (browser→server)/poll Long-poll for agent CLI/source Raw source file reader (no-HMR fallback)+ /status Durable recovery status (token-protected)/health Health check`);process.exit(0);}@@ -594,7 +730,7 @@ Endpoints:if (args.includes('stop')) {const keepInject = args.includes('--keep-inject');try {- const info = JSON.parse(fs.readFileSync(LIVE_PID_FILE, 'utf-8'));+ const { info } = readLiveServerInfo(process.cwd()) || {};const res = await fetch(`http://localhost:${info.port}/stop?token=${info.token}`);if (res.ok) console.log(`Stopped live server on port ${info.port}.`);} catch {@@ -645,7 +781,7 @@ if (args.includes('--background')) {const deadline = Date.now() + 10_000;while (Date.now() < deadline) {try {- const info = JSON.parse(fs.readFileSync(LIVE_PID_FILE, 'utf-8'));+ const { info } = readLiveServerInfo(process.cwd()) || {};if (info.pid !== process.pid) {// Output JSON so the agent can read port + token from stdout.console.log(JSON.stringify(info));@@ -659,30 +795,36 @@ if (args.includes('--background')) {}// Check for existing session-try {- const existing = JSON.parse(fs.readFileSync(LIVE_PID_FILE, 'utf-8'));- try { process.kill(existing.pid, 0);+const existingRecord = readLiveServerInfo(process.cwd());+if (existingRecord?.info) {+ const existing = existingRecord.info;+ try {+ process.kill(existing.pid, 0);console.error(`Live server already running on port ${existing.port} (pid ${existing.pid}).`);console.error('Stop it first with: node ' + path.basename(fileURLToPath(import.meta.url)) + ' stop');process.exit(1);- } catch { fs.unlinkSync(LIVE_PID_FILE); }-} catch {}+ } catch {+ try { fs.unlinkSync(existingRecord.path); } catch {}+ }+}state.token = randomUUID();+state.sessionStore = createLiveSessionStore({ cwd: process.cwd() });+restorePendingEventsFromStore();const portArg = args.find(a => a.startsWith('--port='));state.port = portArg ? parseInt(portArg.split('=')[1], 10) : await findOpenPort();// Annotation screenshots live in the project root so the agent's Read tool// doesn't trip a per-file permission prompt. Sessioned by token so concurrent// projects (or quick restarts) don't collide.-const annotRoot = path.join(process.cwd(), '.impeccable-live', 'annotations');+const annotRoot = getLiveAnnotationsDir(process.cwd());fs.mkdirSync(annotRoot, { recursive: true });state.sessionDir = fs.mkdtempSync(path.join(annotRoot, 'session-'));-const { detectScript, livePath } = loadBrowserScripts();-httpServer = http.createServer(createRequestHandler({ detectScript, livePath }));+const { detectScript, sessionPath, livePath } = loadBrowserScripts();+httpServer = http.createServer(createRequestHandler({ detectScript, sessionPath, livePath }));httpServer.listen(state.port, '127.0.0.1', () => {- fs.writeFileSync(LIVE_PID_FILE, JSON.stringify({ pid: process.pid, port: state.port, token: state.token }));+ writeLiveServerInfo(process.cwd(), { pid: process.pid, port: state.port, token: state.token });const url = `http://localhost:${state.port}`;console.log(`\nImpeccable live server running on ${url}`);console.log(`Token: ${state.token}\n`);diff --git a/.pi/skills/impeccable/scripts/live-session-store.mjs b/.pi/skills/impeccable/scripts/live-session-store.mjsnew file mode 100644index 000000000..d55ed2d3a--- /dev/null+++ b/.pi/skills/impeccable/scripts/live-session-store.mjs@@ -0,0 +1,254 @@+import fs from 'node:fs';+import path from 'node:path';+import { getLegacyLiveSessionsDir, getLiveSessionsDir } from './impeccable-paths.mjs';++const COMPLETED_PHASES = new Set(['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;+ }++ function getReadableJournalPath(id) {+ const primary = getJournalPath(rootDir, id);+ if (fs.existsSync(primary)) return primary;+ const legacy = getJournalPath(legacyRootDir, id);+ if (fs.existsSync(legacy)) return legacy;+ return primary;+ }++ return {+ rootDir,+ legacyRootDir,+ appendEvent(event) {+ const normalized = normalizeEvent(event, sessionId);+ const journalPath = getJournalPath(rootDir, normalized.id);+ const snapshotPath = getSnapshotPath(rootDir, normalized.id);+ const legacyJournalPath = getJournalPath(legacyRootDir, normalized.id);+ if (!fs.existsSync(journalPath) && fs.existsSync(legacyJournalPath)) {+ fs.copyFileSync(legacyJournalPath, journalPath);+ }+ const prior = loadCachedOrRebuild(normalized.id);+ const seq = prior.nextSeq;+ const entry = {+ seq,+ id: normalized.id,+ type: normalized.type,+ ts: new Date().toISOString(),+ event: normalized,+ };+ 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;+ },+ getSnapshot(id = sessionId, opts = {}) {+ if (!id) throw new Error('session id required');+ 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;+ },+ listActiveSessions() {+ const ids = new Set();+ for (const dir of [legacyRootDir, rootDir]) {+ if (!fs.existsSync(dir)) continue;+ for (const name of fs.readdirSync(dir)) {+ if (name.endsWith('.jsonl')) ids.add(name.slice(0, -'.jsonl'.length));+ }+ }+ return [...ids]+ .sort()+ .map((id) => this.getSnapshot(id))+ .filter(Boolean);+ },+ };+}++function normalizeEvent(event, fallbackId) {+ if (!event || typeof event !== 'object') throw new Error('event object required');+ const id = event.id || fallbackId;+ if (!id || typeof id !== 'string') throw new Error('event id required');+ if (!event.type || typeof event.type !== 'string') throw new Error('event type required');+ return { ...event, id };+}++function getJournalPath(rootDir, id) {+ return path.join(rootDir, safeSessionId(id) + '.jsonl');+}++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,+ phase: 'new',+ pageUrl: null,+ sourceFile: null,+ expectedVariants: 0,+ arrivedVariants: 0,+ visibleVariant: null,+ paramValues: {},+ pendingEventSeq: null,+ pendingEvent: null,+ deliveryLease: null,+ checkpointRevision: 0,+ activeOwner: null,+ sourceMarkers: {},+ fallbackMode: null,+ annotationArtifacts: [],+ diagnostics: [],+ updatedAt: null,+ };+}++function rebuildSnapshotFromJournal(journalPath, id) {+ let snapshot = baseSnapshot(id);+ const diagnostics = [];+ let nextSeq = 1;+ if (!fs.existsSync(journalPath)) return { snapshot, diagnostics, nextSeq };++ const lines = fs.readFileSync(journalPath, 'utf-8').split('\n');+ for (let i = 0; i < lines.length; i++) {+ const line = lines[i];+ if (!line.trim()) continue;+ try {+ const entry = JSON.parse(line);+ if (!entry || typeof entry !== 'object') throw new Error('entry is not object');+ if (Number.isInteger(entry.seq)) nextSeq = Math.max(nextSeq, entry.seq + 1);+ snapshot = applyEvent(snapshot, entry);+ } catch (err) {+ diagnostics.push({+ error: 'journal_parse_failed',+ line: i + 1,+ message: err.message,+ });+ }+ }+ snapshot.diagnostics = [...snapshot.diagnostics, ...diagnostics];+ return { snapshot, diagnostics, nextSeq };+}++function applyEvent(snapshot, entry, inheritedDiagnostics = []) {+ const event = entry.event || entry;+ const next = {+ ...snapshot,+ paramValues: { ...(snapshot.paramValues || {}) },+ sourceMarkers: { ...(snapshot.sourceMarkers || {}) },+ annotationArtifacts: [...(snapshot.annotationArtifacts || [])],+ diagnostics: [...(snapshot.diagnostics || [])],+ updatedAt: entry.ts || new Date().toISOString(),+ };++ if (inheritedDiagnostics.length && next.diagnostics.length === 0) {+ next.diagnostics = [...inheritedDiagnostics];+ }++ switch (event.type) {+ case 'generate':+ next.phase = 'generate_requested';+ next.pageUrl = event.pageUrl ?? next.pageUrl;+ next.expectedVariants = event.count ?? next.expectedVariants;+ next.pendingEventSeq = entry.seq ?? next.pendingEventSeq;+ next.pendingEvent = toPendingEvent(event);+ if (event.screenshotPath) upsertArtifact(next.annotationArtifacts, { type: 'screenshot', path: event.screenshotPath });+ break;+ case 'variants_ready':+ case 'agent_done':+ next.phase = event.carbonize === true ? 'carbonize_required' : 'variants_ready';+ next.sourceFile = event.file ?? next.sourceFile;+ next.arrivedVariants = event.arrivedVariants ?? (next.arrivedVariants ?? next.expectedVariants);+ next.pendingEventSeq = null;+ next.pendingEvent = null;+ if (event.carbonize === true) {+ next.diagnostics.push({+ error: 'carbonize_cleanup_required',+ file: event.file || null,+ message: 'Accepted variant still has carbonize markers that must be folded into source CSS.',+ });+ }+ break;+ case 'checkpoint':+ 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;+ if (event.paramValues) next.paramValues = { ...event.paramValues };+ } else {+ next.diagnostics.push({ error: 'stale_checkpoint_ignored', revision: event.revision });+ }+ break;+ case 'accept':+ case 'accept_intent':+ next.phase = 'accept_requested';+ next.visibleVariant = Number(event.variantId ?? next.visibleVariant);+ if (event.paramValues) next.paramValues = { ...event.paramValues };+ next.pendingEventSeq = entry.seq ?? next.pendingEventSeq;+ next.pendingEvent = toPendingEvent(event);+ break;+ case 'discard':+ next.phase = 'discard_requested';+ next.pendingEventSeq = entry.seq ?? next.pendingEventSeq;+ next.pendingEvent = toPendingEvent(event);+ break;+ case 'discarded':+ next.phase = 'discarded';+ next.pendingEventSeq = null;+ next.pendingEvent = null;+ break;+ case 'complete':+ next.phase = 'completed';+ next.pendingEventSeq = null;+ next.pendingEvent = null;+ break;+ case 'agent_error':+ next.phase = 'agent_error';+ next.pendingEventSeq = null;+ next.pendingEvent = null;+ next.diagnostics.push({ error: 'agent_error', message: event.message || 'unknown agent error' });+ break;+ default:+ next.diagnostics.push({ error: 'unknown_event_type', type: event.type });+ break;+ }+ return next;+}++function toPendingEvent(event) {+ const pending = { ...event };+ delete pending.token;+ return pending;+}++function upsertArtifact(artifacts, artifact) {+ if (!artifacts.some((existing) => existing.path === artifact.path && existing.type === artifact.type)) {+ artifacts.push(artifact);+ }+}++function writeSnapshot(snapshotPath, snapshot) {+ fs.writeFileSync(snapshotPath, JSON.stringify(snapshot, null, 2) + '\n');+}diff --git a/.pi/skills/impeccable/scripts/live-status.mjs b/.pi/skills/impeccable/scripts/live-status.mjsnew file mode 100644index 000000000..dce1fbca2--- /dev/null+++ b/.pi/skills/impeccable/scripts/live-status.mjs@@ -0,0 +1,47 @@+#!/usr/bin/env node+/**+ * Print durable recovery status for Impeccable live sessions.+ */++import { createLiveSessionStore } from './live-session-store.mjs';+import { readLiveServerInfo } from './impeccable-paths.mjs';++function readServerInfo() {+ return readLiveServerInfo(process.cwd())?.info || null;+}++async function fetchServerStatus(info) {+ if (!info) return null;+ try {+ const res = await fetch(`http://localhost:${info.port}/status?token=${info.token}`);+ if (!res.ok) return null;+ return await res.json();+ } catch {+ return null;+ }+}++export async function statusCli() {+ const info = readServerInfo();+ const server = await fetchServerStatus(info);+ const store = createLiveSessionStore({ cwd: process.cwd() });+ const activeSessions = store.listActiveSessions();+ const payload = {+ liveServer: server ? {+ status: server.status,+ port: server.port,+ connectedClients: server.connectedClients,+ pendingEvents: server.pendingEvents,+ } : null,+ activeSessions: server?.activeSessions || activeSessions,+ recoveryHint: 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.',+ };+ console.log(JSON.stringify(payload, null, 2));+}++const _running = process.argv[1];+if (_running?.endsWith('live-status.mjs') || _running?.endsWith('live-status.mjs/')) {+ statusCli();+}diff --git a/.pi/skills/impeccable/scripts/live-wrap.mjs b/.pi/skills/impeccable/scripts/live-wrap.mjsindex a5769a50a..d46328b9f 100644--- a/.pi/skills/impeccable/scripts/live-wrap.mjs+++ b/.pi/skills/impeccable/scripts/live-wrap.mjs@@ -185,6 +185,7 @@ The agent should insert variant HTML at insertLine.`);const { startLine, endLine } = match;const commentSyntax = detectCommentSyntax(targetFile);+ const styleMode = detectStyleMode(targetFile);const isJsx = commentSyntax.open === '{/*';const indent = lines[startLine].match(/^(\s*)/)[1];@@ -269,6 +270,10 @@ The agent should insert variant HTML at insertLine.`);endLine: startLine + wrapperLines.length + (originalLines.length - 1), // 1-indexedinsertLine: insertLine + 1, // 1-indexed: where variants gocommentSyntax: commentSyntax,+ styleMode: styleMode.mode,+ styleTag: styleMode.styleTag,+ cssSelectorPrefixExamples: buildCssSelectorPrefixExamples(styleMode.mode, count),+ cssAuthoring: buildCssAuthoring(styleMode, count),originalLineCount: originalLines.length,}));}@@ -335,6 +340,62 @@ function detectCommentSyntax(filePath) {return { open: '<!--', close: '-->' };}+function detectStyleMode(filePath) {+ const ext = path.extname(filePath).toLowerCase();+ if (ext === '.astro') {+ return {+ mode: 'astro-global-prefixed',+ styleTag: '<style is:inline data-impeccable-css="SESSION_ID">',+ };+ }+ return {+ mode: 'scoped',+ styleTag: '<style data-impeccable-css="SESSION_ID">',+ };+}++function buildCssSelectorPrefixExamples(styleMode, count) {+ if (styleMode !== 'astro-global-prefixed') return [];+ return Array.from({ length: count }, (_, i) => `[data-impeccable-variant="${i + 1}"]`);+}++function buildCssAuthoring(styleMode, count) {+ const variantNumbers = Array.from({ length: count }, (_, i) => i + 1);+ if (styleMode.mode === 'astro-global-prefixed') {+ return {+ mode: styleMode.mode,+ styleTag: styleMode.styleTag,+ strategy: 'global-prefixed',+ rulePattern: '[data-impeccable-variant="N"] > .variant-class { ... }',+ selectorExamples: variantNumbers.map((n) => `[data-impeccable-variant="${n}"] > .variant-class`),+ requirements: [+ 'Use the styleTag exactly; the is:inline attribute is required for this file.',+ 'Prefix every preview selector with the matching [data-impeccable-variant="N"] selector.',+ 'Keep selectors anchored to the generated variant wrapper; do not rely on component CSS scoping for preview rules.',+ ],+ forbidden: [+ 'Do not use @scope for this styleMode.',+ ],+ };+ }+ return {+ mode: styleMode.mode,+ styleTag: styleMode.styleTag,+ strategy: 'scope-rule',+ rulePattern: '@scope ([data-impeccable-variant="N"]) { :scope > .variant-class { ... } }',+ selectorExamples: variantNumbers.map((n) => `@scope ([data-impeccable-variant="${n}"]) { :scope > .variant-class { ... } }`),+ requirements: [+ 'Use @scope blocks keyed to each [data-impeccable-variant="N"] wrapper.',+ 'Inside each @scope block, make :scope rules step into the replacement element with a descendant combinator.',+ 'Use the styleTag exactly; do not add framework-specific style attributes unless this object says to.',+ ],+ forbidden: [+ 'Do not use global [data-impeccable-variant="N"] selector prefixes for this styleMode.',+ 'Do not add is:inline to the style tag for this styleMode.',+ ],+ };+}+/*** Search project files for the query string (class name, ID, etc.)* Returns the first matching file path, or null.diff --git a/.pi/skills/impeccable/scripts/live.mjs b/.pi/skills/impeccable/scripts/live.mjsindex befbdb8ed..cafb0eca9 100644--- a/.pi/skills/impeccable/scripts/live.mjs+++ b/.pi/skills/impeccable/scripts/live.mjs@@ -2,10 +2,10 @@* CLI entry point: prepare everything needed to enter the live variant poll loop.** Does (all in one command):- * 1. Check config.json (returns config_missing if first-ever run)+ * 1. Check .impeccable/live/config.json (returns config_missing if first-ever run)* 2. Start the live server in the background (or reuse a running one)* 3. Inject the browser script tag into the project's entry file- * 4. Read .impeccable.md for design context (if present)+ * 4. Read PRODUCT.md / DESIGN.md for project context* 5. Print a single JSON blob with everything the agent needs** After this, the agent's only remaining steps are:@@ -23,9 +23,9 @@ import path from 'node:path';import { fileURLToPath } from 'node:url';import { loadContext } from './load-context.mjs';import { resolveFiles } from './live-inject.mjs';+import { readLiveServerInfo } from './impeccable-paths.mjs';const __dirname = path.dirname(fileURLToPath(import.meta.url));-const PID_FILE = path.join(process.cwd(), '.impeccable-live.json');async function liveCli() {const args = process.argv.slice(2);@@ -34,10 +34,10 @@ async function liveCli() {console.log(`Usage: node live.mjsPrepare everything for live variant mode in a single command:- - Checks scripts/config.json (required, created once per project)+ - Checks .impeccable/live/config.json (required, created once per project)- Starts (or reuses) the live server in the background- Injects the browser script tag- - Reads .impeccable.md for design context+ - Reads PRODUCT.md / DESIGN.md for project contextOn success, prints a JSON blob with:{ ok, serverPort, serverToken, pageFile, hasContext, context }@@ -223,7 +223,7 @@ function safeParse(out) {function ensureServerRunning() {// Try to reuse an existing servertry {- const existing = JSON.parse(fs.readFileSync(PID_FILE, 'utf-8'));+ const existing = readLiveServerInfo(process.cwd())?.info;if (existing && existing.pid) {try {process.kill(existing.pid, 0); // throws if deaddiff --git a/.pi/skills/impeccable/scripts/load-context.mjs b/.pi/skills/impeccable/scripts/load-context.mjsindex dca23c1f8..dc340bf16 100644--- a/.pi/skills/impeccable/scripts/load-context.mjs+++ b/.pi/skills/impeccable/scripts/load-context.mjs@@ -39,7 +39,7 @@ const LEGACY_NAMES = ['.impeccable.md'];const FALLBACK_DIRS = ['.agents/context', 'docs'];/**- * Resolve the directory that holds PRODUCT.md / DESIGN.md / DESIGN.json for+ * Resolve the directory that holds PRODUCT.md / DESIGN.md for* this project. Exported so other scripts (e.g. live-server.mjs) can read the* design files from the same location the loader uses.*/diff --git a/.qoder/skills/impeccable/reference/document.md b/.qoder/skills/impeccable/reference/document.mdindex 0e36d02de..2722dc872 100644--- a/.qoder/skills/impeccable/reference/document.md+++ b/.qoder/skills/impeccable/reference/document.md@@ -237,11 +237,11 @@ Concrete, forceful guardrails. Lead each with "Do" or "Don't". Be specific: incl- **Don't** [...]```-### Step 4b: Write DESIGN.json sidecar (extensions only)+### Step 4b: Write .impeccable/design.json sidecar (extensions only)-The frontmatter owns token primitives (colors, typography, rounded, spacing, components). The sidecar at `DESIGN.json` carries **what Stitch's schema can't hold**: tonal ramps per color, shadow/elevation tokens, motion tokens, breakpoints, full component HTML/CSS snippets (the panel renders these into a shadow DOM), and narrative (north star, rules, do's/don'ts). It extends the frontmatter, it doesn't duplicate it.+The frontmatter owns token primitives (colors, typography, rounded, spacing, components). The sidecar at `.impeccable/design.json` carries **what Stitch's schema can't hold**: tonal ramps per color, shadow/elevation tokens, motion tokens, breakpoints, full component HTML/CSS snippets (the panel renders these into a shadow DOM), and narrative (north star, rules, do's/don'ts). It extends the frontmatter, it doesn't duplicate it.-Regenerate the sidecar whenever you regenerate DESIGN.md. If the user only asks to refresh the sidecar (e.g., from the live panel's stale-hint), preserve DESIGN.md and write only DESIGN.json.+Regenerate the sidecar whenever you regenerate root `DESIGN.md`. If the user only asks to refresh the sidecar (e.g., from the live panel's stale-hint), preserve `DESIGN.md` and write only `.impeccable/design.json`.#### Schema@@ -310,7 +310,7 @@ Aim for a tight set of **5-10 components** that best represent the visual system- **Signature components (include if distinctive):** hero CTA, featured card, filter pill, any custom pattern the user mentioned as important in PRODUCT.md.- **Skip the rest.** Utility components, form building blocks, wrapper layouts: not worth documenting unless visually distinctive.-If the project has **no component library yet** (bare landing page, new project), synthesize canonical primitives from the tokens using best-practice defaults consistent with the DESIGN.md's rules. Every DESIGN.json has *something* to render, even on day zero.+If the project has **no component library yet** (bare landing page, new project), synthesize canonical primitives from the tokens using best-practice defaults consistent with the DESIGN.md's rules. Every `.impeccable/design.json` has *something* to render, even on day zero.#### Tonal ramps@@ -331,7 +331,7 @@ Do not reword. The panel shows these as secondary collapsible context; the same### Step 5: Confirm, refine, and refresh session cache1. Show the user the full DESIGN.md you wrote. Briefly highlight the non-obvious creative choices (descriptive color names, atmosphere language, named rules).-2. Mention that `DESIGN.json` was also written alongside; the live panel will now render this project's actual button/input/nav primitives instead of generic approximations.+2. Mention that `.impeccable/design.json` was also written alongside; the live panel will now render this project's actual button/input/nav primitives instead of generic approximations.3. Offer to refine any section: "Want me to revise a section, add component patterns I missed, or adjust the atmosphere language?"4. **Refresh the session cache.** Run `node .qoder/skills/impeccable/scripts/load-context.mjs` one final time so the newly-written DESIGN.md lands in conversation. Subsequent commands in this session will use the fresh version automatically without re-reading.@@ -392,7 +392,7 @@ Per-section guidance in seed mode:- **Components**: omit entirely; no components exist yet.- **Do's and Don'ts**: carry PRODUCT.md's anti-references directly plus the anti-reference named in Q5.-Seed mode writes a minimal frontmatter with `name` and `description` only; no colors, typography, rounded, spacing, or components yet. Real tokens land on the next Scan-mode run. Skip the `DESIGN.json` sidecar in seed mode for the same reason: nothing to render.+Seed mode writes a minimal frontmatter with `name` and `description` only; no colors, typography, rounded, spacing, or components yet. Real tokens land on the next Scan-mode run. Skip the `.impeccable/design.json` sidecar in seed mode for the same reason: nothing to render.### Step 4: Confirm and refresh session cachediff --git a/.qoder/skills/impeccable/reference/live.md b/.qoder/skills/impeccable/reference/live.mdindex 124ea374f..f5777c1f1 100644--- a/.qoder/skills/impeccable/reference/live.md+++ b/.qoder/skills/impeccable/reference/live.md@@ -12,8 +12,9 @@ Execute in order. No step skipped, no step reordered.2. Navigate to the URL that serves `pageFile` (infer from `package.json`, docs, terminal output, or an open tab). If you can't infer it confidently, tell the user once to open their dev/preview URL. Never use `serverPort` as that URL; it's the helper, not the app.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=`.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.-5. On `accept` / `discard`: the poll script already cleaned up; just poll again.-6. On `exit`: run the cleanup at the bottom.+5. 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. If interrupted, run `live-status.mjs` or `live-resume.mjs` before guessing. The durable journal replays unacknowledged work after helper restart.+7. 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.@@ -43,13 +44,31 @@ LOOP:Read JSON; dispatch on "type""generate" → Handle Generate; reply done; LOOP- "accept" → Handle Accept; LOOP+ "accept" → Handle Accept; complete carbonize cleanup if required; LOOP"discard" → Handle Discard; LOOP"prefetch" → Handle Prefetch; LOOP"timeout" → LOOP"exit" → break → Cleanup```+## Recovery commands++The live helper persists an append-only journal under `.impeccable/live/sessions/`. Browser checkpoints are advisory but durable; the journal is canonical. This is local durable recovery state, not project source.++Use these commands when the chat was interrupted, polling was missed, the helper restarted, or the browser reloaded:++```bash+node .qoder/skills/impeccable/scripts/live-status.mjs+node .qoder/skills/impeccable/scripts/live-resume.mjs --id SESSION_ID+node .qoder/skills/impeccable/scripts/live-complete.mjs --id SESSION_ID+```++- `live-status.mjs` prints connected helper state, active durable sessions, and queued pending events. It works even when the helper is down by reading the journal directly.+- `live-resume.mjs` prints the active snapshot, pending event, checkpoint phase, visible variant, parameter values, and the next safe agent action.+- `live-complete.mjs` is the canonical manual final acknowledgement. Use it after carbonize/manual cleanup is verified and no further poll acknowledgement will happen automatically.++Server restart rule: start `live-server.mjs` again, then poll. Startup requeues unacknowledged pending events from the journal, so do not ask the user to click Go again unless `live-resume.mjs` says no active session exists.+## Handle `generate`Event: `{id, action, freeformPrompt?, count, pageUrl, element, screenshotPath?, comments?, strokes?}`.@@ -88,7 +107,14 @@ The helper searches ID first, then classes, then tag + class combo. If `event.paIf `--text` matches multiple candidates equally well, wrap exits with `{ error: "element_ambiguous", candidates: [...] }` and `fallback: "agent-driven"`: read the candidate line ranges, decide which one matches the picked element from page context, and write the wrapper manually per the fallback flow.-Output on success: `{ file, insertLine, commentSyntax }`.+Output on success: `{ file, insertLine, commentSyntax, styleMode, styleTag, cssSelectorPrefixExamples, cssAuthoring }`.++`styleMode` controls how preview CSS must be authored. Treat it as a detected capability mode, not a framework guess:++- `scoped`: use `@scope ([data-impeccable-variant="N"])` rules.+- `astro-global-prefixed`: use explicit `[data-impeccable-variant="N"]` selector prefixes and the exact `styleTag` returned by the tool.++Use `cssAuthoring` as the source of truth for the current file. It includes the exact `styleTag`, selector strategy, selector examples, requirements, and forbidden patterns. Do not apply a framework-specific exception unless the returned `styleMode` / `cssAuthoring.mode` says to.**Fallback errors.** Wrap only writes into files it judges to be source (tracked by git, not marked GENERATED, not listed in config's `generatedFiles`). If it can't land on a source file, it errors without writing; accepting a variant into a generated file is silent data loss. Three shapes:@@ -208,13 +234,14 @@ When the prompt and PRODUCT.md anti-references conflict (the prompt asks for X,Complete 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 scoped 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).+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).++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:```html<!-- Variants: insert below this line --><style data-impeccable-css="SESSION_ID">- @scope ([data-impeccable-variant="1"]) { ... }- @scope ([data-impeccable-variant="2"]) { ... }+ /* rules matching cssAuthoring.rulePattern */</style><div data-impeccable-variant="1"><!-- variant 1: full element replacement (single top-level element) -->@@ -229,11 +256,11 @@ Write CSS + all variants in ONE edit at the `insertLine` reported by `wrap`. Col**Each variant div contains exactly one top-level element: the full replacement for the original.** Use the same tag as the original (e.g. `<section>` if the user picked a `<section>`). Loose siblings (heading + paragraph + div as direct children of the variant div) break the outline tracking and the accept flow, which both assume one child.-The first variant has no `display: none` (visible by default). All others do. If variants use only inline styles and no scoped CSS, omit the `<style>` tag entirely. Use `@scope` for CSS isolation (Chrome 118+ / Firefox 128+ / Safari 17.4+).+The 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.-**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 rule starts `:scope > ...`.+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 > ...`.**JSX / TSX target files.** Wrap `<style>` content in a template literal so the CSS `{` / `}` aren't parsed as JSX expressions, and use `className=` / `style={{…}}` on every variant element. Keep `data-impeccable-*` attributes as-is; they're plain strings:@@ -369,10 +396,11 @@ Remove the wrapper you inserted in Step 2. Nothing else to do.## Handle `accept`-Event: `{id, variantId, _acceptResult}`. The poll script already ran `live-accept.mjs` to handle the file operation deterministically; the browser DOM is already updated.+Event: `{id, variantId, _acceptResult, _completionAck}`. The poll script already ran `live-accept.mjs` to handle the file operation deterministically, then acknowledged event delivery to the helper. The browser DOM is already updated.+- `_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 and a stderr banner both list the steps explicitly; neither is decorative.+- `_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: 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` without `mode`: manual cleanup: read file, find markers, edit.@@ -388,13 +416,13 @@ Do these five steps in the current thread, synchronously, before the next poll.4. **Unwrap the accepted content.** Delete the `<div data-impeccable-variant="N" style="display: contents">` that wraps it. Drop `data-impeccable-params` and any `data-p-*` attributes from it; 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.-Then poll again.+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.## Handle `discard`-Event: `{id, _acceptResult}`. The poll script already restored the original and removed all variant markers. Nothing to do. Poll again.+Event: `{id, _acceptResult, _completionAck}`. The poll script already restored the original, removed all variant markers, and acknowledged `discarded` durable completion. Nothing to do unless `_completionAck.ok !== true`; in that case run `live-complete.mjs --id EVENT_ID --discarded`, then poll again.## Handle `prefetch`@@ -424,7 +452,7 @@ When the poll returns `exit`, proceed to cleanup. If the poll is still running anode .qoder/skills/impeccable/scripts/live-server.mjs stop```-Stops the HTTP server and runs `live-inject.mjs --remove` to strip `localhost:…/live.js` from the HTML entry. To stop the server but keep the inject tag (for a quick restart), use `stop --keep-inject`. `config.json` persists for future sessions.+Stops the HTTP server and runs `live-inject.mjs --remove` to strip `localhost:…/live.js` from the HTML entry. To stop the server but keep the inject tag (for a quick restart), use `stop --keep-inject`. `.impeccable/live/config.json` persists as project config for future sessions.Then:- Remove any leftover variant wrappers (search for `impeccable-variants-start` markers).@@ -432,7 +460,7 @@ Then:## First-time setup (config missing or invalid)-If `live.mjs` outputs `{ ok: false, error: "config_missing" | "config_invalid", path }`, write `config.json` at the reported path.+If `live.mjs` outputs `{ ok: false, error: "config_missing" | "config_invalid", path }`, write the live config at the reported path. By default this is `.impeccable/live/config.json`.Schema:@@ -512,7 +540,7 @@ node .qoder/skills/impeccable/scripts/detect-csp.mjsOutput: `{ shape, signals }` where `shape` is one of `append-arrays`, `append-string`, `middleware`, `meta-tag`, or `null`. The shape is named by *patch mechanism*, so one template covers many frameworks.-- **`null`**: no CSP; skip to writing `config.json` with `cspChecked: true`.+- **`null`**: no CSP; skip to writing `.impeccable/live/config.json` with `cspChecked: true`.- **`append-arrays`**: CSP defined as structured directive arrays. Auto-patchable. See *append-arrays* below. Covers:- Monorepo helpers with `additionalScriptSrc` / `additionalConnectSrc` options (Next.js + shared config package)- SvelteKit `kit.csp.directives`@@ -589,6 +617,6 @@ Reference outputs:### Troubleshooting-If a user says "no" to the CSP patch at setup time and later complains that live doesn't work: their dev CSP blocks `http://localhost:8400`. Fix: delete `cspChecked` from `config.json` and re-run `live.mjs`: setup will ask again.+If a user says "no" to the CSP patch at setup time and later complains that live doesn't work: their dev CSP blocks `http://localhost:8400`. Fix: delete `cspChecked` from `.impeccable/live/config.json` and re-run `live.mjs`: setup will ask again.Then re-run `live.mjs`.diff --git a/.qoder/skills/impeccable/reference/teach.md b/.qoder/skills/impeccable/reference/teach.mdindex e9f657e40..2fa563e97 100644--- a/.qoder/skills/impeccable/reference/teach.md+++ b/.qoder/skills/impeccable/reference/teach.md@@ -2,8 +2,8 @@Gathers design context for a project and writes two complementary files at the project root:-- **PRODUCT.md** (strategic): register, target users, product purpose, brand personality, anti-references, strategic design principles. Answers "who/what/why".-- **DESIGN.md** (visual): visual theme, color palette, typography, components, layout. Follows the [Google Stitch DESIGN.md format](https://stitch.withgoogle.com/docs/design-md/format/). Answers "how it looks".+- **PRODUCT.md** (strategic): root project file for register, target users, product purpose, brand personality, anti-references, strategic design principles. Answers "who/what/why".+- **DESIGN.md** (visual): root project file for visual theme, color palette, typography, components, layout. Follows the [Google Stitch DESIGN.md format](https://stitch.withgoogle.com/docs/design-md/format/). Answers "how it looks".Every other impeccable command reads these files before doing any work.diff --git a/.qoder/skills/impeccable/scripts/impeccable-paths.mjs b/.qoder/skills/impeccable/scripts/impeccable-paths.mjsnew file mode 100644index 000000000..ba852bae9--- /dev/null+++ b/.qoder/skills/impeccable/scripts/impeccable-paths.mjs@@ -0,0 +1,105 @@+import fs from 'node:fs';+import path from 'node:path';++export const IMPECCABLE_DIR = '.impeccable';+export const LIVE_DIR = 'live';++export function getImpeccableDir(cwd = process.cwd()) {+ return path.join(cwd, IMPECCABLE_DIR);+}++export function getDesignSidecarPath(cwd = process.cwd()) {+ return path.join(getImpeccableDir(cwd), 'design.json');+}++export function getDesignSidecarCandidates(cwd = process.cwd(), contextDir = cwd) {+ const candidates = [+ getDesignSidecarPath(cwd),+ path.join(cwd, 'DESIGN.json'),+ ];+ const contextLegacy = path.join(contextDir, 'DESIGN.json');+ if (!candidates.includes(contextLegacy)) candidates.push(contextLegacy);+ return candidates;+}++export function resolveDesignSidecarPath(cwd = process.cwd(), contextDir = cwd) {+ return firstExisting(getDesignSidecarCandidates(cwd, contextDir));+}++export function getLiveDir(cwd = process.cwd()) {+ return path.join(getImpeccableDir(cwd), LIVE_DIR);+}++export function getLiveConfigPath(cwd = process.cwd()) {+ return path.join(getLiveDir(cwd), 'config.json');+}++export function getLegacyLiveConfigPath(scriptsDir) {+ return path.join(scriptsDir, 'config.json');+}++export function resolveLiveConfigPath({ cwd = process.cwd(), scriptsDir, env = process.env } = {}) {+ if (env.IMPECCABLE_LIVE_CONFIG && env.IMPECCABLE_LIVE_CONFIG.trim()) {+ const configured = env.IMPECCABLE_LIVE_CONFIG.trim();+ return path.isAbsolute(configured) ? configured : path.resolve(cwd, configured);+ }+ const primary = getLiveConfigPath(cwd);+ if (fs.existsSync(primary)) return primary;+ if (scriptsDir) {+ const legacy = getLegacyLiveConfigPath(scriptsDir);+ if (fs.existsSync(legacy)) return legacy;+ }+ return primary;+}++export function getLiveServerPath(cwd = process.cwd()) {+ return path.join(getLiveDir(cwd), 'server.json');+}++export function getLegacyLiveServerPath(cwd = process.cwd()) {+ return path.join(cwd, '.impeccable-live.json');+}++export function readLiveServerInfo(cwd = process.cwd()) {+ for (const filePath of [getLiveServerPath(cwd), getLegacyLiveServerPath(cwd)]) {+ try {+ return { info: JSON.parse(fs.readFileSync(filePath, 'utf-8')), path: filePath };+ } catch {+ /* try next */+ }+ }+ return null;+}++export function writeLiveServerInfo(cwd = process.cwd(), info) {+ const filePath = getLiveServerPath(cwd);+ fs.mkdirSync(path.dirname(filePath), { recursive: true });+ fs.writeFileSync(filePath, JSON.stringify(info));+ return filePath;+}++export function removeLiveServerInfo(cwd = process.cwd()) {+ for (const filePath of [getLiveServerPath(cwd), getLegacyLiveServerPath(cwd)]) {+ try { fs.unlinkSync(filePath); } catch {}+ }+}++export function getLiveSessionsDir(cwd = process.cwd()) {+ return path.join(getLiveDir(cwd), 'sessions');+}++export function getLegacyLiveSessionsDir(cwd = process.cwd()) {+ return path.join(cwd, '.impeccable-live', 'sessions');+}++export function getLiveAnnotationsDir(cwd = process.cwd()) {+ return path.join(getLiveDir(cwd), 'annotations');+}++export function getLegacyLiveAnnotationsDir(cwd = process.cwd()) {+ return path.join(cwd, '.impeccable-live', 'annotations');+}++function firstExisting(paths) {+ return paths.find((filePath) => fs.existsSync(filePath)) || null;+}diff --git a/.qoder/skills/impeccable/scripts/live-browser-session.js b/.qoder/skills/impeccable/scripts/live-browser-session.jsnew file mode 100644index 000000000..0e362d6be--- /dev/null+++ b/.qoder/skills/impeccable/scripts/live-browser-session.js@@ -0,0 +1,123 @@+/**+ * Browser-side durable session helpers for Impeccable live mode.+ *+ * Kept separate from live-browser.js so recovery state can be tested without+ * booting the full overlay UI. Served before live-browser.js and attached to+ * window.__IMPECCABLE_LIVE_SESSION__.+ */+(function (root) {+ 'use strict';++ function createLiveBrowserSessionState({ prefix, storage, idFactory }) {+ if (!prefix) throw new Error('prefix required');+ const store = storage || root.localStorage;+ const makeId = idFactory || function () { return Math.random().toString(16).slice(2, 10); };+ const sessionKey = prefix + '-session';+ const handledKey = sessionKey + '-handled';+ const scrollKey = sessionKey + '-scroll';+ let checkpointRevision = 0;+ const owner = makeId();++ function safeRead(key) {+ try { return store.getItem(key); } catch { return null; }+ }++ function safeWrite(key, value) {+ try { store.setItem(key, value); } catch { /* quota exceeded or private mode */ }+ }++ function safeRemove(key) {+ try { store.removeItem(key); } catch { /* unavailable storage */ }+ }++ function loadSession() {+ try {+ const raw = safeRead(sessionKey);+ if (!raw) return null;+ const parsed = JSON.parse(raw);+ if (Number.isInteger(parsed.checkpointRevision)) {+ checkpointRevision = Math.max(checkpointRevision, parsed.checkpointRevision);+ }+ return parsed;+ } catch { return null; }+ }++ function saveSession(session) {+ if (!session || !session.id) return;+ const payload = {+ ...session,+ checkpointRevision,+ };+ safeWrite(sessionKey, JSON.stringify(payload));+ }++ function clearSession() {+ safeRemove(sessionKey);+ }++ function nextCheckpointRevision() {+ checkpointRevision += 1;+ const existing = loadSession();+ if (existing?.id) saveSession(existing);+ return checkpointRevision;+ }++ function seedCheckpointRevision(value) {+ if (Number.isInteger(value)) checkpointRevision = Math.max(checkpointRevision, value);+ return checkpointRevision;+ }++ function currentCheckpointRevision() {+ return checkpointRevision;+ }++ function markHandled(id) {+ if (!id) return;+ safeWrite(handledKey, id);+ }++ function isHandled(id) {+ return !!id && safeRead(handledKey) === id;+ }++ function clearHandled() {+ safeRemove(handledKey);+ }++ function writeScrollY(y) {+ safeWrite(scrollKey, String(y));+ }++ function readScrollY() {+ const raw = safeRead(scrollKey);+ if (raw == null) return null;+ const n = parseFloat(raw);+ return isFinite(n) ? n : null;+ }++ function clearScrollY() {+ safeRemove(scrollKey);+ }++ return {+ owner,+ sessionKey,+ handledKey,+ scrollKey,+ saveSession,+ loadSession,+ clearSession,+ nextCheckpointRevision,+ seedCheckpointRevision,+ currentCheckpointRevision,+ markHandled,+ isHandled,+ clearHandled,+ writeScrollY,+ readScrollY,+ clearScrollY,+ };+ }++ root.__IMPECCABLE_LIVE_SESSION__ = { createLiveBrowserSessionState };+})(typeof window !== 'undefined' ? window : globalThis);diff --git a/.qoder/skills/impeccable/scripts/live-browser.js b/.qoder/skills/impeccable/scripts/live-browser.jsindex 3da76bb96..e67cd01ed 100644--- a/.qoder/skills/impeccable/scripts/live-browser.js+++ b/.qoder/skills/impeccable/scripts/live-browser.js@@ -50,6 +50,16 @@const Z = { highlight: 100001, bar: 100005, picker: 100007, toast: 100010 };const EASE = 'cubic-bezier(0.22, 1, 0.36, 1)'; // ease-out-quintconst PREFIX = 'impeccable-live';+ const sessionState = window.__IMPECCABLE_LIVE_SESSION__?.createLiveBrowserSessionState({+ prefix: PREFIX,+ storage: localStorage,+ idFactory: () => crypto.randomUUID().replace(/-/g, '').slice(0, 8),+ });+ if (!sessionState) {+ console.error('[impeccable] live-browser-session.js was not loaded. Live mode cannot start safely.');+ window.__IMPECCABLE_LIVE_INIT__ = false;+ return;+ }const HIGHLIGHT_TRANSITION ='top 140ms ' + EASE +', left 140ms ' + EASE +@@ -112,6 +122,8 @@let hasProjectContext = false;let selectedAction = 'impeccable';let selectedCount = 3;+ const browserOwner = sessionState.owner;+ let checkpointTimer = null;// Scroll lock — holds window.scrollY at a fixed value while the session is// active, so HMR DOM patches and variant swaps can't drift the page. See@@ -126,21 +138,9 @@// (Previously: saveSession wrote scrollY alongside state, so every call// during resume overwrote the pre-reload value with whatever the browser// had landed on, typically 0.)- const SCROLL_KEY_SUFFIX = '-scroll';- function writeScrollY(y) {- try { localStorage.setItem(LS_KEY + SCROLL_KEY_SUFFIX, String(y)); } catch {}- }- function readScrollY() {- try {- const raw = localStorage.getItem(LS_KEY + SCROLL_KEY_SUFFIX);- if (raw == null) return null;- const n = parseFloat(raw);- return isFinite(n) ? n : null;- } catch { return null; }- }- function clearScrollY() {- try { localStorage.removeItem(LS_KEY + SCROLL_KEY_SUFFIX); } catch {}- }+ function writeScrollY(y) { sessionState.writeScrollY(y); }+ function readScrollY() { return sessionState.readScrollY(); }+ function clearScrollY() { sessionState.clearScrollY(); }// Pre-empt the browser: apply manual scroll restoration and jump to the// saved scrollY at script-parse time. Retries on fonts.ready and load@@ -1585,6 +1585,7 @@paramsCurrentValues[p.id] = v;readout.textContent = formatRangeValue(input);applyParamValue(variantEl, p, v);+ queueCheckpoint('param_changed');});row.appendChild(input);} else if (p.kind === 'toggle') {@@ -1615,6 +1616,7 @@knob.style.left = next ? '18px' : '2px';readout.textContent = next ? 'On' : 'Off';applyParamValue(variantEl, p, next);+ queueCheckpoint('param_changed');});row.appendChild(track);} else if (p.kind === 'steps') {@@ -1651,6 +1653,7 @@btn.style.color = on ? 'oklch(98% 0 0)' : P.text;});applyParamValue(variantEl, p, o.value);+ queueCheckpoint('param_changed');});segRow.appendChild(b);segBtns.push({ btn: b, val: o.value });@@ -1872,19 +1875,26 @@return;}+ const previousVisibleVariant = currentSessionId === sessionId ? visibleVariant : 0;+// Replace the live element with the full wrapper from sourceconst wrapper = srcWrapper.cloneNode(true);liveEl.parentElement.replaceChild(wrapper, liveEl);- // Update state: count variants, show the first one+ // Update state: count variants, preserving the user's current variant+ // when a late HMR/source reinjection lands after they have cycled.const variants = wrapper.querySelectorAll('[data-impeccable-variant]:not([data-impeccable-variant="original"])');arrivedVariants = variants.length;expectedVariants = parseInt(wrapper.dataset.impeccableVariantCount || arrivedVariants);- visibleVariant = 1;- showVariantInDOM(sessionId, 1);+ const saved = loadSession();+ const savedVisibleVariant = saved && saved.id === sessionId ? saved.visible : 0;+ visibleVariant = previousVisibleVariant > 0 && previousVisibleVariant <= arrivedVariants+ ? previousVisibleVariant+ : (savedVisibleVariant > 0 && savedVisibleVariant <= arrivedVariants ? savedVisibleVariant : 1);+ showVariantInDOM(sessionId, visibleVariant);// Update selectedElement to the visible variant's content- selectedElement = pickVariantContent(wrapper, 1) || wrapper.parentElement;+ selectedElement = pickVariantContent(wrapper, visibleVariant) || wrapper.parentElement;state = 'CYCLING';hideShaderOverlay();@@ -1907,6 +1917,7 @@updateSelectedElement();updateBarContent('cycling');saveSession();+ queueCheckpoint('variant_changed');}function updateSelectedElement() {@@ -1917,6 +1928,18 @@if (visEl) selectedElement = visEl;}+ function readVisibleVariantFromDOM(sessionId) {+ const wrapper = document.querySelector('[data-impeccable-variants="' + sessionId + '"]');+ if (!wrapper) return 0;+ const variants = wrapper.querySelectorAll('[data-impeccable-variant]:not([data-impeccable-variant="original"])');+ for (const variant of variants) {+ if (variant.style.display === 'none') continue;+ const idx = parseInt(variant.dataset.impeccableVariant || '0', 10);+ if (idx > 0) return idx;+ }+ return 0;+ }+// Resolve the element that represents the variant's visible content.// Contract: each variant div should contain exactly one top-level element// (the full replacement). In practice a model may ship loose siblings or@@ -2107,8 +2130,10 @@updating = true;arrivedVariants = count;if (visibleVariant === 0 && arrivedVariants > 0) {- visibleVariant = 1;- showVariantInDOM(sessionId, 1);+ const saved = loadSession();+ const savedVisibleVariant = saved && saved.id === sessionId ? saved.visible : 0;+ visibleVariant = savedVisibleVariant > 0 && savedVisibleVariant <= arrivedVariants ? savedVisibleVariant : 1;+ showVariantInDOM(sessionId, visibleVariant);// showVariantInDOM hid the original (display:none); if we were still// anchored to the original's content, its boundingRect is now zero// and the bar snaps to (0,0). Re-point at the visible variant instead.@@ -2128,6 +2153,7 @@updateBarContent('generating');}saveSession();+ queueCheckpoint(state === 'CYCLING' ? 'variants_ready' : 'variants_progress');updating = false;});@@ -2236,6 +2262,7 @@/** Server died or became unreachable. Reset UI to a clean state. */function handleServerLost() {+ const recoveryState = currentSessionId ? state : 'IDLE';if (state === 'GENERATING' || state === 'CYCLING' || state === 'SAVING') {showToast('Live server disconnected. Session ended.', 5000);}@@ -2246,21 +2273,61 @@stopScrollTracking();if (variantObserver) { variantObserver.disconnect(); variantObserver = null; }stopScrollLock();- clearScrollY();- clearSession();+ // Preserve local session state on server loss. The durable journal is the+ // source of truth, but localStorage plus the variant wrapper lets the UI+ // resume after a helper restart or page reload instead of treating a+ // transient disconnect as an explicit discard.selectedElement = null;- currentSessionId = null;selectedAction = 'impeccable';- state = 'IDLE';+ state = recoveryState;+ if (currentSessionId) saveSession();}- function sendEvent(msg) {+ function sendEvent(msg, opts) {msg.token = TOKEN;- fetch('http://localhost:' + PORT + '/events', {+ function handleFailure(err) {+ console.error('[impeccable] Failed to send event:', err);+ if (opts && opts.throwOnError) throw err;+ return null;+ }+ return fetch('http://localhost:' + PORT + '/events', {method: 'POST',headers: { 'Content-Type': 'application/json' },body: JSON.stringify(msg),- }).catch(err => console.error('[impeccable] Failed to send event:', err));+ }).then(res => {+ if (res.ok) return res;+ return handleFailure(new Error('HTTP ' + res.status + ' ' + res.statusText));+ }).catch(handleFailure);+ }++ function checkpointPayload(reason) {+ return {+ type: 'checkpoint',+ id: currentSessionId,+ revision: sessionState.nextCheckpointRevision(),+ owner: browserOwner,+ phase: String(state || '').toLowerCase(),+ reason,+ pageUrl: location.pathname,+ expectedVariants,+ arrivedVariants,+ visibleVariant,+ paramValues: { ...paramsCurrentValues },+ };+ }++ function sendCheckpoint(reason) {+ if (!currentSessionId) return Promise.resolve(null);+ return sendEvent(checkpointPayload(reason)).catch(() => null);+ }++ function queueCheckpoint(reason) {+ if (!currentSessionId) return;+ if (checkpointTimer) clearTimeout(checkpointTimer);+ checkpointTimer = setTimeout(() => {+ checkpointTimer = null;+ sendCheckpoint(reason);+ }, 120);}// ---------------------------------------------------------------------------@@ -2496,6 +2563,7 @@state = 'GENERATING';showBar('generating');saveSession();+ sendCheckpoint('generate_started');writeScrollY(window.scrollY);if (variantObserver) variantObserver.disconnect();variantObserver = startVariantObserver(currentSessionId);@@ -2920,13 +2988,12 @@ void main() {function handleAccept() {if (!currentSessionId || arrivedVariants === 0) return;+ const domVisibleVariant = readVisibleVariantFromDOM(currentSessionId);+ if (domVisibleVariant > 0) visibleVariant = domVisibleVariant;const acceptPayload = { type: 'accept', id: currentSessionId, variantId: String(visibleVariant) };if (Object.keys(paramsCurrentValues).length > 0) {acceptPayload.paramValues = { ...paramsCurrentValues };}- sendEvent(acceptPayload);- markSessionHandled();-// The accepted variant is already the only visible child of the wrapper// (all other variants are display:none). HMR from the source rewrite will// replace the wrapper imminently. Don't eagerly replaceChild here — React@@ -2936,9 +3003,28 @@ void main() {const acceptedSessionId = currentSessionId;const acceptedVariant = visibleVariant;- state = 'CONFIRMED';- updateBarContent('confirmed');- setTimeout(function() {+ state = 'SAVING';+ updateBarContent('saving');++ sendEvent(acceptPayload, { throwOnError: true })+ .then(() => {+ markSessionHandled();+ confirmAcceptAfterReceipt();+ })+ .catch(() => {+ state = 'CYCLING';+ updateBarContent('cycling');+ showToast('Could not confirm accept with the live server. Session kept for recovery; try Accept again.', 5000);+ });++ function confirmAcceptAfterReceipt() {+ state = 'CONFIRMED';+ updateBarContent('confirmed');+ scheduleAcceptCleanup();+ }++ function scheduleAcceptCleanup() {+ setTimeout(function() {hideBar();hideHighlight();stopScrollTracking();@@ -2967,50 +3053,46 @@ void main() {accepted.style.display = 'contents';parent.replaceChild(accepted, wrapper);}- }, 2000);+ }, 2000);+ }}function handleDiscard() {if (!currentSessionId) return;- sendEvent({ type: 'discard', id: currentSessionId });- markSessionHandled();- // Instant DOM restore + fire-and-forget (script handles file cleanup)- cleanup();+ sendEvent({ type: 'discard', id: currentSessionId }, { throwOnError: true })+ .then(() => {+ markSessionHandled();+ cleanup();+ })+ .catch(() => showToast('Could not confirm discard with the live server. Session kept for recovery.', 5000));}// ---------------------------------------------------------------------------- // Session persistence via localStorage+ // Session persistence via live-browser-session.js// ---------------------------------------------------------------------------// Survives page reloads, browser close/reopen, HMR, and accidental refreshes.- const LS_KEY = PREFIX + '-session';-function saveSession() {if (!currentSessionId) return;// NOTE: scrollY is stored under a separate key (writeScrollY). Storing// it here would overwrite the Go-time value every time state changes.- try {- localStorage.setItem(LS_KEY, JSON.stringify({- id: currentSessionId,- state: state,- action: selectedAction,- count: selectedCount,- expected: expectedVariants,- arrived: arrivedVariants,- visible: visibleVariant,- }));- } catch { /* quota exceeded or private mode */ }+ sessionState.saveSession({+ id: currentSessionId,+ state,+ action: selectedAction,+ count: selectedCount,+ expected: expectedVariants,+ arrived: arrivedVariants,+ visible: visibleVariant,+ });}function loadSession() {- try {- const raw = localStorage.getItem(LS_KEY);- return raw ? JSON.parse(raw) : null;- } catch { return null; }+ return sessionState.loadSession();}function clearSession() {- try { localStorage.removeItem(LS_KEY); } catch {}+ sessionState.clearSession();}/** Mark session as handled (accepted/discarded). The agent will clean up@@ -3018,19 +3100,15 @@ void main() {* prevents resumeSession from picking it up again after reload. */function markSessionHandled() {if (!currentSessionId) return;- try {- localStorage.setItem(LS_KEY + '-handled', currentSessionId);- } catch {}+ sessionState.markHandled(currentSessionId);}function isSessionHandled(id) {- try {- return localStorage.getItem(LS_KEY + '-handled') === id;- } catch { return false; }+ return sessionState.isHandled(id);}function clearHandled() {- try { localStorage.removeItem(LS_KEY + '-handled'); } catch {}+ sessionState.clearHandled();}function cleanup() {@@ -3161,6 +3239,7 @@ void main() {// hid. Now that state is CYCLING, re-fire.if (state === 'CYCLING') refreshParamsPanel();saveSession();+ queueCheckpoint('browser_resumed');// Start observing for more variants AFTER initial setupif (variantObserver) variantObserver.disconnect();@@ -3617,7 +3696,7 @@ void main() {}// ---------------------------------------------------------------------------- // Design System Panel — visualizes the project's DESIGN.json sidecar+ // Design System Panel — visualizes the project's .impeccable/design.json sidecar// ---------------------------------------------------------------------------const DESIGN_PREFS_KEY = 'impeccable-live-design-panel';@@ -3629,7 +3708,7 @@ void main() {open: false,tab: 'visual', // 'visual' | 'raw'parsed: null, // parseDesignMd output (frontmatter + body sections)- sidecar: null, // DESIGN.json v2 payload (extensions + components + narrative)+ sidecar: null, // .impeccable/design.json v2 payload (extensions + components + narrative)hasMd: false,hasSidecar: false,present: null, // true/false once fetch resolves@@ -4130,7 +4209,7 @@ void main() {box.className = 'stale';box.innerHTML = `<span class="stale-dot"></span>- <span class="stale-text"><strong>DESIGN.md is newer than DESIGN.json.</strong> Run <code>/impeccable document</code> to refresh the sidecar.</span>+ <span class="stale-text"><strong>DESIGN.md is newer than .impeccable/design.json.</strong> Run <code>/impeccable document</code> to refresh the sidecar.</span>`;return box;}@@ -4138,7 +4217,7 @@ void main() {function renderParsedMdCta() {const box = document.createElement('div');box.className = 'parsed-md-cta';- box.innerHTML = `<strong>Basic view</strong>This panel reads the tokens in your <code>DESIGN.md</code> frontmatter. Running <code>/impeccable document</code> also generates a <code>DESIGN.json</code> sidecar with your project's actual component snippets (button, input, nav) and tonal ramps, rendered live below the tokens.`;+ box.innerHTML = `<strong>Basic view</strong>This panel reads the tokens in your <code>DESIGN.md</code> frontmatter. Running <code>/impeccable document</code> also generates a <code>.impeccable/design.json</code> sidecar with your project's actual component snippets (button, input, nav) and tonal ramps, rendered live below the tokens.`;return box;}@@ -4598,7 +4677,7 @@ void main() {function cssSafe(v) {// Strip anything outside valid CSS value chars to prevent injection via- // DESIGN.json values rendered into inline style strings.+ // .impeccable/design.json values rendered into inline style strings.return String(v).replace(/[<>"'`\n]/g, '');}diff --git a/.qoder/skills/impeccable/scripts/live-complete.mjs b/.qoder/skills/impeccable/scripts/live-complete.mjsnew file mode 100644index 000000000..78155af85--- /dev/null+++ b/.qoder/skills/impeccable/scripts/live-complete.mjs@@ -0,0 +1,75 @@+#!/usr/bin/env node+/**+ * Canonical durable completion acknowledgement for Impeccable live sessions.+ */++import { createLiveSessionStore } from './live-session-store.mjs';+import { readLiveServerInfo } from './impeccable-paths.mjs';++function parseArgs(argv) {+ const out = { status: 'complete' };+ for (let i = 0; i < argv.length; i++) {+ const arg = argv[i];+ if (arg === '--id') out.id = argv[++i];+ else if (arg.startsWith('--id=')) out.id = arg.slice('--id='.length);+ else if (arg === '--discarded' || arg === '--discard') out.status = 'discarded';+ else if (arg === '--error') { out.status = 'agent_error'; out.message = argv[++i] || 'unknown error'; }+ else if (arg.startsWith('--error=')) { out.status = 'agent_error'; out.message = arg.slice('--error='.length); }+ else if (arg === '--help' || arg === '-h') out.help = true;+ }+ return out;+}++export async function completeCli() {+ const args = parseArgs(process.argv.slice(2));+ if (args.help || !args.id) {+ console.log(`Usage: node live-complete.mjs --id SESSION_ID [--discarded|--error MESSAGE]\n\nAppend the final durable session acknowledgement. Use after accept/discard cleanup is verified.`);+ process.exit(args.help ? 0 : 1);+ }++ const serverInfo = readServerInfo();+ const serverResult = serverInfo ? await completeThroughServer(serverInfo, args) : null;+ if (serverResult?.ok) {+ const store = createLiveSessionStore({ cwd: process.cwd(), sessionId: args.id });+ const snapshot = store.getSnapshot(args.id, { includeCompleted: true });+ console.log(JSON.stringify({ ok: true, id: args.id, phase: snapshot?.phase || args.status, snapshot }, null, 2));+ return;+ }++ const store = createLiveSessionStore({ cwd: process.cwd(), sessionId: args.id });+ const event = args.status === 'discarded'+ ? { type: 'discarded', id: args.id }+ : args.status === 'agent_error'+ ? { type: 'agent_error', id: args.id, message: args.message || 'unknown error' }+ : { type: 'complete', id: args.id };+ const snapshot = store.appendEvent(event);+ console.log(JSON.stringify({ ok: true, id: args.id, phase: snapshot.phase, snapshot }, null, 2));+}++function readServerInfo() {+ return readLiveServerInfo(process.cwd())?.info || null;+}++async function completeThroughServer(info, args) {+ const type = args.status === 'discarded'+ ? 'discarded'+ : args.status === 'agent_error'+ ? 'error'+ : 'complete';+ try {+ const res = await fetch(`http://localhost:${info.port}/poll`, {+ method: 'POST',+ headers: { 'Content-Type': 'application/json' },+ body: JSON.stringify({ token: info.token, id: args.id, type, message: args.message }),+ });+ if (!res.ok) return null;+ return await res.json();+ } catch {+ return null;+ }+}++const _running = process.argv[1];+if (_running?.endsWith('live-complete.mjs') || _running?.endsWith('live-complete.mjs/')) {+ completeCli();+}diff --git a/.qoder/skills/impeccable/scripts/live-completion.mjs b/.qoder/skills/impeccable/scripts/live-completion.mjsnew file mode 100644index 000000000..86b637fff--- /dev/null+++ b/.qoder/skills/impeccable/scripts/live-completion.mjs@@ -0,0 +1,18 @@+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';+ return 'agent_done';+}++export function completionAckForAcceptResult(eventId, completionType, acceptResult) {+ const ack = { ok: true, type: completionType };+ if (acceptResult?.handled === true && acceptResult?.carbonize === true) {+ ack.final = false;+ ack.requiresComplete = true;+ ack.nextCommand = `live-complete.mjs --id ${eventId}`;+ ack.message = 'Carbonize cleanup must be verified, then the session must be completed explicitly before polling again.';+ }+ return ack;+}diff --git a/.qoder/skills/impeccable/scripts/live-inject.mjs b/.qoder/skills/impeccable/scripts/live-inject.mjsindex 1d2ae12f7..555c3a36a 100644--- a/.qoder/skills/impeccable/scripts/live-inject.mjs+++ b/.qoder/skills/impeccable/scripts/live-inject.mjs@@ -2,23 +2,24 @@* CLI helper: insert/remove the live variant mode script tag in the project's* main HTML entry point.*- * On first live run, the agent generates `config.json` in this script's- * directory with the project's insertion target (framework-specific). On+ * On first live run, the agent generates `.impeccable/live/config.json`+ * with the project's insertion target (framework-specific). On* every subsequent run, this script handles insert/remove deterministically* with zero LLM involvement.** Usage:* node live-inject.mjs --port PORT # Insert the live script tag* node live-inject.mjs --remove # Remove the live script tag- * node live-inject.mjs --check # Check whether config.json exists+ * node live-inject.mjs --check # Check whether live config exists*/import fs from 'node:fs';import path from 'node:path';import { fileURLToPath } from 'node:url';+import { resolveLiveConfigPath } from './impeccable-paths.mjs';const __dirname = path.dirname(fileURLToPath(import.meta.url));-const CONFIG_PATH = process.env.IMPECCABLE_LIVE_CONFIG || path.join(__dirname, 'config.json');+const CONFIG_PATH = resolveLiveConfigPath({ cwd: process.cwd(), scriptsDir: __dirname });const MARKER_OPEN_TEXT = 'impeccable-live-start';const MARKER_CLOSE_TEXT = 'impeccable-live-end';@@ -39,12 +40,12 @@ export async function injectCli() {console.log(`Usage: node live-inject.mjs [options]Insert or remove the live mode script tag in the project's HTML entry point.-Reads configuration from config.json (in this same directory).+Reads configuration from .impeccable/live/config.json.Modes:--port PORT Insert script tag pointing at http://localhost:PORT/live.js--remove Remove the script tag (if present)- --check Print whether config.json exists and its content+ --check Print whether .impeccable/live/config.json exists and its contentOutput (JSON):{ ok, file, inserted|removed, config? }`);diff --git a/.qoder/skills/impeccable/scripts/live-poll.mjs b/.qoder/skills/impeccable/scripts/live-poll.mjsindex eb8f1586a..10d452491 100644--- a/.qoder/skills/impeccable/scripts/live-poll.mjs+++ b/.qoder/skills/impeccable/scripts/live-poll.mjs@@ -9,10 +9,10 @@*/import { execFileSync } from 'node:child_process';-import fs from 'node:fs';import path from 'node:path';-import os from 'node:os';import { fileURLToPath } from 'node:url';+import { completionAckForAcceptResult, completionTypeForAcceptResult } from './live-completion.mjs';+import { readLiveServerInfo } from './impeccable-paths.mjs';// Node's built-in fetch (undici under the hood) enforces a 300s headers// timeout that can't be lowered per-request. We cap each request below@@ -20,15 +20,29 @@ import { fileURLToPath } from 'node:url';// depending on the standalone undici package.const PER_REQUEST_TIMEOUT_MS = 270_000;-const LIVE_PID_FILE = path.join(process.cwd(), '.impeccable-live.json');-function readServerInfo() {- try {- return JSON.parse(fs.readFileSync(LIVE_PID_FILE, 'utf-8'));- } catch {+ const record = readLiveServerInfo(process.cwd());+ if (!record) {console.error('No running live server found. Start one with: npx impeccable live');process.exit(1);}+ return record.info;+}++export function buildPollReplyPayload(token, { id, type, message, file, data }) {+ return { token, id, type, message, file, data };+}++async function postReply(base, token, reply) {+ const res = await fetch(`${base}/poll`, {+ method: 'POST',+ headers: { 'Content-Type': 'application/json' },+ body: JSON.stringify(buildPollReplyPayload(token, reply)),+ });+ if (!res.ok) {+ const body = await res.json().catch(() => ({}));+ throw new Error(body.error || res.statusText);+ }}export async function pollCli() {@@ -69,23 +83,7 @@ Options:}try {- const res = await fetch(`${base}/poll`, {- method: 'POST',- headers: { 'Content-Type': 'application/json' },- body: JSON.stringify({- token: info.token,- id,- type: status,- message,- file: filePath,- }),- });-- if (!res.ok) {- const body = await res.json().catch(() => ({}));- console.error(`Reply failed (${res.status}):`, body.error || res.statusText);- process.exit(1);- }+ await postReply(base, info.token, { id, type: status, message, file: filePath });// Success — silent exit (agent doesn't need output for replies)} catch (err) {@@ -156,7 +154,23 @@ Options:);event._acceptResult = JSON.parse(out.trim());} catch (err) {- event._acceptResult = { handled: false, error: err.message };+ event._acceptResult = { handled: false, mode: 'error', error: err.message };+ }++ const completionType = completionTypeForAcceptResult(event.type, event._acceptResult);+ try {+ await postReply(base, info.token, {+ id: event.id,+ type: completionType,+ message: event._acceptResult?.error,+ file: event._acceptResult?.file,+ data: event._acceptResult?.carbonize === true ? { carbonize: true } : undefined,+ });+ } catch (err) {+ event._completionAck = { ok: false, error: err.message };+ }+ if (!event._completionAck) {+ event._completionAck = completionAckForAcceptResult(event.id, completionType, event._acceptResult);}}@@ -164,7 +178,7 @@ Options:// JSON but skips nested fields. One line is enough — the full checklist// is in reference/live.md.if (event._acceptResult?.carbonize === true) {- process.stderr.write('\n⚠ Carbonize cleanup REQUIRED before next poll. See reference/live.md "Required after accept".\n\n');+ process.stderr.write('\n⚠ Carbonize cleanup REQUIRED before next poll. After cleanup, run live-complete.mjs --id ' + event.id + '. See reference/live.md "Required after accept".\n\n');}// Print the event as JSON — the agent reads this from stdoutdiff --git a/.qoder/skills/impeccable/scripts/live-resume.mjs b/.qoder/skills/impeccable/scripts/live-resume.mjsnew file mode 100644index 000000000..a3465c9b5--- /dev/null+++ b/.qoder/skills/impeccable/scripts/live-resume.mjs@@ -0,0 +1,48 @@+#!/usr/bin/env node+/**+ * Recover the next agent action from the durable live-session journal.+ */++import { createLiveSessionStore } from './live-session-store.mjs';++function parseArgs(argv) {+ const out = { id: null };+ for (let i = 0; i < argv.length; i++) {+ const arg = argv[i];+ if (arg === '--id') out.id = argv[++i];+ else if (arg.startsWith('--id=')) out.id = arg.slice('--id='.length);+ else if (arg === '--help' || arg === '-h') out.help = true;+ }+ return out;+}++export async function resumeCli() {+ const args = parseArgs(process.argv.slice(2));+ if (args.help) {+ console.log(`Usage: node live-resume.mjs [--id SESSION_ID]\n\nPrint the active durable session checkpoint and the next safe agent action.`);+ return;+ }++ const store = createLiveSessionStore({ cwd: process.cwd(), sessionId: args.id || undefined });+ const snapshot = args.id ? store.getSnapshot(args.id) : store.listActiveSessions()[0] || null;+ if (!snapshot) {+ console.log(JSON.stringify({ active: false, nextAction: 'No active durable live session found.' }, null, 2));+ return;+ }++ const pending = snapshot.pendingEvent || null;+ const nextAction = pending+ ? `Run live-poll.mjs, handle ${pending.type} ${pending.id}, then acknowledge with live-poll.mjs --reply ${pending.id} done.`+ : snapshot.phase === 'carbonize_required'+ ? `Finish carbonize cleanup${snapshot.sourceFile ? ` in ${snapshot.sourceFile}` : ''}, then run live-complete.mjs --id ${snapshot.id}.`+ : snapshot.phase === 'accept_requested'+ ? `Run live-complete.mjs --id ${snapshot.id} after verifying the accepted variant is written.`+ : `Inspect ${snapshot.id}; no pending agent event is currently queued.`;++ console.log(JSON.stringify({ active: true, snapshot, pendingEvent: pending, nextAction }, null, 2));+}++const _running = process.argv[1];+if (_running?.endsWith('live-resume.mjs') || _running?.endsWith('live-resume.mjs/')) {+ resumeCli();+}diff --git a/.qoder/skills/impeccable/scripts/live-server.mjs b/.qoder/skills/impeccable/scripts/live-server.mjsindex 90614fbf7..53d8f21cb 100644--- a/.qoder/skills/impeccable/scripts/live-server.mjs+++ b/.qoder/skills/impeccable/scripts/live-server.mjs@@ -22,14 +22,20 @@ import net from 'node:net';import { fileURLToPath } from 'node:url';import { parseDesignMd } from './design-parser.mjs';import { resolveContextDir } from './load-context.mjs';+import { createLiveSessionStore } from './live-session-store.mjs';+import {+ getDesignSidecarPath,+ getLiveAnnotationsDir,+ readLiveServerInfo,+ removeLiveServerInfo,+ resolveDesignSidecarPath,+ writeLiveServerInfo,+} from './impeccable-paths.mjs';const __dirname = path.dirname(fileURLToPath(import.meta.url));-// PID file in the project root so both the server and agent can find it-// predictably (os.tmpdir() varies across platforms).-const LIVE_PID_FILE = path.join(process.cwd(), '.impeccable-live.json');-// PRODUCT.md / DESIGN.md / DESIGN.json live wherever load-context.mjs resolves.-// Keeps live-server in sync with the loader when users keep the docs in-// .agents/context/, docs/, or a path set via IMPECCABLE_CONTEXT_DIR.+// PRODUCT.md / DESIGN.md live wherever load-context.mjs resolves. The generated+// DESIGN sidecar is project-local at .impeccable/design.json, with legacy+// DESIGN.json fallback for existing projects.const CONTEXT_DIR = resolveContextDir(process.cwd());const DEFAULT_POLL_TIMEOUT = 600_000; // 10 min — agent re-polls on timeout anywayconst SSE_HEARTBEAT_INTERVAL = 30_000; // keepalive ping every 30s@@ -57,10 +63,12 @@ const state = {token: null,port: null,sseClients: new Set(), // SSE response objects (server→browser push)- pendingEvents: [], // browser events waiting for agent poll+ pendingEvents: [], // browser events waiting for agent ack ({ event, leaseUntil })pendingPolls: [], // agent poll callbacks waiting for browser eventsexitTimer: null,sessionDir: null, // per-session tmp dir for annotation screenshots+ sessionStore: null,+ leaseTimer: null,};// Cap per-annotation upload size. A full 1920×1080 PNG is typically <1 MB;@@ -68,11 +76,70 @@ const state = {const MAX_ANNOTATION_BYTES = 10 * 1024 * 1024;function enqueueEvent(event) {- if (state.pendingPolls.length > 0) {- state.pendingPolls.shift()(event);- } else {- state.pendingEvents.push(event);+ if (!event || (event.id && state.pendingEvents.some((entry) => entry.event?.id === event.id && entry.event?.type === event.type))) return;+ state.pendingEvents.push({ event, leaseUntil: 0 });+ flushPendingPolls();+}++function restorePendingEventsFromStore() {+ if (!state.sessionStore) return;+ for (const snapshot of state.sessionStore.listActiveSessions()) {+ if (snapshot.pendingEvent) enqueueEvent(snapshot.pendingEvent);+ }+}++function findAvailablePendingEvent(now = Date.now()) {+ return state.pendingEvents.find((entry) => !entry.leaseUntil || entry.leaseUntil <= now);+}++function leaseEvent(entry, leaseMs) {+ if (!entry.event?.id) {+ const idx = state.pendingEvents.indexOf(entry);+ if (idx !== -1) state.pendingEvents.splice(idx, 1);+ return entry.event;}+ entry.leaseUntil = Date.now() + leaseMs;+ return entry.event;+}++function acknowledgePendingEvent(id) {+ if (!id) return false;+ const idx = state.pendingEvents.findIndex((entry) => entry.event?.id === id);+ if (idx === -1) return false;+ state.pendingEvents.splice(idx, 1);+ scheduleLeaseFlush();+ return true;+}++function scheduleLeaseFlush() {+ if (state.leaseTimer) {+ clearTimeout(state.leaseTimer);+ state.leaseTimer = null;+ }+ if (state.pendingPolls.length === 0) return;+ const now = Date.now();+ const nextLeaseUntil = state.pendingEvents+ .map((entry) => entry.leaseUntil || 0)+ .filter((leaseUntil) => leaseUntil > now)+ .sort((a, b) => a - b)[0];+ if (!nextLeaseUntil) return;+ state.leaseTimer = setTimeout(() => {+ state.leaseTimer = null;+ flushPendingPolls();+ }, Math.max(0, nextLeaseUntil - now));+}++function flushPendingPolls() {+ while (state.pendingPolls.length > 0) {+ const entry = findAvailablePendingEvent();+ if (!entry) {+ scheduleLeaseFlush();+ return;+ }+ const poll = state.pendingPolls.shift();+ poll.resolve(leaseEvent(entry, poll.leaseMs));+ }+ scheduleLeaseFlush();}/** Push a message to all connected SSE clients. */@@ -103,13 +170,16 @@ function loadBrowserScripts() {// live-browser.js: DO NOT cache. Return the path so the /live.js handler// can re-read on every request. Editing the browser script during iteration// should land on the next tab reload, not require a server restart.+ const sessionPath = path.join(__dirname, 'live-browser-session.js');const livePath = path.join(__dirname, 'live-browser.js');- if (!fs.existsSync(livePath)) {- process.stderr.write('Error: live-browser.js not found at ' + livePath + '\n');- process.exit(1);+ for (const p of [sessionPath, livePath]) {+ if (!fs.existsSync(p)) {+ process.stderr.write('Error: live browser script not found at ' + p + '\n');+ process.exit(1);+ }}- return { detectScript, livePath };+ return { detectScript, sessionPath, livePath };}function hasProjectContext() {@@ -170,6 +240,13 @@ function validateEvent(msg) {return null;case 'discard':return isValidId(msg.id) ? null : 'discard: missing or malformed id';+ case 'checkpoint':+ if (!isValidId(msg.id)) return 'checkpoint: missing or malformed id';+ if (!Number.isInteger(msg.revision) || msg.revision < 0) return 'checkpoint: revision must be a non-negative integer';+ if (msg.paramValues !== undefined && (typeof msg.paramValues !== 'object' || msg.paramValues === null || Array.isArray(msg.paramValues))) {+ return 'checkpoint: paramValues must be an object';+ }+ return null;case 'exit':return null;case 'prefetch':@@ -184,7 +261,7 @@ function validateEvent(msg) {// HTTP request handler// ----------------------------------------------------------------------------function createRequestHandler({ detectScript, livePath }) {+function createRequestHandler({ detectScript, sessionPath, livePath }) {return (req, res) => {const url = new URL(req.url, `http://localhost:${state.port}`);res.setHeader('Access-Control-Allow-Origin', '*');@@ -200,17 +277,20 @@ function createRequestHandler({ detectScript, livePath }) {// the next tab reload. No-store headers prevent browser caching across// sessions — during iteration, a cached old script silently breaks// every subsequent session.+ let sessionScript;let liveScript;try {+ sessionScript = fs.readFileSync(sessionPath, 'utf-8');liveScript = fs.readFileSync(livePath, 'utf-8');} catch (err) {res.writeHead(500, { 'Content-Type': 'text/plain' });- res.end('Error reading live-browser.js: ' + err.message);+ res.end('Error reading live browser scripts: ' + err.message);return;}const body =`window.__IMPECCABLE_TOKEN__ = '${state.token}';\n` +`window.__IMPECCABLE_PORT__ = ${state.port};\n` ++ sessionScript + '\n' +liveScript;res.writeHead(200, {'Content-Type': 'application/javascript',@@ -305,6 +385,26 @@ function createRequestHandler({ detectScript, livePath }) {}// --- Health ---+ if (p === '/status') {+ const token = url.searchParams.get('token');+ if (token !== state.token) { res.writeHead(401, { 'Content-Type': 'application/json' }); res.end(JSON.stringify({ error: 'Unauthorized' })); return; }+ const sessions = state.sessionStore ? state.sessionStore.listActiveSessions() : [];+ res.writeHead(200, { 'Content-Type': 'application/json' });+ res.end(JSON.stringify({+ status: 'ok',+ port: state.port,+ connectedClients: state.sseClients.size,+ pendingEvents: state.pendingEvents.map((entry) => ({+ id: entry.event?.id,+ type: entry.event?.type,+ leased: !!(entry.leaseUntil && entry.leaseUntil > Date.now()),+ leaseUntil: entry.leaseUntil || null,+ })),+ activeSessions: sessions,+ }));+ return;+ }+if (p === '/health') {res.writeHead(200, { 'Content-Type': 'application/json' });res.end(JSON.stringify({@@ -316,13 +416,13 @@ function createRequestHandler({ detectScript, livePath }) {}// --- Design system (unified v2 response) + raw ---- // /design-system.json returns both parsed DESIGN.md and DESIGN.json+ // /design-system.json returns both parsed DESIGN.md and .impeccable/design.json// sidecar when present. Panel merges them:// { present, parsed, sidecar, hasMd, hasSidecar,// mdNewerThanJson, parseError?, sidecarError? }// - parsed: output of parseDesignMd (frontmatter// + six canonical sections) when DESIGN.md exists.- // - sidecar: DESIGN.json contents when present.+ // - sidecar: .impeccable/design.json contents when present.// Expected shape: schemaVersion 2, carrying// extensions + components + narrative.// /design-system/raw returns DESIGN.md markdown verbatim@@ -331,7 +431,7 @@ function createRequestHandler({ detectScript, livePath }) {if (token !== state.token) { res.writeHead(401); res.end('Unauthorized'); return; }const mdPath = path.join(CONTEXT_DIR, 'DESIGN.md');- const jsonPath = path.join(CONTEXT_DIR, 'DESIGN.json');+ const jsonPath = resolveDesignSidecarPath(process.cwd(), CONTEXT_DIR) || getDesignSidecarPath(process.cwd());const mdStat = statOrNull(mdPath);const jsonStat = statOrNull(jsonPath);@@ -367,7 +467,7 @@ function createRequestHandler({ detectScript, livePath }) {try {response.sidecar = JSON.parse(fs.readFileSync(jsonPath, 'utf-8'));} catch (err) {- response.sidecarError = 'Failed to parse DESIGN.json: ' + err.message;+ response.sidecarError = 'Failed to parse .impeccable/design.json: ' + err.message;}}@@ -449,7 +549,16 @@ function createRequestHandler({ detectScript, livePath }) {res.end(JSON.stringify({ error }));return;}- enqueueEvent(msg);+ if (state.sessionStore && msg.id) {+ try {+ state.sessionStore.appendEvent(msg);+ } catch (err) {+ res.writeHead(500, { 'Content-Type': 'application/json' });+ res.end(JSON.stringify({ error: 'session_store_append_failed', message: err.message }));+ return;+ }+ }+ if (msg.type !== 'checkpoint') enqueueEvent(msg);res.writeHead(200, { 'Content-Type': 'application/json' });res.end(JSON.stringify({ ok: true }));});@@ -492,13 +601,16 @@ function handlePollGet(req, res, url) {return;}const timeout = parseInt(url.searchParams.get('timeout') || DEFAULT_POLL_TIMEOUT, 10);- if (state.pendingEvents.length > 0) {+ const leaseMs = parseInt(url.searchParams.get('leaseMs') || '30000', 10);+ const available = findAvailablePendingEvent();+ if (available) {res.writeHead(200, { 'Content-Type': 'application/json' });- res.end(JSON.stringify(state.pendingEvents.shift()));+ res.end(JSON.stringify(leaseEvent(available, leaseMs)));return;}+ const poll = { resolve, leaseMs };const timer = setTimeout(() => {- const idx = state.pendingPolls.indexOf(resolve);+ const idx = state.pendingPolls.indexOf(poll);if (idx !== -1) state.pendingPolls.splice(idx, 1);res.writeHead(200, { 'Content-Type': 'application/json' });res.end(JSON.stringify({ type: 'timeout' }));@@ -508,10 +620,11 @@ function handlePollGet(req, res, url) {res.writeHead(200, { 'Content-Type': 'application/json' });res.end(JSON.stringify(event));}- state.pendingPolls.push(resolve);+ state.pendingPolls.push(poll);+ scheduleLeaseFlush();req.on('close', () => {clearTimeout(timer);- const idx = state.pendingPolls.indexOf(resolve);+ const idx = state.pendingPolls.indexOf(poll);if (idx !== -1) state.pendingPolls.splice(idx, 1);});}@@ -531,6 +644,26 @@ function handlePollPost(req, res) {res.end(JSON.stringify({ error: 'Unauthorized' }));return;}+ acknowledgePendingEvent(msg.id);+ if (state.sessionStore && msg.id) {+ try {+ const eventType = msg.type === 'discard' || msg.type === 'discarded'+ ? 'discarded'+ : msg.type === 'complete'+ ? 'complete'+ : msg.type === 'error'+ ? 'agent_error'+ : 'agent_done';+ state.sessionStore.appendEvent({+ type: eventType,+ id: msg.id,+ file: msg.file,+ message: msg.message,+ carbonize: msg.data?.carbonize === true,+ });+ } catch { /* keep reply path best-effort; browser still needs SSE */ }+ }+ flushPendingPolls();// Forward the reply to the browser via SSEbroadcast({ type: msg.type || 'done', id: msg.id, message: msg.message, file: msg.file, data: msg.data });res.writeHead(200, { 'Content-Type': 'application/json' });@@ -545,13 +678,15 @@ function handlePollPost(req, res) {let httpServer = null;function shutdown() {- try { fs.unlinkSync(LIVE_PID_FILE); } catch {}+ removeLiveServerInfo(process.cwd());+ if (state.leaseTimer) clearTimeout(state.leaseTimer);+ state.leaseTimer = null;if (state.sessionDir) {try { fs.rmSync(state.sessionDir, { recursive: true, force: true }); } catch {}}for (const res of state.sseClients) { try { res.end(); } catch {} }state.sseClients.clear();- for (const resolve of state.pendingPolls) resolve({ type: 'exit' });+ for (const poll of state.pendingPolls) poll.resolve({ type: 'exit' });state.pendingPolls.length = 0;if (httpServer) httpServer.close();process.exit(0);@@ -587,6 +722,7 @@ Endpoints:/events SSE stream (server→browser) + POST (browser→server)/poll Long-poll for agent CLI/source Raw source file reader (no-HMR fallback)+ /status Durable recovery status (token-protected)/health Health check`);process.exit(0);}@@ -594,7 +730,7 @@ Endpoints:if (args.includes('stop')) {const keepInject = args.includes('--keep-inject');try {- const info = JSON.parse(fs.readFileSync(LIVE_PID_FILE, 'utf-8'));+ const { info } = readLiveServerInfo(process.cwd()) || {};const res = await fetch(`http://localhost:${info.port}/stop?token=${info.token}`);if (res.ok) console.log(`Stopped live server on port ${info.port}.`);} catch {@@ -645,7 +781,7 @@ if (args.includes('--background')) {const deadline = Date.now() + 10_000;while (Date.now() < deadline) {try {- const info = JSON.parse(fs.readFileSync(LIVE_PID_FILE, 'utf-8'));+ const { info } = readLiveServerInfo(process.cwd()) || {};if (info.pid !== process.pid) {// Output JSON so the agent can read port + token from stdout.console.log(JSON.stringify(info));@@ -659,30 +795,36 @@ if (args.includes('--background')) {}// Check for existing session-try {- const existing = JSON.parse(fs.readFileSync(LIVE_PID_FILE, 'utf-8'));- try { process.kill(existing.pid, 0);+const existingRecord = readLiveServerInfo(process.cwd());+if (existingRecord?.info) {+ const existing = existingRecord.info;+ try {+ process.kill(existing.pid, 0);console.error(`Live server already running on port ${existing.port} (pid ${existing.pid}).`);console.error('Stop it first with: node ' + path.basename(fileURLToPath(import.meta.url)) + ' stop');process.exit(1);- } catch { fs.unlinkSync(LIVE_PID_FILE); }-} catch {}+ } catch {+ try { fs.unlinkSync(existingRecord.path); } catch {}+ }+}state.token = randomUUID();+state.sessionStore = createLiveSessionStore({ cwd: process.cwd() });+restorePendingEventsFromStore();const portArg = args.find(a => a.startsWith('--port='));state.port = portArg ? parseInt(portArg.split('=')[1], 10) : await findOpenPort();// Annotation screenshots live in the project root so the agent's Read tool// doesn't trip a per-file permission prompt. Sessioned by token so concurrent// projects (or quick restarts) don't collide.-const annotRoot = path.join(process.cwd(), '.impeccable-live', 'annotations');+const annotRoot = getLiveAnnotationsDir(process.cwd());fs.mkdirSync(annotRoot, { recursive: true });state.sessionDir = fs.mkdtempSync(path.join(annotRoot, 'session-'));-const { detectScript, livePath } = loadBrowserScripts();-httpServer = http.createServer(createRequestHandler({ detectScript, livePath }));+const { detectScript, sessionPath, livePath } = loadBrowserScripts();+httpServer = http.createServer(createRequestHandler({ detectScript, sessionPath, livePath }));httpServer.listen(state.port, '127.0.0.1', () => {- fs.writeFileSync(LIVE_PID_FILE, JSON.stringify({ pid: process.pid, port: state.port, token: state.token }));+ writeLiveServerInfo(process.cwd(), { pid: process.pid, port: state.port, token: state.token });const url = `http://localhost:${state.port}`;console.log(`\nImpeccable live server running on ${url}`);console.log(`Token: ${state.token}\n`);diff --git a/.qoder/skills/impeccable/scripts/live-session-store.mjs b/.qoder/skills/impeccable/scripts/live-session-store.mjsnew file mode 100644index 000000000..d55ed2d3a--- /dev/null+++ b/.qoder/skills/impeccable/scripts/live-session-store.mjs@@ -0,0 +1,254 @@+import fs from 'node:fs';+import path from 'node:path';+import { getLegacyLiveSessionsDir, getLiveSessionsDir } from './impeccable-paths.mjs';++const COMPLETED_PHASES = new Set(['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;+ }++ function getReadableJournalPath(id) {+ const primary = getJournalPath(rootDir, id);+ if (fs.existsSync(primary)) return primary;+ const legacy = getJournalPath(legacyRootDir, id);+ if (fs.existsSync(legacy)) return legacy;+ return primary;+ }++ return {+ rootDir,+ legacyRootDir,+ appendEvent(event) {+ const normalized = normalizeEvent(event, sessionId);+ const journalPath = getJournalPath(rootDir, normalized.id);+ const snapshotPath = getSnapshotPath(rootDir, normalized.id);+ const legacyJournalPath = getJournalPath(legacyRootDir, normalized.id);+ if (!fs.existsSync(journalPath) && fs.existsSync(legacyJournalPath)) {+ fs.copyFileSync(legacyJournalPath, journalPath);+ }+ const prior = loadCachedOrRebuild(normalized.id);+ const seq = prior.nextSeq;+ const entry = {+ seq,+ id: normalized.id,+ type: normalized.type,+ ts: new Date().toISOString(),+ event: normalized,+ };+ 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;+ },+ getSnapshot(id = sessionId, opts = {}) {+ if (!id) throw new Error('session id required');+ 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;+ },+ listActiveSessions() {+ const ids = new Set();+ for (const dir of [legacyRootDir, rootDir]) {+ if (!fs.existsSync(dir)) continue;+ for (const name of fs.readdirSync(dir)) {+ if (name.endsWith('.jsonl')) ids.add(name.slice(0, -'.jsonl'.length));+ }+ }+ return [...ids]+ .sort()+ .map((id) => this.getSnapshot(id))+ .filter(Boolean);+ },+ };+}++function normalizeEvent(event, fallbackId) {+ if (!event || typeof event !== 'object') throw new Error('event object required');+ const id = event.id || fallbackId;+ if (!id || typeof id !== 'string') throw new Error('event id required');+ if (!event.type || typeof event.type !== 'string') throw new Error('event type required');+ return { ...event, id };+}++function getJournalPath(rootDir, id) {+ return path.join(rootDir, safeSessionId(id) + '.jsonl');+}++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,+ phase: 'new',+ pageUrl: null,+ sourceFile: null,+ expectedVariants: 0,+ arrivedVariants: 0,+ visibleVariant: null,+ paramValues: {},+ pendingEventSeq: null,+ pendingEvent: null,+ deliveryLease: null,+ checkpointRevision: 0,+ activeOwner: null,+ sourceMarkers: {},+ fallbackMode: null,+ annotationArtifacts: [],+ diagnostics: [],+ updatedAt: null,+ };+}++function rebuildSnapshotFromJournal(journalPath, id) {+ let snapshot = baseSnapshot(id);+ const diagnostics = [];+ let nextSeq = 1;+ if (!fs.existsSync(journalPath)) return { snapshot, diagnostics, nextSeq };++ const lines = fs.readFileSync(journalPath, 'utf-8').split('\n');+ for (let i = 0; i < lines.length; i++) {+ const line = lines[i];+ if (!line.trim()) continue;+ try {+ const entry = JSON.parse(line);+ if (!entry || typeof entry !== 'object') throw new Error('entry is not object');+ if (Number.isInteger(entry.seq)) nextSeq = Math.max(nextSeq, entry.seq + 1);+ snapshot = applyEvent(snapshot, entry);+ } catch (err) {+ diagnostics.push({+ error: 'journal_parse_failed',+ line: i + 1,+ message: err.message,+ });+ }+ }+ snapshot.diagnostics = [...snapshot.diagnostics, ...diagnostics];+ return { snapshot, diagnostics, nextSeq };+}++function applyEvent(snapshot, entry, inheritedDiagnostics = []) {+ const event = entry.event || entry;+ const next = {+ ...snapshot,+ paramValues: { ...(snapshot.paramValues || {}) },+ sourceMarkers: { ...(snapshot.sourceMarkers || {}) },+ annotationArtifacts: [...(snapshot.annotationArtifacts || [])],+ diagnostics: [...(snapshot.diagnostics || [])],+ updatedAt: entry.ts || new Date().toISOString(),+ };++ if (inheritedDiagnostics.length && next.diagnostics.length === 0) {+ next.diagnostics = [...inheritedDiagnostics];+ }++ switch (event.type) {+ case 'generate':+ next.phase = 'generate_requested';+ next.pageUrl = event.pageUrl ?? next.pageUrl;+ next.expectedVariants = event.count ?? next.expectedVariants;+ next.pendingEventSeq = entry.seq ?? next.pendingEventSeq;+ next.pendingEvent = toPendingEvent(event);+ if (event.screenshotPath) upsertArtifact(next.annotationArtifacts, { type: 'screenshot', path: event.screenshotPath });+ break;+ case 'variants_ready':+ case 'agent_done':+ next.phase = event.carbonize === true ? 'carbonize_required' : 'variants_ready';+ next.sourceFile = event.file ?? next.sourceFile;+ next.arrivedVariants = event.arrivedVariants ?? (next.arrivedVariants ?? next.expectedVariants);+ next.pendingEventSeq = null;+ next.pendingEvent = null;+ if (event.carbonize === true) {+ next.diagnostics.push({+ error: 'carbonize_cleanup_required',+ file: event.file || null,+ message: 'Accepted variant still has carbonize markers that must be folded into source CSS.',+ });+ }+ break;+ case 'checkpoint':+ 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;+ if (event.paramValues) next.paramValues = { ...event.paramValues };+ } else {+ next.diagnostics.push({ error: 'stale_checkpoint_ignored', revision: event.revision });+ }+ break;+ case 'accept':+ case 'accept_intent':+ next.phase = 'accept_requested';+ next.visibleVariant = Number(event.variantId ?? next.visibleVariant);+ if (event.paramValues) next.paramValues = { ...event.paramValues };+ next.pendingEventSeq = entry.seq ?? next.pendingEventSeq;+ next.pendingEvent = toPendingEvent(event);+ break;+ case 'discard':+ next.phase = 'discard_requested';+ next.pendingEventSeq = entry.seq ?? next.pendingEventSeq;+ next.pendingEvent = toPendingEvent(event);+ break;+ case 'discarded':+ next.phase = 'discarded';+ next.pendingEventSeq = null;+ next.pendingEvent = null;+ break;+ case 'complete':+ next.phase = 'completed';+ next.pendingEventSeq = null;+ next.pendingEvent = null;+ break;+ case 'agent_error':+ next.phase = 'agent_error';+ next.pendingEventSeq = null;+ next.pendingEvent = null;+ next.diagnostics.push({ error: 'agent_error', message: event.message || 'unknown agent error' });+ break;+ default:+ next.diagnostics.push({ error: 'unknown_event_type', type: event.type });+ break;+ }+ return next;+}++function toPendingEvent(event) {+ const pending = { ...event };+ delete pending.token;+ return pending;+}++function upsertArtifact(artifacts, artifact) {+ if (!artifacts.some((existing) => existing.path === artifact.path && existing.type === artifact.type)) {+ artifacts.push(artifact);+ }+}++function writeSnapshot(snapshotPath, snapshot) {+ fs.writeFileSync(snapshotPath, JSON.stringify(snapshot, null, 2) + '\n');+}diff --git a/.qoder/skills/impeccable/scripts/live-status.mjs b/.qoder/skills/impeccable/scripts/live-status.mjsnew file mode 100644index 000000000..dce1fbca2--- /dev/null+++ b/.qoder/skills/impeccable/scripts/live-status.mjs@@ -0,0 +1,47 @@+#!/usr/bin/env node+/**+ * Print durable recovery status for Impeccable live sessions.+ */++import { createLiveSessionStore } from './live-session-store.mjs';+import { readLiveServerInfo } from './impeccable-paths.mjs';++function readServerInfo() {+ return readLiveServerInfo(process.cwd())?.info || null;+}++async function fetchServerStatus(info) {+ if (!info) return null;+ try {+ const res = await fetch(`http://localhost:${info.port}/status?token=${info.token}`);+ if (!res.ok) return null;+ return await res.json();+ } catch {+ return null;+ }+}++export async function statusCli() {+ const info = readServerInfo();+ const server = await fetchServerStatus(info);+ const store = createLiveSessionStore({ cwd: process.cwd() });+ const activeSessions = store.listActiveSessions();+ const payload = {+ liveServer: server ? {+ status: server.status,+ port: server.port,+ connectedClients: server.connectedClients,+ pendingEvents: server.pendingEvents,+ } : null,+ activeSessions: server?.activeSessions || activeSessions,+ recoveryHint: 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.',+ };+ console.log(JSON.stringify(payload, null, 2));+}++const _running = process.argv[1];+if (_running?.endsWith('live-status.mjs') || _running?.endsWith('live-status.mjs/')) {+ statusCli();+}diff --git a/.qoder/skills/impeccable/scripts/live-wrap.mjs b/.qoder/skills/impeccable/scripts/live-wrap.mjsindex a5769a50a..d46328b9f 100644--- a/.qoder/skills/impeccable/scripts/live-wrap.mjs+++ b/.qoder/skills/impeccable/scripts/live-wrap.mjs@@ -185,6 +185,7 @@ The agent should insert variant HTML at insertLine.`);const { startLine, endLine } = match;const commentSyntax = detectCommentSyntax(targetFile);+ const styleMode = detectStyleMode(targetFile);const isJsx = commentSyntax.open === '{/*';const indent = lines[startLine].match(/^(\s*)/)[1];@@ -269,6 +270,10 @@ The agent should insert variant HTML at insertLine.`);endLine: startLine + wrapperLines.length + (originalLines.length - 1), // 1-indexedinsertLine: insertLine + 1, // 1-indexed: where variants gocommentSyntax: commentSyntax,+ styleMode: styleMode.mode,+ styleTag: styleMode.styleTag,+ cssSelectorPrefixExamples: buildCssSelectorPrefixExamples(styleMode.mode, count),+ cssAuthoring: buildCssAuthoring(styleMode, count),originalLineCount: originalLines.length,}));}@@ -335,6 +340,62 @@ function detectCommentSyntax(filePath) {return { open: '<!--', close: '-->' };}+function detectStyleMode(filePath) {+ const ext = path.extname(filePath).toLowerCase();+ if (ext === '.astro') {+ return {+ mode: 'astro-global-prefixed',+ styleTag: '<style is:inline data-impeccable-css="SESSION_ID">',+ };+ }+ return {+ mode: 'scoped',+ styleTag: '<style data-impeccable-css="SESSION_ID">',+ };+}++function buildCssSelectorPrefixExamples(styleMode, count) {+ if (styleMode !== 'astro-global-prefixed') return [];+ return Array.from({ length: count }, (_, i) => `[data-impeccable-variant="${i + 1}"]`);+}++function buildCssAuthoring(styleMode, count) {+ const variantNumbers = Array.from({ length: count }, (_, i) => i + 1);+ if (styleMode.mode === 'astro-global-prefixed') {+ return {+ mode: styleMode.mode,+ styleTag: styleMode.styleTag,+ strategy: 'global-prefixed',+ rulePattern: '[data-impeccable-variant="N"] > .variant-class { ... }',+ selectorExamples: variantNumbers.map((n) => `[data-impeccable-variant="${n}"] > .variant-class`),+ requirements: [+ 'Use the styleTag exactly; the is:inline attribute is required for this file.',+ 'Prefix every preview selector with the matching [data-impeccable-variant="N"] selector.',+ 'Keep selectors anchored to the generated variant wrapper; do not rely on component CSS scoping for preview rules.',+ ],+ forbidden: [+ 'Do not use @scope for this styleMode.',+ ],+ };+ }+ return {+ mode: styleMode.mode,+ styleTag: styleMode.styleTag,+ strategy: 'scope-rule',+ rulePattern: '@scope ([data-impeccable-variant="N"]) { :scope > .variant-class { ... } }',+ selectorExamples: variantNumbers.map((n) => `@scope ([data-impeccable-variant="${n}"]) { :scope > .variant-class { ... } }`),+ requirements: [+ 'Use @scope blocks keyed to each [data-impeccable-variant="N"] wrapper.',+ 'Inside each @scope block, make :scope rules step into the replacement element with a descendant combinator.',+ 'Use the styleTag exactly; do not add framework-specific style attributes unless this object says to.',+ ],+ forbidden: [+ 'Do not use global [data-impeccable-variant="N"] selector prefixes for this styleMode.',+ 'Do not add is:inline to the style tag for this styleMode.',+ ],+ };+}+/*** Search project files for the query string (class name, ID, etc.)* Returns the first matching file path, or null.diff --git a/.qoder/skills/impeccable/scripts/live.mjs b/.qoder/skills/impeccable/scripts/live.mjsindex befbdb8ed..cafb0eca9 100644--- a/.qoder/skills/impeccable/scripts/live.mjs+++ b/.qoder/skills/impeccable/scripts/live.mjs@@ -2,10 +2,10 @@* CLI entry point: prepare everything needed to enter the live variant poll loop.** Does (all in one command):- * 1. Check config.json (returns config_missing if first-ever run)+ * 1. Check .impeccable/live/config.json (returns config_missing if first-ever run)* 2. Start the live server in the background (or reuse a running one)* 3. Inject the browser script tag into the project's entry file- * 4. Read .impeccable.md for design context (if present)+ * 4. Read PRODUCT.md / DESIGN.md for project context* 5. Print a single JSON blob with everything the agent needs** After this, the agent's only remaining steps are:@@ -23,9 +23,9 @@ import path from 'node:path';import { fileURLToPath } from 'node:url';import { loadContext } from './load-context.mjs';import { resolveFiles } from './live-inject.mjs';+import { readLiveServerInfo } from './impeccable-paths.mjs';const __dirname = path.dirname(fileURLToPath(import.meta.url));-const PID_FILE = path.join(process.cwd(), '.impeccable-live.json');async function liveCli() {const args = process.argv.slice(2);@@ -34,10 +34,10 @@ async function liveCli() {console.log(`Usage: node live.mjsPrepare everything for live variant mode in a single command:- - Checks scripts/config.json (required, created once per project)+ - Checks .impeccable/live/config.json (required, created once per project)- Starts (or reuses) the live server in the background- Injects the browser script tag- - Reads .impeccable.md for design context+ - Reads PRODUCT.md / DESIGN.md for project contextOn success, prints a JSON blob with:{ ok, serverPort, serverToken, pageFile, hasContext, context }@@ -223,7 +223,7 @@ function safeParse(out) {function ensureServerRunning() {// Try to reuse an existing servertry {- const existing = JSON.parse(fs.readFileSync(PID_FILE, 'utf-8'));+ const existing = readLiveServerInfo(process.cwd())?.info;if (existing && existing.pid) {try {process.kill(existing.pid, 0); // throws if deaddiff --git a/.qoder/skills/impeccable/scripts/load-context.mjs b/.qoder/skills/impeccable/scripts/load-context.mjsindex dca23c1f8..dc340bf16 100644--- a/.qoder/skills/impeccable/scripts/load-context.mjs+++ b/.qoder/skills/impeccable/scripts/load-context.mjs@@ -39,7 +39,7 @@ const LEGACY_NAMES = ['.impeccable.md'];const FALLBACK_DIRS = ['.agents/context', 'docs'];/**- * Resolve the directory that holds PRODUCT.md / DESIGN.md / DESIGN.json for+ * Resolve the directory that holds PRODUCT.md / DESIGN.md for* this project. Exported so other scripts (e.g. live-server.mjs) can read the* design files from the same location the loader uses.*/diff --git a/.rovodev/skills/impeccable/reference/document.md b/.rovodev/skills/impeccable/reference/document.mdindex 9c7a339f9..16111d610 100644--- a/.rovodev/skills/impeccable/reference/document.md+++ b/.rovodev/skills/impeccable/reference/document.md@@ -237,11 +237,11 @@ Concrete, forceful guardrails. Lead each with "Do" or "Don't". Be specific: incl- **Don't** [...]```-### Step 4b: Write DESIGN.json sidecar (extensions only)+### Step 4b: Write .impeccable/design.json sidecar (extensions only)-The frontmatter owns token primitives (colors, typography, rounded, spacing, components). The sidecar at `DESIGN.json` carries **what Stitch's schema can't hold**: tonal ramps per color, shadow/elevation tokens, motion tokens, breakpoints, full component HTML/CSS snippets (the panel renders these into a shadow DOM), and narrative (north star, rules, do's/don'ts). It extends the frontmatter, it doesn't duplicate it.+The frontmatter owns token primitives (colors, typography, rounded, spacing, components). The sidecar at `.impeccable/design.json` carries **what Stitch's schema can't hold**: tonal ramps per color, shadow/elevation tokens, motion tokens, breakpoints, full component HTML/CSS snippets (the panel renders these into a shadow DOM), and narrative (north star, rules, do's/don'ts). It extends the frontmatter, it doesn't duplicate it.-Regenerate the sidecar whenever you regenerate DESIGN.md. If the user only asks to refresh the sidecar (e.g., from the live panel's stale-hint), preserve DESIGN.md and write only DESIGN.json.+Regenerate the sidecar whenever you regenerate root `DESIGN.md`. If the user only asks to refresh the sidecar (e.g., from the live panel's stale-hint), preserve `DESIGN.md` and write only `.impeccable/design.json`.#### Schema@@ -310,7 +310,7 @@ Aim for a tight set of **5-10 components** that best represent the visual system- **Signature components (include if distinctive):** hero CTA, featured card, filter pill, any custom pattern the user mentioned as important in PRODUCT.md.- **Skip the rest.** Utility components, form building blocks, wrapper layouts: not worth documenting unless visually distinctive.-If the project has **no component library yet** (bare landing page, new project), synthesize canonical primitives from the tokens using best-practice defaults consistent with the DESIGN.md's rules. Every DESIGN.json has *something* to render, even on day zero.+If the project has **no component library yet** (bare landing page, new project), synthesize canonical primitives from the tokens using best-practice defaults consistent with the DESIGN.md's rules. Every `.impeccable/design.json` has *something* to render, even on day zero.#### Tonal ramps@@ -331,7 +331,7 @@ Do not reword. The panel shows these as secondary collapsible context; the same### Step 5: Confirm, refine, and refresh session cache1. Show the user the full DESIGN.md you wrote. Briefly highlight the non-obvious creative choices (descriptive color names, atmosphere language, named rules).-2. Mention that `DESIGN.json` was also written alongside; the live panel will now render this project's actual button/input/nav primitives instead of generic approximations.+2. Mention that `.impeccable/design.json` was also written alongside; the live panel will now render this project's actual button/input/nav primitives instead of generic approximations.3. Offer to refine any section: "Want me to revise a section, add component patterns I missed, or adjust the atmosphere language?"4. **Refresh the session cache.** Run `node .rovodev/skills/impeccable/scripts/load-context.mjs` one final time so the newly-written DESIGN.md lands in conversation. Subsequent commands in this session will use the fresh version automatically without re-reading.@@ -392,7 +392,7 @@ Per-section guidance in seed mode:- **Components**: omit entirely; no components exist yet.- **Do's and Don'ts**: carry PRODUCT.md's anti-references directly plus the anti-reference named in Q5.-Seed mode writes a minimal frontmatter with `name` and `description` only; no colors, typography, rounded, spacing, or components yet. Real tokens land on the next Scan-mode run. Skip the `DESIGN.json` sidecar in seed mode for the same reason: nothing to render.+Seed mode writes a minimal frontmatter with `name` and `description` only; no colors, typography, rounded, spacing, or components yet. Real tokens land on the next Scan-mode run. Skip the `.impeccable/design.json` sidecar in seed mode for the same reason: nothing to render.### Step 4: Confirm and refresh session cachediff --git a/.rovodev/skills/impeccable/reference/live.md b/.rovodev/skills/impeccable/reference/live.mdindex f7e007312..87b039505 100644--- a/.rovodev/skills/impeccable/reference/live.md+++ b/.rovodev/skills/impeccable/reference/live.md@@ -12,8 +12,9 @@ Execute in order. No step skipped, no step reordered.2. Navigate to the URL that serves `pageFile` (infer from `package.json`, docs, terminal output, or an open tab). If you can't infer it confidently, tell the user once to open their dev/preview URL. Never use `serverPort` as that URL; it's the helper, not the app.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=`.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.-5. On `accept` / `discard`: the poll script already cleaned up; just poll again.-6. On `exit`: run the cleanup at the bottom.+5. 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. If interrupted, run `live-status.mjs` or `live-resume.mjs` before guessing. The durable journal replays unacknowledged work after helper restart.+7. 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.@@ -43,13 +44,31 @@ LOOP:Read JSON; dispatch on "type""generate" → Handle Generate; reply done; LOOP- "accept" → Handle Accept; LOOP+ "accept" → Handle Accept; complete carbonize cleanup if required; LOOP"discard" → Handle Discard; LOOP"prefetch" → Handle Prefetch; LOOP"timeout" → LOOP"exit" → break → Cleanup```+## Recovery commands++The live helper persists an append-only journal under `.impeccable/live/sessions/`. Browser checkpoints are advisory but durable; the journal is canonical. This is local durable recovery state, not project source.++Use these commands when the chat was interrupted, polling was missed, the helper restarted, or the browser reloaded:++```bash+node .rovodev/skills/impeccable/scripts/live-status.mjs+node .rovodev/skills/impeccable/scripts/live-resume.mjs --id SESSION_ID+node .rovodev/skills/impeccable/scripts/live-complete.mjs --id SESSION_ID+```++- `live-status.mjs` prints connected helper state, active durable sessions, and queued pending events. It works even when the helper is down by reading the journal directly.+- `live-resume.mjs` prints the active snapshot, pending event, checkpoint phase, visible variant, parameter values, and the next safe agent action.+- `live-complete.mjs` is the canonical manual final acknowledgement. Use it after carbonize/manual cleanup is verified and no further poll acknowledgement will happen automatically.++Server restart rule: start `live-server.mjs` again, then poll. Startup requeues unacknowledged pending events from the journal, so do not ask the user to click Go again unless `live-resume.mjs` says no active session exists.+## Handle `generate`Event: `{id, action, freeformPrompt?, count, pageUrl, element, screenshotPath?, comments?, strokes?}`.@@ -88,7 +107,14 @@ The helper searches ID first, then classes, then tag + class combo. If `event.paIf `--text` matches multiple candidates equally well, wrap exits with `{ error: "element_ambiguous", candidates: [...] }` and `fallback: "agent-driven"`: read the candidate line ranges, decide which one matches the picked element from page context, and write the wrapper manually per the fallback flow.-Output on success: `{ file, insertLine, commentSyntax }`.+Output on success: `{ file, insertLine, commentSyntax, styleMode, styleTag, cssSelectorPrefixExamples, cssAuthoring }`.++`styleMode` controls how preview CSS must be authored. Treat it as a detected capability mode, not a framework guess:++- `scoped`: use `@scope ([data-impeccable-variant="N"])` rules.+- `astro-global-prefixed`: use explicit `[data-impeccable-variant="N"]` selector prefixes and the exact `styleTag` returned by the tool.++Use `cssAuthoring` as the source of truth for the current file. It includes the exact `styleTag`, selector strategy, selector examples, requirements, and forbidden patterns. Do not apply a framework-specific exception unless the returned `styleMode` / `cssAuthoring.mode` says to.**Fallback errors.** Wrap only writes into files it judges to be source (tracked by git, not marked GENERATED, not listed in config's `generatedFiles`). If it can't land on a source file, it errors without writing; accepting a variant into a generated file is silent data loss. Three shapes:@@ -208,13 +234,14 @@ When the prompt and PRODUCT.md anti-references conflict (the prompt asks for X,Complete 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 scoped 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).+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).++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:```html<!-- Variants: insert below this line --><style data-impeccable-css="SESSION_ID">- @scope ([data-impeccable-variant="1"]) { ... }- @scope ([data-impeccable-variant="2"]) { ... }+ /* rules matching cssAuthoring.rulePattern */</style><div data-impeccable-variant="1"><!-- variant 1: full element replacement (single top-level element) -->@@ -229,11 +256,11 @@ Write CSS + all variants in ONE edit at the `insertLine` reported by `wrap`. Col**Each variant div contains exactly one top-level element: the full replacement for the original.** Use the same tag as the original (e.g. `<section>` if the user picked a `<section>`). Loose siblings (heading + paragraph + div as direct children of the variant div) break the outline tracking and the accept flow, which both assume one child.-The first variant has no `display: none` (visible by default). All others do. If variants use only inline styles and no scoped CSS, omit the `<style>` tag entirely. Use `@scope` for CSS isolation (Chrome 118+ / Firefox 128+ / Safari 17.4+).+The 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.-**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 rule starts `:scope > ...`.+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 > ...`.**JSX / TSX target files.** Wrap `<style>` content in a template literal so the CSS `{` / `}` aren't parsed as JSX expressions, and use `className=` / `style={{…}}` on every variant element. Keep `data-impeccable-*` attributes as-is; they're plain strings:@@ -369,10 +396,11 @@ Remove the wrapper you inserted in Step 2. Nothing else to do.## Handle `accept`-Event: `{id, variantId, _acceptResult}`. The poll script already ran `live-accept.mjs` to handle the file operation deterministically; the browser DOM is already updated.+Event: `{id, variantId, _acceptResult, _completionAck}`. The poll script already ran `live-accept.mjs` to handle the file operation deterministically, then acknowledged event delivery to the helper. The browser DOM is already updated.+- `_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 and a stderr banner both list the steps explicitly; neither is decorative.+- `_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: 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` without `mode`: manual cleanup: read file, find markers, edit.@@ -388,13 +416,13 @@ Do these five steps in the current thread, synchronously, before the next poll.4. **Unwrap the accepted content.** Delete the `<div data-impeccable-variant="N" style="display: contents">` that wraps it. Drop `data-impeccable-params` and any `data-p-*` attributes from it; 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.-Then poll again.+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.## Handle `discard`-Event: `{id, _acceptResult}`. The poll script already restored the original and removed all variant markers. Nothing to do. Poll again.+Event: `{id, _acceptResult, _completionAck}`. The poll script already restored the original, removed all variant markers, and acknowledged `discarded` durable completion. Nothing to do unless `_completionAck.ok !== true`; in that case run `live-complete.mjs --id EVENT_ID --discarded`, then poll again.## Handle `prefetch`@@ -424,7 +452,7 @@ When the poll returns `exit`, proceed to cleanup. If the poll is still running anode .rovodev/skills/impeccable/scripts/live-server.mjs stop```-Stops the HTTP server and runs `live-inject.mjs --remove` to strip `localhost:…/live.js` from the HTML entry. To stop the server but keep the inject tag (for a quick restart), use `stop --keep-inject`. `config.json` persists for future sessions.+Stops the HTTP server and runs `live-inject.mjs --remove` to strip `localhost:…/live.js` from the HTML entry. To stop the server but keep the inject tag (for a quick restart), use `stop --keep-inject`. `.impeccable/live/config.json` persists as project config for future sessions.Then:- Remove any leftover variant wrappers (search for `impeccable-variants-start` markers).@@ -432,7 +460,7 @@ Then:## First-time setup (config missing or invalid)-If `live.mjs` outputs `{ ok: false, error: "config_missing" | "config_invalid", path }`, write `config.json` at the reported path.+If `live.mjs` outputs `{ ok: false, error: "config_missing" | "config_invalid", path }`, write the live config at the reported path. By default this is `.impeccable/live/config.json`.Schema:@@ -512,7 +540,7 @@ node .rovodev/skills/impeccable/scripts/detect-csp.mjsOutput: `{ shape, signals }` where `shape` is one of `append-arrays`, `append-string`, `middleware`, `meta-tag`, or `null`. The shape is named by *patch mechanism*, so one template covers many frameworks.-- **`null`**: no CSP; skip to writing `config.json` with `cspChecked: true`.+- **`null`**: no CSP; skip to writing `.impeccable/live/config.json` with `cspChecked: true`.- **`append-arrays`**: CSP defined as structured directive arrays. Auto-patchable. See *append-arrays* below. Covers:- Monorepo helpers with `additionalScriptSrc` / `additionalConnectSrc` options (Next.js + shared config package)- SvelteKit `kit.csp.directives`@@ -589,6 +617,6 @@ Reference outputs:### Troubleshooting-If a user says "no" to the CSP patch at setup time and later complains that live doesn't work: their dev CSP blocks `http://localhost:8400`. Fix: delete `cspChecked` from `config.json` and re-run `live.mjs`: setup will ask again.+If a user says "no" to the CSP patch at setup time and later complains that live doesn't work: their dev CSP blocks `http://localhost:8400`. Fix: delete `cspChecked` from `.impeccable/live/config.json` and re-run `live.mjs`: setup will ask again.Then re-run `live.mjs`.diff --git a/.rovodev/skills/impeccable/reference/teach.md b/.rovodev/skills/impeccable/reference/teach.mdindex bca7c3f3e..4b45f28d2 100644--- a/.rovodev/skills/impeccable/reference/teach.md+++ b/.rovodev/skills/impeccable/reference/teach.md@@ -2,8 +2,8 @@Gathers design context for a project and writes two complementary files at the project root:-- **PRODUCT.md** (strategic): register, target users, product purpose, brand personality, anti-references, strategic design principles. Answers "who/what/why".-- **DESIGN.md** (visual): visual theme, color palette, typography, components, layout. Follows the [Google Stitch DESIGN.md format](https://stitch.withgoogle.com/docs/design-md/format/). Answers "how it looks".+- **PRODUCT.md** (strategic): root project file for register, target users, product purpose, brand personality, anti-references, strategic design principles. Answers "who/what/why".+- **DESIGN.md** (visual): root project file for visual theme, color palette, typography, components, layout. Follows the [Google Stitch DESIGN.md format](https://stitch.withgoogle.com/docs/design-md/format/). Answers "how it looks".Every other impeccable command reads these files before doing any work.diff --git a/.rovodev/skills/impeccable/scripts/impeccable-paths.mjs b/.rovodev/skills/impeccable/scripts/impeccable-paths.mjsnew file mode 100644index 000000000..ba852bae9--- /dev/null+++ b/.rovodev/skills/impeccable/scripts/impeccable-paths.mjs@@ -0,0 +1,105 @@+import fs from 'node:fs';+import path from 'node:path';++export const IMPECCABLE_DIR = '.impeccable';+export const LIVE_DIR = 'live';++export function getImpeccableDir(cwd = process.cwd()) {+ return path.join(cwd, IMPECCABLE_DIR);+}++export function getDesignSidecarPath(cwd = process.cwd()) {+ return path.join(getImpeccableDir(cwd), 'design.json');+}++export function getDesignSidecarCandidates(cwd = process.cwd(), contextDir = cwd) {+ const candidates = [+ getDesignSidecarPath(cwd),+ path.join(cwd, 'DESIGN.json'),+ ];+ const contextLegacy = path.join(contextDir, 'DESIGN.json');+ if (!candidates.includes(contextLegacy)) candidates.push(contextLegacy);+ return candidates;+}++export function resolveDesignSidecarPath(cwd = process.cwd(), contextDir = cwd) {+ return firstExisting(getDesignSidecarCandidates(cwd, contextDir));+}++export function getLiveDir(cwd = process.cwd()) {+ return path.join(getImpeccableDir(cwd), LIVE_DIR);+}++export function getLiveConfigPath(cwd = process.cwd()) {+ return path.join(getLiveDir(cwd), 'config.json');+}++export function getLegacyLiveConfigPath(scriptsDir) {+ return path.join(scriptsDir, 'config.json');+}++export function resolveLiveConfigPath({ cwd = process.cwd(), scriptsDir, env = process.env } = {}) {+ if (env.IMPECCABLE_LIVE_CONFIG && env.IMPECCABLE_LIVE_CONFIG.trim()) {+ const configured = env.IMPECCABLE_LIVE_CONFIG.trim();+ return path.isAbsolute(configured) ? configured : path.resolve(cwd, configured);+ }+ const primary = getLiveConfigPath(cwd);+ if (fs.existsSync(primary)) return primary;+ if (scriptsDir) {+ const legacy = getLegacyLiveConfigPath(scriptsDir);+ if (fs.existsSync(legacy)) return legacy;+ }+ return primary;+}++export function getLiveServerPath(cwd = process.cwd()) {+ return path.join(getLiveDir(cwd), 'server.json');+}++export function getLegacyLiveServerPath(cwd = process.cwd()) {+ return path.join(cwd, '.impeccable-live.json');+}++export function readLiveServerInfo(cwd = process.cwd()) {+ for (const filePath of [getLiveServerPath(cwd), getLegacyLiveServerPath(cwd)]) {+ try {+ return { info: JSON.parse(fs.readFileSync(filePath, 'utf-8')), path: filePath };+ } catch {+ /* try next */+ }+ }+ return null;+}++export function writeLiveServerInfo(cwd = process.cwd(), info) {+ const filePath = getLiveServerPath(cwd);+ fs.mkdirSync(path.dirname(filePath), { recursive: true });+ fs.writeFileSync(filePath, JSON.stringify(info));+ return filePath;+}++export function removeLiveServerInfo(cwd = process.cwd()) {+ for (const filePath of [getLiveServerPath(cwd), getLegacyLiveServerPath(cwd)]) {+ try { fs.unlinkSync(filePath); } catch {}+ }+}++export function getLiveSessionsDir(cwd = process.cwd()) {+ return path.join(getLiveDir(cwd), 'sessions');+}++export function getLegacyLiveSessionsDir(cwd = process.cwd()) {+ return path.join(cwd, '.impeccable-live', 'sessions');+}++export function getLiveAnnotationsDir(cwd = process.cwd()) {+ return path.join(getLiveDir(cwd), 'annotations');+}++export function getLegacyLiveAnnotationsDir(cwd = process.cwd()) {+ return path.join(cwd, '.impeccable-live', 'annotations');+}++function firstExisting(paths) {+ return paths.find((filePath) => fs.existsSync(filePath)) || null;+}diff --git a/.rovodev/skills/impeccable/scripts/live-browser-session.js b/.rovodev/skills/impeccable/scripts/live-browser-session.jsnew file mode 100644index 000000000..0e362d6be--- /dev/null+++ b/.rovodev/skills/impeccable/scripts/live-browser-session.js@@ -0,0 +1,123 @@+/**+ * Browser-side durable session helpers for Impeccable live mode.+ *+ * Kept separate from live-browser.js so recovery state can be tested without+ * booting the full overlay UI. Served before live-browser.js and attached to+ * window.__IMPECCABLE_LIVE_SESSION__.+ */+(function (root) {+ 'use strict';++ function createLiveBrowserSessionState({ prefix, storage, idFactory }) {+ if (!prefix) throw new Error('prefix required');+ const store = storage || root.localStorage;+ const makeId = idFactory || function () { return Math.random().toString(16).slice(2, 10); };+ const sessionKey = prefix + '-session';+ const handledKey = sessionKey + '-handled';+ const scrollKey = sessionKey + '-scroll';+ let checkpointRevision = 0;+ const owner = makeId();++ function safeRead(key) {+ try { return store.getItem(key); } catch { return null; }+ }++ function safeWrite(key, value) {+ try { store.setItem(key, value); } catch { /* quota exceeded or private mode */ }+ }++ function safeRemove(key) {+ try { store.removeItem(key); } catch { /* unavailable storage */ }+ }++ function loadSession() {+ try {+ const raw = safeRead(sessionKey);+ if (!raw) return null;+ const parsed = JSON.parse(raw);+ if (Number.isInteger(parsed.checkpointRevision)) {+ checkpointRevision = Math.max(checkpointRevision, parsed.checkpointRevision);+ }+ return parsed;+ } catch { return null; }+ }++ function saveSession(session) {+ if (!session || !session.id) return;+ const payload = {+ ...session,+ checkpointRevision,+ };+ safeWrite(sessionKey, JSON.stringify(payload));+ }++ function clearSession() {+ safeRemove(sessionKey);+ }++ function nextCheckpointRevision() {+ checkpointRevision += 1;+ const existing = loadSession();+ if (existing?.id) saveSession(existing);+ return checkpointRevision;+ }++ function seedCheckpointRevision(value) {+ if (Number.isInteger(value)) checkpointRevision = Math.max(checkpointRevision, value);+ return checkpointRevision;+ }++ function currentCheckpointRevision() {+ return checkpointRevision;+ }++ function markHandled(id) {+ if (!id) return;+ safeWrite(handledKey, id);+ }++ function isHandled(id) {+ return !!id && safeRead(handledKey) === id;+ }++ function clearHandled() {+ safeRemove(handledKey);+ }++ function writeScrollY(y) {+ safeWrite(scrollKey, String(y));+ }++ function readScrollY() {+ const raw = safeRead(scrollKey);+ if (raw == null) return null;+ const n = parseFloat(raw);+ return isFinite(n) ? n : null;+ }++ function clearScrollY() {+ safeRemove(scrollKey);+ }++ return {+ owner,+ sessionKey,+ handledKey,+ scrollKey,+ saveSession,+ loadSession,+ clearSession,+ nextCheckpointRevision,+ seedCheckpointRevision,+ currentCheckpointRevision,+ markHandled,+ isHandled,+ clearHandled,+ writeScrollY,+ readScrollY,+ clearScrollY,+ };+ }++ root.__IMPECCABLE_LIVE_SESSION__ = { createLiveBrowserSessionState };+})(typeof window !== 'undefined' ? window : globalThis);diff --git a/.rovodev/skills/impeccable/scripts/live-browser.js b/.rovodev/skills/impeccable/scripts/live-browser.jsindex 3da76bb96..e67cd01ed 100644--- a/.rovodev/skills/impeccable/scripts/live-browser.js+++ b/.rovodev/skills/impeccable/scripts/live-browser.js@@ -50,6 +50,16 @@const Z = { highlight: 100001, bar: 100005, picker: 100007, toast: 100010 };const EASE = 'cubic-bezier(0.22, 1, 0.36, 1)'; // ease-out-quintconst PREFIX = 'impeccable-live';+ const sessionState = window.__IMPECCABLE_LIVE_SESSION__?.createLiveBrowserSessionState({+ prefix: PREFIX,+ storage: localStorage,+ idFactory: () => crypto.randomUUID().replace(/-/g, '').slice(0, 8),+ });+ if (!sessionState) {+ console.error('[impeccable] live-browser-session.js was not loaded. Live mode cannot start safely.');+ window.__IMPECCABLE_LIVE_INIT__ = false;+ return;+ }const HIGHLIGHT_TRANSITION ='top 140ms ' + EASE +', left 140ms ' + EASE +@@ -112,6 +122,8 @@let hasProjectContext = false;let selectedAction = 'impeccable';let selectedCount = 3;+ const browserOwner = sessionState.owner;+ let checkpointTimer = null;// Scroll lock — holds window.scrollY at a fixed value while the session is// active, so HMR DOM patches and variant swaps can't drift the page. See@@ -126,21 +138,9 @@// (Previously: saveSession wrote scrollY alongside state, so every call// during resume overwrote the pre-reload value with whatever the browser// had landed on, typically 0.)- const SCROLL_KEY_SUFFIX = '-scroll';- function writeScrollY(y) {- try { localStorage.setItem(LS_KEY + SCROLL_KEY_SUFFIX, String(y)); } catch {}- }- function readScrollY() {- try {- const raw = localStorage.getItem(LS_KEY + SCROLL_KEY_SUFFIX);- if (raw == null) return null;- const n = parseFloat(raw);- return isFinite(n) ? n : null;- } catch { return null; }- }- function clearScrollY() {- try { localStorage.removeItem(LS_KEY + SCROLL_KEY_SUFFIX); } catch {}- }+ function writeScrollY(y) { sessionState.writeScrollY(y); }+ function readScrollY() { return sessionState.readScrollY(); }+ function clearScrollY() { sessionState.clearScrollY(); }// Pre-empt the browser: apply manual scroll restoration and jump to the// saved scrollY at script-parse time. Retries on fonts.ready and load@@ -1585,6 +1585,7 @@paramsCurrentValues[p.id] = v;readout.textContent = formatRangeValue(input);applyParamValue(variantEl, p, v);+ queueCheckpoint('param_changed');});row.appendChild(input);} else if (p.kind === 'toggle') {@@ -1615,6 +1616,7 @@knob.style.left = next ? '18px' : '2px';readout.textContent = next ? 'On' : 'Off';applyParamValue(variantEl, p, next);+ queueCheckpoint('param_changed');});row.appendChild(track);} else if (p.kind === 'steps') {@@ -1651,6 +1653,7 @@btn.style.color = on ? 'oklch(98% 0 0)' : P.text;});applyParamValue(variantEl, p, o.value);+ queueCheckpoint('param_changed');});segRow.appendChild(b);segBtns.push({ btn: b, val: o.value });@@ -1872,19 +1875,26 @@return;}+ const previousVisibleVariant = currentSessionId === sessionId ? visibleVariant : 0;+// Replace the live element with the full wrapper from sourceconst wrapper = srcWrapper.cloneNode(true);liveEl.parentElement.replaceChild(wrapper, liveEl);- // Update state: count variants, show the first one+ // Update state: count variants, preserving the user's current variant+ // when a late HMR/source reinjection lands after they have cycled.const variants = wrapper.querySelectorAll('[data-impeccable-variant]:not([data-impeccable-variant="original"])');arrivedVariants = variants.length;expectedVariants = parseInt(wrapper.dataset.impeccableVariantCount || arrivedVariants);- visibleVariant = 1;- showVariantInDOM(sessionId, 1);+ const saved = loadSession();+ const savedVisibleVariant = saved && saved.id === sessionId ? saved.visible : 0;+ visibleVariant = previousVisibleVariant > 0 && previousVisibleVariant <= arrivedVariants+ ? previousVisibleVariant+ : (savedVisibleVariant > 0 && savedVisibleVariant <= arrivedVariants ? savedVisibleVariant : 1);+ showVariantInDOM(sessionId, visibleVariant);// Update selectedElement to the visible variant's content- selectedElement = pickVariantContent(wrapper, 1) || wrapper.parentElement;+ selectedElement = pickVariantContent(wrapper, visibleVariant) || wrapper.parentElement;state = 'CYCLING';hideShaderOverlay();@@ -1907,6 +1917,7 @@updateSelectedElement();updateBarContent('cycling');saveSession();+ queueCheckpoint('variant_changed');}function updateSelectedElement() {@@ -1917,6 +1928,18 @@if (visEl) selectedElement = visEl;}+ function readVisibleVariantFromDOM(sessionId) {+ const wrapper = document.querySelector('[data-impeccable-variants="' + sessionId + '"]');+ if (!wrapper) return 0;+ const variants = wrapper.querySelectorAll('[data-impeccable-variant]:not([data-impeccable-variant="original"])');+ for (const variant of variants) {+ if (variant.style.display === 'none') continue;+ const idx = parseInt(variant.dataset.impeccableVariant || '0', 10);+ if (idx > 0) return idx;+ }+ return 0;+ }+// Resolve the element that represents the variant's visible content.// Contract: each variant div should contain exactly one top-level element// (the full replacement). In practice a model may ship loose siblings or@@ -2107,8 +2130,10 @@updating = true;arrivedVariants = count;if (visibleVariant === 0 && arrivedVariants > 0) {- visibleVariant = 1;- showVariantInDOM(sessionId, 1);+ const saved = loadSession();+ const savedVisibleVariant = saved && saved.id === sessionId ? saved.visible : 0;+ visibleVariant = savedVisibleVariant > 0 && savedVisibleVariant <= arrivedVariants ? savedVisibleVariant : 1;+ showVariantInDOM(sessionId, visibleVariant);// showVariantInDOM hid the original (display:none); if we were still// anchored to the original's content, its boundingRect is now zero// and the bar snaps to (0,0). Re-point at the visible variant instead.@@ -2128,6 +2153,7 @@updateBarContent('generating');}saveSession();+ queueCheckpoint(state === 'CYCLING' ? 'variants_ready' : 'variants_progress');updating = false;});@@ -2236,6 +2262,7 @@/** Server died or became unreachable. Reset UI to a clean state. */function handleServerLost() {+ const recoveryState = currentSessionId ? state : 'IDLE';if (state === 'GENERATING' || state === 'CYCLING' || state === 'SAVING') {showToast('Live server disconnected. Session ended.', 5000);}@@ -2246,21 +2273,61 @@stopScrollTracking();if (variantObserver) { variantObserver.disconnect(); variantObserver = null; }stopScrollLock();- clearScrollY();- clearSession();+ // Preserve local session state on server loss. The durable journal is the+ // source of truth, but localStorage plus the variant wrapper lets the UI+ // resume after a helper restart or page reload instead of treating a+ // transient disconnect as an explicit discard.selectedElement = null;- currentSessionId = null;selectedAction = 'impeccable';- state = 'IDLE';+ state = recoveryState;+ if (currentSessionId) saveSession();}- function sendEvent(msg) {+ function sendEvent(msg, opts) {msg.token = TOKEN;- fetch('http://localhost:' + PORT + '/events', {+ function handleFailure(err) {+ console.error('[impeccable] Failed to send event:', err);+ if (opts && opts.throwOnError) throw err;+ return null;+ }+ return fetch('http://localhost:' + PORT + '/events', {method: 'POST',headers: { 'Content-Type': 'application/json' },body: JSON.stringify(msg),- }).catch(err => console.error('[impeccable] Failed to send event:', err));+ }).then(res => {+ if (res.ok) return res;+ return handleFailure(new Error('HTTP ' + res.status + ' ' + res.statusText));+ }).catch(handleFailure);+ }++ function checkpointPayload(reason) {+ return {+ type: 'checkpoint',+ id: currentSessionId,+ revision: sessionState.nextCheckpointRevision(),+ owner: browserOwner,+ phase: String(state || '').toLowerCase(),+ reason,+ pageUrl: location.pathname,+ expectedVariants,+ arrivedVariants,+ visibleVariant,+ paramValues: { ...paramsCurrentValues },+ };+ }++ function sendCheckpoint(reason) {+ if (!currentSessionId) return Promise.resolve(null);+ return sendEvent(checkpointPayload(reason)).catch(() => null);+ }++ function queueCheckpoint(reason) {+ if (!currentSessionId) return;+ if (checkpointTimer) clearTimeout(checkpointTimer);+ checkpointTimer = setTimeout(() => {+ checkpointTimer = null;+ sendCheckpoint(reason);+ }, 120);}// ---------------------------------------------------------------------------@@ -2496,6 +2563,7 @@state = 'GENERATING';showBar('generating');saveSession();+ sendCheckpoint('generate_started');writeScrollY(window.scrollY);if (variantObserver) variantObserver.disconnect();variantObserver = startVariantObserver(currentSessionId);@@ -2920,13 +2988,12 @@ void main() {function handleAccept() {if (!currentSessionId || arrivedVariants === 0) return;+ const domVisibleVariant = readVisibleVariantFromDOM(currentSessionId);+ if (domVisibleVariant > 0) visibleVariant = domVisibleVariant;const acceptPayload = { type: 'accept', id: currentSessionId, variantId: String(visibleVariant) };if (Object.keys(paramsCurrentValues).length > 0) {acceptPayload.paramValues = { ...paramsCurrentValues };}- sendEvent(acceptPayload);- markSessionHandled();-// The accepted variant is already the only visible child of the wrapper// (all other variants are display:none). HMR from the source rewrite will// replace the wrapper imminently. Don't eagerly replaceChild here — React@@ -2936,9 +3003,28 @@ void main() {const acceptedSessionId = currentSessionId;const acceptedVariant = visibleVariant;- state = 'CONFIRMED';- updateBarContent('confirmed');- setTimeout(function() {+ state = 'SAVING';+ updateBarContent('saving');++ sendEvent(acceptPayload, { throwOnError: true })+ .then(() => {+ markSessionHandled();+ confirmAcceptAfterReceipt();+ })+ .catch(() => {+ state = 'CYCLING';+ updateBarContent('cycling');+ showToast('Could not confirm accept with the live server. Session kept for recovery; try Accept again.', 5000);+ });++ function confirmAcceptAfterReceipt() {+ state = 'CONFIRMED';+ updateBarContent('confirmed');+ scheduleAcceptCleanup();+ }++ function scheduleAcceptCleanup() {+ setTimeout(function() {hideBar();hideHighlight();stopScrollTracking();@@ -2967,50 +3053,46 @@ void main() {accepted.style.display = 'contents';parent.replaceChild(accepted, wrapper);}- }, 2000);+ }, 2000);+ }}function handleDiscard() {if (!currentSessionId) return;- sendEvent({ type: 'discard', id: currentSessionId });- markSessionHandled();- // Instant DOM restore + fire-and-forget (script handles file cleanup)- cleanup();+ sendEvent({ type: 'discard', id: currentSessionId }, { throwOnError: true })+ .then(() => {+ markSessionHandled();+ cleanup();+ })+ .catch(() => showToast('Could not confirm discard with the live server. Session kept for recovery.', 5000));}// ---------------------------------------------------------------------------- // Session persistence via localStorage+ // Session persistence via live-browser-session.js// ---------------------------------------------------------------------------// Survives page reloads, browser close/reopen, HMR, and accidental refreshes.- const LS_KEY = PREFIX + '-session';-function saveSession() {if (!currentSessionId) return;// NOTE: scrollY is stored under a separate key (writeScrollY). Storing// it here would overwrite the Go-time value every time state changes.- try {- localStorage.setItem(LS_KEY, JSON.stringify({- id: currentSessionId,- state: state,- action: selectedAction,- count: selectedCount,- expected: expectedVariants,- arrived: arrivedVariants,- visible: visibleVariant,- }));- } catch { /* quota exceeded or private mode */ }+ sessionState.saveSession({+ id: currentSessionId,+ state,+ action: selectedAction,+ count: selectedCount,+ expected: expectedVariants,+ arrived: arrivedVariants,+ visible: visibleVariant,+ });}function loadSession() {- try {- const raw = localStorage.getItem(LS_KEY);- return raw ? JSON.parse(raw) : null;- } catch { return null; }+ return sessionState.loadSession();}function clearSession() {- try { localStorage.removeItem(LS_KEY); } catch {}+ sessionState.clearSession();}/** Mark session as handled (accepted/discarded). The agent will clean up@@ -3018,19 +3100,15 @@ void main() {* prevents resumeSession from picking it up again after reload. */function markSessionHandled() {if (!currentSessionId) return;- try {- localStorage.setItem(LS_KEY + '-handled', currentSessionId);- } catch {}+ sessionState.markHandled(currentSessionId);}function isSessionHandled(id) {- try {- return localStorage.getItem(LS_KEY + '-handled') === id;- } catch { return false; }+ return sessionState.isHandled(id);}function clearHandled() {- try { localStorage.removeItem(LS_KEY + '-handled'); } catch {}+ sessionState.clearHandled();}function cleanup() {@@ -3161,6 +3239,7 @@ void main() {// hid. Now that state is CYCLING, re-fire.if (state === 'CYCLING') refreshParamsPanel();saveSession();+ queueCheckpoint('browser_resumed');// Start observing for more variants AFTER initial setupif (variantObserver) variantObserver.disconnect();@@ -3617,7 +3696,7 @@ void main() {}// ---------------------------------------------------------------------------- // Design System Panel — visualizes the project's DESIGN.json sidecar+ // Design System Panel — visualizes the project's .impeccable/design.json sidecar// ---------------------------------------------------------------------------const DESIGN_PREFS_KEY = 'impeccable-live-design-panel';@@ -3629,7 +3708,7 @@ void main() {open: false,tab: 'visual', // 'visual' | 'raw'parsed: null, // parseDesignMd output (frontmatter + body sections)- sidecar: null, // DESIGN.json v2 payload (extensions + components + narrative)+ sidecar: null, // .impeccable/design.json v2 payload (extensions + components + narrative)hasMd: false,hasSidecar: false,present: null, // true/false once fetch resolves@@ -4130,7 +4209,7 @@ void main() {box.className = 'stale';box.innerHTML = `<span class="stale-dot"></span>- <span class="stale-text"><strong>DESIGN.md is newer than DESIGN.json.</strong> Run <code>/impeccable document</code> to refresh the sidecar.</span>+ <span class="stale-text"><strong>DESIGN.md is newer than .impeccable/design.json.</strong> Run <code>/impeccable document</code> to refresh the sidecar.</span>`;return box;}@@ -4138,7 +4217,7 @@ void main() {function renderParsedMdCta() {const box = document.createElement('div');box.className = 'parsed-md-cta';- box.innerHTML = `<strong>Basic view</strong>This panel reads the tokens in your <code>DESIGN.md</code> frontmatter. Running <code>/impeccable document</code> also generates a <code>DESIGN.json</code> sidecar with your project's actual component snippets (button, input, nav) and tonal ramps, rendered live below the tokens.`;+ box.innerHTML = `<strong>Basic view</strong>This panel reads the tokens in your <code>DESIGN.md</code> frontmatter. Running <code>/impeccable document</code> also generates a <code>.impeccable/design.json</code> sidecar with your project's actual component snippets (button, input, nav) and tonal ramps, rendered live below the tokens.`;return box;}@@ -4598,7 +4677,7 @@ void main() {function cssSafe(v) {// Strip anything outside valid CSS value chars to prevent injection via- // DESIGN.json values rendered into inline style strings.+ // .impeccable/design.json values rendered into inline style strings.return String(v).replace(/[<>"'`\n]/g, '');}diff --git a/.rovodev/skills/impeccable/scripts/live-complete.mjs b/.rovodev/skills/impeccable/scripts/live-complete.mjsnew file mode 100644index 000000000..78155af85--- /dev/null+++ b/.rovodev/skills/impeccable/scripts/live-complete.mjs@@ -0,0 +1,75 @@+#!/usr/bin/env node+/**+ * Canonical durable completion acknowledgement for Impeccable live sessions.+ */++import { createLiveSessionStore } from './live-session-store.mjs';+import { readLiveServerInfo } from './impeccable-paths.mjs';++function parseArgs(argv) {+ const out = { status: 'complete' };+ for (let i = 0; i < argv.length; i++) {+ const arg = argv[i];+ if (arg === '--id') out.id = argv[++i];+ else if (arg.startsWith('--id=')) out.id = arg.slice('--id='.length);+ else if (arg === '--discarded' || arg === '--discard') out.status = 'discarded';+ else if (arg === '--error') { out.status = 'agent_error'; out.message = argv[++i] || 'unknown error'; }+ else if (arg.startsWith('--error=')) { out.status = 'agent_error'; out.message = arg.slice('--error='.length); }+ else if (arg === '--help' || arg === '-h') out.help = true;+ }+ return out;+}++export async function completeCli() {+ const args = parseArgs(process.argv.slice(2));+ if (args.help || !args.id) {+ console.log(`Usage: node live-complete.mjs --id SESSION_ID [--discarded|--error MESSAGE]\n\nAppend the final durable session acknowledgement. Use after accept/discard cleanup is verified.`);+ process.exit(args.help ? 0 : 1);+ }++ const serverInfo = readServerInfo();+ const serverResult = serverInfo ? await completeThroughServer(serverInfo, args) : null;+ if (serverResult?.ok) {+ const store = createLiveSessionStore({ cwd: process.cwd(), sessionId: args.id });+ const snapshot = store.getSnapshot(args.id, { includeCompleted: true });+ console.log(JSON.stringify({ ok: true, id: args.id, phase: snapshot?.phase || args.status, snapshot }, null, 2));+ return;+ }++ const store = createLiveSessionStore({ cwd: process.cwd(), sessionId: args.id });+ const event = args.status === 'discarded'+ ? { type: 'discarded', id: args.id }+ : args.status === 'agent_error'+ ? { type: 'agent_error', id: args.id, message: args.message || 'unknown error' }+ : { type: 'complete', id: args.id };+ const snapshot = store.appendEvent(event);+ console.log(JSON.stringify({ ok: true, id: args.id, phase: snapshot.phase, snapshot }, null, 2));+}++function readServerInfo() {+ return readLiveServerInfo(process.cwd())?.info || null;+}++async function completeThroughServer(info, args) {+ const type = args.status === 'discarded'+ ? 'discarded'+ : args.status === 'agent_error'+ ? 'error'+ : 'complete';+ try {+ const res = await fetch(`http://localhost:${info.port}/poll`, {+ method: 'POST',+ headers: { 'Content-Type': 'application/json' },+ body: JSON.stringify({ token: info.token, id: args.id, type, message: args.message }),+ });+ if (!res.ok) return null;+ return await res.json();+ } catch {+ return null;+ }+}++const _running = process.argv[1];+if (_running?.endsWith('live-complete.mjs') || _running?.endsWith('live-complete.mjs/')) {+ completeCli();+}diff --git a/.rovodev/skills/impeccable/scripts/live-completion.mjs b/.rovodev/skills/impeccable/scripts/live-completion.mjsnew file mode 100644index 000000000..86b637fff--- /dev/null+++ b/.rovodev/skills/impeccable/scripts/live-completion.mjs@@ -0,0 +1,18 @@+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';+ return 'agent_done';+}++export function completionAckForAcceptResult(eventId, completionType, acceptResult) {+ const ack = { ok: true, type: completionType };+ if (acceptResult?.handled === true && acceptResult?.carbonize === true) {+ ack.final = false;+ ack.requiresComplete = true;+ ack.nextCommand = `live-complete.mjs --id ${eventId}`;+ ack.message = 'Carbonize cleanup must be verified, then the session must be completed explicitly before polling again.';+ }+ return ack;+}diff --git a/.rovodev/skills/impeccable/scripts/live-inject.mjs b/.rovodev/skills/impeccable/scripts/live-inject.mjsindex 1d2ae12f7..555c3a36a 100644--- a/.rovodev/skills/impeccable/scripts/live-inject.mjs+++ b/.rovodev/skills/impeccable/scripts/live-inject.mjs@@ -2,23 +2,24 @@* CLI helper: insert/remove the live variant mode script tag in the project's* main HTML entry point.*- * On first live run, the agent generates `config.json` in this script's- * directory with the project's insertion target (framework-specific). On+ * On first live run, the agent generates `.impeccable/live/config.json`+ * with the project's insertion target (framework-specific). On* every subsequent run, this script handles insert/remove deterministically* with zero LLM involvement.** Usage:* node live-inject.mjs --port PORT # Insert the live script tag* node live-inject.mjs --remove # Remove the live script tag- * node live-inject.mjs --check # Check whether config.json exists+ * node live-inject.mjs --check # Check whether live config exists*/import fs from 'node:fs';import path from 'node:path';import { fileURLToPath } from 'node:url';+import { resolveLiveConfigPath } from './impeccable-paths.mjs';const __dirname = path.dirname(fileURLToPath(import.meta.url));-const CONFIG_PATH = process.env.IMPECCABLE_LIVE_CONFIG || path.join(__dirname, 'config.json');+const CONFIG_PATH = resolveLiveConfigPath({ cwd: process.cwd(), scriptsDir: __dirname });const MARKER_OPEN_TEXT = 'impeccable-live-start';const MARKER_CLOSE_TEXT = 'impeccable-live-end';@@ -39,12 +40,12 @@ export async function injectCli() {console.log(`Usage: node live-inject.mjs [options]Insert or remove the live mode script tag in the project's HTML entry point.-Reads configuration from config.json (in this same directory).+Reads configuration from .impeccable/live/config.json.Modes:--port PORT Insert script tag pointing at http://localhost:PORT/live.js--remove Remove the script tag (if present)- --check Print whether config.json exists and its content+ --check Print whether .impeccable/live/config.json exists and its contentOutput (JSON):{ ok, file, inserted|removed, config? }`);diff --git a/.rovodev/skills/impeccable/scripts/live-poll.mjs b/.rovodev/skills/impeccable/scripts/live-poll.mjsindex eb8f1586a..10d452491 100644--- a/.rovodev/skills/impeccable/scripts/live-poll.mjs+++ b/.rovodev/skills/impeccable/scripts/live-poll.mjs@@ -9,10 +9,10 @@*/import { execFileSync } from 'node:child_process';-import fs from 'node:fs';import path from 'node:path';-import os from 'node:os';import { fileURLToPath } from 'node:url';+import { completionAckForAcceptResult, completionTypeForAcceptResult } from './live-completion.mjs';+import { readLiveServerInfo } from './impeccable-paths.mjs';// Node's built-in fetch (undici under the hood) enforces a 300s headers// timeout that can't be lowered per-request. We cap each request below@@ -20,15 +20,29 @@ import { fileURLToPath } from 'node:url';// depending on the standalone undici package.const PER_REQUEST_TIMEOUT_MS = 270_000;-const LIVE_PID_FILE = path.join(process.cwd(), '.impeccable-live.json');-function readServerInfo() {- try {- return JSON.parse(fs.readFileSync(LIVE_PID_FILE, 'utf-8'));- } catch {+ const record = readLiveServerInfo(process.cwd());+ if (!record) {console.error('No running live server found. Start one with: npx impeccable live');process.exit(1);}+ return record.info;+}++export function buildPollReplyPayload(token, { id, type, message, file, data }) {+ return { token, id, type, message, file, data };+}++async function postReply(base, token, reply) {+ const res = await fetch(`${base}/poll`, {+ method: 'POST',+ headers: { 'Content-Type': 'application/json' },+ body: JSON.stringify(buildPollReplyPayload(token, reply)),+ });+ if (!res.ok) {+ const body = await res.json().catch(() => ({}));+ throw new Error(body.error || res.statusText);+ }}export async function pollCli() {@@ -69,23 +83,7 @@ Options:}try {- const res = await fetch(`${base}/poll`, {- method: 'POST',- headers: { 'Content-Type': 'application/json' },- body: JSON.stringify({- token: info.token,- id,- type: status,- message,- file: filePath,- }),- });-- if (!res.ok) {- const body = await res.json().catch(() => ({}));- console.error(`Reply failed (${res.status}):`, body.error || res.statusText);- process.exit(1);- }+ await postReply(base, info.token, { id, type: status, message, file: filePath });// Success — silent exit (agent doesn't need output for replies)} catch (err) {@@ -156,7 +154,23 @@ Options:);event._acceptResult = JSON.parse(out.trim());} catch (err) {- event._acceptResult = { handled: false, error: err.message };+ event._acceptResult = { handled: false, mode: 'error', error: err.message };+ }++ const completionType = completionTypeForAcceptResult(event.type, event._acceptResult);+ try {+ await postReply(base, info.token, {+ id: event.id,+ type: completionType,+ message: event._acceptResult?.error,+ file: event._acceptResult?.file,+ data: event._acceptResult?.carbonize === true ? { carbonize: true } : undefined,+ });+ } catch (err) {+ event._completionAck = { ok: false, error: err.message };+ }+ if (!event._completionAck) {+ event._completionAck = completionAckForAcceptResult(event.id, completionType, event._acceptResult);}}@@ -164,7 +178,7 @@ Options:// JSON but skips nested fields. One line is enough — the full checklist// is in reference/live.md.if (event._acceptResult?.carbonize === true) {- process.stderr.write('\n⚠ Carbonize cleanup REQUIRED before next poll. See reference/live.md "Required after accept".\n\n');+ process.stderr.write('\n⚠ Carbonize cleanup REQUIRED before next poll. After cleanup, run live-complete.mjs --id ' + event.id + '. See reference/live.md "Required after accept".\n\n');}// Print the event as JSON — the agent reads this from stdoutdiff --git a/.rovodev/skills/impeccable/scripts/live-resume.mjs b/.rovodev/skills/impeccable/scripts/live-resume.mjsnew file mode 100644index 000000000..a3465c9b5--- /dev/null+++ b/.rovodev/skills/impeccable/scripts/live-resume.mjs@@ -0,0 +1,48 @@+#!/usr/bin/env node+/**+ * Recover the next agent action from the durable live-session journal.+ */++import { createLiveSessionStore } from './live-session-store.mjs';++function parseArgs(argv) {+ const out = { id: null };+ for (let i = 0; i < argv.length; i++) {+ const arg = argv[i];+ if (arg === '--id') out.id = argv[++i];+ else if (arg.startsWith('--id=')) out.id = arg.slice('--id='.length);+ else if (arg === '--help' || arg === '-h') out.help = true;+ }+ return out;+}++export async function resumeCli() {+ const args = parseArgs(process.argv.slice(2));+ if (args.help) {+ console.log(`Usage: node live-resume.mjs [--id SESSION_ID]\n\nPrint the active durable session checkpoint and the next safe agent action.`);+ return;+ }++ const store = createLiveSessionStore({ cwd: process.cwd(), sessionId: args.id || undefined });+ const snapshot = args.id ? store.getSnapshot(args.id) : store.listActiveSessions()[0] || null;+ if (!snapshot) {+ console.log(JSON.stringify({ active: false, nextAction: 'No active durable live session found.' }, null, 2));+ return;+ }++ const pending = snapshot.pendingEvent || null;+ const nextAction = pending+ ? `Run live-poll.mjs, handle ${pending.type} ${pending.id}, then acknowledge with live-poll.mjs --reply ${pending.id} done.`+ : snapshot.phase === 'carbonize_required'+ ? `Finish carbonize cleanup${snapshot.sourceFile ? ` in ${snapshot.sourceFile}` : ''}, then run live-complete.mjs --id ${snapshot.id}.`+ : snapshot.phase === 'accept_requested'+ ? `Run live-complete.mjs --id ${snapshot.id} after verifying the accepted variant is written.`+ : `Inspect ${snapshot.id}; no pending agent event is currently queued.`;++ console.log(JSON.stringify({ active: true, snapshot, pendingEvent: pending, nextAction }, null, 2));+}++const _running = process.argv[1];+if (_running?.endsWith('live-resume.mjs') || _running?.endsWith('live-resume.mjs/')) {+ resumeCli();+}diff --git a/.rovodev/skills/impeccable/scripts/live-server.mjs b/.rovodev/skills/impeccable/scripts/live-server.mjsindex 90614fbf7..53d8f21cb 100644--- a/.rovodev/skills/impeccable/scripts/live-server.mjs+++ b/.rovodev/skills/impeccable/scripts/live-server.mjs@@ -22,14 +22,20 @@ import net from 'node:net';import { fileURLToPath } from 'node:url';import { parseDesignMd } from './design-parser.mjs';import { resolveContextDir } from './load-context.mjs';+import { createLiveSessionStore } from './live-session-store.mjs';+import {+ getDesignSidecarPath,+ getLiveAnnotationsDir,+ readLiveServerInfo,+ removeLiveServerInfo,+ resolveDesignSidecarPath,+ writeLiveServerInfo,+} from './impeccable-paths.mjs';const __dirname = path.dirname(fileURLToPath(import.meta.url));-// PID file in the project root so both the server and agent can find it-// predictably (os.tmpdir() varies across platforms).-const LIVE_PID_FILE = path.join(process.cwd(), '.impeccable-live.json');-// PRODUCT.md / DESIGN.md / DESIGN.json live wherever load-context.mjs resolves.-// Keeps live-server in sync with the loader when users keep the docs in-// .agents/context/, docs/, or a path set via IMPECCABLE_CONTEXT_DIR.+// PRODUCT.md / DESIGN.md live wherever load-context.mjs resolves. The generated+// DESIGN sidecar is project-local at .impeccable/design.json, with legacy+// DESIGN.json fallback for existing projects.const CONTEXT_DIR = resolveContextDir(process.cwd());const DEFAULT_POLL_TIMEOUT = 600_000; // 10 min — agent re-polls on timeout anywayconst SSE_HEARTBEAT_INTERVAL = 30_000; // keepalive ping every 30s@@ -57,10 +63,12 @@ const state = {token: null,port: null,sseClients: new Set(), // SSE response objects (server→browser push)- pendingEvents: [], // browser events waiting for agent poll+ pendingEvents: [], // browser events waiting for agent ack ({ event, leaseUntil })pendingPolls: [], // agent poll callbacks waiting for browser eventsexitTimer: null,sessionDir: null, // per-session tmp dir for annotation screenshots+ sessionStore: null,+ leaseTimer: null,};// Cap per-annotation upload size. A full 1920×1080 PNG is typically <1 MB;@@ -68,11 +76,70 @@ const state = {const MAX_ANNOTATION_BYTES = 10 * 1024 * 1024;function enqueueEvent(event) {- if (state.pendingPolls.length > 0) {- state.pendingPolls.shift()(event);- } else {- state.pendingEvents.push(event);+ if (!event || (event.id && state.pendingEvents.some((entry) => entry.event?.id === event.id && entry.event?.type === event.type))) return;+ state.pendingEvents.push({ event, leaseUntil: 0 });+ flushPendingPolls();+}++function restorePendingEventsFromStore() {+ if (!state.sessionStore) return;+ for (const snapshot of state.sessionStore.listActiveSessions()) {+ if (snapshot.pendingEvent) enqueueEvent(snapshot.pendingEvent);+ }+}++function findAvailablePendingEvent(now = Date.now()) {+ return state.pendingEvents.find((entry) => !entry.leaseUntil || entry.leaseUntil <= now);+}++function leaseEvent(entry, leaseMs) {+ if (!entry.event?.id) {+ const idx = state.pendingEvents.indexOf(entry);+ if (idx !== -1) state.pendingEvents.splice(idx, 1);+ return entry.event;}+ entry.leaseUntil = Date.now() + leaseMs;+ return entry.event;+}++function acknowledgePendingEvent(id) {+ if (!id) return false;+ const idx = state.pendingEvents.findIndex((entry) => entry.event?.id === id);+ if (idx === -1) return false;+ state.pendingEvents.splice(idx, 1);+ scheduleLeaseFlush();+ return true;+}++function scheduleLeaseFlush() {+ if (state.leaseTimer) {+ clearTimeout(state.leaseTimer);+ state.leaseTimer = null;+ }+ if (state.pendingPolls.length === 0) return;+ const now = Date.now();+ const nextLeaseUntil = state.pendingEvents+ .map((entry) => entry.leaseUntil || 0)+ .filter((leaseUntil) => leaseUntil > now)+ .sort((a, b) => a - b)[0];+ if (!nextLeaseUntil) return;+ state.leaseTimer = setTimeout(() => {+ state.leaseTimer = null;+ flushPendingPolls();+ }, Math.max(0, nextLeaseUntil - now));+}++function flushPendingPolls() {+ while (state.pendingPolls.length > 0) {+ const entry = findAvailablePendingEvent();+ if (!entry) {+ scheduleLeaseFlush();+ return;+ }+ const poll = state.pendingPolls.shift();+ poll.resolve(leaseEvent(entry, poll.leaseMs));+ }+ scheduleLeaseFlush();}/** Push a message to all connected SSE clients. */@@ -103,13 +170,16 @@ function loadBrowserScripts() {// live-browser.js: DO NOT cache. Return the path so the /live.js handler// can re-read on every request. Editing the browser script during iteration// should land on the next tab reload, not require a server restart.+ const sessionPath = path.join(__dirname, 'live-browser-session.js');const livePath = path.join(__dirname, 'live-browser.js');- if (!fs.existsSync(livePath)) {- process.stderr.write('Error: live-browser.js not found at ' + livePath + '\n');- process.exit(1);+ for (const p of [sessionPath, livePath]) {+ if (!fs.existsSync(p)) {+ process.stderr.write('Error: live browser script not found at ' + p + '\n');+ process.exit(1);+ }}- return { detectScript, livePath };+ return { detectScript, sessionPath, livePath };}function hasProjectContext() {@@ -170,6 +240,13 @@ function validateEvent(msg) {return null;case 'discard':return isValidId(msg.id) ? null : 'discard: missing or malformed id';+ case 'checkpoint':+ if (!isValidId(msg.id)) return 'checkpoint: missing or malformed id';+ if (!Number.isInteger(msg.revision) || msg.revision < 0) return 'checkpoint: revision must be a non-negative integer';+ if (msg.paramValues !== undefined && (typeof msg.paramValues !== 'object' || msg.paramValues === null || Array.isArray(msg.paramValues))) {+ return 'checkpoint: paramValues must be an object';+ }+ return null;case 'exit':return null;case 'prefetch':@@ -184,7 +261,7 @@ function validateEvent(msg) {// HTTP request handler// ----------------------------------------------------------------------------function createRequestHandler({ detectScript, livePath }) {+function createRequestHandler({ detectScript, sessionPath, livePath }) {return (req, res) => {const url = new URL(req.url, `http://localhost:${state.port}`);res.setHeader('Access-Control-Allow-Origin', '*');@@ -200,17 +277,20 @@ function createRequestHandler({ detectScript, livePath }) {// the next tab reload. No-store headers prevent browser caching across// sessions — during iteration, a cached old script silently breaks// every subsequent session.+ let sessionScript;let liveScript;try {+ sessionScript = fs.readFileSync(sessionPath, 'utf-8');liveScript = fs.readFileSync(livePath, 'utf-8');} catch (err) {res.writeHead(500, { 'Content-Type': 'text/plain' });- res.end('Error reading live-browser.js: ' + err.message);+ res.end('Error reading live browser scripts: ' + err.message);return;}const body =`window.__IMPECCABLE_TOKEN__ = '${state.token}';\n` +`window.__IMPECCABLE_PORT__ = ${state.port};\n` ++ sessionScript + '\n' +liveScript;res.writeHead(200, {'Content-Type': 'application/javascript',@@ -305,6 +385,26 @@ function createRequestHandler({ detectScript, livePath }) {}// --- Health ---+ if (p === '/status') {+ const token = url.searchParams.get('token');+ if (token !== state.token) { res.writeHead(401, { 'Content-Type': 'application/json' }); res.end(JSON.stringify({ error: 'Unauthorized' })); return; }+ const sessions = state.sessionStore ? state.sessionStore.listActiveSessions() : [];+ res.writeHead(200, { 'Content-Type': 'application/json' });+ res.end(JSON.stringify({+ status: 'ok',+ port: state.port,+ connectedClients: state.sseClients.size,+ pendingEvents: state.pendingEvents.map((entry) => ({+ id: entry.event?.id,+ type: entry.event?.type,+ leased: !!(entry.leaseUntil && entry.leaseUntil > Date.now()),+ leaseUntil: entry.leaseUntil || null,+ })),+ activeSessions: sessions,+ }));+ return;+ }+if (p === '/health') {res.writeHead(200, { 'Content-Type': 'application/json' });res.end(JSON.stringify({@@ -316,13 +416,13 @@ function createRequestHandler({ detectScript, livePath }) {}// --- Design system (unified v2 response) + raw ---- // /design-system.json returns both parsed DESIGN.md and DESIGN.json+ // /design-system.json returns both parsed DESIGN.md and .impeccable/design.json// sidecar when present. Panel merges them:// { present, parsed, sidecar, hasMd, hasSidecar,// mdNewerThanJson, parseError?, sidecarError? }// - parsed: output of parseDesignMd (frontmatter// + six canonical sections) when DESIGN.md exists.- // - sidecar: DESIGN.json contents when present.+ // - sidecar: .impeccable/design.json contents when present.// Expected shape: schemaVersion 2, carrying// extensions + components + narrative.// /design-system/raw returns DESIGN.md markdown verbatim@@ -331,7 +431,7 @@ function createRequestHandler({ detectScript, livePath }) {if (token !== state.token) { res.writeHead(401); res.end('Unauthorized'); return; }const mdPath = path.join(CONTEXT_DIR, 'DESIGN.md');- const jsonPath = path.join(CONTEXT_DIR, 'DESIGN.json');+ const jsonPath = resolveDesignSidecarPath(process.cwd(), CONTEXT_DIR) || getDesignSidecarPath(process.cwd());const mdStat = statOrNull(mdPath);const jsonStat = statOrNull(jsonPath);@@ -367,7 +467,7 @@ function createRequestHandler({ detectScript, livePath }) {try {response.sidecar = JSON.parse(fs.readFileSync(jsonPath, 'utf-8'));} catch (err) {- response.sidecarError = 'Failed to parse DESIGN.json: ' + err.message;+ response.sidecarError = 'Failed to parse .impeccable/design.json: ' + err.message;}}@@ -449,7 +549,16 @@ function createRequestHandler({ detectScript, livePath }) {res.end(JSON.stringify({ error }));return;}- enqueueEvent(msg);+ if (state.sessionStore && msg.id) {+ try {+ state.sessionStore.appendEvent(msg);+ } catch (err) {+ res.writeHead(500, { 'Content-Type': 'application/json' });+ res.end(JSON.stringify({ error: 'session_store_append_failed', message: err.message }));+ return;+ }+ }+ if (msg.type !== 'checkpoint') enqueueEvent(msg);res.writeHead(200, { 'Content-Type': 'application/json' });res.end(JSON.stringify({ ok: true }));});@@ -492,13 +601,16 @@ function handlePollGet(req, res, url) {return;}const timeout = parseInt(url.searchParams.get('timeout') || DEFAULT_POLL_TIMEOUT, 10);- if (state.pendingEvents.length > 0) {+ const leaseMs = parseInt(url.searchParams.get('leaseMs') || '30000', 10);+ const available = findAvailablePendingEvent();+ if (available) {res.writeHead(200, { 'Content-Type': 'application/json' });- res.end(JSON.stringify(state.pendingEvents.shift()));+ res.end(JSON.stringify(leaseEvent(available, leaseMs)));return;}+ const poll = { resolve, leaseMs };const timer = setTimeout(() => {- const idx = state.pendingPolls.indexOf(resolve);+ const idx = state.pendingPolls.indexOf(poll);if (idx !== -1) state.pendingPolls.splice(idx, 1);res.writeHead(200, { 'Content-Type': 'application/json' });res.end(JSON.stringify({ type: 'timeout' }));@@ -508,10 +620,11 @@ function handlePollGet(req, res, url) {res.writeHead(200, { 'Content-Type': 'application/json' });res.end(JSON.stringify(event));}- state.pendingPolls.push(resolve);+ state.pendingPolls.push(poll);+ scheduleLeaseFlush();req.on('close', () => {clearTimeout(timer);- const idx = state.pendingPolls.indexOf(resolve);+ const idx = state.pendingPolls.indexOf(poll);if (idx !== -1) state.pendingPolls.splice(idx, 1);});}@@ -531,6 +644,26 @@ function handlePollPost(req, res) {res.end(JSON.stringify({ error: 'Unauthorized' }));return;}+ acknowledgePendingEvent(msg.id);+ if (state.sessionStore && msg.id) {+ try {+ const eventType = msg.type === 'discard' || msg.type === 'discarded'+ ? 'discarded'+ : msg.type === 'complete'+ ? 'complete'+ : msg.type === 'error'+ ? 'agent_error'+ : 'agent_done';+ state.sessionStore.appendEvent({+ type: eventType,+ id: msg.id,+ file: msg.file,+ message: msg.message,+ carbonize: msg.data?.carbonize === true,+ });+ } catch { /* keep reply path best-effort; browser still needs SSE */ }+ }+ flushPendingPolls();// Forward the reply to the browser via SSEbroadcast({ type: msg.type || 'done', id: msg.id, message: msg.message, file: msg.file, data: msg.data });res.writeHead(200, { 'Content-Type': 'application/json' });@@ -545,13 +678,15 @@ function handlePollPost(req, res) {let httpServer = null;function shutdown() {- try { fs.unlinkSync(LIVE_PID_FILE); } catch {}+ removeLiveServerInfo(process.cwd());+ if (state.leaseTimer) clearTimeout(state.leaseTimer);+ state.leaseTimer = null;if (state.sessionDir) {try { fs.rmSync(state.sessionDir, { recursive: true, force: true }); } catch {}}for (const res of state.sseClients) { try { res.end(); } catch {} }state.sseClients.clear();- for (const resolve of state.pendingPolls) resolve({ type: 'exit' });+ for (const poll of state.pendingPolls) poll.resolve({ type: 'exit' });state.pendingPolls.length = 0;if (httpServer) httpServer.close();process.exit(0);@@ -587,6 +722,7 @@ Endpoints:/events SSE stream (server→browser) + POST (browser→server)/poll Long-poll for agent CLI/source Raw source file reader (no-HMR fallback)+ /status Durable recovery status (token-protected)/health Health check`);process.exit(0);}@@ -594,7 +730,7 @@ Endpoints:if (args.includes('stop')) {const keepInject = args.includes('--keep-inject');try {- const info = JSON.parse(fs.readFileSync(LIVE_PID_FILE, 'utf-8'));+ const { info } = readLiveServerInfo(process.cwd()) || {};const res = await fetch(`http://localhost:${info.port}/stop?token=${info.token}`);if (res.ok) console.log(`Stopped live server on port ${info.port}.`);} catch {@@ -645,7 +781,7 @@ if (args.includes('--background')) {const deadline = Date.now() + 10_000;while (Date.now() < deadline) {try {- const info = JSON.parse(fs.readFileSync(LIVE_PID_FILE, 'utf-8'));+ const { info } = readLiveServerInfo(process.cwd()) || {};if (info.pid !== process.pid) {// Output JSON so the agent can read port + token from stdout.console.log(JSON.stringify(info));@@ -659,30 +795,36 @@ if (args.includes('--background')) {}// Check for existing session-try {- const existing = JSON.parse(fs.readFileSync(LIVE_PID_FILE, 'utf-8'));- try { process.kill(existing.pid, 0);+const existingRecord = readLiveServerInfo(process.cwd());+if (existingRecord?.info) {+ const existing = existingRecord.info;+ try {+ process.kill(existing.pid, 0);console.error(`Live server already running on port ${existing.port} (pid ${existing.pid}).`);console.error('Stop it first with: node ' + path.basename(fileURLToPath(import.meta.url)) + ' stop');process.exit(1);- } catch { fs.unlinkSync(LIVE_PID_FILE); }-} catch {}+ } catch {+ try { fs.unlinkSync(existingRecord.path); } catch {}+ }+}state.token = randomUUID();+state.sessionStore = createLiveSessionStore({ cwd: process.cwd() });+restorePendingEventsFromStore();const portArg = args.find(a => a.startsWith('--port='));state.port = portArg ? parseInt(portArg.split('=')[1], 10) : await findOpenPort();// Annotation screenshots live in the project root so the agent's Read tool// doesn't trip a per-file permission prompt. Sessioned by token so concurrent// projects (or quick restarts) don't collide.-const annotRoot = path.join(process.cwd(), '.impeccable-live', 'annotations');+const annotRoot = getLiveAnnotationsDir(process.cwd());fs.mkdirSync(annotRoot, { recursive: true });state.sessionDir = fs.mkdtempSync(path.join(annotRoot, 'session-'));-const { detectScript, livePath } = loadBrowserScripts();-httpServer = http.createServer(createRequestHandler({ detectScript, livePath }));+const { detectScript, sessionPath, livePath } = loadBrowserScripts();+httpServer = http.createServer(createRequestHandler({ detectScript, sessionPath, livePath }));httpServer.listen(state.port, '127.0.0.1', () => {- fs.writeFileSync(LIVE_PID_FILE, JSON.stringify({ pid: process.pid, port: state.port, token: state.token }));+ writeLiveServerInfo(process.cwd(), { pid: process.pid, port: state.port, token: state.token });const url = `http://localhost:${state.port}`;console.log(`\nImpeccable live server running on ${url}`);console.log(`Token: ${state.token}\n`);diff --git a/.rovodev/skills/impeccable/scripts/live-session-store.mjs b/.rovodev/skills/impeccable/scripts/live-session-store.mjsnew file mode 100644index 000000000..d55ed2d3a--- /dev/null+++ b/.rovodev/skills/impeccable/scripts/live-session-store.mjs@@ -0,0 +1,254 @@+import fs from 'node:fs';+import path from 'node:path';+import { getLegacyLiveSessionsDir, getLiveSessionsDir } from './impeccable-paths.mjs';++const COMPLETED_PHASES = new Set(['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;+ }++ function getReadableJournalPath(id) {+ const primary = getJournalPath(rootDir, id);+ if (fs.existsSync(primary)) return primary;+ const legacy = getJournalPath(legacyRootDir, id);+ if (fs.existsSync(legacy)) return legacy;+ return primary;+ }++ return {+ rootDir,+ legacyRootDir,+ appendEvent(event) {+ const normalized = normalizeEvent(event, sessionId);+ const journalPath = getJournalPath(rootDir, normalized.id);+ const snapshotPath = getSnapshotPath(rootDir, normalized.id);+ const legacyJournalPath = getJournalPath(legacyRootDir, normalized.id);+ if (!fs.existsSync(journalPath) && fs.existsSync(legacyJournalPath)) {+ fs.copyFileSync(legacyJournalPath, journalPath);+ }+ const prior = loadCachedOrRebuild(normalized.id);+ const seq = prior.nextSeq;+ const entry = {+ seq,+ id: normalized.id,+ type: normalized.type,+ ts: new Date().toISOString(),+ event: normalized,+ };+ 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;+ },+ getSnapshot(id = sessionId, opts = {}) {+ if (!id) throw new Error('session id required');+ 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;+ },+ listActiveSessions() {+ const ids = new Set();+ for (const dir of [legacyRootDir, rootDir]) {+ if (!fs.existsSync(dir)) continue;+ for (const name of fs.readdirSync(dir)) {+ if (name.endsWith('.jsonl')) ids.add(name.slice(0, -'.jsonl'.length));+ }+ }+ return [...ids]+ .sort()+ .map((id) => this.getSnapshot(id))+ .filter(Boolean);+ },+ };+}++function normalizeEvent(event, fallbackId) {+ if (!event || typeof event !== 'object') throw new Error('event object required');+ const id = event.id || fallbackId;+ if (!id || typeof id !== 'string') throw new Error('event id required');+ if (!event.type || typeof event.type !== 'string') throw new Error('event type required');+ return { ...event, id };+}++function getJournalPath(rootDir, id) {+ return path.join(rootDir, safeSessionId(id) + '.jsonl');+}++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,+ phase: 'new',+ pageUrl: null,+ sourceFile: null,+ expectedVariants: 0,+ arrivedVariants: 0,+ visibleVariant: null,+ paramValues: {},+ pendingEventSeq: null,+ pendingEvent: null,+ deliveryLease: null,+ checkpointRevision: 0,+ activeOwner: null,+ sourceMarkers: {},+ fallbackMode: null,+ annotationArtifacts: [],+ diagnostics: [],+ updatedAt: null,+ };+}++function rebuildSnapshotFromJournal(journalPath, id) {+ let snapshot = baseSnapshot(id);+ const diagnostics = [];+ let nextSeq = 1;+ if (!fs.existsSync(journalPath)) return { snapshot, diagnostics, nextSeq };++ const lines = fs.readFileSync(journalPath, 'utf-8').split('\n');+ for (let i = 0; i < lines.length; i++) {+ const line = lines[i];+ if (!line.trim()) continue;+ try {+ const entry = JSON.parse(line);+ if (!entry || typeof entry !== 'object') throw new Error('entry is not object');+ if (Number.isInteger(entry.seq)) nextSeq = Math.max(nextSeq, entry.seq + 1);+ snapshot = applyEvent(snapshot, entry);+ } catch (err) {+ diagnostics.push({+ error: 'journal_parse_failed',+ line: i + 1,+ message: err.message,+ });+ }+ }+ snapshot.diagnostics = [...snapshot.diagnostics, ...diagnostics];+ return { snapshot, diagnostics, nextSeq };+}++function applyEvent(snapshot, entry, inheritedDiagnostics = []) {+ const event = entry.event || entry;+ const next = {+ ...snapshot,+ paramValues: { ...(snapshot.paramValues || {}) },+ sourceMarkers: { ...(snapshot.sourceMarkers || {}) },+ annotationArtifacts: [...(snapshot.annotationArtifacts || [])],+ diagnostics: [...(snapshot.diagnostics || [])],+ updatedAt: entry.ts || new Date().toISOString(),+ };++ if (inheritedDiagnostics.length && next.diagnostics.length === 0) {+ next.diagnostics = [...inheritedDiagnostics];+ }++ switch (event.type) {+ case 'generate':+ next.phase = 'generate_requested';+ next.pageUrl = event.pageUrl ?? next.pageUrl;+ next.expectedVariants = event.count ?? next.expectedVariants;+ next.pendingEventSeq = entry.seq ?? next.pendingEventSeq;+ next.pendingEvent = toPendingEvent(event);+ if (event.screenshotPath) upsertArtifact(next.annotationArtifacts, { type: 'screenshot', path: event.screenshotPath });+ break;+ case 'variants_ready':+ case 'agent_done':+ next.phase = event.carbonize === true ? 'carbonize_required' : 'variants_ready';+ next.sourceFile = event.file ?? next.sourceFile;+ next.arrivedVariants = event.arrivedVariants ?? (next.arrivedVariants ?? next.expectedVariants);+ next.pendingEventSeq = null;+ next.pendingEvent = null;+ if (event.carbonize === true) {+ next.diagnostics.push({+ error: 'carbonize_cleanup_required',+ file: event.file || null,+ message: 'Accepted variant still has carbonize markers that must be folded into source CSS.',+ });+ }+ break;+ case 'checkpoint':+ 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;+ if (event.paramValues) next.paramValues = { ...event.paramValues };+ } else {+ next.diagnostics.push({ error: 'stale_checkpoint_ignored', revision: event.revision });+ }+ break;+ case 'accept':+ case 'accept_intent':+ next.phase = 'accept_requested';+ next.visibleVariant = Number(event.variantId ?? next.visibleVariant);+ if (event.paramValues) next.paramValues = { ...event.paramValues };+ next.pendingEventSeq = entry.seq ?? next.pendingEventSeq;+ next.pendingEvent = toPendingEvent(event);+ break;+ case 'discard':+ next.phase = 'discard_requested';+ next.pendingEventSeq = entry.seq ?? next.pendingEventSeq;+ next.pendingEvent = toPendingEvent(event);+ break;+ case 'discarded':+ next.phase = 'discarded';+ next.pendingEventSeq = null;+ next.pendingEvent = null;+ break;+ case 'complete':+ next.phase = 'completed';+ next.pendingEventSeq = null;+ next.pendingEvent = null;+ break;+ case 'agent_error':+ next.phase = 'agent_error';+ next.pendingEventSeq = null;+ next.pendingEvent = null;+ next.diagnostics.push({ error: 'agent_error', message: event.message || 'unknown agent error' });+ break;+ default:+ next.diagnostics.push({ error: 'unknown_event_type', type: event.type });+ break;+ }+ return next;+}++function toPendingEvent(event) {+ const pending = { ...event };+ delete pending.token;+ return pending;+}++function upsertArtifact(artifacts, artifact) {+ if (!artifacts.some((existing) => existing.path === artifact.path && existing.type === artifact.type)) {+ artifacts.push(artifact);+ }+}++function writeSnapshot(snapshotPath, snapshot) {+ fs.writeFileSync(snapshotPath, JSON.stringify(snapshot, null, 2) + '\n');+}diff --git a/.rovodev/skills/impeccable/scripts/live-status.mjs b/.rovodev/skills/impeccable/scripts/live-status.mjsnew file mode 100644index 000000000..dce1fbca2--- /dev/null+++ b/.rovodev/skills/impeccable/scripts/live-status.mjs@@ -0,0 +1,47 @@+#!/usr/bin/env node+/**+ * Print durable recovery status for Impeccable live sessions.+ */++import { createLiveSessionStore } from './live-session-store.mjs';+import { readLiveServerInfo } from './impeccable-paths.mjs';++function readServerInfo() {+ return readLiveServerInfo(process.cwd())?.info || null;+}++async function fetchServerStatus(info) {+ if (!info) return null;+ try {+ const res = await fetch(`http://localhost:${info.port}/status?token=${info.token}`);+ if (!res.ok) return null;+ return await res.json();+ } catch {+ return null;+ }+}++export async function statusCli() {+ const info = readServerInfo();+ const server = await fetchServerStatus(info);+ const store = createLiveSessionStore({ cwd: process.cwd() });+ const activeSessions = store.listActiveSessions();+ const payload = {+ liveServer: server ? {+ status: server.status,+ port: server.port,+ connectedClients: server.connectedClients,+ pendingEvents: server.pendingEvents,+ } : null,+ activeSessions: server?.activeSessions || activeSessions,+ recoveryHint: 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.',+ };+ console.log(JSON.stringify(payload, null, 2));+}++const _running = process.argv[1];+if (_running?.endsWith('live-status.mjs') || _running?.endsWith('live-status.mjs/')) {+ statusCli();+}diff --git a/.rovodev/skills/impeccable/scripts/live-wrap.mjs b/.rovodev/skills/impeccable/scripts/live-wrap.mjsindex a5769a50a..d46328b9f 100644--- a/.rovodev/skills/impeccable/scripts/live-wrap.mjs+++ b/.rovodev/skills/impeccable/scripts/live-wrap.mjs@@ -185,6 +185,7 @@ The agent should insert variant HTML at insertLine.`);const { startLine, endLine } = match;const commentSyntax = detectCommentSyntax(targetFile);+ const styleMode = detectStyleMode(targetFile);const isJsx = commentSyntax.open === '{/*';const indent = lines[startLine].match(/^(\s*)/)[1];@@ -269,6 +270,10 @@ The agent should insert variant HTML at insertLine.`);endLine: startLine + wrapperLines.length + (originalLines.length - 1), // 1-indexedinsertLine: insertLine + 1, // 1-indexed: where variants gocommentSyntax: commentSyntax,+ styleMode: styleMode.mode,+ styleTag: styleMode.styleTag,+ cssSelectorPrefixExamples: buildCssSelectorPrefixExamples(styleMode.mode, count),+ cssAuthoring: buildCssAuthoring(styleMode, count),originalLineCount: originalLines.length,}));}@@ -335,6 +340,62 @@ function detectCommentSyntax(filePath) {return { open: '<!--', close: '-->' };}+function detectStyleMode(filePath) {+ const ext = path.extname(filePath).toLowerCase();+ if (ext === '.astro') {+ return {+ mode: 'astro-global-prefixed',+ styleTag: '<style is:inline data-impeccable-css="SESSION_ID">',+ };+ }+ return {+ mode: 'scoped',+ styleTag: '<style data-impeccable-css="SESSION_ID">',+ };+}++function buildCssSelectorPrefixExamples(styleMode, count) {+ if (styleMode !== 'astro-global-prefixed') return [];+ return Array.from({ length: count }, (_, i) => `[data-impeccable-variant="${i + 1}"]`);+}++function buildCssAuthoring(styleMode, count) {+ const variantNumbers = Array.from({ length: count }, (_, i) => i + 1);+ if (styleMode.mode === 'astro-global-prefixed') {+ return {+ mode: styleMode.mode,+ styleTag: styleMode.styleTag,+ strategy: 'global-prefixed',+ rulePattern: '[data-impeccable-variant="N"] > .variant-class { ... }',+ selectorExamples: variantNumbers.map((n) => `[data-impeccable-variant="${n}"] > .variant-class`),+ requirements: [+ 'Use the styleTag exactly; the is:inline attribute is required for this file.',+ 'Prefix every preview selector with the matching [data-impeccable-variant="N"] selector.',+ 'Keep selectors anchored to the generated variant wrapper; do not rely on component CSS scoping for preview rules.',+ ],+ forbidden: [+ 'Do not use @scope for this styleMode.',+ ],+ };+ }+ return {+ mode: styleMode.mode,+ styleTag: styleMode.styleTag,+ strategy: 'scope-rule',+ rulePattern: '@scope ([data-impeccable-variant="N"]) { :scope > .variant-class { ... } }',+ selectorExamples: variantNumbers.map((n) => `@scope ([data-impeccable-variant="${n}"]) { :scope > .variant-class { ... } }`),+ requirements: [+ 'Use @scope blocks keyed to each [data-impeccable-variant="N"] wrapper.',+ 'Inside each @scope block, make :scope rules step into the replacement element with a descendant combinator.',+ 'Use the styleTag exactly; do not add framework-specific style attributes unless this object says to.',+ ],+ forbidden: [+ 'Do not use global [data-impeccable-variant="N"] selector prefixes for this styleMode.',+ 'Do not add is:inline to the style tag for this styleMode.',+ ],+ };+}+/*** Search project files for the query string (class name, ID, etc.)* Returns the first matching file path, or null.diff --git a/.rovodev/skills/impeccable/scripts/live.mjs b/.rovodev/skills/impeccable/scripts/live.mjsindex befbdb8ed..cafb0eca9 100644--- a/.rovodev/skills/impeccable/scripts/live.mjs+++ b/.rovodev/skills/impeccable/scripts/live.mjs@@ -2,10 +2,10 @@* CLI entry point: prepare everything needed to enter the live variant poll loop.** Does (all in one command):- * 1. Check config.json (returns config_missing if first-ever run)+ * 1. Check .impeccable/live/config.json (returns config_missing if first-ever run)* 2. Start the live server in the background (or reuse a running one)* 3. Inject the browser script tag into the project's entry file- * 4. Read .impeccable.md for design context (if present)+ * 4. Read PRODUCT.md / DESIGN.md for project context* 5. Print a single JSON blob with everything the agent needs** After this, the agent's only remaining steps are:@@ -23,9 +23,9 @@ import path from 'node:path';import { fileURLToPath } from 'node:url';import { loadContext } from './load-context.mjs';import { resolveFiles } from './live-inject.mjs';+import { readLiveServerInfo } from './impeccable-paths.mjs';const __dirname = path.dirname(fileURLToPath(import.meta.url));-const PID_FILE = path.join(process.cwd(), '.impeccable-live.json');async function liveCli() {const args = process.argv.slice(2);@@ -34,10 +34,10 @@ async function liveCli() {console.log(`Usage: node live.mjsPrepare everything for live variant mode in a single command:- - Checks scripts/config.json (required, created once per project)+ - Checks .impeccable/live/config.json (required, created once per project)- Starts (or reuses) the live server in the background- Injects the browser script tag- - Reads .impeccable.md for design context+ - Reads PRODUCT.md / DESIGN.md for project contextOn success, prints a JSON blob with:{ ok, serverPort, serverToken, pageFile, hasContext, context }@@ -223,7 +223,7 @@ function safeParse(out) {function ensureServerRunning() {// Try to reuse an existing servertry {- const existing = JSON.parse(fs.readFileSync(PID_FILE, 'utf-8'));+ const existing = readLiveServerInfo(process.cwd())?.info;if (existing && existing.pid) {try {process.kill(existing.pid, 0); // throws if deaddiff --git a/.rovodev/skills/impeccable/scripts/load-context.mjs b/.rovodev/skills/impeccable/scripts/load-context.mjsindex dca23c1f8..dc340bf16 100644--- a/.rovodev/skills/impeccable/scripts/load-context.mjs+++ b/.rovodev/skills/impeccable/scripts/load-context.mjs@@ -39,7 +39,7 @@ const LEGACY_NAMES = ['.impeccable.md'];const FALLBACK_DIRS = ['.agents/context', 'docs'];/**- * Resolve the directory that holds PRODUCT.md / DESIGN.md / DESIGN.json for+ * Resolve the directory that holds PRODUCT.md / DESIGN.md for* this project. Exported so other scripts (e.g. live-server.mjs) can read the* design files from the same location the loader uses.*/diff --git a/.trae-cn/skills/impeccable/reference/document.md b/.trae-cn/skills/impeccable/reference/document.mdindex 58c45cfc5..3125b37a2 100644--- a/.trae-cn/skills/impeccable/reference/document.md+++ b/.trae-cn/skills/impeccable/reference/document.md@@ -237,11 +237,11 @@ Concrete, forceful guardrails. Lead each with "Do" or "Don't". Be specific: incl- **Don't** [...]```-### Step 4b: Write DESIGN.json sidecar (extensions only)+### Step 4b: Write .impeccable/design.json sidecar (extensions only)-The frontmatter owns token primitives (colors, typography, rounded, spacing, components). The sidecar at `DESIGN.json` carries **what Stitch's schema can't hold**: tonal ramps per color, shadow/elevation tokens, motion tokens, breakpoints, full component HTML/CSS snippets (the panel renders these into a shadow DOM), and narrative (north star, rules, do's/don'ts). It extends the frontmatter, it doesn't duplicate it.+The frontmatter owns token primitives (colors, typography, rounded, spacing, components). The sidecar at `.impeccable/design.json` carries **what Stitch's schema can't hold**: tonal ramps per color, shadow/elevation tokens, motion tokens, breakpoints, full component HTML/CSS snippets (the panel renders these into a shadow DOM), and narrative (north star, rules, do's/don'ts). It extends the frontmatter, it doesn't duplicate it.-Regenerate the sidecar whenever you regenerate DESIGN.md. If the user only asks to refresh the sidecar (e.g., from the live panel's stale-hint), preserve DESIGN.md and write only DESIGN.json.+Regenerate the sidecar whenever you regenerate root `DESIGN.md`. If the user only asks to refresh the sidecar (e.g., from the live panel's stale-hint), preserve `DESIGN.md` and write only `.impeccable/design.json`.#### Schema@@ -310,7 +310,7 @@ Aim for a tight set of **5-10 components** that best represent the visual system- **Signature components (include if distinctive):** hero CTA, featured card, filter pill, any custom pattern the user mentioned as important in PRODUCT.md.- **Skip the rest.** Utility components, form building blocks, wrapper layouts: not worth documenting unless visually distinctive.-If the project has **no component library yet** (bare landing page, new project), synthesize canonical primitives from the tokens using best-practice defaults consistent with the DESIGN.md's rules. Every DESIGN.json has *something* to render, even on day zero.+If the project has **no component library yet** (bare landing page, new project), synthesize canonical primitives from the tokens using best-practice defaults consistent with the DESIGN.md's rules. Every `.impeccable/design.json` has *something* to render, even on day zero.#### Tonal ramps@@ -331,7 +331,7 @@ Do not reword. The panel shows these as secondary collapsible context; the same### Step 5: Confirm, refine, and refresh session cache1. Show the user the full DESIGN.md you wrote. Briefly highlight the non-obvious creative choices (descriptive color names, atmosphere language, named rules).-2. Mention that `DESIGN.json` was also written alongside; the live panel will now render this project's actual button/input/nav primitives instead of generic approximations.+2. Mention that `.impeccable/design.json` was also written alongside; the live panel will now render this project's actual button/input/nav primitives instead of generic approximations.3. Offer to refine any section: "Want me to revise a section, add component patterns I missed, or adjust the atmosphere language?"4. **Refresh the session cache.** Run `node .trae-cn/skills/impeccable/scripts/load-context.mjs` one final time so the newly-written DESIGN.md lands in conversation. Subsequent commands in this session will use the fresh version automatically without re-reading.@@ -392,7 +392,7 @@ Per-section guidance in seed mode:- **Components**: omit entirely; no components exist yet.- **Do's and Don'ts**: carry PRODUCT.md's anti-references directly plus the anti-reference named in Q5.-Seed mode writes a minimal frontmatter with `name` and `description` only; no colors, typography, rounded, spacing, or components yet. Real tokens land on the next Scan-mode run. Skip the `DESIGN.json` sidecar in seed mode for the same reason: nothing to render.+Seed mode writes a minimal frontmatter with `name` and `description` only; no colors, typography, rounded, spacing, or components yet. Real tokens land on the next Scan-mode run. Skip the `.impeccable/design.json` sidecar in seed mode for the same reason: nothing to render.### Step 4: Confirm and refresh session cachediff --git a/.trae-cn/skills/impeccable/reference/live.md b/.trae-cn/skills/impeccable/reference/live.mdindex 685194bb0..159df7d06 100644--- a/.trae-cn/skills/impeccable/reference/live.md+++ b/.trae-cn/skills/impeccable/reference/live.md@@ -12,8 +12,9 @@ Execute in order. No step skipped, no step reordered.2. Navigate to the URL that serves `pageFile` (infer from `package.json`, docs, terminal output, or an open tab). If you can't infer it confidently, tell the user once to open their dev/preview URL. Never use `serverPort` as that URL; it's the helper, not the app.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=`.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.-5. On `accept` / `discard`: the poll script already cleaned up; just poll again.-6. On `exit`: run the cleanup at the bottom.+5. 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. If interrupted, run `live-status.mjs` or `live-resume.mjs` before guessing. The durable journal replays unacknowledged work after helper restart.+7. 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.@@ -43,13 +44,31 @@ LOOP:Read JSON; dispatch on "type""generate" → Handle Generate; reply done; LOOP- "accept" → Handle Accept; LOOP+ "accept" → Handle Accept; complete carbonize cleanup if required; LOOP"discard" → Handle Discard; LOOP"prefetch" → Handle Prefetch; LOOP"timeout" → LOOP"exit" → break → Cleanup```+## Recovery commands++The live helper persists an append-only journal under `.impeccable/live/sessions/`. Browser checkpoints are advisory but durable; the journal is canonical. This is local durable recovery state, not project source.++Use these commands when the chat was interrupted, polling was missed, the helper restarted, or the browser reloaded:++```bash+node .trae-cn/skills/impeccable/scripts/live-status.mjs+node .trae-cn/skills/impeccable/scripts/live-resume.mjs --id SESSION_ID+node .trae-cn/skills/impeccable/scripts/live-complete.mjs --id SESSION_ID+```++- `live-status.mjs` prints connected helper state, active durable sessions, and queued pending events. It works even when the helper is down by reading the journal directly.+- `live-resume.mjs` prints the active snapshot, pending event, checkpoint phase, visible variant, parameter values, and the next safe agent action.+- `live-complete.mjs` is the canonical manual final acknowledgement. Use it after carbonize/manual cleanup is verified and no further poll acknowledgement will happen automatically.++Server restart rule: start `live-server.mjs` again, then poll. Startup requeues unacknowledged pending events from the journal, so do not ask the user to click Go again unless `live-resume.mjs` says no active session exists.+## Handle `generate`Event: `{id, action, freeformPrompt?, count, pageUrl, element, screenshotPath?, comments?, strokes?}`.@@ -88,7 +107,14 @@ The helper searches ID first, then classes, then tag + class combo. If `event.paIf `--text` matches multiple candidates equally well, wrap exits with `{ error: "element_ambiguous", candidates: [...] }` and `fallback: "agent-driven"`: read the candidate line ranges, decide which one matches the picked element from page context, and write the wrapper manually per the fallback flow.-Output on success: `{ file, insertLine, commentSyntax }`.+Output on success: `{ file, insertLine, commentSyntax, styleMode, styleTag, cssSelectorPrefixExamples, cssAuthoring }`.++`styleMode` controls how preview CSS must be authored. Treat it as a detected capability mode, not a framework guess:++- `scoped`: use `@scope ([data-impeccable-variant="N"])` rules.+- `astro-global-prefixed`: use explicit `[data-impeccable-variant="N"]` selector prefixes and the exact `styleTag` returned by the tool.++Use `cssAuthoring` as the source of truth for the current file. It includes the exact `styleTag`, selector strategy, selector examples, requirements, and forbidden patterns. Do not apply a framework-specific exception unless the returned `styleMode` / `cssAuthoring.mode` says to.**Fallback errors.** Wrap only writes into files it judges to be source (tracked by git, not marked GENERATED, not listed in config's `generatedFiles`). If it can't land on a source file, it errors without writing; accepting a variant into a generated file is silent data loss. Three shapes:@@ -208,13 +234,14 @@ When the prompt and PRODUCT.md anti-references conflict (the prompt asks for X,Complete 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 scoped 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).+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).++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:```html<!-- Variants: insert below this line --><style data-impeccable-css="SESSION_ID">- @scope ([data-impeccable-variant="1"]) { ... }- @scope ([data-impeccable-variant="2"]) { ... }+ /* rules matching cssAuthoring.rulePattern */</style><div data-impeccable-variant="1"><!-- variant 1: full element replacement (single top-level element) -->@@ -229,11 +256,11 @@ Write CSS + all variants in ONE edit at the `insertLine` reported by `wrap`. Col**Each variant div contains exactly one top-level element: the full replacement for the original.** Use the same tag as the original (e.g. `<section>` if the user picked a `<section>`). Loose siblings (heading + paragraph + div as direct children of the variant div) break the outline tracking and the accept flow, which both assume one child.-The first variant has no `display: none` (visible by default). All others do. If variants use only inline styles and no scoped CSS, omit the `<style>` tag entirely. Use `@scope` for CSS isolation (Chrome 118+ / Firefox 128+ / Safari 17.4+).+The 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.-**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 rule starts `:scope > ...`.+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 > ...`.**JSX / TSX target files.** Wrap `<style>` content in a template literal so the CSS `{` / `}` aren't parsed as JSX expressions, and use `className=` / `style={{…}}` on every variant element. Keep `data-impeccable-*` attributes as-is; they're plain strings:@@ -369,10 +396,11 @@ Remove the wrapper you inserted in Step 2. Nothing else to do.## Handle `accept`-Event: `{id, variantId, _acceptResult}`. The poll script already ran `live-accept.mjs` to handle the file operation deterministically; the browser DOM is already updated.+Event: `{id, variantId, _acceptResult, _completionAck}`. The poll script already ran `live-accept.mjs` to handle the file operation deterministically, then acknowledged event delivery to the helper. The browser DOM is already updated.+- `_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 and a stderr banner both list the steps explicitly; neither is decorative.+- `_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: 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` without `mode`: manual cleanup: read file, find markers, edit.@@ -388,13 +416,13 @@ Do these five steps in the current thread, synchronously, before the next poll.4. **Unwrap the accepted content.** Delete the `<div data-impeccable-variant="N" style="display: contents">` that wraps it. Drop `data-impeccable-params` and any `data-p-*` attributes from it; 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.-Then poll again.+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.## Handle `discard`-Event: `{id, _acceptResult}`. The poll script already restored the original and removed all variant markers. Nothing to do. Poll again.+Event: `{id, _acceptResult, _completionAck}`. The poll script already restored the original, removed all variant markers, and acknowledged `discarded` durable completion. Nothing to do unless `_completionAck.ok !== true`; in that case run `live-complete.mjs --id EVENT_ID --discarded`, then poll again.## Handle `prefetch`@@ -424,7 +452,7 @@ When the poll returns `exit`, proceed to cleanup. If the poll is still running anode .trae-cn/skills/impeccable/scripts/live-server.mjs stop```-Stops the HTTP server and runs `live-inject.mjs --remove` to strip `localhost:…/live.js` from the HTML entry. To stop the server but keep the inject tag (for a quick restart), use `stop --keep-inject`. `config.json` persists for future sessions.+Stops the HTTP server and runs `live-inject.mjs --remove` to strip `localhost:…/live.js` from the HTML entry. To stop the server but keep the inject tag (for a quick restart), use `stop --keep-inject`. `.impeccable/live/config.json` persists as project config for future sessions.Then:- Remove any leftover variant wrappers (search for `impeccable-variants-start` markers).@@ -432,7 +460,7 @@ Then:## First-time setup (config missing or invalid)-If `live.mjs` outputs `{ ok: false, error: "config_missing" | "config_invalid", path }`, write `config.json` at the reported path.+If `live.mjs` outputs `{ ok: false, error: "config_missing" | "config_invalid", path }`, write the live config at the reported path. By default this is `.impeccable/live/config.json`.Schema:@@ -512,7 +540,7 @@ node .trae-cn/skills/impeccable/scripts/detect-csp.mjsOutput: `{ shape, signals }` where `shape` is one of `append-arrays`, `append-string`, `middleware`, `meta-tag`, or `null`. The shape is named by *patch mechanism*, so one template covers many frameworks.-- **`null`**: no CSP; skip to writing `config.json` with `cspChecked: true`.+- **`null`**: no CSP; skip to writing `.impeccable/live/config.json` with `cspChecked: true`.- **`append-arrays`**: CSP defined as structured directive arrays. Auto-patchable. See *append-arrays* below. Covers:- Monorepo helpers with `additionalScriptSrc` / `additionalConnectSrc` options (Next.js + shared config package)- SvelteKit `kit.csp.directives`@@ -589,6 +617,6 @@ Reference outputs:### Troubleshooting-If a user says "no" to the CSP patch at setup time and later complains that live doesn't work: their dev CSP blocks `http://localhost:8400`. Fix: delete `cspChecked` from `config.json` and re-run `live.mjs`: setup will ask again.+If a user says "no" to the CSP patch at setup time and later complains that live doesn't work: their dev CSP blocks `http://localhost:8400`. Fix: delete `cspChecked` from `.impeccable/live/config.json` and re-run `live.mjs`: setup will ask again.Then re-run `live.mjs`.diff --git a/.trae-cn/skills/impeccable/reference/teach.md b/.trae-cn/skills/impeccable/reference/teach.mdindex da8ea44f7..7937905e9 100644--- a/.trae-cn/skills/impeccable/reference/teach.md+++ b/.trae-cn/skills/impeccable/reference/teach.md@@ -2,8 +2,8 @@Gathers design context for a project and writes two complementary files at the project root:-- **PRODUCT.md** (strategic): register, target users, product purpose, brand personality, anti-references, strategic design principles. Answers "who/what/why".-- **DESIGN.md** (visual): visual theme, color palette, typography, components, layout. Follows the [Google Stitch DESIGN.md format](https://stitch.withgoogle.com/docs/design-md/format/). Answers "how it looks".+- **PRODUCT.md** (strategic): root project file for register, target users, product purpose, brand personality, anti-references, strategic design principles. Answers "who/what/why".+- **DESIGN.md** (visual): root project file for visual theme, color palette, typography, components, layout. Follows the [Google Stitch DESIGN.md format](https://stitch.withgoogle.com/docs/design-md/format/). Answers "how it looks".Every other impeccable command reads these files before doing any work.diff --git a/.trae-cn/skills/impeccable/scripts/impeccable-paths.mjs b/.trae-cn/skills/impeccable/scripts/impeccable-paths.mjsnew file mode 100644index 000000000..ba852bae9--- /dev/null+++ b/.trae-cn/skills/impeccable/scripts/impeccable-paths.mjs@@ -0,0 +1,105 @@+import fs from 'node:fs';+import path from 'node:path';++export const IMPECCABLE_DIR = '.impeccable';+export const LIVE_DIR = 'live';++export function getImpeccableDir(cwd = process.cwd()) {+ return path.join(cwd, IMPECCABLE_DIR);+}++export function getDesignSidecarPath(cwd = process.cwd()) {+ return path.join(getImpeccableDir(cwd), 'design.json');+}++export function getDesignSidecarCandidates(cwd = process.cwd(), contextDir = cwd) {+ const candidates = [+ getDesignSidecarPath(cwd),+ path.join(cwd, 'DESIGN.json'),+ ];+ const contextLegacy = path.join(contextDir, 'DESIGN.json');+ if (!candidates.includes(contextLegacy)) candidates.push(contextLegacy);+ return candidates;+}++export function resolveDesignSidecarPath(cwd = process.cwd(), contextDir = cwd) {+ return firstExisting(getDesignSidecarCandidates(cwd, contextDir));+}++export function getLiveDir(cwd = process.cwd()) {+ return path.join(getImpeccableDir(cwd), LIVE_DIR);+}++export function getLiveConfigPath(cwd = process.cwd()) {+ return path.join(getLiveDir(cwd), 'config.json');+}++export function getLegacyLiveConfigPath(scriptsDir) {+ return path.join(scriptsDir, 'config.json');+}++export function resolveLiveConfigPath({ cwd = process.cwd(), scriptsDir, env = process.env } = {}) {+ if (env.IMPECCABLE_LIVE_CONFIG && env.IMPECCABLE_LIVE_CONFIG.trim()) {+ const configured = env.IMPECCABLE_LIVE_CONFIG.trim();+ return path.isAbsolute(configured) ? configured : path.resolve(cwd, configured);+ }+ const primary = getLiveConfigPath(cwd);+ if (fs.existsSync(primary)) return primary;+ if (scriptsDir) {+ const legacy = getLegacyLiveConfigPath(scriptsDir);+ if (fs.existsSync(legacy)) return legacy;+ }+ return primary;+}++export function getLiveServerPath(cwd = process.cwd()) {+ return path.join(getLiveDir(cwd), 'server.json');+}++export function getLegacyLiveServerPath(cwd = process.cwd()) {+ return path.join(cwd, '.impeccable-live.json');+}++export function readLiveServerInfo(cwd = process.cwd()) {+ for (const filePath of [getLiveServerPath(cwd), getLegacyLiveServerPath(cwd)]) {+ try {+ return { info: JSON.parse(fs.readFileSync(filePath, 'utf-8')), path: filePath };+ } catch {+ /* try next */+ }+ }+ return null;+}++export function writeLiveServerInfo(cwd = process.cwd(), info) {+ const filePath = getLiveServerPath(cwd);+ fs.mkdirSync(path.dirname(filePath), { recursive: true });+ fs.writeFileSync(filePath, JSON.stringify(info));+ return filePath;+}++export function removeLiveServerInfo(cwd = process.cwd()) {+ for (const filePath of [getLiveServerPath(cwd), getLegacyLiveServerPath(cwd)]) {+ try { fs.unlinkSync(filePath); } catch {}+ }+}++export function getLiveSessionsDir(cwd = process.cwd()) {+ return path.join(getLiveDir(cwd), 'sessions');+}++export function getLegacyLiveSessionsDir(cwd = process.cwd()) {+ return path.join(cwd, '.impeccable-live', 'sessions');+}++export function getLiveAnnotationsDir(cwd = process.cwd()) {+ return path.join(getLiveDir(cwd), 'annotations');+}++export function getLegacyLiveAnnotationsDir(cwd = process.cwd()) {+ return path.join(cwd, '.impeccable-live', 'annotations');+}++function firstExisting(paths) {+ return paths.find((filePath) => fs.existsSync(filePath)) || null;+}diff --git a/.trae-cn/skills/impeccable/scripts/live-browser-session.js b/.trae-cn/skills/impeccable/scripts/live-browser-session.jsnew file mode 100644index 000000000..0e362d6be--- /dev/null+++ b/.trae-cn/skills/impeccable/scripts/live-browser-session.js@@ -0,0 +1,123 @@+/**+ * Browser-side durable session helpers for Impeccable live mode.+ *+ * Kept separate from live-browser.js so recovery state can be tested without+ * booting the full overlay UI. Served before live-browser.js and attached to+ * window.__IMPECCABLE_LIVE_SESSION__.+ */+(function (root) {+ 'use strict';++ function createLiveBrowserSessionState({ prefix, storage, idFactory }) {+ if (!prefix) throw new Error('prefix required');+ const store = storage || root.localStorage;+ const makeId = idFactory || function () { return Math.random().toString(16).slice(2, 10); };+ const sessionKey = prefix + '-session';+ const handledKey = sessionKey + '-handled';+ const scrollKey = sessionKey + '-scroll';+ let checkpointRevision = 0;+ const owner = makeId();++ function safeRead(key) {+ try { return store.getItem(key); } catch { return null; }+ }++ function safeWrite(key, value) {+ try { store.setItem(key, value); } catch { /* quota exceeded or private mode */ }+ }++ function safeRemove(key) {+ try { store.removeItem(key); } catch { /* unavailable storage */ }+ }++ function loadSession() {+ try {+ const raw = safeRead(sessionKey);+ if (!raw) return null;+ const parsed = JSON.parse(raw);+ if (Number.isInteger(parsed.checkpointRevision)) {+ checkpointRevision = Math.max(checkpointRevision, parsed.checkpointRevision);+ }+ return parsed;+ } catch { return null; }+ }++ function saveSession(session) {+ if (!session || !session.id) return;+ const payload = {+ ...session,+ checkpointRevision,+ };+ safeWrite(sessionKey, JSON.stringify(payload));+ }++ function clearSession() {+ safeRemove(sessionKey);+ }++ function nextCheckpointRevision() {+ checkpointRevision += 1;+ const existing = loadSession();+ if (existing?.id) saveSession(existing);+ return checkpointRevision;+ }++ function seedCheckpointRevision(value) {+ if (Number.isInteger(value)) checkpointRevision = Math.max(checkpointRevision, value);+ return checkpointRevision;+ }++ function currentCheckpointRevision() {+ return checkpointRevision;+ }++ function markHandled(id) {+ if (!id) return;+ safeWrite(handledKey, id);+ }++ function isHandled(id) {+ return !!id && safeRead(handledKey) === id;+ }++ function clearHandled() {+ safeRemove(handledKey);+ }++ function writeScrollY(y) {+ safeWrite(scrollKey, String(y));+ }++ function readScrollY() {+ const raw = safeRead(scrollKey);+ if (raw == null) return null;+ const n = parseFloat(raw);+ return isFinite(n) ? n : null;+ }++ function clearScrollY() {+ safeRemove(scrollKey);+ }++ return {+ owner,+ sessionKey,+ handledKey,+ scrollKey,+ saveSession,+ loadSession,+ clearSession,+ nextCheckpointRevision,+ seedCheckpointRevision,+ currentCheckpointRevision,+ markHandled,+ isHandled,+ clearHandled,+ writeScrollY,+ readScrollY,+ clearScrollY,+ };+ }++ root.__IMPECCABLE_LIVE_SESSION__ = { createLiveBrowserSessionState };+})(typeof window !== 'undefined' ? window : globalThis);diff --git a/.trae-cn/skills/impeccable/scripts/live-browser.js b/.trae-cn/skills/impeccable/scripts/live-browser.jsindex 3da76bb96..e67cd01ed 100644--- a/.trae-cn/skills/impeccable/scripts/live-browser.js+++ b/.trae-cn/skills/impeccable/scripts/live-browser.js@@ -50,6 +50,16 @@const Z = { highlight: 100001, bar: 100005, picker: 100007, toast: 100010 };const EASE = 'cubic-bezier(0.22, 1, 0.36, 1)'; // ease-out-quintconst PREFIX = 'impeccable-live';+ const sessionState = window.__IMPECCABLE_LIVE_SESSION__?.createLiveBrowserSessionState({+ prefix: PREFIX,+ storage: localStorage,+ idFactory: () => crypto.randomUUID().replace(/-/g, '').slice(0, 8),+ });+ if (!sessionState) {+ console.error('[impeccable] live-browser-session.js was not loaded. Live mode cannot start safely.');+ window.__IMPECCABLE_LIVE_INIT__ = false;+ return;+ }const HIGHLIGHT_TRANSITION ='top 140ms ' + EASE +', left 140ms ' + EASE +@@ -112,6 +122,8 @@let hasProjectContext = false;let selectedAction = 'impeccable';let selectedCount = 3;+ const browserOwner = sessionState.owner;+ let checkpointTimer = null;// Scroll lock — holds window.scrollY at a fixed value while the session is// active, so HMR DOM patches and variant swaps can't drift the page. See@@ -126,21 +138,9 @@// (Previously: saveSession wrote scrollY alongside state, so every call// during resume overwrote the pre-reload value with whatever the browser// had landed on, typically 0.)- const SCROLL_KEY_SUFFIX = '-scroll';- function writeScrollY(y) {- try { localStorage.setItem(LS_KEY + SCROLL_KEY_SUFFIX, String(y)); } catch {}- }- function readScrollY() {- try {- const raw = localStorage.getItem(LS_KEY + SCROLL_KEY_SUFFIX);- if (raw == null) return null;- const n = parseFloat(raw);- return isFinite(n) ? n : null;- } catch { return null; }- }- function clearScrollY() {- try { localStorage.removeItem(LS_KEY + SCROLL_KEY_SUFFIX); } catch {}- }+ function writeScrollY(y) { sessionState.writeScrollY(y); }+ function readScrollY() { return sessionState.readScrollY(); }+ function clearScrollY() { sessionState.clearScrollY(); }// Pre-empt the browser: apply manual scroll restoration and jump to the// saved scrollY at script-parse time. Retries on fonts.ready and load@@ -1585,6 +1585,7 @@paramsCurrentValues[p.id] = v;readout.textContent = formatRangeValue(input);applyParamValue(variantEl, p, v);+ queueCheckpoint('param_changed');});row.appendChild(input);} else if (p.kind === 'toggle') {@@ -1615,6 +1616,7 @@knob.style.left = next ? '18px' : '2px';readout.textContent = next ? 'On' : 'Off';applyParamValue(variantEl, p, next);+ queueCheckpoint('param_changed');});row.appendChild(track);} else if (p.kind === 'steps') {@@ -1651,6 +1653,7 @@btn.style.color = on ? 'oklch(98% 0 0)' : P.text;});applyParamValue(variantEl, p, o.value);+ queueCheckpoint('param_changed');});segRow.appendChild(b);segBtns.push({ btn: b, val: o.value });@@ -1872,19 +1875,26 @@return;}+ const previousVisibleVariant = currentSessionId === sessionId ? visibleVariant : 0;+// Replace the live element with the full wrapper from sourceconst wrapper = srcWrapper.cloneNode(true);liveEl.parentElement.replaceChild(wrapper, liveEl);- // Update state: count variants, show the first one+ // Update state: count variants, preserving the user's current variant+ // when a late HMR/source reinjection lands after they have cycled.const variants = wrapper.querySelectorAll('[data-impeccable-variant]:not([data-impeccable-variant="original"])');arrivedVariants = variants.length;expectedVariants = parseInt(wrapper.dataset.impeccableVariantCount || arrivedVariants);- visibleVariant = 1;- showVariantInDOM(sessionId, 1);+ const saved = loadSession();+ const savedVisibleVariant = saved && saved.id === sessionId ? saved.visible : 0;+ visibleVariant = previousVisibleVariant > 0 && previousVisibleVariant <= arrivedVariants+ ? previousVisibleVariant+ : (savedVisibleVariant > 0 && savedVisibleVariant <= arrivedVariants ? savedVisibleVariant : 1);+ showVariantInDOM(sessionId, visibleVariant);// Update selectedElement to the visible variant's content- selectedElement = pickVariantContent(wrapper, 1) || wrapper.parentElement;+ selectedElement = pickVariantContent(wrapper, visibleVariant) || wrapper.parentElement;state = 'CYCLING';hideShaderOverlay();@@ -1907,6 +1917,7 @@updateSelectedElement();updateBarContent('cycling');saveSession();+ queueCheckpoint('variant_changed');}function updateSelectedElement() {@@ -1917,6 +1928,18 @@if (visEl) selectedElement = visEl;}+ function readVisibleVariantFromDOM(sessionId) {+ const wrapper = document.querySelector('[data-impeccable-variants="' + sessionId + '"]');+ if (!wrapper) return 0;+ const variants = wrapper.querySelectorAll('[data-impeccable-variant]:not([data-impeccable-variant="original"])');+ for (const variant of variants) {+ if (variant.style.display === 'none') continue;+ const idx = parseInt(variant.dataset.impeccableVariant || '0', 10);+ if (idx > 0) return idx;+ }+ return 0;+ }+// Resolve the element that represents the variant's visible content.// Contract: each variant div should contain exactly one top-level element// (the full replacement). In practice a model may ship loose siblings or@@ -2107,8 +2130,10 @@updating = true;arrivedVariants = count;if (visibleVariant === 0 && arrivedVariants > 0) {- visibleVariant = 1;- showVariantInDOM(sessionId, 1);+ const saved = loadSession();+ const savedVisibleVariant = saved && saved.id === sessionId ? saved.visible : 0;+ visibleVariant = savedVisibleVariant > 0 && savedVisibleVariant <= arrivedVariants ? savedVisibleVariant : 1;+ showVariantInDOM(sessionId, visibleVariant);// showVariantInDOM hid the original (display:none); if we were still// anchored to the original's content, its boundingRect is now zero// and the bar snaps to (0,0). Re-point at the visible variant instead.@@ -2128,6 +2153,7 @@updateBarContent('generating');}saveSession();+ queueCheckpoint(state === 'CYCLING' ? 'variants_ready' : 'variants_progress');updating = false;});@@ -2236,6 +2262,7 @@/** Server died or became unreachable. Reset UI to a clean state. */function handleServerLost() {+ const recoveryState = currentSessionId ? state : 'IDLE';if (state === 'GENERATING' || state === 'CYCLING' || state === 'SAVING') {showToast('Live server disconnected. Session ended.', 5000);}@@ -2246,21 +2273,61 @@stopScrollTracking();if (variantObserver) { variantObserver.disconnect(); variantObserver = null; }stopScrollLock();- clearScrollY();- clearSession();+ // Preserve local session state on server loss. The durable journal is the+ // source of truth, but localStorage plus the variant wrapper lets the UI+ // resume after a helper restart or page reload instead of treating a+ // transient disconnect as an explicit discard.selectedElement = null;- currentSessionId = null;selectedAction = 'impeccable';- state = 'IDLE';+ state = recoveryState;+ if (currentSessionId) saveSession();}- function sendEvent(msg) {+ function sendEvent(msg, opts) {msg.token = TOKEN;- fetch('http://localhost:' + PORT + '/events', {+ function handleFailure(err) {+ console.error('[impeccable] Failed to send event:', err);+ if (opts && opts.throwOnError) throw err;+ return null;+ }+ return fetch('http://localhost:' + PORT + '/events', {method: 'POST',headers: { 'Content-Type': 'application/json' },body: JSON.stringify(msg),- }).catch(err => console.error('[impeccable] Failed to send event:', err));+ }).then(res => {+ if (res.ok) return res;+ return handleFailure(new Error('HTTP ' + res.status + ' ' + res.statusText));+ }).catch(handleFailure);+ }++ function checkpointPayload(reason) {+ return {+ type: 'checkpoint',+ id: currentSessionId,+ revision: sessionState.nextCheckpointRevision(),+ owner: browserOwner,+ phase: String(state || '').toLowerCase(),+ reason,+ pageUrl: location.pathname,+ expectedVariants,+ arrivedVariants,+ visibleVariant,+ paramValues: { ...paramsCurrentValues },+ };+ }++ function sendCheckpoint(reason) {+ if (!currentSessionId) return Promise.resolve(null);+ return sendEvent(checkpointPayload(reason)).catch(() => null);+ }++ function queueCheckpoint(reason) {+ if (!currentSessionId) return;+ if (checkpointTimer) clearTimeout(checkpointTimer);+ checkpointTimer = setTimeout(() => {+ checkpointTimer = null;+ sendCheckpoint(reason);+ }, 120);}// ---------------------------------------------------------------------------@@ -2496,6 +2563,7 @@state = 'GENERATING';showBar('generating');saveSession();+ sendCheckpoint('generate_started');writeScrollY(window.scrollY);if (variantObserver) variantObserver.disconnect();variantObserver = startVariantObserver(currentSessionId);@@ -2920,13 +2988,12 @@ void main() {function handleAccept() {if (!currentSessionId || arrivedVariants === 0) return;+ const domVisibleVariant = readVisibleVariantFromDOM(currentSessionId);+ if (domVisibleVariant > 0) visibleVariant = domVisibleVariant;const acceptPayload = { type: 'accept', id: currentSessionId, variantId: String(visibleVariant) };if (Object.keys(paramsCurrentValues).length > 0) {acceptPayload.paramValues = { ...paramsCurrentValues };}- sendEvent(acceptPayload);- markSessionHandled();-// The accepted variant is already the only visible child of the wrapper// (all other variants are display:none). HMR from the source rewrite will// replace the wrapper imminently. Don't eagerly replaceChild here — React@@ -2936,9 +3003,28 @@ void main() {const acceptedSessionId = currentSessionId;const acceptedVariant = visibleVariant;- state = 'CONFIRMED';- updateBarContent('confirmed');- setTimeout(function() {+ state = 'SAVING';+ updateBarContent('saving');++ sendEvent(acceptPayload, { throwOnError: true })+ .then(() => {+ markSessionHandled();+ confirmAcceptAfterReceipt();+ })+ .catch(() => {+ state = 'CYCLING';+ updateBarContent('cycling');+ showToast('Could not confirm accept with the live server. Session kept for recovery; try Accept again.', 5000);+ });++ function confirmAcceptAfterReceipt() {+ state = 'CONFIRMED';+ updateBarContent('confirmed');+ scheduleAcceptCleanup();+ }++ function scheduleAcceptCleanup() {+ setTimeout(function() {hideBar();hideHighlight();stopScrollTracking();@@ -2967,50 +3053,46 @@ void main() {accepted.style.display = 'contents';parent.replaceChild(accepted, wrapper);}- }, 2000);+ }, 2000);+ }}function handleDiscard() {if (!currentSessionId) return;- sendEvent({ type: 'discard', id: currentSessionId });- markSessionHandled();- // Instant DOM restore + fire-and-forget (script handles file cleanup)- cleanup();+ sendEvent({ type: 'discard', id: currentSessionId }, { throwOnError: true })+ .then(() => {+ markSessionHandled();+ cleanup();+ })+ .catch(() => showToast('Could not confirm discard with the live server. Session kept for recovery.', 5000));}// ---------------------------------------------------------------------------- // Session persistence via localStorage+ // Session persistence via live-browser-session.js// ---------------------------------------------------------------------------// Survives page reloads, browser close/reopen, HMR, and accidental refreshes.- const LS_KEY = PREFIX + '-session';-function saveSession() {if (!currentSessionId) return;// NOTE: scrollY is stored under a separate key (writeScrollY). Storing// it here would overwrite the Go-time value every time state changes.- try {- localStorage.setItem(LS_KEY, JSON.stringify({- id: currentSessionId,- state: state,- action: selectedAction,- count: selectedCount,- expected: expectedVariants,- arrived: arrivedVariants,- visible: visibleVariant,- }));- } catch { /* quota exceeded or private mode */ }+ sessionState.saveSession({+ id: currentSessionId,+ state,+ action: selectedAction,+ count: selectedCount,+ expected: expectedVariants,+ arrived: arrivedVariants,+ visible: visibleVariant,+ });}function loadSession() {- try {- const raw = localStorage.getItem(LS_KEY);- return raw ? JSON.parse(raw) : null;- } catch { return null; }+ return sessionState.loadSession();}function clearSession() {- try { localStorage.removeItem(LS_KEY); } catch {}+ sessionState.clearSession();}/** Mark session as handled (accepted/discarded). The agent will clean up@@ -3018,19 +3100,15 @@ void main() {* prevents resumeSession from picking it up again after reload. */function markSessionHandled() {if (!currentSessionId) return;- try {- localStorage.setItem(LS_KEY + '-handled', currentSessionId);- } catch {}+ sessionState.markHandled(currentSessionId);}function isSessionHandled(id) {- try {- return localStorage.getItem(LS_KEY + '-handled') === id;- } catch { return false; }+ return sessionState.isHandled(id);}function clearHandled() {- try { localStorage.removeItem(LS_KEY + '-handled'); } catch {}+ sessionState.clearHandled();}function cleanup() {@@ -3161,6 +3239,7 @@ void main() {// hid. Now that state is CYCLING, re-fire.if (state === 'CYCLING') refreshParamsPanel();saveSession();+ queueCheckpoint('browser_resumed');// Start observing for more variants AFTER initial setupif (variantObserver) variantObserver.disconnect();@@ -3617,7 +3696,7 @@ void main() {}// ---------------------------------------------------------------------------- // Design System Panel — visualizes the project's DESIGN.json sidecar+ // Design System Panel — visualizes the project's .impeccable/design.json sidecar// ---------------------------------------------------------------------------const DESIGN_PREFS_KEY = 'impeccable-live-design-panel';@@ -3629,7 +3708,7 @@ void main() {open: false,tab: 'visual', // 'visual' | 'raw'parsed: null, // parseDesignMd output (frontmatter + body sections)- sidecar: null, // DESIGN.json v2 payload (extensions + components + narrative)+ sidecar: null, // .impeccable/design.json v2 payload (extensions + components + narrative)hasMd: false,hasSidecar: false,present: null, // true/false once fetch resolves@@ -4130,7 +4209,7 @@ void main() {box.className = 'stale';box.innerHTML = `<span class="stale-dot"></span>- <span class="stale-text"><strong>DESIGN.md is newer than DESIGN.json.</strong> Run <code>/impeccable document</code> to refresh the sidecar.</span>+ <span class="stale-text"><strong>DESIGN.md is newer than .impeccable/design.json.</strong> Run <code>/impeccable document</code> to refresh the sidecar.</span>`;return box;}@@ -4138,7 +4217,7 @@ void main() {function renderParsedMdCta() {const box = document.createElement('div');box.className = 'parsed-md-cta';- box.innerHTML = `<strong>Basic view</strong>This panel reads the tokens in your <code>DESIGN.md</code> frontmatter. Running <code>/impeccable document</code> also generates a <code>DESIGN.json</code> sidecar with your project's actual component snippets (button, input, nav) and tonal ramps, rendered live below the tokens.`;+ box.innerHTML = `<strong>Basic view</strong>This panel reads the tokens in your <code>DESIGN.md</code> frontmatter. Running <code>/impeccable document</code> also generates a <code>.impeccable/design.json</code> sidecar with your project's actual component snippets (button, input, nav) and tonal ramps, rendered live below the tokens.`;return box;}@@ -4598,7 +4677,7 @@ void main() {function cssSafe(v) {// Strip anything outside valid CSS value chars to prevent injection via- // DESIGN.json values rendered into inline style strings.+ // .impeccable/design.json values rendered into inline style strings.return String(v).replace(/[<>"'`\n]/g, '');}diff --git a/.trae-cn/skills/impeccable/scripts/live-complete.mjs b/.trae-cn/skills/impeccable/scripts/live-complete.mjsnew file mode 100644index 000000000..78155af85--- /dev/null+++ b/.trae-cn/skills/impeccable/scripts/live-complete.mjs@@ -0,0 +1,75 @@+#!/usr/bin/env node+/**+ * Canonical durable completion acknowledgement for Impeccable live sessions.+ */++import { createLiveSessionStore } from './live-session-store.mjs';+import { readLiveServerInfo } from './impeccable-paths.mjs';++function parseArgs(argv) {+ const out = { status: 'complete' };+ for (let i = 0; i < argv.length; i++) {+ const arg = argv[i];+ if (arg === '--id') out.id = argv[++i];+ else if (arg.startsWith('--id=')) out.id = arg.slice('--id='.length);+ else if (arg === '--discarded' || arg === '--discard') out.status = 'discarded';+ else if (arg === '--error') { out.status = 'agent_error'; out.message = argv[++i] || 'unknown error'; }+ else if (arg.startsWith('--error=')) { out.status = 'agent_error'; out.message = arg.slice('--error='.length); }+ else if (arg === '--help' || arg === '-h') out.help = true;+ }+ return out;+}++export async function completeCli() {+ const args = parseArgs(process.argv.slice(2));+ if (args.help || !args.id) {+ console.log(`Usage: node live-complete.mjs --id SESSION_ID [--discarded|--error MESSAGE]\n\nAppend the final durable session acknowledgement. Use after accept/discard cleanup is verified.`);+ process.exit(args.help ? 0 : 1);+ }++ const serverInfo = readServerInfo();+ const serverResult = serverInfo ? await completeThroughServer(serverInfo, args) : null;+ if (serverResult?.ok) {+ const store = createLiveSessionStore({ cwd: process.cwd(), sessionId: args.id });+ const snapshot = store.getSnapshot(args.id, { includeCompleted: true });+ console.log(JSON.stringify({ ok: true, id: args.id, phase: snapshot?.phase || args.status, snapshot }, null, 2));+ return;+ }++ const store = createLiveSessionStore({ cwd: process.cwd(), sessionId: args.id });+ const event = args.status === 'discarded'+ ? { type: 'discarded', id: args.id }+ : args.status === 'agent_error'+ ? { type: 'agent_error', id: args.id, message: args.message || 'unknown error' }+ : { type: 'complete', id: args.id };+ const snapshot = store.appendEvent(event);+ console.log(JSON.stringify({ ok: true, id: args.id, phase: snapshot.phase, snapshot }, null, 2));+}++function readServerInfo() {+ return readLiveServerInfo(process.cwd())?.info || null;+}++async function completeThroughServer(info, args) {+ const type = args.status === 'discarded'+ ? 'discarded'+ : args.status === 'agent_error'+ ? 'error'+ : 'complete';+ try {+ const res = await fetch(`http://localhost:${info.port}/poll`, {+ method: 'POST',+ headers: { 'Content-Type': 'application/json' },+ body: JSON.stringify({ token: info.token, id: args.id, type, message: args.message }),+ });+ if (!res.ok) return null;+ return await res.json();+ } catch {+ return null;+ }+}++const _running = process.argv[1];+if (_running?.endsWith('live-complete.mjs') || _running?.endsWith('live-complete.mjs/')) {+ completeCli();+}diff --git a/.trae-cn/skills/impeccable/scripts/live-completion.mjs b/.trae-cn/skills/impeccable/scripts/live-completion.mjsnew file mode 100644index 000000000..86b637fff--- /dev/null+++ b/.trae-cn/skills/impeccable/scripts/live-completion.mjs@@ -0,0 +1,18 @@+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';+ return 'agent_done';+}++export function completionAckForAcceptResult(eventId, completionType, acceptResult) {+ const ack = { ok: true, type: completionType };+ if (acceptResult?.handled === true && acceptResult?.carbonize === true) {+ ack.final = false;+ ack.requiresComplete = true;+ ack.nextCommand = `live-complete.mjs --id ${eventId}`;+ ack.message = 'Carbonize cleanup must be verified, then the session must be completed explicitly before polling again.';+ }+ return ack;+}diff --git a/.trae-cn/skills/impeccable/scripts/live-inject.mjs b/.trae-cn/skills/impeccable/scripts/live-inject.mjsindex 1d2ae12f7..555c3a36a 100644--- a/.trae-cn/skills/impeccable/scripts/live-inject.mjs+++ b/.trae-cn/skills/impeccable/scripts/live-inject.mjs@@ -2,23 +2,24 @@* CLI helper: insert/remove the live variant mode script tag in the project's* main HTML entry point.*- * On first live run, the agent generates `config.json` in this script's- * directory with the project's insertion target (framework-specific). On+ * On first live run, the agent generates `.impeccable/live/config.json`+ * with the project's insertion target (framework-specific). On* every subsequent run, this script handles insert/remove deterministically* with zero LLM involvement.** Usage:* node live-inject.mjs --port PORT # Insert the live script tag* node live-inject.mjs --remove # Remove the live script tag- * node live-inject.mjs --check # Check whether config.json exists+ * node live-inject.mjs --check # Check whether live config exists*/import fs from 'node:fs';import path from 'node:path';import { fileURLToPath } from 'node:url';+import { resolveLiveConfigPath } from './impeccable-paths.mjs';const __dirname = path.dirname(fileURLToPath(import.meta.url));-const CONFIG_PATH = process.env.IMPECCABLE_LIVE_CONFIG || path.join(__dirname, 'config.json');+const CONFIG_PATH = resolveLiveConfigPath({ cwd: process.cwd(), scriptsDir: __dirname });const MARKER_OPEN_TEXT = 'impeccable-live-start';const MARKER_CLOSE_TEXT = 'impeccable-live-end';@@ -39,12 +40,12 @@ export async function injectCli() {console.log(`Usage: node live-inject.mjs [options]Insert or remove the live mode script tag in the project's HTML entry point.-Reads configuration from config.json (in this same directory).+Reads configuration from .impeccable/live/config.json.Modes:--port PORT Insert script tag pointing at http://localhost:PORT/live.js--remove Remove the script tag (if present)- --check Print whether config.json exists and its content+ --check Print whether .impeccable/live/config.json exists and its contentOutput (JSON):{ ok, file, inserted|removed, config? }`);diff --git a/.trae-cn/skills/impeccable/scripts/live-poll.mjs b/.trae-cn/skills/impeccable/scripts/live-poll.mjsindex eb8f1586a..10d452491 100644--- a/.trae-cn/skills/impeccable/scripts/live-poll.mjs+++ b/.trae-cn/skills/impeccable/scripts/live-poll.mjs@@ -9,10 +9,10 @@*/import { execFileSync } from 'node:child_process';-import fs from 'node:fs';import path from 'node:path';-import os from 'node:os';import { fileURLToPath } from 'node:url';+import { completionAckForAcceptResult, completionTypeForAcceptResult } from './live-completion.mjs';+import { readLiveServerInfo } from './impeccable-paths.mjs';// Node's built-in fetch (undici under the hood) enforces a 300s headers// timeout that can't be lowered per-request. We cap each request below@@ -20,15 +20,29 @@ import { fileURLToPath } from 'node:url';// depending on the standalone undici package.const PER_REQUEST_TIMEOUT_MS = 270_000;-const LIVE_PID_FILE = path.join(process.cwd(), '.impeccable-live.json');-function readServerInfo() {- try {- return JSON.parse(fs.readFileSync(LIVE_PID_FILE, 'utf-8'));- } catch {+ const record = readLiveServerInfo(process.cwd());+ if (!record) {console.error('No running live server found. Start one with: npx impeccable live');process.exit(1);}+ return record.info;+}++export function buildPollReplyPayload(token, { id, type, message, file, data }) {+ return { token, id, type, message, file, data };+}++async function postReply(base, token, reply) {+ const res = await fetch(`${base}/poll`, {+ method: 'POST',+ headers: { 'Content-Type': 'application/json' },+ body: JSON.stringify(buildPollReplyPayload(token, reply)),+ });+ if (!res.ok) {+ const body = await res.json().catch(() => ({}));+ throw new Error(body.error || res.statusText);+ }}export async function pollCli() {@@ -69,23 +83,7 @@ Options:}try {- const res = await fetch(`${base}/poll`, {- method: 'POST',- headers: { 'Content-Type': 'application/json' },- body: JSON.stringify({- token: info.token,- id,- type: status,- message,- file: filePath,- }),- });-- if (!res.ok) {- const body = await res.json().catch(() => ({}));- console.error(`Reply failed (${res.status}):`, body.error || res.statusText);- process.exit(1);- }+ await postReply(base, info.token, { id, type: status, message, file: filePath });// Success — silent exit (agent doesn't need output for replies)} catch (err) {@@ -156,7 +154,23 @@ Options:);event._acceptResult = JSON.parse(out.trim());} catch (err) {- event._acceptResult = { handled: false, error: err.message };+ event._acceptResult = { handled: false, mode: 'error', error: err.message };+ }++ const completionType = completionTypeForAcceptResult(event.type, event._acceptResult);+ try {+ await postReply(base, info.token, {+ id: event.id,+ type: completionType,+ message: event._acceptResult?.error,+ file: event._acceptResult?.file,+ data: event._acceptResult?.carbonize === true ? { carbonize: true } : undefined,+ });+ } catch (err) {+ event._completionAck = { ok: false, error: err.message };+ }+ if (!event._completionAck) {+ event._completionAck = completionAckForAcceptResult(event.id, completionType, event._acceptResult);}}@@ -164,7 +178,7 @@ Options:// JSON but skips nested fields. One line is enough — the full checklist// is in reference/live.md.if (event._acceptResult?.carbonize === true) {- process.stderr.write('\n⚠ Carbonize cleanup REQUIRED before next poll. See reference/live.md "Required after accept".\n\n');+ process.stderr.write('\n⚠ Carbonize cleanup REQUIRED before next poll. After cleanup, run live-complete.mjs --id ' + event.id + '. See reference/live.md "Required after accept".\n\n');}// Print the event as JSON — the agent reads this from stdoutdiff --git a/.trae-cn/skills/impeccable/scripts/live-resume.mjs b/.trae-cn/skills/impeccable/scripts/live-resume.mjsnew file mode 100644index 000000000..a3465c9b5--- /dev/null+++ b/.trae-cn/skills/impeccable/scripts/live-resume.mjs@@ -0,0 +1,48 @@+#!/usr/bin/env node+/**+ * Recover the next agent action from the durable live-session journal.+ */++import { createLiveSessionStore } from './live-session-store.mjs';++function parseArgs(argv) {+ const out = { id: null };+ for (let i = 0; i < argv.length; i++) {+ const arg = argv[i];+ if (arg === '--id') out.id = argv[++i];+ else if (arg.startsWith('--id=')) out.id = arg.slice('--id='.length);+ else if (arg === '--help' || arg === '-h') out.help = true;+ }+ return out;+}++export async function resumeCli() {+ const args = parseArgs(process.argv.slice(2));+ if (args.help) {+ console.log(`Usage: node live-resume.mjs [--id SESSION_ID]\n\nPrint the active durable session checkpoint and the next safe agent action.`);+ return;+ }++ const store = createLiveSessionStore({ cwd: process.cwd(), sessionId: args.id || undefined });+ const snapshot = args.id ? store.getSnapshot(args.id) : store.listActiveSessions()[0] || null;+ if (!snapshot) {+ console.log(JSON.stringify({ active: false, nextAction: 'No active durable live session found.' }, null, 2));+ return;+ }++ const pending = snapshot.pendingEvent || null;+ const nextAction = pending+ ? `Run live-poll.mjs, handle ${pending.type} ${pending.id}, then acknowledge with live-poll.mjs --reply ${pending.id} done.`+ : snapshot.phase === 'carbonize_required'+ ? `Finish carbonize cleanup${snapshot.sourceFile ? ` in ${snapshot.sourceFile}` : ''}, then run live-complete.mjs --id ${snapshot.id}.`+ : snapshot.phase === 'accept_requested'+ ? `Run live-complete.mjs --id ${snapshot.id} after verifying the accepted variant is written.`+ : `Inspect ${snapshot.id}; no pending agent event is currently queued.`;++ console.log(JSON.stringify({ active: true, snapshot, pendingEvent: pending, nextAction }, null, 2));+}++const _running = process.argv[1];+if (_running?.endsWith('live-resume.mjs') || _running?.endsWith('live-resume.mjs/')) {+ resumeCli();+}diff --git a/.trae-cn/skills/impeccable/scripts/live-server.mjs b/.trae-cn/skills/impeccable/scripts/live-server.mjsindex 90614fbf7..53d8f21cb 100644--- a/.trae-cn/skills/impeccable/scripts/live-server.mjs+++ b/.trae-cn/skills/impeccable/scripts/live-server.mjs@@ -22,14 +22,20 @@ import net from 'node:net';import { fileURLToPath } from 'node:url';import { parseDesignMd } from './design-parser.mjs';import { resolveContextDir } from './load-context.mjs';+import { createLiveSessionStore } from './live-session-store.mjs';+import {+ getDesignSidecarPath,+ getLiveAnnotationsDir,+ readLiveServerInfo,+ removeLiveServerInfo,+ resolveDesignSidecarPath,+ writeLiveServerInfo,+} from './impeccable-paths.mjs';const __dirname = path.dirname(fileURLToPath(import.meta.url));-// PID file in the project root so both the server and agent can find it-// predictably (os.tmpdir() varies across platforms).-const LIVE_PID_FILE = path.join(process.cwd(), '.impeccable-live.json');-// PRODUCT.md / DESIGN.md / DESIGN.json live wherever load-context.mjs resolves.-// Keeps live-server in sync with the loader when users keep the docs in-// .agents/context/, docs/, or a path set via IMPECCABLE_CONTEXT_DIR.+// PRODUCT.md / DESIGN.md live wherever load-context.mjs resolves. The generated+// DESIGN sidecar is project-local at .impeccable/design.json, with legacy+// DESIGN.json fallback for existing projects.const CONTEXT_DIR = resolveContextDir(process.cwd());const DEFAULT_POLL_TIMEOUT = 600_000; // 10 min — agent re-polls on timeout anywayconst SSE_HEARTBEAT_INTERVAL = 30_000; // keepalive ping every 30s@@ -57,10 +63,12 @@ const state = {token: null,port: null,sseClients: new Set(), // SSE response objects (server→browser push)- pendingEvents: [], // browser events waiting for agent poll+ pendingEvents: [], // browser events waiting for agent ack ({ event, leaseUntil })pendingPolls: [], // agent poll callbacks waiting for browser eventsexitTimer: null,sessionDir: null, // per-session tmp dir for annotation screenshots+ sessionStore: null,+ leaseTimer: null,};// Cap per-annotation upload size. A full 1920×1080 PNG is typically <1 MB;@@ -68,11 +76,70 @@ const state = {const MAX_ANNOTATION_BYTES = 10 * 1024 * 1024;function enqueueEvent(event) {- if (state.pendingPolls.length > 0) {- state.pendingPolls.shift()(event);- } else {- state.pendingEvents.push(event);+ if (!event || (event.id && state.pendingEvents.some((entry) => entry.event?.id === event.id && entry.event?.type === event.type))) return;+ state.pendingEvents.push({ event, leaseUntil: 0 });+ flushPendingPolls();+}++function restorePendingEventsFromStore() {+ if (!state.sessionStore) return;+ for (const snapshot of state.sessionStore.listActiveSessions()) {+ if (snapshot.pendingEvent) enqueueEvent(snapshot.pendingEvent);+ }+}++function findAvailablePendingEvent(now = Date.now()) {+ return state.pendingEvents.find((entry) => !entry.leaseUntil || entry.leaseUntil <= now);+}++function leaseEvent(entry, leaseMs) {+ if (!entry.event?.id) {+ const idx = state.pendingEvents.indexOf(entry);+ if (idx !== -1) state.pendingEvents.splice(idx, 1);+ return entry.event;}+ entry.leaseUntil = Date.now() + leaseMs;+ return entry.event;+}++function acknowledgePendingEvent(id) {+ if (!id) return false;+ const idx = state.pendingEvents.findIndex((entry) => entry.event?.id === id);+ if (idx === -1) return false;+ state.pendingEvents.splice(idx, 1);+ scheduleLeaseFlush();+ return true;+}++function scheduleLeaseFlush() {+ if (state.leaseTimer) {+ clearTimeout(state.leaseTimer);+ state.leaseTimer = null;+ }+ if (state.pendingPolls.length === 0) return;+ const now = Date.now();+ const nextLeaseUntil = state.pendingEvents+ .map((entry) => entry.leaseUntil || 0)+ .filter((leaseUntil) => leaseUntil > now)+ .sort((a, b) => a - b)[0];+ if (!nextLeaseUntil) return;+ state.leaseTimer = setTimeout(() => {+ state.leaseTimer = null;+ flushPendingPolls();+ }, Math.max(0, nextLeaseUntil - now));+}++function flushPendingPolls() {+ while (state.pendingPolls.length > 0) {+ const entry = findAvailablePendingEvent();+ if (!entry) {+ scheduleLeaseFlush();+ return;+ }+ const poll = state.pendingPolls.shift();+ poll.resolve(leaseEvent(entry, poll.leaseMs));+ }+ scheduleLeaseFlush();}/** Push a message to all connected SSE clients. */@@ -103,13 +170,16 @@ function loadBrowserScripts() {// live-browser.js: DO NOT cache. Return the path so the /live.js handler// can re-read on every request. Editing the browser script during iteration// should land on the next tab reload, not require a server restart.+ const sessionPath = path.join(__dirname, 'live-browser-session.js');const livePath = path.join(__dirname, 'live-browser.js');- if (!fs.existsSync(livePath)) {- process.stderr.write('Error: live-browser.js not found at ' + livePath + '\n');- process.exit(1);+ for (const p of [sessionPath, livePath]) {+ if (!fs.existsSync(p)) {+ process.stderr.write('Error: live browser script not found at ' + p + '\n');+ process.exit(1);+ }}- return { detectScript, livePath };+ return { detectScript, sessionPath, livePath };}function hasProjectContext() {@@ -170,6 +240,13 @@ function validateEvent(msg) {return null;case 'discard':return isValidId(msg.id) ? null : 'discard: missing or malformed id';+ case 'checkpoint':+ if (!isValidId(msg.id)) return 'checkpoint: missing or malformed id';+ if (!Number.isInteger(msg.revision) || msg.revision < 0) return 'checkpoint: revision must be a non-negative integer';+ if (msg.paramValues !== undefined && (typeof msg.paramValues !== 'object' || msg.paramValues === null || Array.isArray(msg.paramValues))) {+ return 'checkpoint: paramValues must be an object';+ }+ return null;case 'exit':return null;case 'prefetch':@@ -184,7 +261,7 @@ function validateEvent(msg) {// HTTP request handler// ----------------------------------------------------------------------------function createRequestHandler({ detectScript, livePath }) {+function createRequestHandler({ detectScript, sessionPath, livePath }) {return (req, res) => {const url = new URL(req.url, `http://localhost:${state.port}`);res.setHeader('Access-Control-Allow-Origin', '*');@@ -200,17 +277,20 @@ function createRequestHandler({ detectScript, livePath }) {// the next tab reload. No-store headers prevent browser caching across// sessions — during iteration, a cached old script silently breaks// every subsequent session.+ let sessionScript;let liveScript;try {+ sessionScript = fs.readFileSync(sessionPath, 'utf-8');liveScript = fs.readFileSync(livePath, 'utf-8');} catch (err) {res.writeHead(500, { 'Content-Type': 'text/plain' });- res.end('Error reading live-browser.js: ' + err.message);+ res.end('Error reading live browser scripts: ' + err.message);return;}const body =`window.__IMPECCABLE_TOKEN__ = '${state.token}';\n` +`window.__IMPECCABLE_PORT__ = ${state.port};\n` ++ sessionScript + '\n' +liveScript;res.writeHead(200, {'Content-Type': 'application/javascript',@@ -305,6 +385,26 @@ function createRequestHandler({ detectScript, livePath }) {}// --- Health ---+ if (p === '/status') {+ const token = url.searchParams.get('token');+ if (token !== state.token) { res.writeHead(401, { 'Content-Type': 'application/json' }); res.end(JSON.stringify({ error: 'Unauthorized' })); return; }+ const sessions = state.sessionStore ? state.sessionStore.listActiveSessions() : [];+ res.writeHead(200, { 'Content-Type': 'application/json' });+ res.end(JSON.stringify({+ status: 'ok',+ port: state.port,+ connectedClients: state.sseClients.size,+ pendingEvents: state.pendingEvents.map((entry) => ({+ id: entry.event?.id,+ type: entry.event?.type,+ leased: !!(entry.leaseUntil && entry.leaseUntil > Date.now()),+ leaseUntil: entry.leaseUntil || null,+ })),+ activeSessions: sessions,+ }));+ return;+ }+if (p === '/health') {res.writeHead(200, { 'Content-Type': 'application/json' });res.end(JSON.stringify({@@ -316,13 +416,13 @@ function createRequestHandler({ detectScript, livePath }) {}// --- Design system (unified v2 response) + raw ---- // /design-system.json returns both parsed DESIGN.md and DESIGN.json+ // /design-system.json returns both parsed DESIGN.md and .impeccable/design.json// sidecar when present. Panel merges them:// { present, parsed, sidecar, hasMd, hasSidecar,// mdNewerThanJson, parseError?, sidecarError? }// - parsed: output of parseDesignMd (frontmatter// + six canonical sections) when DESIGN.md exists.- // - sidecar: DESIGN.json contents when present.+ // - sidecar: .impeccable/design.json contents when present.// Expected shape: schemaVersion 2, carrying// extensions + components + narrative.// /design-system/raw returns DESIGN.md markdown verbatim@@ -331,7 +431,7 @@ function createRequestHandler({ detectScript, livePath }) {if (token !== state.token) { res.writeHead(401); res.end('Unauthorized'); return; }const mdPath = path.join(CONTEXT_DIR, 'DESIGN.md');- const jsonPath = path.join(CONTEXT_DIR, 'DESIGN.json');+ const jsonPath = resolveDesignSidecarPath(process.cwd(), CONTEXT_DIR) || getDesignSidecarPath(process.cwd());const mdStat = statOrNull(mdPath);const jsonStat = statOrNull(jsonPath);@@ -367,7 +467,7 @@ function createRequestHandler({ detectScript, livePath }) {try {response.sidecar = JSON.parse(fs.readFileSync(jsonPath, 'utf-8'));} catch (err) {- response.sidecarError = 'Failed to parse DESIGN.json: ' + err.message;+ response.sidecarError = 'Failed to parse .impeccable/design.json: ' + err.message;}}@@ -449,7 +549,16 @@ function createRequestHandler({ detectScript, livePath }) {res.end(JSON.stringify({ error }));return;}- enqueueEvent(msg);+ if (state.sessionStore && msg.id) {+ try {+ state.sessionStore.appendEvent(msg);+ } catch (err) {+ res.writeHead(500, { 'Content-Type': 'application/json' });+ res.end(JSON.stringify({ error: 'session_store_append_failed', message: err.message }));+ return;+ }+ }+ if (msg.type !== 'checkpoint') enqueueEvent(msg);res.writeHead(200, { 'Content-Type': 'application/json' });res.end(JSON.stringify({ ok: true }));});@@ -492,13 +601,16 @@ function handlePollGet(req, res, url) {return;}const timeout = parseInt(url.searchParams.get('timeout') || DEFAULT_POLL_TIMEOUT, 10);- if (state.pendingEvents.length > 0) {+ const leaseMs = parseInt(url.searchParams.get('leaseMs') || '30000', 10);+ const available = findAvailablePendingEvent();+ if (available) {res.writeHead(200, { 'Content-Type': 'application/json' });- res.end(JSON.stringify(state.pendingEvents.shift()));+ res.end(JSON.stringify(leaseEvent(available, leaseMs)));return;}+ const poll = { resolve, leaseMs };const timer = setTimeout(() => {- const idx = state.pendingPolls.indexOf(resolve);+ const idx = state.pendingPolls.indexOf(poll);if (idx !== -1) state.pendingPolls.splice(idx, 1);res.writeHead(200, { 'Content-Type': 'application/json' });res.end(JSON.stringify({ type: 'timeout' }));@@ -508,10 +620,11 @@ function handlePollGet(req, res, url) {res.writeHead(200, { 'Content-Type': 'application/json' });res.end(JSON.stringify(event));}- state.pendingPolls.push(resolve);+ state.pendingPolls.push(poll);+ scheduleLeaseFlush();req.on('close', () => {clearTimeout(timer);- const idx = state.pendingPolls.indexOf(resolve);+ const idx = state.pendingPolls.indexOf(poll);if (idx !== -1) state.pendingPolls.splice(idx, 1);});}@@ -531,6 +644,26 @@ function handlePollPost(req, res) {res.end(JSON.stringify({ error: 'Unauthorized' }));return;}+ acknowledgePendingEvent(msg.id);+ if (state.sessionStore && msg.id) {+ try {+ const eventType = msg.type === 'discard' || msg.type === 'discarded'+ ? 'discarded'+ : msg.type === 'complete'+ ? 'complete'+ : msg.type === 'error'+ ? 'agent_error'+ : 'agent_done';+ state.sessionStore.appendEvent({+ type: eventType,+ id: msg.id,+ file: msg.file,+ message: msg.message,+ carbonize: msg.data?.carbonize === true,+ });+ } catch { /* keep reply path best-effort; browser still needs SSE */ }+ }+ flushPendingPolls();// Forward the reply to the browser via SSEbroadcast({ type: msg.type || 'done', id: msg.id, message: msg.message, file: msg.file, data: msg.data });res.writeHead(200, { 'Content-Type': 'application/json' });@@ -545,13 +678,15 @@ function handlePollPost(req, res) {let httpServer = null;function shutdown() {- try { fs.unlinkSync(LIVE_PID_FILE); } catch {}+ removeLiveServerInfo(process.cwd());+ if (state.leaseTimer) clearTimeout(state.leaseTimer);+ state.leaseTimer = null;if (state.sessionDir) {try { fs.rmSync(state.sessionDir, { recursive: true, force: true }); } catch {}}for (const res of state.sseClients) { try { res.end(); } catch {} }state.sseClients.clear();- for (const resolve of state.pendingPolls) resolve({ type: 'exit' });+ for (const poll of state.pendingPolls) poll.resolve({ type: 'exit' });state.pendingPolls.length = 0;if (httpServer) httpServer.close();process.exit(0);@@ -587,6 +722,7 @@ Endpoints:/events SSE stream (server→browser) + POST (browser→server)/poll Long-poll for agent CLI/source Raw source file reader (no-HMR fallback)+ /status Durable recovery status (token-protected)/health Health check`);process.exit(0);}@@ -594,7 +730,7 @@ Endpoints:if (args.includes('stop')) {const keepInject = args.includes('--keep-inject');try {- const info = JSON.parse(fs.readFileSync(LIVE_PID_FILE, 'utf-8'));+ const { info } = readLiveServerInfo(process.cwd()) || {};const res = await fetch(`http://localhost:${info.port}/stop?token=${info.token}`);if (res.ok) console.log(`Stopped live server on port ${info.port}.`);} catch {@@ -645,7 +781,7 @@ if (args.includes('--background')) {const deadline = Date.now() + 10_000;while (Date.now() < deadline) {try {- const info = JSON.parse(fs.readFileSync(LIVE_PID_FILE, 'utf-8'));+ const { info } = readLiveServerInfo(process.cwd()) || {};if (info.pid !== process.pid) {// Output JSON so the agent can read port + token from stdout.console.log(JSON.stringify(info));@@ -659,30 +795,36 @@ if (args.includes('--background')) {}// Check for existing session-try {- const existing = JSON.parse(fs.readFileSync(LIVE_PID_FILE, 'utf-8'));- try { process.kill(existing.pid, 0);+const existingRecord = readLiveServerInfo(process.cwd());+if (existingRecord?.info) {+ const existing = existingRecord.info;+ try {+ process.kill(existing.pid, 0);console.error(`Live server already running on port ${existing.port} (pid ${existing.pid}).`);console.error('Stop it first with: node ' + path.basename(fileURLToPath(import.meta.url)) + ' stop');process.exit(1);- } catch { fs.unlinkSync(LIVE_PID_FILE); }-} catch {}+ } catch {+ try { fs.unlinkSync(existingRecord.path); } catch {}+ }+}state.token = randomUUID();+state.sessionStore = createLiveSessionStore({ cwd: process.cwd() });+restorePendingEventsFromStore();const portArg = args.find(a => a.startsWith('--port='));state.port = portArg ? parseInt(portArg.split('=')[1], 10) : await findOpenPort();// Annotation screenshots live in the project root so the agent's Read tool// doesn't trip a per-file permission prompt. Sessioned by token so concurrent// projects (or quick restarts) don't collide.-const annotRoot = path.join(process.cwd(), '.impeccable-live', 'annotations');+const annotRoot = getLiveAnnotationsDir(process.cwd());fs.mkdirSync(annotRoot, { recursive: true });state.sessionDir = fs.mkdtempSync(path.join(annotRoot, 'session-'));-const { detectScript, livePath } = loadBrowserScripts();-httpServer = http.createServer(createRequestHandler({ detectScript, livePath }));+const { detectScript, sessionPath, livePath } = loadBrowserScripts();+httpServer = http.createServer(createRequestHandler({ detectScript, sessionPath, livePath }));httpServer.listen(state.port, '127.0.0.1', () => {- fs.writeFileSync(LIVE_PID_FILE, JSON.stringify({ pid: process.pid, port: state.port, token: state.token }));+ writeLiveServerInfo(process.cwd(), { pid: process.pid, port: state.port, token: state.token });const url = `http://localhost:${state.port}`;console.log(`\nImpeccable live server running on ${url}`);console.log(`Token: ${state.token}\n`);diff --git a/.trae-cn/skills/impeccable/scripts/live-session-store.mjs b/.trae-cn/skills/impeccable/scripts/live-session-store.mjsnew file mode 100644index 000000000..d55ed2d3a--- /dev/null+++ b/.trae-cn/skills/impeccable/scripts/live-session-store.mjs@@ -0,0 +1,254 @@+import fs from 'node:fs';+import path from 'node:path';+import { getLegacyLiveSessionsDir, getLiveSessionsDir } from './impeccable-paths.mjs';++const COMPLETED_PHASES = new Set(['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;+ }++ function getReadableJournalPath(id) {+ const primary = getJournalPath(rootDir, id);+ if (fs.existsSync(primary)) return primary;+ const legacy = getJournalPath(legacyRootDir, id);+ if (fs.existsSync(legacy)) return legacy;+ return primary;+ }++ return {+ rootDir,+ legacyRootDir,+ appendEvent(event) {+ const normalized = normalizeEvent(event, sessionId);+ const journalPath = getJournalPath(rootDir, normalized.id);+ const snapshotPath = getSnapshotPath(rootDir, normalized.id);+ const legacyJournalPath = getJournalPath(legacyRootDir, normalized.id);+ if (!fs.existsSync(journalPath) && fs.existsSync(legacyJournalPath)) {+ fs.copyFileSync(legacyJournalPath, journalPath);+ }+ const prior = loadCachedOrRebuild(normalized.id);+ const seq = prior.nextSeq;+ const entry = {+ seq,+ id: normalized.id,+ type: normalized.type,+ ts: new Date().toISOString(),+ event: normalized,+ };+ 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;+ },+ getSnapshot(id = sessionId, opts = {}) {+ if (!id) throw new Error('session id required');+ 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;+ },+ listActiveSessions() {+ const ids = new Set();+ for (const dir of [legacyRootDir, rootDir]) {+ if (!fs.existsSync(dir)) continue;+ for (const name of fs.readdirSync(dir)) {+ if (name.endsWith('.jsonl')) ids.add(name.slice(0, -'.jsonl'.length));+ }+ }+ return [...ids]+ .sort()+ .map((id) => this.getSnapshot(id))+ .filter(Boolean);+ },+ };+}++function normalizeEvent(event, fallbackId) {+ if (!event || typeof event !== 'object') throw new Error('event object required');+ const id = event.id || fallbackId;+ if (!id || typeof id !== 'string') throw new Error('event id required');+ if (!event.type || typeof event.type !== 'string') throw new Error('event type required');+ return { ...event, id };+}++function getJournalPath(rootDir, id) {+ return path.join(rootDir, safeSessionId(id) + '.jsonl');+}++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,+ phase: 'new',+ pageUrl: null,+ sourceFile: null,+ expectedVariants: 0,+ arrivedVariants: 0,+ visibleVariant: null,+ paramValues: {},+ pendingEventSeq: null,+ pendingEvent: null,+ deliveryLease: null,+ checkpointRevision: 0,+ activeOwner: null,+ sourceMarkers: {},+ fallbackMode: null,+ annotationArtifacts: [],+ diagnostics: [],+ updatedAt: null,+ };+}++function rebuildSnapshotFromJournal(journalPath, id) {+ let snapshot = baseSnapshot(id);+ const diagnostics = [];+ let nextSeq = 1;+ if (!fs.existsSync(journalPath)) return { snapshot, diagnostics, nextSeq };++ const lines = fs.readFileSync(journalPath, 'utf-8').split('\n');+ for (let i = 0; i < lines.length; i++) {+ const line = lines[i];+ if (!line.trim()) continue;+ try {+ const entry = JSON.parse(line);+ if (!entry || typeof entry !== 'object') throw new Error('entry is not object');+ if (Number.isInteger(entry.seq)) nextSeq = Math.max(nextSeq, entry.seq + 1);+ snapshot = applyEvent(snapshot, entry);+ } catch (err) {+ diagnostics.push({+ error: 'journal_parse_failed',+ line: i + 1,+ message: err.message,+ });+ }+ }+ snapshot.diagnostics = [...snapshot.diagnostics, ...diagnostics];+ return { snapshot, diagnostics, nextSeq };+}++function applyEvent(snapshot, entry, inheritedDiagnostics = []) {+ const event = entry.event || entry;+ const next = {+ ...snapshot,+ paramValues: { ...(snapshot.paramValues || {}) },+ sourceMarkers: { ...(snapshot.sourceMarkers || {}) },+ annotationArtifacts: [...(snapshot.annotationArtifacts || [])],+ diagnostics: [...(snapshot.diagnostics || [])],+ updatedAt: entry.ts || new Date().toISOString(),+ };++ if (inheritedDiagnostics.length && next.diagnostics.length === 0) {+ next.diagnostics = [...inheritedDiagnostics];+ }++ switch (event.type) {+ case 'generate':+ next.phase = 'generate_requested';+ next.pageUrl = event.pageUrl ?? next.pageUrl;+ next.expectedVariants = event.count ?? next.expectedVariants;+ next.pendingEventSeq = entry.seq ?? next.pendingEventSeq;+ next.pendingEvent = toPendingEvent(event);+ if (event.screenshotPath) upsertArtifact(next.annotationArtifacts, { type: 'screenshot', path: event.screenshotPath });+ break;+ case 'variants_ready':+ case 'agent_done':+ next.phase = event.carbonize === true ? 'carbonize_required' : 'variants_ready';+ next.sourceFile = event.file ?? next.sourceFile;+ next.arrivedVariants = event.arrivedVariants ?? (next.arrivedVariants ?? next.expectedVariants);+ next.pendingEventSeq = null;+ next.pendingEvent = null;+ if (event.carbonize === true) {+ next.diagnostics.push({+ error: 'carbonize_cleanup_required',+ file: event.file || null,+ message: 'Accepted variant still has carbonize markers that must be folded into source CSS.',+ });+ }+ break;+ case 'checkpoint':+ 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;+ if (event.paramValues) next.paramValues = { ...event.paramValues };+ } else {+ next.diagnostics.push({ error: 'stale_checkpoint_ignored', revision: event.revision });+ }+ break;+ case 'accept':+ case 'accept_intent':+ next.phase = 'accept_requested';+ next.visibleVariant = Number(event.variantId ?? next.visibleVariant);+ if (event.paramValues) next.paramValues = { ...event.paramValues };+ next.pendingEventSeq = entry.seq ?? next.pendingEventSeq;+ next.pendingEvent = toPendingEvent(event);+ break;+ case 'discard':+ next.phase = 'discard_requested';+ next.pendingEventSeq = entry.seq ?? next.pendingEventSeq;+ next.pendingEvent = toPendingEvent(event);+ break;+ case 'discarded':+ next.phase = 'discarded';+ next.pendingEventSeq = null;+ next.pendingEvent = null;+ break;+ case 'complete':+ next.phase = 'completed';+ next.pendingEventSeq = null;+ next.pendingEvent = null;+ break;+ case 'agent_error':+ next.phase = 'agent_error';+ next.pendingEventSeq = null;+ next.pendingEvent = null;+ next.diagnostics.push({ error: 'agent_error', message: event.message || 'unknown agent error' });+ break;+ default:+ next.diagnostics.push({ error: 'unknown_event_type', type: event.type });+ break;+ }+ return next;+}++function toPendingEvent(event) {+ const pending = { ...event };+ delete pending.token;+ return pending;+}++function upsertArtifact(artifacts, artifact) {+ if (!artifacts.some((existing) => existing.path === artifact.path && existing.type === artifact.type)) {+ artifacts.push(artifact);+ }+}++function writeSnapshot(snapshotPath, snapshot) {+ fs.writeFileSync(snapshotPath, JSON.stringify(snapshot, null, 2) + '\n');+}diff --git a/.trae-cn/skills/impeccable/scripts/live-status.mjs b/.trae-cn/skills/impeccable/scripts/live-status.mjsnew file mode 100644index 000000000..dce1fbca2--- /dev/null+++ b/.trae-cn/skills/impeccable/scripts/live-status.mjs@@ -0,0 +1,47 @@+#!/usr/bin/env node+/**+ * Print durable recovery status for Impeccable live sessions.+ */++import { createLiveSessionStore } from './live-session-store.mjs';+import { readLiveServerInfo } from './impeccable-paths.mjs';++function readServerInfo() {+ return readLiveServerInfo(process.cwd())?.info || null;+}++async function fetchServerStatus(info) {+ if (!info) return null;+ try {+ const res = await fetch(`http://localhost:${info.port}/status?token=${info.token}`);+ if (!res.ok) return null;+ return await res.json();+ } catch {+ return null;+ }+}++export async function statusCli() {+ const info = readServerInfo();+ const server = await fetchServerStatus(info);+ const store = createLiveSessionStore({ cwd: process.cwd() });+ const activeSessions = store.listActiveSessions();+ const payload = {+ liveServer: server ? {+ status: server.status,+ port: server.port,+ connectedClients: server.connectedClients,+ pendingEvents: server.pendingEvents,+ } : null,+ activeSessions: server?.activeSessions || activeSessions,+ recoveryHint: 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.',+ };+ console.log(JSON.stringify(payload, null, 2));+}++const _running = process.argv[1];+if (_running?.endsWith('live-status.mjs') || _running?.endsWith('live-status.mjs/')) {+ statusCli();+}diff --git a/.trae-cn/skills/impeccable/scripts/live-wrap.mjs b/.trae-cn/skills/impeccable/scripts/live-wrap.mjsindex a5769a50a..d46328b9f 100644--- a/.trae-cn/skills/impeccable/scripts/live-wrap.mjs+++ b/.trae-cn/skills/impeccable/scripts/live-wrap.mjs@@ -185,6 +185,7 @@ The agent should insert variant HTML at insertLine.`);const { startLine, endLine } = match;const commentSyntax = detectCommentSyntax(targetFile);+ const styleMode = detectStyleMode(targetFile);const isJsx = commentSyntax.open === '{/*';const indent = lines[startLine].match(/^(\s*)/)[1];@@ -269,6 +270,10 @@ The agent should insert variant HTML at insertLine.`);endLine: startLine + wrapperLines.length + (originalLines.length - 1), // 1-indexedinsertLine: insertLine + 1, // 1-indexed: where variants gocommentSyntax: commentSyntax,+ styleMode: styleMode.mode,+ styleTag: styleMode.styleTag,+ cssSelectorPrefixExamples: buildCssSelectorPrefixExamples(styleMode.mode, count),+ cssAuthoring: buildCssAuthoring(styleMode, count),originalLineCount: originalLines.length,}));}@@ -335,6 +340,62 @@ function detectCommentSyntax(filePath) {return { open: '<!--', close: '-->' };}+function detectStyleMode(filePath) {+ const ext = path.extname(filePath).toLowerCase();+ if (ext === '.astro') {+ return {+ mode: 'astro-global-prefixed',+ styleTag: '<style is:inline data-impeccable-css="SESSION_ID">',+ };+ }+ return {+ mode: 'scoped',+ styleTag: '<style data-impeccable-css="SESSION_ID">',+ };+}++function buildCssSelectorPrefixExamples(styleMode, count) {+ if (styleMode !== 'astro-global-prefixed') return [];+ return Array.from({ length: count }, (_, i) => `[data-impeccable-variant="${i + 1}"]`);+}++function buildCssAuthoring(styleMode, count) {+ const variantNumbers = Array.from({ length: count }, (_, i) => i + 1);+ if (styleMode.mode === 'astro-global-prefixed') {+ return {+ mode: styleMode.mode,+ styleTag: styleMode.styleTag,+ strategy: 'global-prefixed',+ rulePattern: '[data-impeccable-variant="N"] > .variant-class { ... }',+ selectorExamples: variantNumbers.map((n) => `[data-impeccable-variant="${n}"] > .variant-class`),+ requirements: [+ 'Use the styleTag exactly; the is:inline attribute is required for this file.',+ 'Prefix every preview selector with the matching [data-impeccable-variant="N"] selector.',+ 'Keep selectors anchored to the generated variant wrapper; do not rely on component CSS scoping for preview rules.',+ ],+ forbidden: [+ 'Do not use @scope for this styleMode.',+ ],+ };+ }+ return {+ mode: styleMode.mode,+ styleTag: styleMode.styleTag,+ strategy: 'scope-rule',+ rulePattern: '@scope ([data-impeccable-variant="N"]) { :scope > .variant-class { ... } }',+ selectorExamples: variantNumbers.map((n) => `@scope ([data-impeccable-variant="${n}"]) { :scope > .variant-class { ... } }`),+ requirements: [+ 'Use @scope blocks keyed to each [data-impeccable-variant="N"] wrapper.',+ 'Inside each @scope block, make :scope rules step into the replacement element with a descendant combinator.',+ 'Use the styleTag exactly; do not add framework-specific style attributes unless this object says to.',+ ],+ forbidden: [+ 'Do not use global [data-impeccable-variant="N"] selector prefixes for this styleMode.',+ 'Do not add is:inline to the style tag for this styleMode.',+ ],+ };+}+/*** Search project files for the query string (class name, ID, etc.)* Returns the first matching file path, or null.diff --git a/.trae-cn/skills/impeccable/scripts/live.mjs b/.trae-cn/skills/impeccable/scripts/live.mjsindex befbdb8ed..cafb0eca9 100644--- a/.trae-cn/skills/impeccable/scripts/live.mjs+++ b/.trae-cn/skills/impeccable/scripts/live.mjs@@ -2,10 +2,10 @@* CLI entry point: prepare everything needed to enter the live variant poll loop.** Does (all in one command):- * 1. Check config.json (returns config_missing if first-ever run)+ * 1. Check .impeccable/live/config.json (returns config_missing if first-ever run)* 2. Start the live server in the background (or reuse a running one)* 3. Inject the browser script tag into the project's entry file- * 4. Read .impeccable.md for design context (if present)+ * 4. Read PRODUCT.md / DESIGN.md for project context* 5. Print a single JSON blob with everything the agent needs** After this, the agent's only remaining steps are:@@ -23,9 +23,9 @@ import path from 'node:path';import { fileURLToPath } from 'node:url';import { loadContext } from './load-context.mjs';import { resolveFiles } from './live-inject.mjs';+import { readLiveServerInfo } from './impeccable-paths.mjs';const __dirname = path.dirname(fileURLToPath(import.meta.url));-const PID_FILE = path.join(process.cwd(), '.impeccable-live.json');async function liveCli() {const args = process.argv.slice(2);@@ -34,10 +34,10 @@ async function liveCli() {console.log(`Usage: node live.mjsPrepare everything for live variant mode in a single command:- - Checks scripts/config.json (required, created once per project)+ - Checks .impeccable/live/config.json (required, created once per project)- Starts (or reuses) the live server in the background- Injects the browser script tag- - Reads .impeccable.md for design context+ - Reads PRODUCT.md / DESIGN.md for project contextOn success, prints a JSON blob with:{ ok, serverPort, serverToken, pageFile, hasContext, context }@@ -223,7 +223,7 @@ function safeParse(out) {function ensureServerRunning() {// Try to reuse an existing servertry {- const existing = JSON.parse(fs.readFileSync(PID_FILE, 'utf-8'));+ const existing = readLiveServerInfo(process.cwd())?.info;if (existing && existing.pid) {try {process.kill(existing.pid, 0); // throws if deaddiff --git a/.trae-cn/skills/impeccable/scripts/load-context.mjs b/.trae-cn/skills/impeccable/scripts/load-context.mjsindex dca23c1f8..dc340bf16 100644--- a/.trae-cn/skills/impeccable/scripts/load-context.mjs+++ b/.trae-cn/skills/impeccable/scripts/load-context.mjs@@ -39,7 +39,7 @@ const LEGACY_NAMES = ['.impeccable.md'];const FALLBACK_DIRS = ['.agents/context', 'docs'];/**- * Resolve the directory that holds PRODUCT.md / DESIGN.md / DESIGN.json for+ * Resolve the directory that holds PRODUCT.md / DESIGN.md for* this project. Exported so other scripts (e.g. live-server.mjs) can read the* design files from the same location the loader uses.*/diff --git a/.trae/skills/impeccable/reference/document.md b/.trae/skills/impeccable/reference/document.mdindex a01235903..02ce8d6f9 100644--- a/.trae/skills/impeccable/reference/document.md+++ b/.trae/skills/impeccable/reference/document.md@@ -237,11 +237,11 @@ Concrete, forceful guardrails. Lead each with "Do" or "Don't". Be specific: incl- **Don't** [...]```-### Step 4b: Write DESIGN.json sidecar (extensions only)+### Step 4b: Write .impeccable/design.json sidecar (extensions only)-The frontmatter owns token primitives (colors, typography, rounded, spacing, components). The sidecar at `DESIGN.json` carries **what Stitch's schema can't hold**: tonal ramps per color, shadow/elevation tokens, motion tokens, breakpoints, full component HTML/CSS snippets (the panel renders these into a shadow DOM), and narrative (north star, rules, do's/don'ts). It extends the frontmatter, it doesn't duplicate it.+The frontmatter owns token primitives (colors, typography, rounded, spacing, components). The sidecar at `.impeccable/design.json` carries **what Stitch's schema can't hold**: tonal ramps per color, shadow/elevation tokens, motion tokens, breakpoints, full component HTML/CSS snippets (the panel renders these into a shadow DOM), and narrative (north star, rules, do's/don'ts). It extends the frontmatter, it doesn't duplicate it.-Regenerate the sidecar whenever you regenerate DESIGN.md. If the user only asks to refresh the sidecar (e.g., from the live panel's stale-hint), preserve DESIGN.md and write only DESIGN.json.+Regenerate the sidecar whenever you regenerate root `DESIGN.md`. If the user only asks to refresh the sidecar (e.g., from the live panel's stale-hint), preserve `DESIGN.md` and write only `.impeccable/design.json`.#### Schema@@ -310,7 +310,7 @@ Aim for a tight set of **5-10 components** that best represent the visual system- **Signature components (include if distinctive):** hero CTA, featured card, filter pill, any custom pattern the user mentioned as important in PRODUCT.md.- **Skip the rest.** Utility components, form building blocks, wrapper layouts: not worth documenting unless visually distinctive.-If the project has **no component library yet** (bare landing page, new project), synthesize canonical primitives from the tokens using best-practice defaults consistent with the DESIGN.md's rules. Every DESIGN.json has *something* to render, even on day zero.+If the project has **no component library yet** (bare landing page, new project), synthesize canonical primitives from the tokens using best-practice defaults consistent with the DESIGN.md's rules. Every `.impeccable/design.json` has *something* to render, even on day zero.#### Tonal ramps@@ -331,7 +331,7 @@ Do not reword. The panel shows these as secondary collapsible context; the same### Step 5: Confirm, refine, and refresh session cache1. Show the user the full DESIGN.md you wrote. Briefly highlight the non-obvious creative choices (descriptive color names, atmosphere language, named rules).-2. Mention that `DESIGN.json` was also written alongside; the live panel will now render this project's actual button/input/nav primitives instead of generic approximations.+2. Mention that `.impeccable/design.json` was also written alongside; the live panel will now render this project's actual button/input/nav primitives instead of generic approximations.3. Offer to refine any section: "Want me to revise a section, add component patterns I missed, or adjust the atmosphere language?"4. **Refresh the session cache.** Run `node .trae/skills/impeccable/scripts/load-context.mjs` one final time so the newly-written DESIGN.md lands in conversation. Subsequent commands in this session will use the fresh version automatically without re-reading.@@ -392,7 +392,7 @@ Per-section guidance in seed mode:- **Components**: omit entirely; no components exist yet.- **Do's and Don'ts**: carry PRODUCT.md's anti-references directly plus the anti-reference named in Q5.-Seed mode writes a minimal frontmatter with `name` and `description` only; no colors, typography, rounded, spacing, or components yet. Real tokens land on the next Scan-mode run. Skip the `DESIGN.json` sidecar in seed mode for the same reason: nothing to render.+Seed mode writes a minimal frontmatter with `name` and `description` only; no colors, typography, rounded, spacing, or components yet. Real tokens land on the next Scan-mode run. Skip the `.impeccable/design.json` sidecar in seed mode for the same reason: nothing to render.### Step 4: Confirm and refresh session cachediff --git a/.trae/skills/impeccable/reference/live.md b/.trae/skills/impeccable/reference/live.mdindex 76c4dcbfb..763e727ef 100644--- a/.trae/skills/impeccable/reference/live.md+++ b/.trae/skills/impeccable/reference/live.md@@ -12,8 +12,9 @@ Execute in order. No step skipped, no step reordered.2. Navigate to the URL that serves `pageFile` (infer from `package.json`, docs, terminal output, or an open tab). If you can't infer it confidently, tell the user once to open their dev/preview URL. Never use `serverPort` as that URL; it's the helper, not the app.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=`.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.-5. On `accept` / `discard`: the poll script already cleaned up; just poll again.-6. On `exit`: run the cleanup at the bottom.+5. 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. If interrupted, run `live-status.mjs` or `live-resume.mjs` before guessing. The durable journal replays unacknowledged work after helper restart.+7. 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.@@ -43,13 +44,31 @@ LOOP:Read JSON; dispatch on "type""generate" → Handle Generate; reply done; LOOP- "accept" → Handle Accept; LOOP+ "accept" → Handle Accept; complete carbonize cleanup if required; LOOP"discard" → Handle Discard; LOOP"prefetch" → Handle Prefetch; LOOP"timeout" → LOOP"exit" → break → Cleanup```+## Recovery commands++The live helper persists an append-only journal under `.impeccable/live/sessions/`. Browser checkpoints are advisory but durable; the journal is canonical. This is local durable recovery state, not project source.++Use these commands when the chat was interrupted, polling was missed, the helper restarted, or the browser reloaded:++```bash+node .trae/skills/impeccable/scripts/live-status.mjs+node .trae/skills/impeccable/scripts/live-resume.mjs --id SESSION_ID+node .trae/skills/impeccable/scripts/live-complete.mjs --id SESSION_ID+```++- `live-status.mjs` prints connected helper state, active durable sessions, and queued pending events. It works even when the helper is down by reading the journal directly.+- `live-resume.mjs` prints the active snapshot, pending event, checkpoint phase, visible variant, parameter values, and the next safe agent action.+- `live-complete.mjs` is the canonical manual final acknowledgement. Use it after carbonize/manual cleanup is verified and no further poll acknowledgement will happen automatically.++Server restart rule: start `live-server.mjs` again, then poll. Startup requeues unacknowledged pending events from the journal, so do not ask the user to click Go again unless `live-resume.mjs` says no active session exists.+## Handle `generate`Event: `{id, action, freeformPrompt?, count, pageUrl, element, screenshotPath?, comments?, strokes?}`.@@ -88,7 +107,14 @@ The helper searches ID first, then classes, then tag + class combo. If `event.paIf `--text` matches multiple candidates equally well, wrap exits with `{ error: "element_ambiguous", candidates: [...] }` and `fallback: "agent-driven"`: read the candidate line ranges, decide which one matches the picked element from page context, and write the wrapper manually per the fallback flow.-Output on success: `{ file, insertLine, commentSyntax }`.+Output on success: `{ file, insertLine, commentSyntax, styleMode, styleTag, cssSelectorPrefixExamples, cssAuthoring }`.++`styleMode` controls how preview CSS must be authored. Treat it as a detected capability mode, not a framework guess:++- `scoped`: use `@scope ([data-impeccable-variant="N"])` rules.+- `astro-global-prefixed`: use explicit `[data-impeccable-variant="N"]` selector prefixes and the exact `styleTag` returned by the tool.++Use `cssAuthoring` as the source of truth for the current file. It includes the exact `styleTag`, selector strategy, selector examples, requirements, and forbidden patterns. Do not apply a framework-specific exception unless the returned `styleMode` / `cssAuthoring.mode` says to.**Fallback errors.** Wrap only writes into files it judges to be source (tracked by git, not marked GENERATED, not listed in config's `generatedFiles`). If it can't land on a source file, it errors without writing; accepting a variant into a generated file is silent data loss. Three shapes:@@ -208,13 +234,14 @@ When the prompt and PRODUCT.md anti-references conflict (the prompt asks for X,Complete 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 scoped 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).+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).++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:```html<!-- Variants: insert below this line --><style data-impeccable-css="SESSION_ID">- @scope ([data-impeccable-variant="1"]) { ... }- @scope ([data-impeccable-variant="2"]) { ... }+ /* rules matching cssAuthoring.rulePattern */</style><div data-impeccable-variant="1"><!-- variant 1: full element replacement (single top-level element) -->@@ -229,11 +256,11 @@ Write CSS + all variants in ONE edit at the `insertLine` reported by `wrap`. Col**Each variant div contains exactly one top-level element: the full replacement for the original.** Use the same tag as the original (e.g. `<section>` if the user picked a `<section>`). Loose siblings (heading + paragraph + div as direct children of the variant div) break the outline tracking and the accept flow, which both assume one child.-The first variant has no `display: none` (visible by default). All others do. If variants use only inline styles and no scoped CSS, omit the `<style>` tag entirely. Use `@scope` for CSS isolation (Chrome 118+ / Firefox 128+ / Safari 17.4+).+The 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.-**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 rule starts `:scope > ...`.+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 > ...`.**JSX / TSX target files.** Wrap `<style>` content in a template literal so the CSS `{` / `}` aren't parsed as JSX expressions, and use `className=` / `style={{…}}` on every variant element. Keep `data-impeccable-*` attributes as-is; they're plain strings:@@ -369,10 +396,11 @@ Remove the wrapper you inserted in Step 2. Nothing else to do.## Handle `accept`-Event: `{id, variantId, _acceptResult}`. The poll script already ran `live-accept.mjs` to handle the file operation deterministically; the browser DOM is already updated.+Event: `{id, variantId, _acceptResult, _completionAck}`. The poll script already ran `live-accept.mjs` to handle the file operation deterministically, then acknowledged event delivery to the helper. The browser DOM is already updated.+- `_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 and a stderr banner both list the steps explicitly; neither is decorative.+- `_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: 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` without `mode`: manual cleanup: read file, find markers, edit.@@ -388,13 +416,13 @@ Do these five steps in the current thread, synchronously, before the next poll.4. **Unwrap the accepted content.** Delete the `<div data-impeccable-variant="N" style="display: contents">` that wraps it. Drop `data-impeccable-params` and any `data-p-*` attributes from it; 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.-Then poll again.+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.## Handle `discard`-Event: `{id, _acceptResult}`. The poll script already restored the original and removed all variant markers. Nothing to do. Poll again.+Event: `{id, _acceptResult, _completionAck}`. The poll script already restored the original, removed all variant markers, and acknowledged `discarded` durable completion. Nothing to do unless `_completionAck.ok !== true`; in that case run `live-complete.mjs --id EVENT_ID --discarded`, then poll again.## Handle `prefetch`@@ -424,7 +452,7 @@ When the poll returns `exit`, proceed to cleanup. If the poll is still running anode .trae/skills/impeccable/scripts/live-server.mjs stop```-Stops the HTTP server and runs `live-inject.mjs --remove` to strip `localhost:…/live.js` from the HTML entry. To stop the server but keep the inject tag (for a quick restart), use `stop --keep-inject`. `config.json` persists for future sessions.+Stops the HTTP server and runs `live-inject.mjs --remove` to strip `localhost:…/live.js` from the HTML entry. To stop the server but keep the inject tag (for a quick restart), use `stop --keep-inject`. `.impeccable/live/config.json` persists as project config for future sessions.Then:- Remove any leftover variant wrappers (search for `impeccable-variants-start` markers).@@ -432,7 +460,7 @@ Then:## First-time setup (config missing or invalid)-If `live.mjs` outputs `{ ok: false, error: "config_missing" | "config_invalid", path }`, write `config.json` at the reported path.+If `live.mjs` outputs `{ ok: false, error: "config_missing" | "config_invalid", path }`, write the live config at the reported path. By default this is `.impeccable/live/config.json`.Schema:@@ -512,7 +540,7 @@ node .trae/skills/impeccable/scripts/detect-csp.mjsOutput: `{ shape, signals }` where `shape` is one of `append-arrays`, `append-string`, `middleware`, `meta-tag`, or `null`. The shape is named by *patch mechanism*, so one template covers many frameworks.-- **`null`**: no CSP; skip to writing `config.json` with `cspChecked: true`.+- **`null`**: no CSP; skip to writing `.impeccable/live/config.json` with `cspChecked: true`.- **`append-arrays`**: CSP defined as structured directive arrays. Auto-patchable. See *append-arrays* below. Covers:- Monorepo helpers with `additionalScriptSrc` / `additionalConnectSrc` options (Next.js + shared config package)- SvelteKit `kit.csp.directives`@@ -589,6 +617,6 @@ Reference outputs:### Troubleshooting-If a user says "no" to the CSP patch at setup time and later complains that live doesn't work: their dev CSP blocks `http://localhost:8400`. Fix: delete `cspChecked` from `config.json` and re-run `live.mjs`: setup will ask again.+If a user says "no" to the CSP patch at setup time and later complains that live doesn't work: their dev CSP blocks `http://localhost:8400`. Fix: delete `cspChecked` from `.impeccable/live/config.json` and re-run `live.mjs`: setup will ask again.Then re-run `live.mjs`.diff --git a/.trae/skills/impeccable/reference/teach.md b/.trae/skills/impeccable/reference/teach.mdindex d759ea15f..ed0ceedd7 100644--- a/.trae/skills/impeccable/reference/teach.md+++ b/.trae/skills/impeccable/reference/teach.md@@ -2,8 +2,8 @@Gathers design context for a project and writes two complementary files at the project root:-- **PRODUCT.md** (strategic): register, target users, product purpose, brand personality, anti-references, strategic design principles. Answers "who/what/why".-- **DESIGN.md** (visual): visual theme, color palette, typography, components, layout. Follows the [Google Stitch DESIGN.md format](https://stitch.withgoogle.com/docs/design-md/format/). Answers "how it looks".+- **PRODUCT.md** (strategic): root project file for register, target users, product purpose, brand personality, anti-references, strategic design principles. Answers "who/what/why".+- **DESIGN.md** (visual): root project file for visual theme, color palette, typography, components, layout. Follows the [Google Stitch DESIGN.md format](https://stitch.withgoogle.com/docs/design-md/format/). Answers "how it looks".Every other impeccable command reads these files before doing any work.diff --git a/.trae/skills/impeccable/scripts/impeccable-paths.mjs b/.trae/skills/impeccable/scripts/impeccable-paths.mjsnew file mode 100644index 000000000..ba852bae9--- /dev/null+++ b/.trae/skills/impeccable/scripts/impeccable-paths.mjs@@ -0,0 +1,105 @@+import fs from 'node:fs';+import path from 'node:path';++export const IMPECCABLE_DIR = '.impeccable';+export const LIVE_DIR = 'live';++export function getImpeccableDir(cwd = process.cwd()) {+ return path.join(cwd, IMPECCABLE_DIR);+}++export function getDesignSidecarPath(cwd = process.cwd()) {+ return path.join(getImpeccableDir(cwd), 'design.json');+}++export function getDesignSidecarCandidates(cwd = process.cwd(), contextDir = cwd) {+ const candidates = [+ getDesignSidecarPath(cwd),+ path.join(cwd, 'DESIGN.json'),+ ];+ const contextLegacy = path.join(contextDir, 'DESIGN.json');+ if (!candidates.includes(contextLegacy)) candidates.push(contextLegacy);+ return candidates;+}++export function resolveDesignSidecarPath(cwd = process.cwd(), contextDir = cwd) {+ return firstExisting(getDesignSidecarCandidates(cwd, contextDir));+}++export function getLiveDir(cwd = process.cwd()) {+ return path.join(getImpeccableDir(cwd), LIVE_DIR);+}++export function getLiveConfigPath(cwd = process.cwd()) {+ return path.join(getLiveDir(cwd), 'config.json');+}++export function getLegacyLiveConfigPath(scriptsDir) {+ return path.join(scriptsDir, 'config.json');+}++export function resolveLiveConfigPath({ cwd = process.cwd(), scriptsDir, env = process.env } = {}) {+ if (env.IMPECCABLE_LIVE_CONFIG && env.IMPECCABLE_LIVE_CONFIG.trim()) {+ const configured = env.IMPECCABLE_LIVE_CONFIG.trim();+ return path.isAbsolute(configured) ? configured : path.resolve(cwd, configured);+ }+ const primary = getLiveConfigPath(cwd);+ if (fs.existsSync(primary)) return primary;+ if (scriptsDir) {+ const legacy = getLegacyLiveConfigPath(scriptsDir);+ if (fs.existsSync(legacy)) return legacy;+ }+ return primary;+}++export function getLiveServerPath(cwd = process.cwd()) {+ return path.join(getLiveDir(cwd), 'server.json');+}++export function getLegacyLiveServerPath(cwd = process.cwd()) {+ return path.join(cwd, '.impeccable-live.json');+}++export function readLiveServerInfo(cwd = process.cwd()) {+ for (const filePath of [getLiveServerPath(cwd), getLegacyLiveServerPath(cwd)]) {+ try {+ return { info: JSON.parse(fs.readFileSync(filePath, 'utf-8')), path: filePath };+ } catch {+ /* try next */+ }+ }+ return null;+}++export function writeLiveServerInfo(cwd = process.cwd(), info) {+ const filePath = getLiveServerPath(cwd);+ fs.mkdirSync(path.dirname(filePath), { recursive: true });+ fs.writeFileSync(filePath, JSON.stringify(info));+ return filePath;+}++export function removeLiveServerInfo(cwd = process.cwd()) {+ for (const filePath of [getLiveServerPath(cwd), getLegacyLiveServerPath(cwd)]) {+ try { fs.unlinkSync(filePath); } catch {}+ }+}++export function getLiveSessionsDir(cwd = process.cwd()) {+ return path.join(getLiveDir(cwd), 'sessions');+}++export function getLegacyLiveSessionsDir(cwd = process.cwd()) {+ return path.join(cwd, '.impeccable-live', 'sessions');+}++export function getLiveAnnotationsDir(cwd = process.cwd()) {+ return path.join(getLiveDir(cwd), 'annotations');+}++export function getLegacyLiveAnnotationsDir(cwd = process.cwd()) {+ return path.join(cwd, '.impeccable-live', 'annotations');+}++function firstExisting(paths) {+ return paths.find((filePath) => fs.existsSync(filePath)) || null;+}diff --git a/.trae/skills/impeccable/scripts/live-browser-session.js b/.trae/skills/impeccable/scripts/live-browser-session.jsnew file mode 100644index 000000000..0e362d6be--- /dev/null+++ b/.trae/skills/impeccable/scripts/live-browser-session.js@@ -0,0 +1,123 @@+/**+ * Browser-side durable session helpers for Impeccable live mode.+ *+ * Kept separate from live-browser.js so recovery state can be tested without+ * booting the full overlay UI. Served before live-browser.js and attached to+ * window.__IMPECCABLE_LIVE_SESSION__.+ */+(function (root) {+ 'use strict';++ function createLiveBrowserSessionState({ prefix, storage, idFactory }) {+ if (!prefix) throw new Error('prefix required');+ const store = storage || root.localStorage;+ const makeId = idFactory || function () { return Math.random().toString(16).slice(2, 10); };+ const sessionKey = prefix + '-session';+ const handledKey = sessionKey + '-handled';+ const scrollKey = sessionKey + '-scroll';+ let checkpointRevision = 0;+ const owner = makeId();++ function safeRead(key) {+ try { return store.getItem(key); } catch { return null; }+ }++ function safeWrite(key, value) {+ try { store.setItem(key, value); } catch { /* quota exceeded or private mode */ }+ }++ function safeRemove(key) {+ try { store.removeItem(key); } catch { /* unavailable storage */ }+ }++ function loadSession() {+ try {+ const raw = safeRead(sessionKey);+ if (!raw) return null;+ const parsed = JSON.parse(raw);+ if (Number.isInteger(parsed.checkpointRevision)) {+ checkpointRevision = Math.max(checkpointRevision, parsed.checkpointRevision);+ }+ return parsed;+ } catch { return null; }+ }++ function saveSession(session) {+ if (!session || !session.id) return;+ const payload = {+ ...session,+ checkpointRevision,+ };+ safeWrite(sessionKey, JSON.stringify(payload));+ }++ function clearSession() {+ safeRemove(sessionKey);+ }++ function nextCheckpointRevision() {+ checkpointRevision += 1;+ const existing = loadSession();+ if (existing?.id) saveSession(existing);+ return checkpointRevision;+ }++ function seedCheckpointRevision(value) {+ if (Number.isInteger(value)) checkpointRevision = Math.max(checkpointRevision, value);+ return checkpointRevision;+ }++ function currentCheckpointRevision() {+ return checkpointRevision;+ }++ function markHandled(id) {+ if (!id) return;+ safeWrite(handledKey, id);+ }++ function isHandled(id) {+ return !!id && safeRead(handledKey) === id;+ }++ function clearHandled() {+ safeRemove(handledKey);+ }++ function writeScrollY(y) {+ safeWrite(scrollKey, String(y));+ }++ function readScrollY() {+ const raw = safeRead(scrollKey);+ if (raw == null) return null;+ const n = parseFloat(raw);+ return isFinite(n) ? n : null;+ }++ function clearScrollY() {+ safeRemove(scrollKey);+ }++ return {+ owner,+ sessionKey,+ handledKey,+ scrollKey,+ saveSession,+ loadSession,+ clearSession,+ nextCheckpointRevision,+ seedCheckpointRevision,+ currentCheckpointRevision,+ markHandled,+ isHandled,+ clearHandled,+ writeScrollY,+ readScrollY,+ clearScrollY,+ };+ }++ root.__IMPECCABLE_LIVE_SESSION__ = { createLiveBrowserSessionState };+})(typeof window !== 'undefined' ? window : globalThis);diff --git a/.trae/skills/impeccable/scripts/live-browser.js b/.trae/skills/impeccable/scripts/live-browser.jsindex 3da76bb96..e67cd01ed 100644--- a/.trae/skills/impeccable/scripts/live-browser.js+++ b/.trae/skills/impeccable/scripts/live-browser.js@@ -50,6 +50,16 @@const Z = { highlight: 100001, bar: 100005, picker: 100007, toast: 100010 };const EASE = 'cubic-bezier(0.22, 1, 0.36, 1)'; // ease-out-quintconst PREFIX = 'impeccable-live';+ const sessionState = window.__IMPECCABLE_LIVE_SESSION__?.createLiveBrowserSessionState({+ prefix: PREFIX,+ storage: localStorage,+ idFactory: () => crypto.randomUUID().replace(/-/g, '').slice(0, 8),+ });+ if (!sessionState) {+ console.error('[impeccable] live-browser-session.js was not loaded. Live mode cannot start safely.');+ window.__IMPECCABLE_LIVE_INIT__ = false;+ return;+ }const HIGHLIGHT_TRANSITION ='top 140ms ' + EASE +', left 140ms ' + EASE +@@ -112,6 +122,8 @@let hasProjectContext = false;let selectedAction = 'impeccable';let selectedCount = 3;+ const browserOwner = sessionState.owner;+ let checkpointTimer = null;// Scroll lock — holds window.scrollY at a fixed value while the session is// active, so HMR DOM patches and variant swaps can't drift the page. See@@ -126,21 +138,9 @@// (Previously: saveSession wrote scrollY alongside state, so every call// during resume overwrote the pre-reload value with whatever the browser// had landed on, typically 0.)- const SCROLL_KEY_SUFFIX = '-scroll';- function writeScrollY(y) {- try { localStorage.setItem(LS_KEY + SCROLL_KEY_SUFFIX, String(y)); } catch {}- }- function readScrollY() {- try {- const raw = localStorage.getItem(LS_KEY + SCROLL_KEY_SUFFIX);- if (raw == null) return null;- const n = parseFloat(raw);- return isFinite(n) ? n : null;- } catch { return null; }- }- function clearScrollY() {- try { localStorage.removeItem(LS_KEY + SCROLL_KEY_SUFFIX); } catch {}- }+ function writeScrollY(y) { sessionState.writeScrollY(y); }+ function readScrollY() { return sessionState.readScrollY(); }+ function clearScrollY() { sessionState.clearScrollY(); }// Pre-empt the browser: apply manual scroll restoration and jump to the// saved scrollY at script-parse time. Retries on fonts.ready and load@@ -1585,6 +1585,7 @@paramsCurrentValues[p.id] = v;readout.textContent = formatRangeValue(input);applyParamValue(variantEl, p, v);+ queueCheckpoint('param_changed');});row.appendChild(input);} else if (p.kind === 'toggle') {@@ -1615,6 +1616,7 @@knob.style.left = next ? '18px' : '2px';readout.textContent = next ? 'On' : 'Off';applyParamValue(variantEl, p, next);+ queueCheckpoint('param_changed');});row.appendChild(track);} else if (p.kind === 'steps') {@@ -1651,6 +1653,7 @@btn.style.color = on ? 'oklch(98% 0 0)' : P.text;});applyParamValue(variantEl, p, o.value);+ queueCheckpoint('param_changed');});segRow.appendChild(b);segBtns.push({ btn: b, val: o.value });@@ -1872,19 +1875,26 @@return;}+ const previousVisibleVariant = currentSessionId === sessionId ? visibleVariant : 0;+// Replace the live element with the full wrapper from sourceconst wrapper = srcWrapper.cloneNode(true);liveEl.parentElement.replaceChild(wrapper, liveEl);- // Update state: count variants, show the first one+ // Update state: count variants, preserving the user's current variant+ // when a late HMR/source reinjection lands after they have cycled.const variants = wrapper.querySelectorAll('[data-impeccable-variant]:not([data-impeccable-variant="original"])');arrivedVariants = variants.length;expectedVariants = parseInt(wrapper.dataset.impeccableVariantCount || arrivedVariants);- visibleVariant = 1;- showVariantInDOM(sessionId, 1);+ const saved = loadSession();+ const savedVisibleVariant = saved && saved.id === sessionId ? saved.visible : 0;+ visibleVariant = previousVisibleVariant > 0 && previousVisibleVariant <= arrivedVariants+ ? previousVisibleVariant+ : (savedVisibleVariant > 0 && savedVisibleVariant <= arrivedVariants ? savedVisibleVariant : 1);+ showVariantInDOM(sessionId, visibleVariant);// Update selectedElement to the visible variant's content- selectedElement = pickVariantContent(wrapper, 1) || wrapper.parentElement;+ selectedElement = pickVariantContent(wrapper, visibleVariant) || wrapper.parentElement;state = 'CYCLING';hideShaderOverlay();@@ -1907,6 +1917,7 @@updateSelectedElement();updateBarContent('cycling');saveSession();+ queueCheckpoint('variant_changed');}function updateSelectedElement() {@@ -1917,6 +1928,18 @@if (visEl) selectedElement = visEl;}+ function readVisibleVariantFromDOM(sessionId) {+ const wrapper = document.querySelector('[data-impeccable-variants="' + sessionId + '"]');+ if (!wrapper) return 0;+ const variants = wrapper.querySelectorAll('[data-impeccable-variant]:not([data-impeccable-variant="original"])');+ for (const variant of variants) {+ if (variant.style.display === 'none') continue;+ const idx = parseInt(variant.dataset.impeccableVariant || '0', 10);+ if (idx > 0) return idx;+ }+ return 0;+ }+// Resolve the element that represents the variant's visible content.// Contract: each variant div should contain exactly one top-level element// (the full replacement). In practice a model may ship loose siblings or@@ -2107,8 +2130,10 @@updating = true;arrivedVariants = count;if (visibleVariant === 0 && arrivedVariants > 0) {- visibleVariant = 1;- showVariantInDOM(sessionId, 1);+ const saved = loadSession();+ const savedVisibleVariant = saved && saved.id === sessionId ? saved.visible : 0;+ visibleVariant = savedVisibleVariant > 0 && savedVisibleVariant <= arrivedVariants ? savedVisibleVariant : 1;+ showVariantInDOM(sessionId, visibleVariant);// showVariantInDOM hid the original (display:none); if we were still// anchored to the original's content, its boundingRect is now zero// and the bar snaps to (0,0). Re-point at the visible variant instead.@@ -2128,6 +2153,7 @@updateBarContent('generating');}saveSession();+ queueCheckpoint(state === 'CYCLING' ? 'variants_ready' : 'variants_progress');updating = false;});@@ -2236,6 +2262,7 @@/** Server died or became unreachable. Reset UI to a clean state. */function handleServerLost() {+ const recoveryState = currentSessionId ? state : 'IDLE';if (state === 'GENERATING' || state === 'CYCLING' || state === 'SAVING') {showToast('Live server disconnected. Session ended.', 5000);}@@ -2246,21 +2273,61 @@stopScrollTracking();if (variantObserver) { variantObserver.disconnect(); variantObserver = null; }stopScrollLock();- clearScrollY();- clearSession();+ // Preserve local session state on server loss. The durable journal is the+ // source of truth, but localStorage plus the variant wrapper lets the UI+ // resume after a helper restart or page reload instead of treating a+ // transient disconnect as an explicit discard.selectedElement = null;- currentSessionId = null;selectedAction = 'impeccable';- state = 'IDLE';+ state = recoveryState;+ if (currentSessionId) saveSession();}- function sendEvent(msg) {+ function sendEvent(msg, opts) {msg.token = TOKEN;- fetch('http://localhost:' + PORT + '/events', {+ function handleFailure(err) {+ console.error('[impeccable] Failed to send event:', err);+ if (opts && opts.throwOnError) throw err;+ return null;+ }+ return fetch('http://localhost:' + PORT + '/events', {method: 'POST',headers: { 'Content-Type': 'application/json' },body: JSON.stringify(msg),- }).catch(err => console.error('[impeccable] Failed to send event:', err));+ }).then(res => {+ if (res.ok) return res;+ return handleFailure(new Error('HTTP ' + res.status + ' ' + res.statusText));+ }).catch(handleFailure);+ }++ function checkpointPayload(reason) {+ return {+ type: 'checkpoint',+ id: currentSessionId,+ revision: sessionState.nextCheckpointRevision(),+ owner: browserOwner,+ phase: String(state || '').toLowerCase(),+ reason,+ pageUrl: location.pathname,+ expectedVariants,+ arrivedVariants,+ visibleVariant,+ paramValues: { ...paramsCurrentValues },+ };+ }++ function sendCheckpoint(reason) {+ if (!currentSessionId) return Promise.resolve(null);+ return sendEvent(checkpointPayload(reason)).catch(() => null);+ }++ function queueCheckpoint(reason) {+ if (!currentSessionId) return;+ if (checkpointTimer) clearTimeout(checkpointTimer);+ checkpointTimer = setTimeout(() => {+ checkpointTimer = null;+ sendCheckpoint(reason);+ }, 120);}// ---------------------------------------------------------------------------@@ -2496,6 +2563,7 @@state = 'GENERATING';showBar('generating');saveSession();+ sendCheckpoint('generate_started');writeScrollY(window.scrollY);if (variantObserver) variantObserver.disconnect();variantObserver = startVariantObserver(currentSessionId);@@ -2920,13 +2988,12 @@ void main() {function handleAccept() {if (!currentSessionId || arrivedVariants === 0) return;+ const domVisibleVariant = readVisibleVariantFromDOM(currentSessionId);+ if (domVisibleVariant > 0) visibleVariant = domVisibleVariant;const acceptPayload = { type: 'accept', id: currentSessionId, variantId: String(visibleVariant) };if (Object.keys(paramsCurrentValues).length > 0) {acceptPayload.paramValues = { ...paramsCurrentValues };}- sendEvent(acceptPayload);- markSessionHandled();-// The accepted variant is already the only visible child of the wrapper// (all other variants are display:none). HMR from the source rewrite will// replace the wrapper imminently. Don't eagerly replaceChild here — React@@ -2936,9 +3003,28 @@ void main() {const acceptedSessionId = currentSessionId;const acceptedVariant = visibleVariant;- state = 'CONFIRMED';- updateBarContent('confirmed');- setTimeout(function() {+ state = 'SAVING';+ updateBarContent('saving');++ sendEvent(acceptPayload, { throwOnError: true })+ .then(() => {+ markSessionHandled();+ confirmAcceptAfterReceipt();+ })+ .catch(() => {+ state = 'CYCLING';+ updateBarContent('cycling');+ showToast('Could not confirm accept with the live server. Session kept for recovery; try Accept again.', 5000);+ });++ function confirmAcceptAfterReceipt() {+ state = 'CONFIRMED';+ updateBarContent('confirmed');+ scheduleAcceptCleanup();+ }++ function scheduleAcceptCleanup() {+ setTimeout(function() {hideBar();hideHighlight();stopScrollTracking();@@ -2967,50 +3053,46 @@ void main() {accepted.style.display = 'contents';parent.replaceChild(accepted, wrapper);}- }, 2000);+ }, 2000);+ }}function handleDiscard() {if (!currentSessionId) return;- sendEvent({ type: 'discard', id: currentSessionId });- markSessionHandled();- // Instant DOM restore + fire-and-forget (script handles file cleanup)- cleanup();+ sendEvent({ type: 'discard', id: currentSessionId }, { throwOnError: true })+ .then(() => {+ markSessionHandled();+ cleanup();+ })+ .catch(() => showToast('Could not confirm discard with the live server. Session kept for recovery.', 5000));}// ---------------------------------------------------------------------------- // Session persistence via localStorage+ // Session persistence via live-browser-session.js// ---------------------------------------------------------------------------// Survives page reloads, browser close/reopen, HMR, and accidental refreshes.- const LS_KEY = PREFIX + '-session';-function saveSession() {if (!currentSessionId) return;// NOTE: scrollY is stored under a separate key (writeScrollY). Storing// it here would overwrite the Go-time value every time state changes.- try {- localStorage.setItem(LS_KEY, JSON.stringify({- id: currentSessionId,- state: state,- action: selectedAction,- count: selectedCount,- expected: expectedVariants,- arrived: arrivedVariants,- visible: visibleVariant,- }));- } catch { /* quota exceeded or private mode */ }+ sessionState.saveSession({+ id: currentSessionId,+ state,+ action: selectedAction,+ count: selectedCount,+ expected: expectedVariants,+ arrived: arrivedVariants,+ visible: visibleVariant,+ });}function loadSession() {- try {- const raw = localStorage.getItem(LS_KEY);- return raw ? JSON.parse(raw) : null;- } catch { return null; }+ return sessionState.loadSession();}function clearSession() {- try { localStorage.removeItem(LS_KEY); } catch {}+ sessionState.clearSession();}/** Mark session as handled (accepted/discarded). The agent will clean up@@ -3018,19 +3100,15 @@ void main() {* prevents resumeSession from picking it up again after reload. */function markSessionHandled() {if (!currentSessionId) return;- try {- localStorage.setItem(LS_KEY + '-handled', currentSessionId);- } catch {}+ sessionState.markHandled(currentSessionId);}function isSessionHandled(id) {- try {- return localStorage.getItem(LS_KEY + '-handled') === id;- } catch { return false; }+ return sessionState.isHandled(id);}function clearHandled() {- try { localStorage.removeItem(LS_KEY + '-handled'); } catch {}+ sessionState.clearHandled();}function cleanup() {@@ -3161,6 +3239,7 @@ void main() {// hid. Now that state is CYCLING, re-fire.if (state === 'CYCLING') refreshParamsPanel();saveSession();+ queueCheckpoint('browser_resumed');// Start observing for more variants AFTER initial setupif (variantObserver) variantObserver.disconnect();@@ -3617,7 +3696,7 @@ void main() {}// ---------------------------------------------------------------------------- // Design System Panel — visualizes the project's DESIGN.json sidecar+ // Design System Panel — visualizes the project's .impeccable/design.json sidecar// ---------------------------------------------------------------------------const DESIGN_PREFS_KEY = 'impeccable-live-design-panel';@@ -3629,7 +3708,7 @@ void main() {open: false,tab: 'visual', // 'visual' | 'raw'parsed: null, // parseDesignMd output (frontmatter + body sections)- sidecar: null, // DESIGN.json v2 payload (extensions + components + narrative)+ sidecar: null, // .impeccable/design.json v2 payload (extensions + components + narrative)hasMd: false,hasSidecar: false,present: null, // true/false once fetch resolves@@ -4130,7 +4209,7 @@ void main() {box.className = 'stale';box.innerHTML = `<span class="stale-dot"></span>- <span class="stale-text"><strong>DESIGN.md is newer than DESIGN.json.</strong> Run <code>/impeccable document</code> to refresh the sidecar.</span>+ <span class="stale-text"><strong>DESIGN.md is newer than .impeccable/design.json.</strong> Run <code>/impeccable document</code> to refresh the sidecar.</span>`;return box;}@@ -4138,7 +4217,7 @@ void main() {function renderParsedMdCta() {const box = document.createElement('div');box.className = 'parsed-md-cta';- box.innerHTML = `<strong>Basic view</strong>This panel reads the tokens in your <code>DESIGN.md</code> frontmatter. Running <code>/impeccable document</code> also generates a <code>DESIGN.json</code> sidecar with your project's actual component snippets (button, input, nav) and tonal ramps, rendered live below the tokens.`;+ box.innerHTML = `<strong>Basic view</strong>This panel reads the tokens in your <code>DESIGN.md</code> frontmatter. Running <code>/impeccable document</code> also generates a <code>.impeccable/design.json</code> sidecar with your project's actual component snippets (button, input, nav) and tonal ramps, rendered live below the tokens.`;return box;}@@ -4598,7 +4677,7 @@ void main() {function cssSafe(v) {// Strip anything outside valid CSS value chars to prevent injection via- // DESIGN.json values rendered into inline style strings.+ // .impeccable/design.json values rendered into inline style strings.return String(v).replace(/[<>"'`\n]/g, '');}diff --git a/.trae/skills/impeccable/scripts/live-complete.mjs b/.trae/skills/impeccable/scripts/live-complete.mjsnew file mode 100644index 000000000..78155af85--- /dev/null+++ b/.trae/skills/impeccable/scripts/live-complete.mjs@@ -0,0 +1,75 @@+#!/usr/bin/env node+/**+ * Canonical durable completion acknowledgement for Impeccable live sessions.+ */++import { createLiveSessionStore } from './live-session-store.mjs';+import { readLiveServerInfo } from './impeccable-paths.mjs';++function parseArgs(argv) {+ const out = { status: 'complete' };+ for (let i = 0; i < argv.length; i++) {+ const arg = argv[i];+ if (arg === '--id') out.id = argv[++i];+ else if (arg.startsWith('--id=')) out.id = arg.slice('--id='.length);+ else if (arg === '--discarded' || arg === '--discard') out.status = 'discarded';+ else if (arg === '--error') { out.status = 'agent_error'; out.message = argv[++i] || 'unknown error'; }+ else if (arg.startsWith('--error=')) { out.status = 'agent_error'; out.message = arg.slice('--error='.length); }+ else if (arg === '--help' || arg === '-h') out.help = true;+ }+ return out;+}++export async function completeCli() {+ const args = parseArgs(process.argv.slice(2));+ if (args.help || !args.id) {+ console.log(`Usage: node live-complete.mjs --id SESSION_ID [--discarded|--error MESSAGE]\n\nAppend the final durable session acknowledgement. Use after accept/discard cleanup is verified.`);+ process.exit(args.help ? 0 : 1);+ }++ const serverInfo = readServerInfo();+ const serverResult = serverInfo ? await completeThroughServer(serverInfo, args) : null;+ if (serverResult?.ok) {+ const store = createLiveSessionStore({ cwd: process.cwd(), sessionId: args.id });+ const snapshot = store.getSnapshot(args.id, { includeCompleted: true });+ console.log(JSON.stringify({ ok: true, id: args.id, phase: snapshot?.phase || args.status, snapshot }, null, 2));+ return;+ }++ const store = createLiveSessionStore({ cwd: process.cwd(), sessionId: args.id });+ const event = args.status === 'discarded'+ ? { type: 'discarded', id: args.id }+ : args.status === 'agent_error'+ ? { type: 'agent_error', id: args.id, message: args.message || 'unknown error' }+ : { type: 'complete', id: args.id };+ const snapshot = store.appendEvent(event);+ console.log(JSON.stringify({ ok: true, id: args.id, phase: snapshot.phase, snapshot }, null, 2));+}++function readServerInfo() {+ return readLiveServerInfo(process.cwd())?.info || null;+}++async function completeThroughServer(info, args) {+ const type = args.status === 'discarded'+ ? 'discarded'+ : args.status === 'agent_error'+ ? 'error'+ : 'complete';+ try {+ const res = await fetch(`http://localhost:${info.port}/poll`, {+ method: 'POST',+ headers: { 'Content-Type': 'application/json' },+ body: JSON.stringify({ token: info.token, id: args.id, type, message: args.message }),+ });+ if (!res.ok) return null;+ return await res.json();+ } catch {+ return null;+ }+}++const _running = process.argv[1];+if (_running?.endsWith('live-complete.mjs') || _running?.endsWith('live-complete.mjs/')) {+ completeCli();+}diff --git a/.trae/skills/impeccable/scripts/live-completion.mjs b/.trae/skills/impeccable/scripts/live-completion.mjsnew file mode 100644index 000000000..86b637fff--- /dev/null+++ b/.trae/skills/impeccable/scripts/live-completion.mjs@@ -0,0 +1,18 @@+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';+ return 'agent_done';+}++export function completionAckForAcceptResult(eventId, completionType, acceptResult) {+ const ack = { ok: true, type: completionType };+ if (acceptResult?.handled === true && acceptResult?.carbonize === true) {+ ack.final = false;+ ack.requiresComplete = true;+ ack.nextCommand = `live-complete.mjs --id ${eventId}`;+ ack.message = 'Carbonize cleanup must be verified, then the session must be completed explicitly before polling again.';+ }+ return ack;+}diff --git a/.trae/skills/impeccable/scripts/live-inject.mjs b/.trae/skills/impeccable/scripts/live-inject.mjsindex 1d2ae12f7..555c3a36a 100644--- a/.trae/skills/impeccable/scripts/live-inject.mjs+++ b/.trae/skills/impeccable/scripts/live-inject.mjs@@ -2,23 +2,24 @@* CLI helper: insert/remove the live variant mode script tag in the project's* main HTML entry point.*- * On first live run, the agent generates `config.json` in this script's- * directory with the project's insertion target (framework-specific). On+ * On first live run, the agent generates `.impeccable/live/config.json`+ * with the project's insertion target (framework-specific). On* every subsequent run, this script handles insert/remove deterministically* with zero LLM involvement.** Usage:* node live-inject.mjs --port PORT # Insert the live script tag* node live-inject.mjs --remove # Remove the live script tag- * node live-inject.mjs --check # Check whether config.json exists+ * node live-inject.mjs --check # Check whether live config exists*/import fs from 'node:fs';import path from 'node:path';import { fileURLToPath } from 'node:url';+import { resolveLiveConfigPath } from './impeccable-paths.mjs';const __dirname = path.dirname(fileURLToPath(import.meta.url));-const CONFIG_PATH = process.env.IMPECCABLE_LIVE_CONFIG || path.join(__dirname, 'config.json');+const CONFIG_PATH = resolveLiveConfigPath({ cwd: process.cwd(), scriptsDir: __dirname });const MARKER_OPEN_TEXT = 'impeccable-live-start';const MARKER_CLOSE_TEXT = 'impeccable-live-end';@@ -39,12 +40,12 @@ export async function injectCli() {console.log(`Usage: node live-inject.mjs [options]Insert or remove the live mode script tag in the project's HTML entry point.-Reads configuration from config.json (in this same directory).+Reads configuration from .impeccable/live/config.json.Modes:--port PORT Insert script tag pointing at http://localhost:PORT/live.js--remove Remove the script tag (if present)- --check Print whether config.json exists and its content+ --check Print whether .impeccable/live/config.json exists and its contentOutput (JSON):{ ok, file, inserted|removed, config? }`);diff --git a/.trae/skills/impeccable/scripts/live-poll.mjs b/.trae/skills/impeccable/scripts/live-poll.mjsindex eb8f1586a..10d452491 100644--- a/.trae/skills/impeccable/scripts/live-poll.mjs+++ b/.trae/skills/impeccable/scripts/live-poll.mjs@@ -9,10 +9,10 @@*/import { execFileSync } from 'node:child_process';-import fs from 'node:fs';import path from 'node:path';-import os from 'node:os';import { fileURLToPath } from 'node:url';+import { completionAckForAcceptResult, completionTypeForAcceptResult } from './live-completion.mjs';+import { readLiveServerInfo } from './impeccable-paths.mjs';// Node's built-in fetch (undici under the hood) enforces a 300s headers// timeout that can't be lowered per-request. We cap each request below@@ -20,15 +20,29 @@ import { fileURLToPath } from 'node:url';// depending on the standalone undici package.const PER_REQUEST_TIMEOUT_MS = 270_000;-const LIVE_PID_FILE = path.join(process.cwd(), '.impeccable-live.json');-function readServerInfo() {- try {- return JSON.parse(fs.readFileSync(LIVE_PID_FILE, 'utf-8'));- } catch {+ const record = readLiveServerInfo(process.cwd());+ if (!record) {console.error('No running live server found. Start one with: npx impeccable live');process.exit(1);}+ return record.info;+}++export function buildPollReplyPayload(token, { id, type, message, file, data }) {+ return { token, id, type, message, file, data };+}++async function postReply(base, token, reply) {+ const res = await fetch(`${base}/poll`, {+ method: 'POST',+ headers: { 'Content-Type': 'application/json' },+ body: JSON.stringify(buildPollReplyPayload(token, reply)),+ });+ if (!res.ok) {+ const body = await res.json().catch(() => ({}));+ throw new Error(body.error || res.statusText);+ }}export async function pollCli() {@@ -69,23 +83,7 @@ Options:}try {- const res = await fetch(`${base}/poll`, {- method: 'POST',- headers: { 'Content-Type': 'application/json' },- body: JSON.stringify({- token: info.token,- id,- type: status,- message,- file: filePath,- }),- });-- if (!res.ok) {- const body = await res.json().catch(() => ({}));- console.error(`Reply failed (${res.status}):`, body.error || res.statusText);- process.exit(1);- }+ await postReply(base, info.token, { id, type: status, message, file: filePath });// Success — silent exit (agent doesn't need output for replies)} catch (err) {@@ -156,7 +154,23 @@ Options:);event._acceptResult = JSON.parse(out.trim());} catch (err) {- event._acceptResult = { handled: false, error: err.message };+ event._acceptResult = { handled: false, mode: 'error', error: err.message };+ }++ const completionType = completionTypeForAcceptResult(event.type, event._acceptResult);+ try {+ await postReply(base, info.token, {+ id: event.id,+ type: completionType,+ message: event._acceptResult?.error,+ file: event._acceptResult?.file,+ data: event._acceptResult?.carbonize === true ? { carbonize: true } : undefined,+ });+ } catch (err) {+ event._completionAck = { ok: false, error: err.message };+ }+ if (!event._completionAck) {+ event._completionAck = completionAckForAcceptResult(event.id, completionType, event._acceptResult);}}@@ -164,7 +178,7 @@ Options:// JSON but skips nested fields. One line is enough — the full checklist// is in reference/live.md.if (event._acceptResult?.carbonize === true) {- process.stderr.write('\n⚠ Carbonize cleanup REQUIRED before next poll. See reference/live.md "Required after accept".\n\n');+ process.stderr.write('\n⚠ Carbonize cleanup REQUIRED before next poll. After cleanup, run live-complete.mjs --id ' + event.id + '. See reference/live.md "Required after accept".\n\n');}// Print the event as JSON — the agent reads this from stdoutdiff --git a/.trae/skills/impeccable/scripts/live-resume.mjs b/.trae/skills/impeccable/scripts/live-resume.mjsnew file mode 100644index 000000000..a3465c9b5--- /dev/null+++ b/.trae/skills/impeccable/scripts/live-resume.mjs@@ -0,0 +1,48 @@+#!/usr/bin/env node+/**+ * Recover the next agent action from the durable live-session journal.+ */++import { createLiveSessionStore } from './live-session-store.mjs';++function parseArgs(argv) {+ const out = { id: null };+ for (let i = 0; i < argv.length; i++) {+ const arg = argv[i];+ if (arg === '--id') out.id = argv[++i];+ else if (arg.startsWith('--id=')) out.id = arg.slice('--id='.length);+ else if (arg === '--help' || arg === '-h') out.help = true;+ }+ return out;+}++export async function resumeCli() {+ const args = parseArgs(process.argv.slice(2));+ if (args.help) {+ console.log(`Usage: node live-resume.mjs [--id SESSION_ID]\n\nPrint the active durable session checkpoint and the next safe agent action.`);+ return;+ }++ const store = createLiveSessionStore({ cwd: process.cwd(), sessionId: args.id || undefined });+ const snapshot = args.id ? store.getSnapshot(args.id) : store.listActiveSessions()[0] || null;+ if (!snapshot) {+ console.log(JSON.stringify({ active: false, nextAction: 'No active durable live session found.' }, null, 2));+ return;+ }++ const pending = snapshot.pendingEvent || null;+ const nextAction = pending+ ? `Run live-poll.mjs, handle ${pending.type} ${pending.id}, then acknowledge with live-poll.mjs --reply ${pending.id} done.`+ : snapshot.phase === 'carbonize_required'+ ? `Finish carbonize cleanup${snapshot.sourceFile ? ` in ${snapshot.sourceFile}` : ''}, then run live-complete.mjs --id ${snapshot.id}.`+ : snapshot.phase === 'accept_requested'+ ? `Run live-complete.mjs --id ${snapshot.id} after verifying the accepted variant is written.`+ : `Inspect ${snapshot.id}; no pending agent event is currently queued.`;++ console.log(JSON.stringify({ active: true, snapshot, pendingEvent: pending, nextAction }, null, 2));+}++const _running = process.argv[1];+if (_running?.endsWith('live-resume.mjs') || _running?.endsWith('live-resume.mjs/')) {+ resumeCli();+}diff --git a/.trae/skills/impeccable/scripts/live-server.mjs b/.trae/skills/impeccable/scripts/live-server.mjsindex 90614fbf7..53d8f21cb 100644--- a/.trae/skills/impeccable/scripts/live-server.mjs+++ b/.trae/skills/impeccable/scripts/live-server.mjs@@ -22,14 +22,20 @@ import net from 'node:net';import { fileURLToPath } from 'node:url';import { parseDesignMd } from './design-parser.mjs';import { resolveContextDir } from './load-context.mjs';+import { createLiveSessionStore } from './live-session-store.mjs';+import {+ getDesignSidecarPath,+ getLiveAnnotationsDir,+ readLiveServerInfo,+ removeLiveServerInfo,+ resolveDesignSidecarPath,+ writeLiveServerInfo,+} from './impeccable-paths.mjs';const __dirname = path.dirname(fileURLToPath(import.meta.url));-// PID file in the project root so both the server and agent can find it-// predictably (os.tmpdir() varies across platforms).-const LIVE_PID_FILE = path.join(process.cwd(), '.impeccable-live.json');-// PRODUCT.md / DESIGN.md / DESIGN.json live wherever load-context.mjs resolves.-// Keeps live-server in sync with the loader when users keep the docs in-// .agents/context/, docs/, or a path set via IMPECCABLE_CONTEXT_DIR.+// PRODUCT.md / DESIGN.md live wherever load-context.mjs resolves. The generated+// DESIGN sidecar is project-local at .impeccable/design.json, with legacy+// DESIGN.json fallback for existing projects.const CONTEXT_DIR = resolveContextDir(process.cwd());const DEFAULT_POLL_TIMEOUT = 600_000; // 10 min — agent re-polls on timeout anywayconst SSE_HEARTBEAT_INTERVAL = 30_000; // keepalive ping every 30s@@ -57,10 +63,12 @@ const state = {token: null,port: null,sseClients: new Set(), // SSE response objects (server→browser push)- pendingEvents: [], // browser events waiting for agent poll+ pendingEvents: [], // browser events waiting for agent ack ({ event, leaseUntil })pendingPolls: [], // agent poll callbacks waiting for browser eventsexitTimer: null,sessionDir: null, // per-session tmp dir for annotation screenshots+ sessionStore: null,+ leaseTimer: null,};// Cap per-annotation upload size. A full 1920×1080 PNG is typically <1 MB;@@ -68,11 +76,70 @@ const state = {const MAX_ANNOTATION_BYTES = 10 * 1024 * 1024;function enqueueEvent(event) {- if (state.pendingPolls.length > 0) {- state.pendingPolls.shift()(event);- } else {- state.pendingEvents.push(event);+ if (!event || (event.id && state.pendingEvents.some((entry) => entry.event?.id === event.id && entry.event?.type === event.type))) return;+ state.pendingEvents.push({ event, leaseUntil: 0 });+ flushPendingPolls();+}++function restorePendingEventsFromStore() {+ if (!state.sessionStore) return;+ for (const snapshot of state.sessionStore.listActiveSessions()) {+ if (snapshot.pendingEvent) enqueueEvent(snapshot.pendingEvent);+ }+}++function findAvailablePendingEvent(now = Date.now()) {+ return state.pendingEvents.find((entry) => !entry.leaseUntil || entry.leaseUntil <= now);+}++function leaseEvent(entry, leaseMs) {+ if (!entry.event?.id) {+ const idx = state.pendingEvents.indexOf(entry);+ if (idx !== -1) state.pendingEvents.splice(idx, 1);+ return entry.event;}+ entry.leaseUntil = Date.now() + leaseMs;+ return entry.event;+}++function acknowledgePendingEvent(id) {+ if (!id) return false;+ const idx = state.pendingEvents.findIndex((entry) => entry.event?.id === id);+ if (idx === -1) return false;+ state.pendingEvents.splice(idx, 1);+ scheduleLeaseFlush();+ return true;+}++function scheduleLeaseFlush() {+ if (state.leaseTimer) {+ clearTimeout(state.leaseTimer);+ state.leaseTimer = null;+ }+ if (state.pendingPolls.length === 0) return;+ const now = Date.now();+ const nextLeaseUntil = state.pendingEvents+ .map((entry) => entry.leaseUntil || 0)+ .filter((leaseUntil) => leaseUntil > now)+ .sort((a, b) => a - b)[0];+ if (!nextLeaseUntil) return;+ state.leaseTimer = setTimeout(() => {+ state.leaseTimer = null;+ flushPendingPolls();+ }, Math.max(0, nextLeaseUntil - now));+}++function flushPendingPolls() {+ while (state.pendingPolls.length > 0) {+ const entry = findAvailablePendingEvent();+ if (!entry) {+ scheduleLeaseFlush();+ return;+ }+ const poll = state.pendingPolls.shift();+ poll.resolve(leaseEvent(entry, poll.leaseMs));+ }+ scheduleLeaseFlush();}/** Push a message to all connected SSE clients. */@@ -103,13 +170,16 @@ function loadBrowserScripts() {// live-browser.js: DO NOT cache. Return the path so the /live.js handler// can re-read on every request. Editing the browser script during iteration// should land on the next tab reload, not require a server restart.+ const sessionPath = path.join(__dirname, 'live-browser-session.js');const livePath = path.join(__dirname, 'live-browser.js');- if (!fs.existsSync(livePath)) {- process.stderr.write('Error: live-browser.js not found at ' + livePath + '\n');- process.exit(1);+ for (const p of [sessionPath, livePath]) {+ if (!fs.existsSync(p)) {+ process.stderr.write('Error: live browser script not found at ' + p + '\n');+ process.exit(1);+ }}- return { detectScript, livePath };+ return { detectScript, sessionPath, livePath };}function hasProjectContext() {@@ -170,6 +240,13 @@ function validateEvent(msg) {return null;case 'discard':return isValidId(msg.id) ? null : 'discard: missing or malformed id';+ case 'checkpoint':+ if (!isValidId(msg.id)) return 'checkpoint: missing or malformed id';+ if (!Number.isInteger(msg.revision) || msg.revision < 0) return 'checkpoint: revision must be a non-negative integer';+ if (msg.paramValues !== undefined && (typeof msg.paramValues !== 'object' || msg.paramValues === null || Array.isArray(msg.paramValues))) {+ return 'checkpoint: paramValues must be an object';+ }+ return null;case 'exit':return null;case 'prefetch':@@ -184,7 +261,7 @@ function validateEvent(msg) {// HTTP request handler// ----------------------------------------------------------------------------function createRequestHandler({ detectScript, livePath }) {+function createRequestHandler({ detectScript, sessionPath, livePath }) {return (req, res) => {const url = new URL(req.url, `http://localhost:${state.port}`);res.setHeader('Access-Control-Allow-Origin', '*');@@ -200,17 +277,20 @@ function createRequestHandler({ detectScript, livePath }) {// the next tab reload. No-store headers prevent browser caching across// sessions — during iteration, a cached old script silently breaks// every subsequent session.+ let sessionScript;let liveScript;try {+ sessionScript = fs.readFileSync(sessionPath, 'utf-8');liveScript = fs.readFileSync(livePath, 'utf-8');} catch (err) {res.writeHead(500, { 'Content-Type': 'text/plain' });- res.end('Error reading live-browser.js: ' + err.message);+ res.end('Error reading live browser scripts: ' + err.message);return;}const body =`window.__IMPECCABLE_TOKEN__ = '${state.token}';\n` +`window.__IMPECCABLE_PORT__ = ${state.port};\n` ++ sessionScript + '\n' +liveScript;res.writeHead(200, {'Content-Type': 'application/javascript',@@ -305,6 +385,26 @@ function createRequestHandler({ detectScript, livePath }) {}// --- Health ---+ if (p === '/status') {+ const token = url.searchParams.get('token');+ if (token !== state.token) { res.writeHead(401, { 'Content-Type': 'application/json' }); res.end(JSON.stringify({ error: 'Unauthorized' })); return; }+ const sessions = state.sessionStore ? state.sessionStore.listActiveSessions() : [];+ res.writeHead(200, { 'Content-Type': 'application/json' });+ res.end(JSON.stringify({+ status: 'ok',+ port: state.port,+ connectedClients: state.sseClients.size,+ pendingEvents: state.pendingEvents.map((entry) => ({+ id: entry.event?.id,+ type: entry.event?.type,+ leased: !!(entry.leaseUntil && entry.leaseUntil > Date.now()),+ leaseUntil: entry.leaseUntil || null,+ })),+ activeSessions: sessions,+ }));+ return;+ }+if (p === '/health') {res.writeHead(200, { 'Content-Type': 'application/json' });res.end(JSON.stringify({@@ -316,13 +416,13 @@ function createRequestHandler({ detectScript, livePath }) {}// --- Design system (unified v2 response) + raw ---- // /design-system.json returns both parsed DESIGN.md and DESIGN.json+ // /design-system.json returns both parsed DESIGN.md and .impeccable/design.json// sidecar when present. Panel merges them:// { present, parsed, sidecar, hasMd, hasSidecar,// mdNewerThanJson, parseError?, sidecarError? }// - parsed: output of parseDesignMd (frontmatter// + six canonical sections) when DESIGN.md exists.- // - sidecar: DESIGN.json contents when present.+ // - sidecar: .impeccable/design.json contents when present.// Expected shape: schemaVersion 2, carrying// extensions + components + narrative.// /design-system/raw returns DESIGN.md markdown verbatim@@ -331,7 +431,7 @@ function createRequestHandler({ detectScript, livePath }) {if (token !== state.token) { res.writeHead(401); res.end('Unauthorized'); return; }const mdPath = path.join(CONTEXT_DIR, 'DESIGN.md');- const jsonPath = path.join(CONTEXT_DIR, 'DESIGN.json');+ const jsonPath = resolveDesignSidecarPath(process.cwd(), CONTEXT_DIR) || getDesignSidecarPath(process.cwd());const mdStat = statOrNull(mdPath);const jsonStat = statOrNull(jsonPath);@@ -367,7 +467,7 @@ function createRequestHandler({ detectScript, livePath }) {try {response.sidecar = JSON.parse(fs.readFileSync(jsonPath, 'utf-8'));} catch (err) {- response.sidecarError = 'Failed to parse DESIGN.json: ' + err.message;+ response.sidecarError = 'Failed to parse .impeccable/design.json: ' + err.message;}}@@ -449,7 +549,16 @@ function createRequestHandler({ detectScript, livePath }) {res.end(JSON.stringify({ error }));return;}- enqueueEvent(msg);+ if (state.sessionStore && msg.id) {+ try {+ state.sessionStore.appendEvent(msg);+ } catch (err) {+ res.writeHead(500, { 'Content-Type': 'application/json' });+ res.end(JSON.stringify({ error: 'session_store_append_failed', message: err.message }));+ return;+ }+ }+ if (msg.type !== 'checkpoint') enqueueEvent(msg);res.writeHead(200, { 'Content-Type': 'application/json' });res.end(JSON.stringify({ ok: true }));});@@ -492,13 +601,16 @@ function handlePollGet(req, res, url) {return;}const timeout = parseInt(url.searchParams.get('timeout') || DEFAULT_POLL_TIMEOUT, 10);- if (state.pendingEvents.length > 0) {+ const leaseMs = parseInt(url.searchParams.get('leaseMs') || '30000', 10);+ const available = findAvailablePendingEvent();+ if (available) {res.writeHead(200, { 'Content-Type': 'application/json' });- res.end(JSON.stringify(state.pendingEvents.shift()));+ res.end(JSON.stringify(leaseEvent(available, leaseMs)));return;}+ const poll = { resolve, leaseMs };const timer = setTimeout(() => {- const idx = state.pendingPolls.indexOf(resolve);+ const idx = state.pendingPolls.indexOf(poll);if (idx !== -1) state.pendingPolls.splice(idx, 1);res.writeHead(200, { 'Content-Type': 'application/json' });res.end(JSON.stringify({ type: 'timeout' }));@@ -508,10 +620,11 @@ function handlePollGet(req, res, url) {res.writeHead(200, { 'Content-Type': 'application/json' });res.end(JSON.stringify(event));}- state.pendingPolls.push(resolve);+ state.pendingPolls.push(poll);+ scheduleLeaseFlush();req.on('close', () => {clearTimeout(timer);- const idx = state.pendingPolls.indexOf(resolve);+ const idx = state.pendingPolls.indexOf(poll);if (idx !== -1) state.pendingPolls.splice(idx, 1);});}@@ -531,6 +644,26 @@ function handlePollPost(req, res) {res.end(JSON.stringify({ error: 'Unauthorized' }));return;}+ acknowledgePendingEvent(msg.id);+ if (state.sessionStore && msg.id) {+ try {+ const eventType = msg.type === 'discard' || msg.type === 'discarded'+ ? 'discarded'+ : msg.type === 'complete'+ ? 'complete'+ : msg.type === 'error'+ ? 'agent_error'+ : 'agent_done';+ state.sessionStore.appendEvent({+ type: eventType,+ id: msg.id,+ file: msg.file,+ message: msg.message,+ carbonize: msg.data?.carbonize === true,+ });+ } catch { /* keep reply path best-effort; browser still needs SSE */ }+ }+ flushPendingPolls();// Forward the reply to the browser via SSEbroadcast({ type: msg.type || 'done', id: msg.id, message: msg.message, file: msg.file, data: msg.data });res.writeHead(200, { 'Content-Type': 'application/json' });@@ -545,13 +678,15 @@ function handlePollPost(req, res) {let httpServer = null;function shutdown() {- try { fs.unlinkSync(LIVE_PID_FILE); } catch {}+ removeLiveServerInfo(process.cwd());+ if (state.leaseTimer) clearTimeout(state.leaseTimer);+ state.leaseTimer = null;if (state.sessionDir) {try { fs.rmSync(state.sessionDir, { recursive: true, force: true }); } catch {}}for (const res of state.sseClients) { try { res.end(); } catch {} }state.sseClients.clear();- for (const resolve of state.pendingPolls) resolve({ type: 'exit' });+ for (const poll of state.pendingPolls) poll.resolve({ type: 'exit' });state.pendingPolls.length = 0;if (httpServer) httpServer.close();process.exit(0);@@ -587,6 +722,7 @@ Endpoints:/events SSE stream (server→browser) + POST (browser→server)/poll Long-poll for agent CLI/source Raw source file reader (no-HMR fallback)+ /status Durable recovery status (token-protected)/health Health check`);process.exit(0);}@@ -594,7 +730,7 @@ Endpoints:if (args.includes('stop')) {const keepInject = args.includes('--keep-inject');try {- const info = JSON.parse(fs.readFileSync(LIVE_PID_FILE, 'utf-8'));+ const { info } = readLiveServerInfo(process.cwd()) || {};const res = await fetch(`http://localhost:${info.port}/stop?token=${info.token}`);if (res.ok) console.log(`Stopped live server on port ${info.port}.`);} catch {@@ -645,7 +781,7 @@ if (args.includes('--background')) {const deadline = Date.now() + 10_000;while (Date.now() < deadline) {try {- const info = JSON.parse(fs.readFileSync(LIVE_PID_FILE, 'utf-8'));+ const { info } = readLiveServerInfo(process.cwd()) || {};if (info.pid !== process.pid) {// Output JSON so the agent can read port + token from stdout.console.log(JSON.stringify(info));@@ -659,30 +795,36 @@ if (args.includes('--background')) {}// Check for existing session-try {- const existing = JSON.parse(fs.readFileSync(LIVE_PID_FILE, 'utf-8'));- try { process.kill(existing.pid, 0);+const existingRecord = readLiveServerInfo(process.cwd());+if (existingRecord?.info) {+ const existing = existingRecord.info;+ try {+ process.kill(existing.pid, 0);console.error(`Live server already running on port ${existing.port} (pid ${existing.pid}).`);console.error('Stop it first with: node ' + path.basename(fileURLToPath(import.meta.url)) + ' stop');process.exit(1);- } catch { fs.unlinkSync(LIVE_PID_FILE); }-} catch {}+ } catch {+ try { fs.unlinkSync(existingRecord.path); } catch {}+ }+}state.token = randomUUID();+state.sessionStore = createLiveSessionStore({ cwd: process.cwd() });+restorePendingEventsFromStore();const portArg = args.find(a => a.startsWith('--port='));state.port = portArg ? parseInt(portArg.split('=')[1], 10) : await findOpenPort();// Annotation screenshots live in the project root so the agent's Read tool// doesn't trip a per-file permission prompt. Sessioned by token so concurrent// projects (or quick restarts) don't collide.-const annotRoot = path.join(process.cwd(), '.impeccable-live', 'annotations');+const annotRoot = getLiveAnnotationsDir(process.cwd());fs.mkdirSync(annotRoot, { recursive: true });state.sessionDir = fs.mkdtempSync(path.join(annotRoot, 'session-'));-const { detectScript, livePath } = loadBrowserScripts();-httpServer = http.createServer(createRequestHandler({ detectScript, livePath }));+const { detectScript, sessionPath, livePath } = loadBrowserScripts();+httpServer = http.createServer(createRequestHandler({ detectScript, sessionPath, livePath }));httpServer.listen(state.port, '127.0.0.1', () => {- fs.writeFileSync(LIVE_PID_FILE, JSON.stringify({ pid: process.pid, port: state.port, token: state.token }));+ writeLiveServerInfo(process.cwd(), { pid: process.pid, port: state.port, token: state.token });const url = `http://localhost:${state.port}`;console.log(`\nImpeccable live server running on ${url}`);console.log(`Token: ${state.token}\n`);diff --git a/.trae/skills/impeccable/scripts/live-session-store.mjs b/.trae/skills/impeccable/scripts/live-session-store.mjsnew file mode 100644index 000000000..d55ed2d3a--- /dev/null+++ b/.trae/skills/impeccable/scripts/live-session-store.mjs@@ -0,0 +1,254 @@+import fs from 'node:fs';+import path from 'node:path';+import { getLegacyLiveSessionsDir, getLiveSessionsDir } from './impeccable-paths.mjs';++const COMPLETED_PHASES = new Set(['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;+ }++ function getReadableJournalPath(id) {+ const primary = getJournalPath(rootDir, id);+ if (fs.existsSync(primary)) return primary;+ const legacy = getJournalPath(legacyRootDir, id);+ if (fs.existsSync(legacy)) return legacy;+ return primary;+ }++ return {+ rootDir,+ legacyRootDir,+ appendEvent(event) {+ const normalized = normalizeEvent(event, sessionId);+ const journalPath = getJournalPath(rootDir, normalized.id);+ const snapshotPath = getSnapshotPath(rootDir, normalized.id);+ const legacyJournalPath = getJournalPath(legacyRootDir, normalized.id);+ if (!fs.existsSync(journalPath) && fs.existsSync(legacyJournalPath)) {+ fs.copyFileSync(legacyJournalPath, journalPath);+ }+ const prior = loadCachedOrRebuild(normalized.id);+ const seq = prior.nextSeq;+ const entry = {+ seq,+ id: normalized.id,+ type: normalized.type,+ ts: new Date().toISOString(),+ event: normalized,+ };+ 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;+ },+ getSnapshot(id = sessionId, opts = {}) {+ if (!id) throw new Error('session id required');+ 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;+ },+ listActiveSessions() {+ const ids = new Set();+ for (const dir of [legacyRootDir, rootDir]) {+ if (!fs.existsSync(dir)) continue;+ for (const name of fs.readdirSync(dir)) {+ if (name.endsWith('.jsonl')) ids.add(name.slice(0, -'.jsonl'.length));+ }+ }+ return [...ids]+ .sort()+ .map((id) => this.getSnapshot(id))+ .filter(Boolean);+ },+ };+}++function normalizeEvent(event, fallbackId) {+ if (!event || typeof event !== 'object') throw new Error('event object required');+ const id = event.id || fallbackId;+ if (!id || typeof id !== 'string') throw new Error('event id required');+ if (!event.type || typeof event.type !== 'string') throw new Error('event type required');+ return { ...event, id };+}++function getJournalPath(rootDir, id) {+ return path.join(rootDir, safeSessionId(id) + '.jsonl');+}++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,+ phase: 'new',+ pageUrl: null,+ sourceFile: null,+ expectedVariants: 0,+ arrivedVariants: 0,+ visibleVariant: null,+ paramValues: {},+ pendingEventSeq: null,+ pendingEvent: null,+ deliveryLease: null,+ checkpointRevision: 0,+ activeOwner: null,+ sourceMarkers: {},+ fallbackMode: null,+ annotationArtifacts: [],+ diagnostics: [],+ updatedAt: null,+ };+}++function rebuildSnapshotFromJournal(journalPath, id) {+ let snapshot = baseSnapshot(id);+ const diagnostics = [];+ let nextSeq = 1;+ if (!fs.existsSync(journalPath)) return { snapshot, diagnostics, nextSeq };++ const lines = fs.readFileSync(journalPath, 'utf-8').split('\n');+ for (let i = 0; i < lines.length; i++) {+ const line = lines[i];+ if (!line.trim()) continue;+ try {+ const entry = JSON.parse(line);+ if (!entry || typeof entry !== 'object') throw new Error('entry is not object');+ if (Number.isInteger(entry.seq)) nextSeq = Math.max(nextSeq, entry.seq + 1);+ snapshot = applyEvent(snapshot, entry);+ } catch (err) {+ diagnostics.push({+ error: 'journal_parse_failed',+ line: i + 1,+ message: err.message,+ });+ }+ }+ snapshot.diagnostics = [...snapshot.diagnostics, ...diagnostics];+ return { snapshot, diagnostics, nextSeq };+}++function applyEvent(snapshot, entry, inheritedDiagnostics = []) {+ const event = entry.event || entry;+ const next = {+ ...snapshot,+ paramValues: { ...(snapshot.paramValues || {}) },+ sourceMarkers: { ...(snapshot.sourceMarkers || {}) },+ annotationArtifacts: [...(snapshot.annotationArtifacts || [])],+ diagnostics: [...(snapshot.diagnostics || [])],+ updatedAt: entry.ts || new Date().toISOString(),+ };++ if (inheritedDiagnostics.length && next.diagnostics.length === 0) {+ next.diagnostics = [...inheritedDiagnostics];+ }++ switch (event.type) {+ case 'generate':+ next.phase = 'generate_requested';+ next.pageUrl = event.pageUrl ?? next.pageUrl;+ next.expectedVariants = event.count ?? next.expectedVariants;+ next.pendingEventSeq = entry.seq ?? next.pendingEventSeq;+ next.pendingEvent = toPendingEvent(event);+ if (event.screenshotPath) upsertArtifact(next.annotationArtifacts, { type: 'screenshot', path: event.screenshotPath });+ break;+ case 'variants_ready':+ case 'agent_done':+ next.phase = event.carbonize === true ? 'carbonize_required' : 'variants_ready';+ next.sourceFile = event.file ?? next.sourceFile;+ next.arrivedVariants = event.arrivedVariants ?? (next.arrivedVariants ?? next.expectedVariants);+ next.pendingEventSeq = null;+ next.pendingEvent = null;+ if (event.carbonize === true) {+ next.diagnostics.push({+ error: 'carbonize_cleanup_required',+ file: event.file || null,+ message: 'Accepted variant still has carbonize markers that must be folded into source CSS.',+ });+ }+ break;+ case 'checkpoint':+ 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;+ if (event.paramValues) next.paramValues = { ...event.paramValues };+ } else {+ next.diagnostics.push({ error: 'stale_checkpoint_ignored', revision: event.revision });+ }+ break;+ case 'accept':+ case 'accept_intent':+ next.phase = 'accept_requested';+ next.visibleVariant = Number(event.variantId ?? next.visibleVariant);+ if (event.paramValues) next.paramValues = { ...event.paramValues };+ next.pendingEventSeq = entry.seq ?? next.pendingEventSeq;+ next.pendingEvent = toPendingEvent(event);+ break;+ case 'discard':+ next.phase = 'discard_requested';+ next.pendingEventSeq = entry.seq ?? next.pendingEventSeq;+ next.pendingEvent = toPendingEvent(event);+ break;+ case 'discarded':+ next.phase = 'discarded';+ next.pendingEventSeq = null;+ next.pendingEvent = null;+ break;+ case 'complete':+ next.phase = 'completed';+ next.pendingEventSeq = null;+ next.pendingEvent = null;+ break;+ case 'agent_error':+ next.phase = 'agent_error';+ next.pendingEventSeq = null;+ next.pendingEvent = null;+ next.diagnostics.push({ error: 'agent_error', message: event.message || 'unknown agent error' });+ break;+ default:+ next.diagnostics.push({ error: 'unknown_event_type', type: event.type });+ break;+ }+ return next;+}++function toPendingEvent(event) {+ const pending = { ...event };+ delete pending.token;+ return pending;+}++function upsertArtifact(artifacts, artifact) {+ if (!artifacts.some((existing) => existing.path === artifact.path && existing.type === artifact.type)) {+ artifacts.push(artifact);+ }+}++function writeSnapshot(snapshotPath, snapshot) {+ fs.writeFileSync(snapshotPath, JSON.stringify(snapshot, null, 2) + '\n');+}diff --git a/.trae/skills/impeccable/scripts/live-status.mjs b/.trae/skills/impeccable/scripts/live-status.mjsnew file mode 100644index 000000000..dce1fbca2--- /dev/null+++ b/.trae/skills/impeccable/scripts/live-status.mjs@@ -0,0 +1,47 @@+#!/usr/bin/env node+/**+ * Print durable recovery status for Impeccable live sessions.+ */++import { createLiveSessionStore } from './live-session-store.mjs';+import { readLiveServerInfo } from './impeccable-paths.mjs';++function readServerInfo() {+ return readLiveServerInfo(process.cwd())?.info || null;+}++async function fetchServerStatus(info) {+ if (!info) return null;+ try {+ const res = await fetch(`http://localhost:${info.port}/status?token=${info.token}`);+ if (!res.ok) return null;+ return await res.json();+ } catch {+ return null;+ }+}++export async function statusCli() {+ const info = readServerInfo();+ const server = await fetchServerStatus(info);+ const store = createLiveSessionStore({ cwd: process.cwd() });+ const activeSessions = store.listActiveSessions();+ const payload = {+ liveServer: server ? {+ status: server.status,+ port: server.port,+ connectedClients: server.connectedClients,+ pendingEvents: server.pendingEvents,+ } : null,+ activeSessions: server?.activeSessions || activeSessions,+ recoveryHint: 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.',+ };+ console.log(JSON.stringify(payload, null, 2));+}++const _running = process.argv[1];+if (_running?.endsWith('live-status.mjs') || _running?.endsWith('live-status.mjs/')) {+ statusCli();+}diff --git a/.trae/skills/impeccable/scripts/live-wrap.mjs b/.trae/skills/impeccable/scripts/live-wrap.mjsindex a5769a50a..d46328b9f 100644--- a/.trae/skills/impeccable/scripts/live-wrap.mjs+++ b/.trae/skills/impeccable/scripts/live-wrap.mjs@@ -185,6 +185,7 @@ The agent should insert variant HTML at insertLine.`);const { startLine, endLine } = match;const commentSyntax = detectCommentSyntax(targetFile);+ const styleMode = detectStyleMode(targetFile);const isJsx = commentSyntax.open === '{/*';const indent = lines[startLine].match(/^(\s*)/)[1];@@ -269,6 +270,10 @@ The agent should insert variant HTML at insertLine.`);endLine: startLine + wrapperLines.length + (originalLines.length - 1), // 1-indexedinsertLine: insertLine + 1, // 1-indexed: where variants gocommentSyntax: commentSyntax,+ styleMode: styleMode.mode,+ styleTag: styleMode.styleTag,+ cssSelectorPrefixExamples: buildCssSelectorPrefixExamples(styleMode.mode, count),+ cssAuthoring: buildCssAuthoring(styleMode, count),originalLineCount: originalLines.length,}));}@@ -335,6 +340,62 @@ function detectCommentSyntax(filePath) {return { open: '<!--', close: '-->' };}+function detectStyleMode(filePath) {+ const ext = path.extname(filePath).toLowerCase();+ if (ext === '.astro') {+ return {+ mode: 'astro-global-prefixed',+ styleTag: '<style is:inline data-impeccable-css="SESSION_ID">',+ };+ }+ return {+ mode: 'scoped',+ styleTag: '<style data-impeccable-css="SESSION_ID">',+ };+}++function buildCssSelectorPrefixExamples(styleMode, count) {+ if (styleMode !== 'astro-global-prefixed') return [];+ return Array.from({ length: count }, (_, i) => `[data-impeccable-variant="${i + 1}"]`);+}++function buildCssAuthoring(styleMode, count) {+ const variantNumbers = Array.from({ length: count }, (_, i) => i + 1);+ if (styleMode.mode === 'astro-global-prefixed') {+ return {+ mode: styleMode.mode,+ styleTag: styleMode.styleTag,+ strategy: 'global-prefixed',+ rulePattern: '[data-impeccable-variant="N"] > .variant-class { ... }',+ selectorExamples: variantNumbers.map((n) => `[data-impeccable-variant="${n}"] > .variant-class`),+ requirements: [+ 'Use the styleTag exactly; the is:inline attribute is required for this file.',+ 'Prefix every preview selector with the matching [data-impeccable-variant="N"] selector.',+ 'Keep selectors anchored to the generated variant wrapper; do not rely on component CSS scoping for preview rules.',+ ],+ forbidden: [+ 'Do not use @scope for this styleMode.',+ ],+ };+ }+ return {+ mode: styleMode.mode,+ styleTag: styleMode.styleTag,+ strategy: 'scope-rule',+ rulePattern: '@scope ([data-impeccable-variant="N"]) { :scope > .variant-class { ... } }',+ selectorExamples: variantNumbers.map((n) => `@scope ([data-impeccable-variant="${n}"]) { :scope > .variant-class { ... } }`),+ requirements: [+ 'Use @scope blocks keyed to each [data-impeccable-variant="N"] wrapper.',+ 'Inside each @scope block, make :scope rules step into the replacement element with a descendant combinator.',+ 'Use the styleTag exactly; do not add framework-specific style attributes unless this object says to.',+ ],+ forbidden: [+ 'Do not use global [data-impeccable-variant="N"] selector prefixes for this styleMode.',+ 'Do not add is:inline to the style tag for this styleMode.',+ ],+ };+}+/*** Search project files for the query string (class name, ID, etc.)* Returns the first matching file path, or null.diff --git a/.trae/skills/impeccable/scripts/live.mjs b/.trae/skills/impeccable/scripts/live.mjsindex befbdb8ed..cafb0eca9 100644--- a/.trae/skills/impeccable/scripts/live.mjs+++ b/.trae/skills/impeccable/scripts/live.mjs@@ -2,10 +2,10 @@* CLI entry point: prepare everything needed to enter the live variant poll loop.** Does (all in one command):- * 1. Check config.json (returns config_missing if first-ever run)+ * 1. Check .impeccable/live/config.json (returns config_missing if first-ever run)* 2. Start the live server in the background (or reuse a running one)* 3. Inject the browser script tag into the project's entry file- * 4. Read .impeccable.md for design context (if present)+ * 4. Read PRODUCT.md / DESIGN.md for project context* 5. Print a single JSON blob with everything the agent needs** After this, the agent's only remaining steps are:@@ -23,9 +23,9 @@ import path from 'node:path';import { fileURLToPath } from 'node:url';import { loadContext } from './load-context.mjs';import { resolveFiles } from './live-inject.mjs';+import { readLiveServerInfo } from './impeccable-paths.mjs';const __dirname = path.dirname(fileURLToPath(import.meta.url));-const PID_FILE = path.join(process.cwd(), '.impeccable-live.json');async function liveCli() {const args = process.argv.slice(2);@@ -34,10 +34,10 @@ async function liveCli() {console.log(`Usage: node live.mjsPrepare everything for live variant mode in a single command:- - Checks scripts/config.json (required, created once per project)+ - Checks .impeccable/live/config.json (required, created once per project)- Starts (or reuses) the live server in the background- Injects the browser script tag- - Reads .impeccable.md for design context+ - Reads PRODUCT.md / DESIGN.md for project contextOn success, prints a JSON blob with:{ ok, serverPort, serverToken, pageFile, hasContext, context }@@ -223,7 +223,7 @@ function safeParse(out) {function ensureServerRunning() {// Try to reuse an existing servertry {- const existing = JSON.parse(fs.readFileSync(PID_FILE, 'utf-8'));+ const existing = readLiveServerInfo(process.cwd())?.info;if (existing && existing.pid) {try {process.kill(existing.pid, 0); // throws if deaddiff --git a/.trae/skills/impeccable/scripts/load-context.mjs b/.trae/skills/impeccable/scripts/load-context.mjsindex dca23c1f8..dc340bf16 100644--- a/.trae/skills/impeccable/scripts/load-context.mjs+++ b/.trae/skills/impeccable/scripts/load-context.mjs@@ -39,7 +39,7 @@ const LEGACY_NAMES = ['.impeccable.md'];const FALLBACK_DIRS = ['.agents/context', 'docs'];/**- * Resolve the directory that holds PRODUCT.md / DESIGN.md / DESIGN.json for+ * Resolve the directory that holds PRODUCT.md / DESIGN.md for* this project. Exported so other scripts (e.g. live-server.mjs) can read the* design files from the same location the loader uses.*/diff --git a/README.md b/README.mdindex 962b568b2..ed5c2ee0f 100644--- a/README.md+++ b/README.md@@ -38,8 +38,8 @@ All commands are accessed through `/impeccable`:| Command | What it does ||---------|--------------|| `/impeccable craft` | Full shape-then-build flow with visual iteration |-| `/impeccable teach` | One-time setup: gather design context, write PRODUCT.md and DESIGN.md |-| `/impeccable document` | Generate DESIGN.md from existing project code |+| `/impeccable teach` | One-time setup: gather design context, write root PRODUCT.md and DESIGN.md |+| `/impeccable document` | Generate root DESIGN.md from existing project code || `/impeccable extract` | Pull reusable components and tokens into the design system || `/impeccable shape` | Plan UX/UI before writing code || `/impeccable critique` | UX design review: hierarchy, clarity, emotional resonance |diff --git a/docs/adr-live-variant-mode.md b/docs/adr-live-variant-mode.mdindex 82c978c01..0390e2a94 100644--- a/docs/adr-live-variant-mode.md+++ b/docs/adr-live-variant-mode.md@@ -82,7 +82,7 @@ For dev servers that don't support HMR (like Bun's static HTML import), the brow│ └── GET /stop — graceful shutdown ││ ││ State: session token, SSE client set, event queue, poll queue │- │ PID file: .impeccable-live.json (project root) │+ │ Server file: .impeccable/live/server.json (project root) ││ │└────────────┬──────────────────────────────────┬─────────────────┘│ GET /poll (long-poll) │ POST /poll (reply)@@ -228,7 +228,7 @@ This survives page reloads, browser close/reopen, HMR, and accidental refreshes.- **Session token**: `crypto.randomUUID()`, checked on all mutating endpoints and SSE connections.- **Localhost only**: server binds to `127.0.0.1`, not `0.0.0.0`.-- **Token in PID file**: `.impeccable-live.json` in project root. Only the user's processes can read it.+- **Token in server file**: `.impeccable/live/server.json` in project root. Only the user's processes can read it.- **Token injected into `/live.js`**: the server prepends `window.__IMPECCABLE_TOKEN__` at serve time.- **Path traversal guard**: `/source` endpoint validates the requested path is within `process.cwd()`.- **No eval/innerHTML**: all browser UI built with `createElement` and `textContent`.diff --git a/docs/plans/2026-04-28-001-feat-live-session-recovery-plan.md b/docs/plans/2026-04-28-001-feat-live-session-recovery-plan.mdnew file mode 100644index 000000000..c185375e5--- /dev/null+++ b/docs/plans/2026-04-28-001-feat-live-session-recovery-plan.md@@ -0,0 +1,555 @@+---+title: feat: Add durable live session recovery+type: feat+status: active+date: 2026-04-28+deepened: 2026-04-28+---++# feat: Add durable live session recovery++## Overview++Impeccable live mode should remain recoverable when the browser changes live-session state while the agent is not actively polling, after the agent is interrupted, or after the helper server/page reloads. The change adds a durable live-session journal, a resumable server/browser state contract, and an agent-facing status command so a fresh agent can reconstruct the active session and continue from the correct next action.++This plan does not change the core source-first live-mode architecture from `docs/adr-live-variant-mode.md`: variants are still written to source, the browser still previews through HMR or `/source`, and the agent still uses long-poll. It makes the state machine durable and inspectable instead of relying on chat memory plus in-process queues.++---++## Problem Frame++The observed failure mode was: the user accepted and tuned a live variant in the browser while the agent was not listening continuously. The browser moved forward, source entered a transitional state, and the agent no longer had authoritative context for what the user had done. Current code already has useful browser `localStorage` resume behavior and server in-memory queues, but neither is sufficient as a recovery source after interruption, server restart, browser cleanup, or missed polling.++The product expectation is stronger: if the user changes live-mode state in the browser, a later agent should be able to ask, “what happened and what do I need to do next?” and receive a complete, durable answer.++---++## Requirements Trace++- R1. Browser live-session changes are durably recorded outside browser memory and chat context.+- R2. A new or interrupted agent can reconstruct the current live session, selected variant, parameter values, source file, and next required action.+- R3. Accept/discard events are not silently lost when the agent is not polling or when the helper server restarts.+- R4. Browser resume behavior treats source markers and durable session state as recoverable truth rather than hiding unfinished work behind a local handled flag.+- R5. Durable replay is idempotent: duplicate, late, or conflicting events must not corrupt source.+- R6. Carbonize-required accepts are represented as an explicit incomplete state until cleanup is done, and can reconcile to complete when source markers prove cleanup already happened.+- R7. Existing browser/agent event transport remains self-contained, zero-dependency, token-protected, and compatible with the current SSE plus long-poll protocol. Status/resume may be implemented as a separate CLI/file-reader API.+- R8. Agent delivery uses an explicit lease/ack model so a poll response is not treated as completed work until the agent reports a result.+- R9. Annotated screenshots and generated-file fallback metadata remain recoverable while a session is incomplete.++---++## Scope Boundaries++- This plan does not replace long-poll with WebSockets or a harness-specific integration.+- This plan does not make accept fully atomic in one step. It records and resumes the incomplete state first; a later plan may remove carbonize as a manual cleanup stage.+- This plan does not redesign generated variant quality or CSS specificity behavior, except where preview state metadata needs to be captured.+- This plan does not introduce a database or external service. Durable state should live in project-local files managed by the helper server.+- This plan does not support multiple simultaneous browser tabs editing different sessions as a first-class collaboration mode. It should avoid corrupting them, but single active session remains the baseline.++### Deferred to Follow-Up Work++- Atomic accept/carbonize: a later plan can make `live-accept.mjs` produce permanent clean source in one deterministic step.+- Safer generated-preview layout defaults: a later plan can harden wrapper sizing, overflow, and scoped selector guidance.+- Multi-user or multi-tab collaboration semantics: out of scope until live mode intentionally supports collaborative sessions.++---++## Context & Research++### Relevant Code and Patterns++- `source/skills/impeccable/scripts/live-server.mjs` owns `/events`, `/poll`, `/source`, `/health`, token validation, in-memory `pendingEvents`, and browser SSE clients.+- `source/skills/impeccable/scripts/live-browser.js` owns picker state, variant cycling, parameter controls, `localStorage` session resume, handled-session sentinels, and accept/discard browser behavior.+- `source/skills/impeccable/scripts/live-poll.mjs` is the agent-facing poll client and auto-runs `live-accept.mjs` for accept/discard events.+- `source/skills/impeccable/scripts/live-accept.mjs` deterministically accepts/discards variant wrappers and can emit carbonize-required results.+- `source/skills/impeccable/scripts/live-wrap.mjs` creates source markers and original/variant wrapper structure.+- `tests/live-server.test.mjs`, `tests/live-accept.test.mjs`, `tests/live-wrap.test.mjs`, and `tests/live-e2e.test.mjs` are the relevant verification surfaces.+- `docs/adr-live-variant-mode.md` documents the current architecture and should be updated if the durable journal changes the lifecycle contract.++### Institutional Learnings++- `docs/adr-live-variant-mode.md` explicitly values source modification over DOM patching, zero-dependency scripts, SSE plus fetch, long-poll for agent compatibility, and `display: contents` wrappers.+- `source/skills/impeccable/reference/live.md` currently encodes the operational assumption that the agent continuously polls and performs carbonize cleanup before the next poll.++### External References++- External research skipped. This is a repo-owned local protocol and the existing architecture is well documented; local patterns are more authoritative than generic event-sourcing guidance.++---++## Key Technical Decisions++- Add a project-local durable live-session store rather than relying on browser `localStorage` or server memory alone: this is the minimum change that lets any future agent reconstruct state.+- Use append-only session events plus a compact session snapshot: append-only events preserve the audit trail for recovery; the snapshot makes status reads fast and simple. The append-only journal and source markers are canonical; snapshots are rebuildable caches.+- Treat poll delivery as a leased work item, not queue removal: an event becomes terminal only after the agent posts a result/ack, and stale leases are redelivered idempotently.+- Keep browser `localStorage` as a UI convenience, not the source of truth: source markers plus durable server journal should win when they disagree.+- Add explicit server-side session states instead of ad hoc flags: states make accept/discard replay, stale checkpoint rejection, and invalid transitions enforceable.+- Make accept/discard delivery acknowledged before the browser clears recoverable state: this prevents “browser thinks handled, source did not change” split-brain.+- Add agent-facing status/resume scripts instead of requiring agents to inspect raw files: live mode needs a stable agent API, not folklore.++---++## Open Questions++### Resolved During Planning++- Should the first fix be durable resumability or atomic accept? Durable resumability comes first because it solves missed polling, interrupted agents, and transitional source states without requiring a full accept rewrite.+- Should durability depend on external storage? No. Live mode is intentionally self-contained and should use project-local files.++### Deferred to Implementation++- Exact file naming inside the session store: implementation should choose a simple structure after reviewing how `.impeccable-live.json` is currently managed.+- Exact retention policy defaults: implementation should start conservative and prune old completed sessions only after tests cover recovery.+- Exact browser UI copy for pending accept/reconnect states: copy should be short and can be refined during implementation.+- Exact helper-server restart UX: auto-rebind across token/port rotation is out of scope for this plan unless implementation discovers a safe lightweight path. The default recovery is `live-status` plus asking the user to reload/reopen the instrumented page when needed.++---++## Output Structure++ source/skills/impeccable/scripts/+ live-session-store.mjs+ live-status.mjs+ live-resume.mjs+ live-server.mjs+ live-browser.js+ live-poll.mjs+ live-accept.mjs+ tests/+ live-session-store.test.mjs+ live-server.test.mjs+ live-browser-recovery.test.mjs+ live-poll.test.mjs+ live-status.test.mjs+ live-e2e.test.mjs+ package.json+ docs/+ adr-live-variant-mode.md++---++## High-Level Technical Design++> *This illustrates the intended approach and is directional guidance for review, not implementation specification. The implementing agent should treat it as context, not code to reproduce.*++```mermaid+stateDiagram-v2+ [*] --> configuring+ configuring --> generating: browser Go+ generating --> source_wrapped: agent wrapped source; file known+ source_wrapped --> variants_written: agent wrote variants+ variants_written --> cycling: agent replies done or browser sees wrapper+ cycling --> accept_pending: browser Accept+ cycling --> discard_pending: browser Discard+ accept_pending --> accepted_source_pending: agent/live-accept wrote accepted variant with carbonize markers+ accepted_source_pending --> complete: carbonize cleanup done+ discard_pending --> complete: source restored+ generating --> stranded: server/page/agent interruption+ cycling --> stranded: server/page/agent interruption+ accept_pending --> stranded: server/page/agent interruption+ stranded --> generating: resume pending leased event+ stranded --> source_wrapped: resume wrapper/original-only source+ stranded --> cycling: resume from durable journal + source markers+ stranded --> accepted_source_pending: resume from carbonize markers+```++```mermaid+sequenceDiagram+ participant B as Browser+ participant S as Live server+ participant J as Session journal+ participant A as Agent+ participant F as Source files++ B->>S: POST /events accept_intent(session, variant, params)+ S->>J: append event; rebuild/atomically update snapshot(accept_pending)+ S-->>B: 202 accepted + durable sequence+ A->>S: GET /poll or live-status+ S->>J: lease next pending event+ S-->>A: accept event + recovery context + lease id+ A->>F: live-accept / cleanup+ A->>S: POST /poll done + file/result + lease id+ S->>J: append agent_result; mark lease acked; update snapshot+ S-->>B: SSE done/committed+ B->>B: clear local pending state only after committed+```++---++## Implementation Units++- U1. **Define durable session store**++**Goal:** Add a small storage module that can append events, update snapshots, read active sessions, and recover pending work after process restart.++**Requirements:** R1, R2, R3, R5, R7, R8, R9++**Dependencies:** None++**Files:**+- Create: `source/skills/impeccable/scripts/live-session-store.mjs`+- Create: `tests/live-session-store.test.mjs`+- Modify: `source/skills/impeccable/scripts/live-server.mjs`+- Modify: `package.json`++**Approach:**+- Store state under a project-local live directory, separate from `.impeccable-live.json` but discoverable from the same project root.+- Write append-only JSONL events per session and a compact JSON snapshot per session. The JSONL journal is authoritative; snapshots are derived and must be rebuildable when missing, stale, or contradictory.+- Include session id, event sequence, event type, phase, source file when known, visible variant, param values, timestamps, delivery lease/ack metadata, checkpoint revision, generated-file fallback mode, and annotation artifact paths.+- Persist annotation screenshot assets for incomplete sessions when generate events include annotations; status should report missing artifacts as diagnostics.+- Keep the module dependency-free and synchronous or simple async Node filesystem code consistent with current scripts.+- Route browser checkpoints through `/events` as a first-class `checkpoint` event type, with monotonic client revision and session owner metadata.+- Wire new non-E2E tests into the default test script, because `package.json` enumerates test files explicitly rather than globbing all `tests/*.test.mjs`.+- Treat malformed journal entries as recoverable diagnostics rather than crashing the helper server when possible.++**Execution note:** Start test-first for the storage module because it is the new source of truth.++**Technical design:** Directional event shape:++```text+SessionSnapshot = {+ id,+ phase,+ pageUrl,+ sourceFile,+ expectedVariants,+ arrivedVariants,+ visibleVariant,+ paramValues,+ pendingEventSeq,+ deliveryLease,+ checkpointRevision,+ activeOwner,+ sourceMarkers,+ fallbackMode,+ annotationArtifacts,+ diagnostics,+ updatedAt+}+```++**Patterns to follow:**+- `source/skills/impeccable/scripts/live-server.mjs` for project-root PID file handling.+- `tests/live-server.test.mjs` for temp-directory test isolation.++**Test scenarios:**+- Happy path: appending `generate`, `variants_ready`, and `accept_intent` events for one session yields a snapshot with the latest phase and selected variant.+- Happy path: reading active sessions after constructing a new store instance returns the session written by the previous store instance.+- Edge case: duplicate event id or sequence is idempotent and does not append conflicting state twice.+- Edge case: a completed session remains readable for audit but is not returned as the active session by default.+- Edge case: journal and snapshot disagree after a simulated crash; status rebuilds the snapshot from the journal and records a repair diagnostic.+- Edge case: annotated generate event keeps its screenshot artifact available until the session completes.+- Error path: corrupted JSONL line is reported in diagnostics while valid prior events still reconstruct the snapshot.+- Error path: storage directory creation failure returns a structured error to the caller.++**Verification:**+- Durable state survives module re-instantiation and can answer “what is the active session and next action?” without browser or server memory.++---++- U2. **Journal browser events and enforce session transitions**++**Goal:** Make `/events` persist generate/accept/discard and checkpoint events before they are exposed to agent polling.++**Requirements:** R1, R3, R5, R7, R8++**Dependencies:** U1++**Files:**+- Modify: `source/skills/impeccable/scripts/live-server.mjs`+- Modify: `tests/live-server.test.mjs`++**Approach:**+- On `POST /events`, validate generate/accept/discard/checkpoint events, assign or validate a durable event sequence, append to the session journal, then enqueue actionable events for polling. Checkpoints update durable state but do not necessarily create agent work.+- Add a server-side session state machine that accepts valid transitions and treats duplicate valid events idempotently.+- Add an at-least-once poll delivery model: pending events are leased to a poll response, redelivered after lease expiry, and marked complete only when the agent posts a matching result.+- Keep `exit` as lower priority than real session events so queued generate/accept/discard work is not masked by tab disconnect.+- Preserve current token validation and in-memory fast path, but make disk the replayable source.+- On server startup, rebuild pending work from the journal into the in-memory queue. `/poll` may consult the store when memory is empty, but the journal remains canonical.++**Patterns to follow:**+- Existing `validateEvent()` and `enqueueEvent()` in `source/skills/impeccable/scripts/live-server.mjs`.+- Existing `/events` and `/poll` tests in `tests/live-server.test.mjs`.++**Test scenarios:**+- Happy path: `POST /events` for generate persists an event before a poll consumes it.+- Happy path: if the server object is recreated with the same project store, `/poll` returns the previously unconsumed generate event.+- Edge case: duplicate accept for the same session and variant returns the same durable state without creating conflicting queue entries.+- Edge case: discard after accept-pending is rejected or ignored according to the state machine and returns a diagnostic response.+- Error path: invalid transition returns a clear JSON error and does not append to the journal.+- Integration: queued real events are delivered before synthetic `exit` events.+- Integration: event delivered to a poll but never acked is redelivered after lease timeout and remains idempotent when eventually completed.++**Verification:**+- Browser events are not lost by an idle agent or helper server restart as long as the project-local journal remains.++---++- U3. **Add browser checkpoints and acknowledged accept/discard**++**Goal:** Have the browser record current live state durably and stop clearing recoverable local state until the server acknowledges the state change.++**Requirements:** R1, R2, R3, R4, R5++**Dependencies:** U1, U2++**Files:**+- Modify: `source/skills/impeccable/scripts/live-browser.js`+- Modify: `tests/live-e2e.test.mjs`+- Create: `tests/live-browser-recovery.test.mjs`++**Approach:**+- Add a browser checkpoint helper that sends current session state to `/events` as `type: "checkpoint"` whenever variant, parameter values, phase, or selected source file context changes.+- Include monotonic client revisions and an active-session owner/epoch so stale checkpoints from old tabs cannot regress a newer accepted/discarded phase.+- Change accept/discard from fire-and-forget to acknowledged durable receipt before `markSessionHandled()` and before local session cleanup. Agent completion remains a later state.+- Keep a local pending state if acknowledgement fails, with a visible “waiting for agent/server” or “reconnect to recover” state instead of silently resetting.+- Preserve existing `localStorage` resume as a UI fast path, but do not let its single handled key suppress recovery when source markers or durable server state indicate pending work.+- Capture current parameter values on every change, not only at accept time, so resume can reconstruct user tuning even before Accept.++**Patterns to follow:**+- Existing `saveSession()`, `resumeSession()`, `paramsCurrentValues`, and `handleAccept()` in `source/skills/impeccable/scripts/live-browser.js`.+- Existing scroll restoration and MutationObserver recovery patterns in `source/skills/impeccable/scripts/live-browser.js`.++**Test scenarios:**+- Happy path: moving a parameter slider sends a checkpoint with updated param values and does not reset the tune panel.+- Happy path: clicking Accept receives server acknowledgement, then transitions the browser to confirmed/pending-agent state.+- Edge case: Accept POST fails due to server down; browser keeps session recoverable and shows a reconnect/retry state.+- Edge case: page reload after accept acknowledgement but before agent completion resumes as pending cleanup rather than picking mode.+- Edge case: local handled flag exists but source wrapper still exists; browser resumes or reports pending cleanup instead of hiding the session.+- Edge case: stale checkpoint from a background tab arrives after accept-pending; server rejects it or records it as stale without changing snapshot phase.+- Integration: after HMR inserts variants, browser checkpoint records arrived variant count and visible variant.++**Verification:**+- The browser never becomes the only place where selected variant and tune values exist.++---++- U4. **Expose agent status and resume commands**++**Goal:** Give agents a stable CLI/API to inspect and continue live state without manually reading raw journal files or source markers.++**Requirements:** R2, R4, R6, R7++**Dependencies:** U1, U2++**Files:**+- Create: `source/skills/impeccable/scripts/live-status.mjs`+- Create: `source/skills/impeccable/scripts/live-resume.mjs`+- Create: `source/skills/impeccable/scripts/live-complete.mjs`+- Modify: `source/skills/impeccable/scripts/live-server.mjs`+- Modify: `source/skills/impeccable/reference/live.md`+- Modify: `tests/live-server.test.mjs`+- Create: `tests/live-status.test.mjs`++**Approach:**+- Add a status endpoint or direct store reader that returns active session snapshots, pending events, source marker status, and recommended next action.+- Add `live-status.mjs` for human/agent-readable JSON status.+- Add `live-resume.mjs` if the status command should also requeue pending events or print a normalized next event for the agent.+- Include source-marker scanning for `impeccable-variants-start`, `impeccable-carbonize-start`, and `impeccable-param-values` so source truth can repair journal/browser drift. The scan domain should include resolved live config targets, journal-known files, and existing source roots used by marker helpers; generated/served files covered by live config must be diagnosable.+- Consult the generated-file guard before recommending deterministic `live-accept`; generated/served-file fallback sessions should return `persist_fallback_to_true_source`.+- Distinguish generate recovery phases: pending event only, wrapper/original-only source, variants partially/fully written, and browser not yet confirmed cycling.+- Keep output JSON stable and agent-readable: explicit `nextAction`, `reason`, `file`, `sessionId`, `paramValues`, `lease`, and `diagnostics` fields.+- After completion acknowledgement, completed sessions return `no_active_session` by default unless an include-completed flag is requested.++**Technical design:** Directional `nextAction` values:++```text+poll_for_pending_event+write_variants+continue_writing_variants+run_accept_cleanup+run_carbonize_cleanup+acknowledge_completion+persist_fallback_to_true_source+restore_discard+ask_user_to_reopen_browser+no_active_session+```++**Patterns to follow:**+- `source/skills/impeccable/scripts/live-poll.mjs` for CLI JSON output style.+- `source/skills/impeccable/scripts/live-accept.mjs` marker parsing helpers where reusable.++**Test scenarios:**+- Happy path: status with a pending accept event returns `run_accept_cleanup` and includes variant id and param values.+- Happy path: status with carbonize markers in source returns `run_carbonize_cleanup` even if no browser is connected.+- Edge case: status with no active journal but source variant markers returns a recoverable source-marker session.+- Edge case: status with stale completed sessions returns `no_active_session` by default and can include completed sessions only when requested.+- Edge case: source markers exist in a generated/served file covered by live config; status recommends fallback true-source persistence rather than deterministic accept.+- Edge case: wrapper exists with only original content; status recommends continuing variant writing rather than accept cleanup.+- Error path: missing or unreadable source file appears as a structured diagnostic, not an unhandled exception.+- Integration: `live-resume.mjs` can requeue or emit the pending event after a helper server restart.++**Verification:**+- A fresh agent can run one command and know exactly what happened in live mode and what to do next.++---++- U5. **Make poll/accept acknowledge durable completion**++**Goal:** Ensure agent-side handling updates durable session state after source writes and carbonize cleanup so browser and future agents know whether the session is complete.++**Requirements:** R2, R5, R6++**Dependencies:** U1, U2, U4++**Files:**+- Modify: `source/skills/impeccable/scripts/live-poll.mjs`+- Modify: `source/skills/impeccable/scripts/live-accept.mjs`+- Modify: `source/skills/impeccable/scripts/live-server.mjs`+- Modify: `tests/live-accept.test.mjs`+- Modify: `tests/live-server.test.mjs`+- Create: `tests/live-poll.test.mjs`++**Approach:**+- Have `live-poll.mjs` report auto-accept/discard results back to the server/session store, not only print `_acceptResult` to stdout.+- Complete the delivery lease only after this result is durably recorded; failed source writes should release or mark the lease recoverable with diagnostics.+- Represent `carbonize: true` as `accepted_source_pending` until cleanup is confirmed.+- Add `live-complete.mjs` as the canonical completion acknowledgement path after carbonize cleanup. `live-status.mjs` reports that completion is needed; `live-resume.mjs` helps recover pending work; only `live-complete.mjs` marks carbonize cleanup complete.+- Reconcile lost completion acknowledgements from source truth: if carbonize markers are gone and accepted content is materialized, status can idempotently record a synthetic completion event.+- Make duplicate completion acknowledgements idempotent.+- Preserve the stderr warning as a human attention signal, but do not rely on warning text as the state machine.++**Patterns to follow:**+- Current `_acceptResult` attachment in `source/skills/impeccable/scripts/live-poll.mjs`.+- Current carbonize marker output in `source/skills/impeccable/scripts/live-accept.mjs`.++**Test scenarios:**+- Happy path: accept event processed by `live-poll.mjs` updates durable session to `accepted_source_pending` when carbonize is required.+- Happy path: discard event processed by `live-poll.mjs` updates durable session to complete.+- Happy path: a `live-poll.mjs` CLI/integration test processes an accept event and records the durable lease/result acknowledgement through the real poll script path.+- Edge case: running accept twice for the same event returns the same final durable phase without rewriting source twice.+- Error path: `live-accept.mjs` failure records an agent error in the session journal and leaves next action recoverable.+- Integration: browser reload after agent accept but before carbonize can be diagnosed by `live-status.mjs`.+- Integration: completion acknowledgement is lost after source cleanup; status detects the condition and recommends `acknowledge_completion`, then `live-complete.mjs` resolves the session complete.++**Verification:**+- Durable state reflects what happened to source, not only what browser requested.++---++- U6. **Update live-mode guidance and recovery UX**++**Goal:** Teach both agents and users the new recovery contract and make recovery visible in live mode.++**Requirements:** R2, R4, R6, R7++**Dependencies:** U3, U4, U5++**Files:**+- Modify: `source/skills/impeccable/reference/live.md`+- Modify: `docs/adr-live-variant-mode.md`+- Modify: `source/skills/impeccable/scripts/live-browser.js`+- Modify: `README.md` if live command usage is documented there++**Approach:**+- Update `reference/live.md` to start with a status check when resuming a session or when the agent suspects it missed events.+- Document the durable journal and session states in the ADR.+- Add concise browser states for pending accept, reconnect/recover, and agent cleanup pending.+- Keep chat overhead low: the agent should use status JSON instead of asking the user to describe browser state.++**Patterns to follow:**+- Existing `reference/live.md` contract sections for poll loop, accept, carbonize, and cleanup.+- Existing toast and bar state patterns in `source/skills/impeccable/scripts/live-browser.js`.++**Test scenarios:**+- Test expectation: mostly documentation and UX copy. Behavioral coverage belongs to U3-U5; this unit should be verified through review plus any snapshot/E2E assertions added for visible pending states.++**Verification:**+- A new agent reading `reference/live.md` knows to recover state before making assumptions after interruption.++---++- U7. **Add restart and interruption E2E coverage**++**Goal:** Prove the durable recovery contract in realistic browser/server/agent flows.++**Requirements:** R1, R2, R3, R4, R5, R6++**Dependencies:** U1, U2, U3, U4, U5++**Files:**+- Modify: `tests/live-e2e.test.mjs`+- Modify: `tests/framework-fixtures/README.md` if new fixture expectations are needed+- Modify: `tests/live-e2e/agent.mjs` if deterministic agent hooks need to simulate interruption++**Approach:**+- Add focused E2E cases for missed polling, helper server restart, browser reload, accept before agent resumes, and carbonize-pending status.+- Prefer one or two compact fixtures over broad matrix explosion.+- Keep deterministic fake agent path as the primary verification route; LLM agent remains opt-in.++**Patterns to follow:**+- Existing live-mode E2E setup in `tests/live-e2e.test.mjs`.+- Fixture authoring guidance in `tests/framework-fixtures/README.md`.++**Test scenarios:**+- Integration: user clicks Go while no poll is active; later poll receives durable generate event and completes variants.+- Integration: user changes Tune values, reloads browser, and status/resume reports the same values.+- Integration: user clicks Accept, agent is interrupted, new agent runs status and sees `run_accept_cleanup` with variant id and params.+- Integration: helper server restarts after queued generate; resumed server can still surface the pending event.+- Integration: agent receives a poll event through the real `live-poll.mjs` path and then crashes before posting result; a resumed poll redelivers the leased event after timeout.+- Integration: source contains carbonize markers; status returns cleanup pending even without an active browser tab.+- Integration: out-of-order checkpoint after accept does not regress pending accept state.+- Error path: duplicate accept and late discard do not corrupt final source.++**Verification:**+- E2E coverage demonstrates recovery from the exact “agent was not listening” failure mode.++---++## System-Wide Impact++- **Interaction graph:** Browser `live-browser.js` posts events/checkpoints to `live-server.mjs`; server persists them through `live-session-store.mjs`; agent observes them through `live-poll.mjs`, `live-status.mjs`, or `live-resume.mjs`; source mutations still happen through `live-wrap.mjs` and `live-accept.mjs`.+- **Error propagation:** Failed event persistence must be visible to the browser before it clears state. Failed source cleanup must be visible in status output and kept recoverable.+- **State lifecycle risks:** The key risk is split-brain among browser localStorage, server journal, in-memory queue, snapshots, and source markers. The plan makes source markers plus durable journal canonical, snapshots rebuildable, in-memory queues cache-only, and browser localStorage only an optimization.+- **API surface parity:** The new status/resume scripts become agent-facing APIs and should be reflected in `reference/live.md` and tests.+- **Integration coverage:** Unit tests alone will not prove recovery. E2E must cover browser reload, server restart, missed poll, duplicate events, and carbonize pending states.+- **Unchanged invariants:** Live mode remains source-first, self-contained, zero-dependency, token-protected, and transport-compatible with current AI harnesses.++---++## Risks & Dependencies++| Risk | Mitigation |+|------|------------|+| Durable journal becomes another state source that can drift | Make source markers plus journal reconciliation explicit in `live-status.mjs`; keep browser localStorage advisory. |+| Event replay causes duplicate source rewrites | Add idempotency keys, state-machine validation, leased delivery, and tests for duplicate accept/discard. |+| Browser waits forever after accept if agent is absent | Show explicit pending/reconnect state and provide status/resume command for the agent. |+| Poll delivery is mistaken for completion | Model leased delivery separately from completion acknowledgement and redeliver expired leases. |+| Snapshot contradicts journal after crash | Treat journal as canonical and rebuild/repair snapshots on startup/status reads. |+| Annotated screenshot path goes stale before recovery | Store annotation artifacts with the incomplete session and retain them until completion cleanup. |+| Disk writes fail in restricted environments | Return structured server errors and do not clear browser state until persistence succeeds. |+| Tests become slow or brittle | Keep most coverage in store/server tests and add only targeted E2E cases for true cross-process recovery. |+| Backward compatibility with existing installed skill output drifts | Update source skill files first, then run the project build to regenerate provider outputs in a separate execution phase. |++---++## Documentation / Operational Notes++- Update `docs/adr-live-variant-mode.md` because durability changes the architecture from memory queue plus localStorage to journaled sessions.+- Update `source/skills/impeccable/reference/live.md` so agents know to run status/resume after interruption or before assuming no pending work.+- If generated provider skill outputs are tracked, implementation should regenerate them with the existing build process after changing `source/skills/impeccable/`.+- Because the default test script enumerates test files, implementation must update `package.json` when adding new non-E2E test files.+- Consider adding `.impeccable-live/` or the chosen session-store directory to gitignore if it is not already ignored.++---++## Sources & References++- Related architecture: `docs/adr-live-variant-mode.md`+- Live instructions: `source/skills/impeccable/reference/live.md`+- Browser live implementation: `source/skills/impeccable/scripts/live-browser.js`+- Server transport: `source/skills/impeccable/scripts/live-server.mjs`+- Agent poll client: `source/skills/impeccable/scripts/live-poll.mjs`+- Accept/discard source cleanup: `source/skills/impeccable/scripts/live-accept.mjs`+- Live-mode tests: `tests/live-server.test.mjs`, `tests/live-accept.test.mjs`, `tests/live-e2e.test.mjs`++---++## Surgical Overhaul Follow-Ups (2026-04-29)++- Dependency audit is now Bun-native via `bun run audit`, but the gate currently fails on transitive advisories:+ - `archiver -> archiver-utils -> lodash` and `brace-expansion`+ - optional `puppeteer -> @puppeteer/browsers -> basic-ftp`+- Decision: keep the audit script honest and failing instead of adding ignores before exploitability and replacement cost are reviewed.+- Recommended next dependency work: evaluate whether release ZIP creation still needs `archiver`, and whether optional Puppeteer screenshot tooling can be replaced, isolated, or upgraded without bloating install size.diff --git a/package.json b/package.jsonindex 83c6f06bc..45de6f500 100644--- a/package.json+++ b/package.json@@ -26,6 +26,7 @@"engines": {"node": ">=18"},+ "packageManager": "[email protected]","type": "module","bin": {"impeccable": "bin/cli.js"@@ -51,8 +52,9 @@"dev": "npx astro dev","preview": "bun run build && npx astro preview","deploy": "bun run build && wrangler pages deploy build/",- "test": "bun test tests/build.test.js tests/detect-antipatterns.test.js tests/windows-path-fix.test.js && node --test tests/detect-antipatterns-fixtures.test.mjs && node --test tests/detect-antipatterns-browser.test.mjs && node --test tests/cleanup-deprecated.test.mjs && node --test tests/live-wrap.test.mjs && node --test tests/live-accept.test.mjs && node --test tests/live-inject.test.mjs && node --test tests/live-server.test.mjs && node --test tests/live-browser-regression.test.mjs && node --test tests/framework-fixtures.test.mjs",+ "test": "bun test tests/build.test.js tests/detect-antipatterns.test.js tests/windows-path-fix.test.js && node --test tests/detect-antipatterns-fixtures.test.mjs && node --test tests/detect-antipatterns-browser.test.mjs && node --test tests/cleanup-deprecated.test.mjs && node --test tests/impeccable-paths.test.mjs && node --test tests/live-wrap.test.mjs && node --test tests/live-reference.test.mjs && node --test tests/live-accept.test.mjs && node --test tests/live-inject.test.mjs && node --test tests/live-poll.test.mjs && node --test tests/live-server.test.mjs && node --test tests/live-browser-regression.test.mjs && node --test tests/live-session-store.test.mjs && node --test tests/live-browser-session.test.mjs && node --test tests/live-browser-source.test.mjs && node --test tests/live-completion.test.mjs && node --test tests/live-recovery-commands.test.mjs && node --test tests/framework-fixtures.test.mjs","test:live-e2e": "node --test --test-timeout=600000 tests/live-e2e.test.mjs",+ "audit": "bun audit --audit-level=moderate","prepack": "cp README.md README.repo.md && cp README.npm.md README.md","postpack": "cp README.repo.md README.md && rm README.repo.md","release:skill": "node scripts/release.mjs skill",diff --git a/plugin/skills/impeccable/reference/document.md b/plugin/skills/impeccable/reference/document.mdindex 44f123bed..a091ec98e 100644--- a/plugin/skills/impeccable/reference/document.md+++ b/plugin/skills/impeccable/reference/document.md@@ -237,11 +237,11 @@ Concrete, forceful guardrails. Lead each with "Do" or "Don't". Be specific: incl- **Don't** [...]```-### Step 4b: Write DESIGN.json sidecar (extensions only)+### Step 4b: Write .impeccable/design.json sidecar (extensions only)-The frontmatter owns token primitives (colors, typography, rounded, spacing, components). The sidecar at `DESIGN.json` carries **what Stitch's schema can't hold**: tonal ramps per color, shadow/elevation tokens, motion tokens, breakpoints, full component HTML/CSS snippets (the panel renders these into a shadow DOM), and narrative (north star, rules, do's/don'ts). It extends the frontmatter, it doesn't duplicate it.+The frontmatter owns token primitives (colors, typography, rounded, spacing, components). The sidecar at `.impeccable/design.json` carries **what Stitch's schema can't hold**: tonal ramps per color, shadow/elevation tokens, motion tokens, breakpoints, full component HTML/CSS snippets (the panel renders these into a shadow DOM), and narrative (north star, rules, do's/don'ts). It extends the frontmatter, it doesn't duplicate it.-Regenerate the sidecar whenever you regenerate DESIGN.md. If the user only asks to refresh the sidecar (e.g., from the live panel's stale-hint), preserve DESIGN.md and write only DESIGN.json.+Regenerate the sidecar whenever you regenerate root `DESIGN.md`. If the user only asks to refresh the sidecar (e.g., from the live panel's stale-hint), preserve `DESIGN.md` and write only `.impeccable/design.json`.#### Schema@@ -310,7 +310,7 @@ Aim for a tight set of **5-10 components** that best represent the visual system- **Signature components (include if distinctive):** hero CTA, featured card, filter pill, any custom pattern the user mentioned as important in PRODUCT.md.- **Skip the rest.** Utility components, form building blocks, wrapper layouts: not worth documenting unless visually distinctive.-If the project has **no component library yet** (bare landing page, new project), synthesize canonical primitives from the tokens using best-practice defaults consistent with the DESIGN.md's rules. Every DESIGN.json has *something* to render, even on day zero.+If the project has **no component library yet** (bare landing page, new project), synthesize canonical primitives from the tokens using best-practice defaults consistent with the DESIGN.md's rules. Every `.impeccable/design.json` has *something* to render, even on day zero.#### Tonal ramps@@ -331,7 +331,7 @@ Do not reword. The panel shows these as secondary collapsible context; the same### Step 5: Confirm, refine, and refresh session cache1. Show the user the full DESIGN.md you wrote. Briefly highlight the non-obvious creative choices (descriptive color names, atmosphere language, named rules).-2. Mention that `DESIGN.json` was also written alongside; the live panel will now render this project's actual button/input/nav primitives instead of generic approximations.+2. Mention that `.impeccable/design.json` was also written alongside; the live panel will now render this project's actual button/input/nav primitives instead of generic approximations.3. Offer to refine any section: "Want me to revise a section, add component patterns I missed, or adjust the atmosphere language?"4. **Refresh the session cache.** Run `node .claude/skills/impeccable/scripts/load-context.mjs` one final time so the newly-written DESIGN.md lands in conversation. Subsequent commands in this session will use the fresh version automatically without re-reading.@@ -392,7 +392,7 @@ Per-section guidance in seed mode:- **Components**: omit entirely; no components exist yet.- **Do's and Don'ts**: carry PRODUCT.md's anti-references directly plus the anti-reference named in Q5.-Seed mode writes a minimal frontmatter with `name` and `description` only; no colors, typography, rounded, spacing, or components yet. Real tokens land on the next Scan-mode run. Skip the `DESIGN.json` sidecar in seed mode for the same reason: nothing to render.+Seed mode writes a minimal frontmatter with `name` and `description` only; no colors, typography, rounded, spacing, or components yet. Real tokens land on the next Scan-mode run. Skip the `.impeccable/design.json` sidecar in seed mode for the same reason: nothing to render.### Step 4: Confirm and refresh session cachediff --git a/plugin/skills/impeccable/reference/live.md b/plugin/skills/impeccable/reference/live.mdindex d65c00bd4..8943721ca 100644--- a/plugin/skills/impeccable/reference/live.md+++ b/plugin/skills/impeccable/reference/live.md@@ -12,8 +12,9 @@ Execute in order. No step skipped, no step reordered.2. Navigate to the URL that serves `pageFile` (infer from `package.json`, docs, terminal output, or an open tab). If you can't infer it confidently, tell the user once to open their dev/preview URL. Never use `serverPort` as that URL; it's the helper, not the app.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=`.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.-5. On `accept` / `discard`: the poll script already cleaned up; just poll again.-6. On `exit`: run the cleanup at the bottom.+5. 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. If interrupted, run `live-status.mjs` or `live-resume.mjs` before guessing. The durable journal replays unacknowledged work after helper restart.+7. 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.@@ -43,13 +44,31 @@ LOOP:Read JSON; dispatch on "type""generate" → Handle Generate; reply done; LOOP- "accept" → Handle Accept; LOOP+ "accept" → Handle Accept; complete carbonize cleanup if required; LOOP"discard" → Handle Discard; LOOP"prefetch" → Handle Prefetch; LOOP"timeout" → LOOP"exit" → break → Cleanup```+## Recovery commands++The live helper persists an append-only journal under `.impeccable/live/sessions/`. Browser checkpoints are advisory but durable; the journal is canonical. This is local durable recovery state, not project source.++Use these commands when the chat was interrupted, polling was missed, the helper restarted, or the browser reloaded:++```bash+node .claude/skills/impeccable/scripts/live-status.mjs+node .claude/skills/impeccable/scripts/live-resume.mjs --id SESSION_ID+node .claude/skills/impeccable/scripts/live-complete.mjs --id SESSION_ID+```++- `live-status.mjs` prints connected helper state, active durable sessions, and queued pending events. It works even when the helper is down by reading the journal directly.+- `live-resume.mjs` prints the active snapshot, pending event, checkpoint phase, visible variant, parameter values, and the next safe agent action.+- `live-complete.mjs` is the canonical manual final acknowledgement. Use it after carbonize/manual cleanup is verified and no further poll acknowledgement will happen automatically.++Server restart rule: start `live-server.mjs` again, then poll. Startup requeues unacknowledged pending events from the journal, so do not ask the user to click Go again unless `live-resume.mjs` says no active session exists.+## Handle `generate`Event: `{id, action, freeformPrompt?, count, pageUrl, element, screenshotPath?, comments?, strokes?}`.@@ -88,7 +107,14 @@ The helper searches ID first, then classes, then tag + class combo. If `event.paIf `--text` matches multiple candidates equally well, wrap exits with `{ error: "element_ambiguous", candidates: [...] }` and `fallback: "agent-driven"`: read the candidate line ranges, decide which one matches the picked element from page context, and write the wrapper manually per the fallback flow.-Output on success: `{ file, insertLine, commentSyntax }`.+Output on success: `{ file, insertLine, commentSyntax, styleMode, styleTag, cssSelectorPrefixExamples, cssAuthoring }`.++`styleMode` controls how preview CSS must be authored. Treat it as a detected capability mode, not a framework guess:++- `scoped`: use `@scope ([data-impeccable-variant="N"])` rules.+- `astro-global-prefixed`: use explicit `[data-impeccable-variant="N"]` selector prefixes and the exact `styleTag` returned by the tool.++Use `cssAuthoring` as the source of truth for the current file. It includes the exact `styleTag`, selector strategy, selector examples, requirements, and forbidden patterns. Do not apply a framework-specific exception unless the returned `styleMode` / `cssAuthoring.mode` says to.**Fallback errors.** Wrap only writes into files it judges to be source (tracked by git, not marked GENERATED, not listed in config's `generatedFiles`). If it can't land on a source file, it errors without writing; accepting a variant into a generated file is silent data loss. Three shapes:@@ -208,13 +234,14 @@ When the prompt and PRODUCT.md anti-references conflict (the prompt asks for X,Complete 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 scoped 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).+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).++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:```html<!-- Variants: insert below this line --><style data-impeccable-css="SESSION_ID">- @scope ([data-impeccable-variant="1"]) { ... }- @scope ([data-impeccable-variant="2"]) { ... }+ /* rules matching cssAuthoring.rulePattern */</style><div data-impeccable-variant="1"><!-- variant 1: full element replacement (single top-level element) -->@@ -229,11 +256,11 @@ Write CSS + all variants in ONE edit at the `insertLine` reported by `wrap`. Col**Each variant div contains exactly one top-level element: the full replacement for the original.** Use the same tag as the original (e.g. `<section>` if the user picked a `<section>`). Loose siblings (heading + paragraph + div as direct children of the variant div) break the outline tracking and the accept flow, which both assume one child.-The first variant has no `display: none` (visible by default). All others do. If variants use only inline styles and no scoped CSS, omit the `<style>` tag entirely. Use `@scope` for CSS isolation (Chrome 118+ / Firefox 128+ / Safari 17.4+).+The 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.-**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 rule starts `:scope > ...`.+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 > ...`.**JSX / TSX target files.** Wrap `<style>` content in a template literal so the CSS `{` / `}` aren't parsed as JSX expressions, and use `className=` / `style={{…}}` on every variant element. Keep `data-impeccable-*` attributes as-is; they're plain strings:@@ -369,10 +396,11 @@ Remove the wrapper you inserted in Step 2. Nothing else to do.## Handle `accept`-Event: `{id, variantId, _acceptResult}`. The poll script already ran `live-accept.mjs` to handle the file operation deterministically; the browser DOM is already updated.+Event: `{id, variantId, _acceptResult, _completionAck}`. The poll script already ran `live-accept.mjs` to handle the file operation deterministically, then acknowledged event delivery to the helper. The browser DOM is already updated.+- `_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 and a stderr banner both list the steps explicitly; neither is decorative.+- `_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: 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` without `mode`: manual cleanup: read file, find markers, edit.@@ -388,13 +416,13 @@ Do these five steps in the current thread, synchronously, before the next poll.4. **Unwrap the accepted content.** Delete the `<div data-impeccable-variant="N" style="display: contents">` that wraps it. Drop `data-impeccable-params` and any `data-p-*` attributes from it; 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.-Then poll again.+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.## Handle `discard`-Event: `{id, _acceptResult}`. The poll script already restored the original and removed all variant markers. Nothing to do. Poll again.+Event: `{id, _acceptResult, _completionAck}`. The poll script already restored the original, removed all variant markers, and acknowledged `discarded` durable completion. Nothing to do unless `_completionAck.ok !== true`; in that case run `live-complete.mjs --id EVENT_ID --discarded`, then poll again.## Handle `prefetch`@@ -424,7 +452,7 @@ When the poll returns `exit`, proceed to cleanup. If the poll is still running anode .claude/skills/impeccable/scripts/live-server.mjs stop```-Stops the HTTP server and runs `live-inject.mjs --remove` to strip `localhost:…/live.js` from the HTML entry. To stop the server but keep the inject tag (for a quick restart), use `stop --keep-inject`. `config.json` persists for future sessions.+Stops the HTTP server and runs `live-inject.mjs --remove` to strip `localhost:…/live.js` from the HTML entry. To stop the server but keep the inject tag (for a quick restart), use `stop --keep-inject`. `.impeccable/live/config.json` persists as project config for future sessions.Then:- Remove any leftover variant wrappers (search for `impeccable-variants-start` markers).@@ -432,7 +460,7 @@ Then:## First-time setup (config missing or invalid)-If `live.mjs` outputs `{ ok: false, error: "config_missing" | "config_invalid", path }`, write `config.json` at the reported path.+If `live.mjs` outputs `{ ok: false, error: "config_missing" | "config_invalid", path }`, write the live config at the reported path. By default this is `.impeccable/live/config.json`.Schema:@@ -512,7 +540,7 @@ node .claude/skills/impeccable/scripts/detect-csp.mjsOutput: `{ shape, signals }` where `shape` is one of `append-arrays`, `append-string`, `middleware`, `meta-tag`, or `null`. The shape is named by *patch mechanism*, so one template covers many frameworks.-- **`null`**: no CSP; skip to writing `config.json` with `cspChecked: true`.+- **`null`**: no CSP; skip to writing `.impeccable/live/config.json` with `cspChecked: true`.- **`append-arrays`**: CSP defined as structured directive arrays. Auto-patchable. See *append-arrays* below. Covers:- Monorepo helpers with `additionalScriptSrc` / `additionalConnectSrc` options (Next.js + shared config package)- SvelteKit `kit.csp.directives`@@ -589,6 +617,6 @@ Reference outputs:### Troubleshooting-If a user says "no" to the CSP patch at setup time and later complains that live doesn't work: their dev CSP blocks `http://localhost:8400`. Fix: delete `cspChecked` from `config.json` and re-run `live.mjs`: setup will ask again.+If a user says "no" to the CSP patch at setup time and later complains that live doesn't work: their dev CSP blocks `http://localhost:8400`. Fix: delete `cspChecked` from `.impeccable/live/config.json` and re-run `live.mjs`: setup will ask again.Then re-run `live.mjs`.diff --git a/plugin/skills/impeccable/reference/teach.md b/plugin/skills/impeccable/reference/teach.mdindex 2aeeb9d73..34a189055 100644--- a/plugin/skills/impeccable/reference/teach.md+++ b/plugin/skills/impeccable/reference/teach.md@@ -2,8 +2,8 @@Gathers design context for a project and writes two complementary files at the project root:-- **PRODUCT.md** (strategic): register, target users, product purpose, brand personality, anti-references, strategic design principles. Answers "who/what/why".-- **DESIGN.md** (visual): visual theme, color palette, typography, components, layout. Follows the [Google Stitch DESIGN.md format](https://stitch.withgoogle.com/docs/design-md/format/). Answers "how it looks".+- **PRODUCT.md** (strategic): root project file for register, target users, product purpose, brand personality, anti-references, strategic design principles. Answers "who/what/why".+- **DESIGN.md** (visual): root project file for visual theme, color palette, typography, components, layout. Follows the [Google Stitch DESIGN.md format](https://stitch.withgoogle.com/docs/design-md/format/). Answers "how it looks".Every other impeccable command reads these files before doing any work.diff --git a/plugin/skills/impeccable/scripts/impeccable-paths.mjs b/plugin/skills/impeccable/scripts/impeccable-paths.mjsnew file mode 100644index 000000000..ba852bae9--- /dev/null+++ b/plugin/skills/impeccable/scripts/impeccable-paths.mjs@@ -0,0 +1,105 @@+import fs from 'node:fs';+import path from 'node:path';++export const IMPECCABLE_DIR = '.impeccable';+export const LIVE_DIR = 'live';++export function getImpeccableDir(cwd = process.cwd()) {+ return path.join(cwd, IMPECCABLE_DIR);+}++export function getDesignSidecarPath(cwd = process.cwd()) {+ return path.join(getImpeccableDir(cwd), 'design.json');+}++export function getDesignSidecarCandidates(cwd = process.cwd(), contextDir = cwd) {+ const candidates = [+ getDesignSidecarPath(cwd),+ path.join(cwd, 'DESIGN.json'),+ ];+ const contextLegacy = path.join(contextDir, 'DESIGN.json');+ if (!candidates.includes(contextLegacy)) candidates.push(contextLegacy);+ return candidates;+}++export function resolveDesignSidecarPath(cwd = process.cwd(), contextDir = cwd) {+ return firstExisting(getDesignSidecarCandidates(cwd, contextDir));+}++export function getLiveDir(cwd = process.cwd()) {+ return path.join(getImpeccableDir(cwd), LIVE_DIR);+}++export function getLiveConfigPath(cwd = process.cwd()) {+ return path.join(getLiveDir(cwd), 'config.json');+}++export function getLegacyLiveConfigPath(scriptsDir) {+ return path.join(scriptsDir, 'config.json');+}++export function resolveLiveConfigPath({ cwd = process.cwd(), scriptsDir, env = process.env } = {}) {+ if (env.IMPECCABLE_LIVE_CONFIG && env.IMPECCABLE_LIVE_CONFIG.trim()) {+ const configured = env.IMPECCABLE_LIVE_CONFIG.trim();+ return path.isAbsolute(configured) ? configured : path.resolve(cwd, configured);+ }+ const primary = getLiveConfigPath(cwd);+ if (fs.existsSync(primary)) return primary;+ if (scriptsDir) {+ const legacy = getLegacyLiveConfigPath(scriptsDir);+ if (fs.existsSync(legacy)) return legacy;+ }+ return primary;+}++export function getLiveServerPath(cwd = process.cwd()) {+ return path.join(getLiveDir(cwd), 'server.json');+}++export function getLegacyLiveServerPath(cwd = process.cwd()) {+ return path.join(cwd, '.impeccable-live.json');+}++export function readLiveServerInfo(cwd = process.cwd()) {+ for (const filePath of [getLiveServerPath(cwd), getLegacyLiveServerPath(cwd)]) {+ try {+ return { info: JSON.parse(fs.readFileSync(filePath, 'utf-8')), path: filePath };+ } catch {+ /* try next */+ }+ }+ return null;+}++export function writeLiveServerInfo(cwd = process.cwd(), info) {+ const filePath = getLiveServerPath(cwd);+ fs.mkdirSync(path.dirname(filePath), { recursive: true });+ fs.writeFileSync(filePath, JSON.stringify(info));+ return filePath;+}++export function removeLiveServerInfo(cwd = process.cwd()) {+ for (const filePath of [getLiveServerPath(cwd), getLegacyLiveServerPath(cwd)]) {+ try { fs.unlinkSync(filePath); } catch {}+ }+}++export function getLiveSessionsDir(cwd = process.cwd()) {+ return path.join(getLiveDir(cwd), 'sessions');+}++export function getLegacyLiveSessionsDir(cwd = process.cwd()) {+ return path.join(cwd, '.impeccable-live', 'sessions');+}++export function getLiveAnnotationsDir(cwd = process.cwd()) {+ return path.join(getLiveDir(cwd), 'annotations');+}++export function getLegacyLiveAnnotationsDir(cwd = process.cwd()) {+ return path.join(cwd, '.impeccable-live', 'annotations');+}++function firstExisting(paths) {+ return paths.find((filePath) => fs.existsSync(filePath)) || null;+}diff --git a/plugin/skills/impeccable/scripts/live-browser-session.js b/plugin/skills/impeccable/scripts/live-browser-session.jsnew file mode 100644index 000000000..0e362d6be--- /dev/null+++ b/plugin/skills/impeccable/scripts/live-browser-session.js@@ -0,0 +1,123 @@+/**+ * Browser-side durable session helpers for Impeccable live mode.+ *+ * Kept separate from live-browser.js so recovery state can be tested without+ * booting the full overlay UI. Served before live-browser.js and attached to+ * window.__IMPECCABLE_LIVE_SESSION__.+ */+(function (root) {+ 'use strict';++ function createLiveBrowserSessionState({ prefix, storage, idFactory }) {+ if (!prefix) throw new Error('prefix required');+ const store = storage || root.localStorage;+ const makeId = idFactory || function () { return Math.random().toString(16).slice(2, 10); };+ const sessionKey = prefix + '-session';+ const handledKey = sessionKey + '-handled';+ const scrollKey = sessionKey + '-scroll';+ let checkpointRevision = 0;+ const owner = makeId();++ function safeRead(key) {+ try { return store.getItem(key); } catch { return null; }+ }++ function safeWrite(key, value) {+ try { store.setItem(key, value); } catch { /* quota exceeded or private mode */ }+ }++ function safeRemove(key) {+ try { store.removeItem(key); } catch { /* unavailable storage */ }+ }++ function loadSession() {+ try {+ const raw = safeRead(sessionKey);+ if (!raw) return null;+ const parsed = JSON.parse(raw);+ if (Number.isInteger(parsed.checkpointRevision)) {+ checkpointRevision = Math.max(checkpointRevision, parsed.checkpointRevision);+ }+ return parsed;+ } catch { return null; }+ }++ function saveSession(session) {+ if (!session || !session.id) return;+ const payload = {+ ...session,+ checkpointRevision,+ };+ safeWrite(sessionKey, JSON.stringify(payload));+ }++ function clearSession() {+ safeRemove(sessionKey);+ }++ function nextCheckpointRevision() {+ checkpointRevision += 1;+ const existing = loadSession();+ if (existing?.id) saveSession(existing);+ return checkpointRevision;+ }++ function seedCheckpointRevision(value) {+ if (Number.isInteger(value)) checkpointRevision = Math.max(checkpointRevision, value);+ return checkpointRevision;+ }++ function currentCheckpointRevision() {+ return checkpointRevision;+ }++ function markHandled(id) {+ if (!id) return;+ safeWrite(handledKey, id);+ }++ function isHandled(id) {+ return !!id && safeRead(handledKey) === id;+ }++ function clearHandled() {+ safeRemove(handledKey);+ }++ function writeScrollY(y) {+ safeWrite(scrollKey, String(y));+ }++ function readScrollY() {+ const raw = safeRead(scrollKey);+ if (raw == null) return null;+ const n = parseFloat(raw);+ return isFinite(n) ? n : null;+ }++ function clearScrollY() {+ safeRemove(scrollKey);+ }++ return {+ owner,+ sessionKey,+ handledKey,+ scrollKey,+ saveSession,+ loadSession,+ clearSession,+ nextCheckpointRevision,+ seedCheckpointRevision,+ currentCheckpointRevision,+ markHandled,+ isHandled,+ clearHandled,+ writeScrollY,+ readScrollY,+ clearScrollY,+ };+ }++ root.__IMPECCABLE_LIVE_SESSION__ = { createLiveBrowserSessionState };+})(typeof window !== 'undefined' ? window : globalThis);diff --git a/plugin/skills/impeccable/scripts/live-browser.js b/plugin/skills/impeccable/scripts/live-browser.jsindex 3da76bb96..e67cd01ed 100644--- a/plugin/skills/impeccable/scripts/live-browser.js+++ b/plugin/skills/impeccable/scripts/live-browser.js@@ -50,6 +50,16 @@const Z = { highlight: 100001, bar: 100005, picker: 100007, toast: 100010 };const EASE = 'cubic-bezier(0.22, 1, 0.36, 1)'; // ease-out-quintconst PREFIX = 'impeccable-live';+ const sessionState = window.__IMPECCABLE_LIVE_SESSION__?.createLiveBrowserSessionState({+ prefix: PREFIX,+ storage: localStorage,+ idFactory: () => crypto.randomUUID().replace(/-/g, '').slice(0, 8),+ });+ if (!sessionState) {+ console.error('[impeccable] live-browser-session.js was not loaded. Live mode cannot start safely.');+ window.__IMPECCABLE_LIVE_INIT__ = false;+ return;+ }const HIGHLIGHT_TRANSITION ='top 140ms ' + EASE +', left 140ms ' + EASE +@@ -112,6 +122,8 @@let hasProjectContext = false;let selectedAction = 'impeccable';let selectedCount = 3;+ const browserOwner = sessionState.owner;+ let checkpointTimer = null;// Scroll lock — holds window.scrollY at a fixed value while the session is// active, so HMR DOM patches and variant swaps can't drift the page. See@@ -126,21 +138,9 @@// (Previously: saveSession wrote scrollY alongside state, so every call// during resume overwrote the pre-reload value with whatever the browser// had landed on, typically 0.)- const SCROLL_KEY_SUFFIX = '-scroll';- function writeScrollY(y) {- try { localStorage.setItem(LS_KEY + SCROLL_KEY_SUFFIX, String(y)); } catch {}- }- function readScrollY() {- try {- const raw = localStorage.getItem(LS_KEY + SCROLL_KEY_SUFFIX);- if (raw == null) return null;- const n = parseFloat(raw);- return isFinite(n) ? n : null;- } catch { return null; }- }- function clearScrollY() {- try { localStorage.removeItem(LS_KEY + SCROLL_KEY_SUFFIX); } catch {}- }+ function writeScrollY(y) { sessionState.writeScrollY(y); }+ function readScrollY() { return sessionState.readScrollY(); }+ function clearScrollY() { sessionState.clearScrollY(); }// Pre-empt the browser: apply manual scroll restoration and jump to the// saved scrollY at script-parse time. Retries on fonts.ready and load@@ -1585,6 +1585,7 @@paramsCurrentValues[p.id] = v;readout.textContent = formatRangeValue(input);applyParamValue(variantEl, p, v);+ queueCheckpoint('param_changed');});row.appendChild(input);} else if (p.kind === 'toggle') {@@ -1615,6 +1616,7 @@knob.style.left = next ? '18px' : '2px';readout.textContent = next ? 'On' : 'Off';applyParamValue(variantEl, p, next);+ queueCheckpoint('param_changed');});row.appendChild(track);} else if (p.kind === 'steps') {@@ -1651,6 +1653,7 @@btn.style.color = on ? 'oklch(98% 0 0)' : P.text;});applyParamValue(variantEl, p, o.value);+ queueCheckpoint('param_changed');});segRow.appendChild(b);segBtns.push({ btn: b, val: o.value });@@ -1872,19 +1875,26 @@return;}+ const previousVisibleVariant = currentSessionId === sessionId ? visibleVariant : 0;+// Replace the live element with the full wrapper from sourceconst wrapper = srcWrapper.cloneNode(true);liveEl.parentElement.replaceChild(wrapper, liveEl);- // Update state: count variants, show the first one+ // Update state: count variants, preserving the user's current variant+ // when a late HMR/source reinjection lands after they have cycled.const variants = wrapper.querySelectorAll('[data-impeccable-variant]:not([data-impeccable-variant="original"])');arrivedVariants = variants.length;expectedVariants = parseInt(wrapper.dataset.impeccableVariantCount || arrivedVariants);- visibleVariant = 1;- showVariantInDOM(sessionId, 1);+ const saved = loadSession();+ const savedVisibleVariant = saved && saved.id === sessionId ? saved.visible : 0;+ visibleVariant = previousVisibleVariant > 0 && previousVisibleVariant <= arrivedVariants+ ? previousVisibleVariant+ : (savedVisibleVariant > 0 && savedVisibleVariant <= arrivedVariants ? savedVisibleVariant : 1);+ showVariantInDOM(sessionId, visibleVariant);// Update selectedElement to the visible variant's content- selectedElement = pickVariantContent(wrapper, 1) || wrapper.parentElement;+ selectedElement = pickVariantContent(wrapper, visibleVariant) || wrapper.parentElement;state = 'CYCLING';hideShaderOverlay();@@ -1907,6 +1917,7 @@updateSelectedElement();updateBarContent('cycling');saveSession();+ queueCheckpoint('variant_changed');}function updateSelectedElement() {@@ -1917,6 +1928,18 @@if (visEl) selectedElement = visEl;}+ function readVisibleVariantFromDOM(sessionId) {+ const wrapper = document.querySelector('[data-impeccable-variants="' + sessionId + '"]');+ if (!wrapper) return 0;+ const variants = wrapper.querySelectorAll('[data-impeccable-variant]:not([data-impeccable-variant="original"])');+ for (const variant of variants) {+ if (variant.style.display === 'none') continue;+ const idx = parseInt(variant.dataset.impeccableVariant || '0', 10);+ if (idx > 0) return idx;+ }+ return 0;+ }+// Resolve the element that represents the variant's visible content.// Contract: each variant div should contain exactly one top-level element// (the full replacement). In practice a model may ship loose siblings or@@ -2107,8 +2130,10 @@updating = true;arrivedVariants = count;if (visibleVariant === 0 && arrivedVariants > 0) {- visibleVariant = 1;- showVariantInDOM(sessionId, 1);+ const saved = loadSession();+ const savedVisibleVariant = saved && saved.id === sessionId ? saved.visible : 0;+ visibleVariant = savedVisibleVariant > 0 && savedVisibleVariant <= arrivedVariants ? savedVisibleVariant : 1;+ showVariantInDOM(sessionId, visibleVariant);// showVariantInDOM hid the original (display:none); if we were still// anchored to the original's content, its boundingRect is now zero// and the bar snaps to (0,0). Re-point at the visible variant instead.@@ -2128,6 +2153,7 @@updateBarContent('generating');}saveSession();+ queueCheckpoint(state === 'CYCLING' ? 'variants_ready' : 'variants_progress');updating = false;});@@ -2236,6 +2262,7 @@/** Server died or became unreachable. Reset UI to a clean state. */function handleServerLost() {+ const recoveryState = currentSessionId ? state : 'IDLE';if (state === 'GENERATING' || state === 'CYCLING' || state === 'SAVING') {showToast('Live server disconnected. Session ended.', 5000);}@@ -2246,21 +2273,61 @@stopScrollTracking();if (variantObserver) { variantObserver.disconnect(); variantObserver = null; }stopScrollLock();- clearScrollY();- clearSession();+ // Preserve local session state on server loss. The durable journal is the+ // source of truth, but localStorage plus the variant wrapper lets the UI+ // resume after a helper restart or page reload instead of treating a+ // transient disconnect as an explicit discard.selectedElement = null;- currentSessionId = null;selectedAction = 'impeccable';- state = 'IDLE';+ state = recoveryState;+ if (currentSessionId) saveSession();}- function sendEvent(msg) {+ function sendEvent(msg, opts) {msg.token = TOKEN;- fetch('http://localhost:' + PORT + '/events', {+ function handleFailure(err) {+ console.error('[impeccable] Failed to send event:', err);+ if (opts && opts.throwOnError) throw err;+ return null;+ }+ return fetch('http://localhost:' + PORT + '/events', {method: 'POST',headers: { 'Content-Type': 'application/json' },body: JSON.stringify(msg),- }).catch(err => console.error('[impeccable] Failed to send event:', err));+ }).then(res => {+ if (res.ok) return res;+ return handleFailure(new Error('HTTP ' + res.status + ' ' + res.statusText));+ }).catch(handleFailure);+ }++ function checkpointPayload(reason) {+ return {+ type: 'checkpoint',+ id: currentSessionId,+ revision: sessionState.nextCheckpointRevision(),+ owner: browserOwner,+ phase: String(state || '').toLowerCase(),+ reason,+ pageUrl: location.pathname,+ expectedVariants,+ arrivedVariants,+ visibleVariant,+ paramValues: { ...paramsCurrentValues },+ };+ }++ function sendCheckpoint(reason) {+ if (!currentSessionId) return Promise.resolve(null);+ return sendEvent(checkpointPayload(reason)).catch(() => null);+ }++ function queueCheckpoint(reason) {+ if (!currentSessionId) return;+ if (checkpointTimer) clearTimeout(checkpointTimer);+ checkpointTimer = setTimeout(() => {+ checkpointTimer = null;+ sendCheckpoint(reason);+ }, 120);}// ---------------------------------------------------------------------------@@ -2496,6 +2563,7 @@state = 'GENERATING';showBar('generating');saveSession();+ sendCheckpoint('generate_started');writeScrollY(window.scrollY);if (variantObserver) variantObserver.disconnect();variantObserver = startVariantObserver(currentSessionId);@@ -2920,13 +2988,12 @@ void main() {function handleAccept() {if (!currentSessionId || arrivedVariants === 0) return;+ const domVisibleVariant = readVisibleVariantFromDOM(currentSessionId);+ if (domVisibleVariant > 0) visibleVariant = domVisibleVariant;const acceptPayload = { type: 'accept', id: currentSessionId, variantId: String(visibleVariant) };if (Object.keys(paramsCurrentValues).length > 0) {acceptPayload.paramValues = { ...paramsCurrentValues };}- sendEvent(acceptPayload);- markSessionHandled();-// The accepted variant is already the only visible child of the wrapper// (all other variants are display:none). HMR from the source rewrite will// replace the wrapper imminently. Don't eagerly replaceChild here — React@@ -2936,9 +3003,28 @@ void main() {const acceptedSessionId = currentSessionId;const acceptedVariant = visibleVariant;- state = 'CONFIRMED';- updateBarContent('confirmed');- setTimeout(function() {+ state = 'SAVING';+ updateBarContent('saving');++ sendEvent(acceptPayload, { throwOnError: true })+ .then(() => {+ markSessionHandled();+ confirmAcceptAfterReceipt();+ })+ .catch(() => {+ state = 'CYCLING';+ updateBarContent('cycling');+ showToast('Could not confirm accept with the live server. Session kept for recovery; try Accept again.', 5000);+ });++ function confirmAcceptAfterReceipt() {+ state = 'CONFIRMED';+ updateBarContent('confirmed');+ scheduleAcceptCleanup();+ }++ function scheduleAcceptCleanup() {+ setTimeout(function() {hideBar();hideHighlight();stopScrollTracking();@@ -2967,50 +3053,46 @@ void main() {accepted.style.display = 'contents';parent.replaceChild(accepted, wrapper);}- }, 2000);+ }, 2000);+ }}function handleDiscard() {if (!currentSessionId) return;- sendEvent({ type: 'discard', id: currentSessionId });- markSessionHandled();- // Instant DOM restore + fire-and-forget (script handles file cleanup)- cleanup();+ sendEvent({ type: 'discard', id: currentSessionId }, { throwOnError: true })+ .then(() => {+ markSessionHandled();+ cleanup();+ })+ .catch(() => showToast('Could not confirm discard with the live server. Session kept for recovery.', 5000));}// ---------------------------------------------------------------------------- // Session persistence via localStorage+ // Session persistence via live-browser-session.js// ---------------------------------------------------------------------------// Survives page reloads, browser close/reopen, HMR, and accidental refreshes.- const LS_KEY = PREFIX + '-session';-function saveSession() {if (!currentSessionId) return;// NOTE: scrollY is stored under a separate key (writeScrollY). Storing// it here would overwrite the Go-time value every time state changes.- try {- localStorage.setItem(LS_KEY, JSON.stringify({- id: currentSessionId,- state: state,- action: selectedAction,- count: selectedCount,- expected: expectedVariants,- arrived: arrivedVariants,- visible: visibleVariant,- }));- } catch { /* quota exceeded or private mode */ }+ sessionState.saveSession({+ id: currentSessionId,+ state,+ action: selectedAction,+ count: selectedCount,+ expected: expectedVariants,+ arrived: arrivedVariants,+ visible: visibleVariant,+ });}function loadSession() {- try {- const raw = localStorage.getItem(LS_KEY);- return raw ? JSON.parse(raw) : null;- } catch { return null; }+ return sessionState.loadSession();}function clearSession() {- try { localStorage.removeItem(LS_KEY); } catch {}+ sessionState.clearSession();}/** Mark session as handled (accepted/discarded). The agent will clean up@@ -3018,19 +3100,15 @@ void main() {* prevents resumeSession from picking it up again after reload. */function markSessionHandled() {if (!currentSessionId) return;- try {- localStorage.setItem(LS_KEY + '-handled', currentSessionId);- } catch {}+ sessionState.markHandled(currentSessionId);}function isSessionHandled(id) {- try {- return localStorage.getItem(LS_KEY + '-handled') === id;- } catch { return false; }+ return sessionState.isHandled(id);}function clearHandled() {- try { localStorage.removeItem(LS_KEY + '-handled'); } catch {}+ sessionState.clearHandled();}function cleanup() {@@ -3161,6 +3239,7 @@ void main() {// hid. Now that state is CYCLING, re-fire.if (state === 'CYCLING') refreshParamsPanel();saveSession();+ queueCheckpoint('browser_resumed');// Start observing for more variants AFTER initial setupif (variantObserver) variantObserver.disconnect();@@ -3617,7 +3696,7 @@ void main() {}// ---------------------------------------------------------------------------- // Design System Panel — visualizes the project's DESIGN.json sidecar+ // Design System Panel — visualizes the project's .impeccable/design.json sidecar// ---------------------------------------------------------------------------const DESIGN_PREFS_KEY = 'impeccable-live-design-panel';@@ -3629,7 +3708,7 @@ void main() {open: false,tab: 'visual', // 'visual' | 'raw'parsed: null, // parseDesignMd output (frontmatter + body sections)- sidecar: null, // DESIGN.json v2 payload (extensions + components + narrative)+ sidecar: null, // .impeccable/design.json v2 payload (extensions + components + narrative)hasMd: false,hasSidecar: false,present: null, // true/false once fetch resolves@@ -4130,7 +4209,7 @@ void main() {box.className = 'stale';box.innerHTML = `<span class="stale-dot"></span>- <span class="stale-text"><strong>DESIGN.md is newer than DESIGN.json.</strong> Run <code>/impeccable document</code> to refresh the sidecar.</span>+ <span class="stale-text"><strong>DESIGN.md is newer than .impeccable/design.json.</strong> Run <code>/impeccable document</code> to refresh the sidecar.</span>`;return box;}@@ -4138,7 +4217,7 @@ void main() {function renderParsedMdCta() {const box = document.createElement('div');box.className = 'parsed-md-cta';- box.innerHTML = `<strong>Basic view</strong>This panel reads the tokens in your <code>DESIGN.md</code> frontmatter. Running <code>/impeccable document</code> also generates a <code>DESIGN.json</code> sidecar with your project's actual component snippets (button, input, nav) and tonal ramps, rendered live below the tokens.`;+ box.innerHTML = `<strong>Basic view</strong>This panel reads the tokens in your <code>DESIGN.md</code> frontmatter. Running <code>/impeccable document</code> also generates a <code>.impeccable/design.json</code> sidecar with your project's actual component snippets (button, input, nav) and tonal ramps, rendered live below the tokens.`;return box;}@@ -4598,7 +4677,7 @@ void main() {function cssSafe(v) {// Strip anything outside valid CSS value chars to prevent injection via- // DESIGN.json values rendered into inline style strings.+ // .impeccable/design.json values rendered into inline style strings.return String(v).replace(/[<>"'`\n]/g, '');}diff --git a/plugin/skills/impeccable/scripts/live-complete.mjs b/plugin/skills/impeccable/scripts/live-complete.mjsnew file mode 100644index 000000000..78155af85--- /dev/null+++ b/plugin/skills/impeccable/scripts/live-complete.mjs@@ -0,0 +1,75 @@+#!/usr/bin/env node+/**+ * Canonical durable completion acknowledgement for Impeccable live sessions.+ */++import { createLiveSessionStore } from './live-session-store.mjs';+import { readLiveServerInfo } from './impeccable-paths.mjs';++function parseArgs(argv) {+ const out = { status: 'complete' };+ for (let i = 0; i < argv.length; i++) {+ const arg = argv[i];+ if (arg === '--id') out.id = argv[++i];+ else if (arg.startsWith('--id=')) out.id = arg.slice('--id='.length);+ else if (arg === '--discarded' || arg === '--discard') out.status = 'discarded';+ else if (arg === '--error') { out.status = 'agent_error'; out.message = argv[++i] || 'unknown error'; }+ else if (arg.startsWith('--error=')) { out.status = 'agent_error'; out.message = arg.slice('--error='.length); }+ else if (arg === '--help' || arg === '-h') out.help = true;+ }+ return out;+}++export async function completeCli() {+ const args = parseArgs(process.argv.slice(2));+ if (args.help || !args.id) {+ console.log(`Usage: node live-complete.mjs --id SESSION_ID [--discarded|--error MESSAGE]\n\nAppend the final durable session acknowledgement. Use after accept/discard cleanup is verified.`);+ process.exit(args.help ? 0 : 1);+ }++ const serverInfo = readServerInfo();+ const serverResult = serverInfo ? await completeThroughServer(serverInfo, args) : null;+ if (serverResult?.ok) {+ const store = createLiveSessionStore({ cwd: process.cwd(), sessionId: args.id });+ const snapshot = store.getSnapshot(args.id, { includeCompleted: true });+ console.log(JSON.stringify({ ok: true, id: args.id, phase: snapshot?.phase || args.status, snapshot }, null, 2));+ return;+ }++ const store = createLiveSessionStore({ cwd: process.cwd(), sessionId: args.id });+ const event = args.status === 'discarded'+ ? { type: 'discarded', id: args.id }+ : args.status === 'agent_error'+ ? { type: 'agent_error', id: args.id, message: args.message || 'unknown error' }+ : { type: 'complete', id: args.id };+ const snapshot = store.appendEvent(event);+ console.log(JSON.stringify({ ok: true, id: args.id, phase: snapshot.phase, snapshot }, null, 2));+}++function readServerInfo() {+ return readLiveServerInfo(process.cwd())?.info || null;+}++async function completeThroughServer(info, args) {+ const type = args.status === 'discarded'+ ? 'discarded'+ : args.status === 'agent_error'+ ? 'error'+ : 'complete';+ try {+ const res = await fetch(`http://localhost:${info.port}/poll`, {+ method: 'POST',+ headers: { 'Content-Type': 'application/json' },+ body: JSON.stringify({ token: info.token, id: args.id, type, message: args.message }),+ });+ if (!res.ok) return null;+ return await res.json();+ } catch {+ return null;+ }+}++const _running = process.argv[1];+if (_running?.endsWith('live-complete.mjs') || _running?.endsWith('live-complete.mjs/')) {+ completeCli();+}diff --git a/plugin/skills/impeccable/scripts/live-completion.mjs b/plugin/skills/impeccable/scripts/live-completion.mjsnew file mode 100644index 000000000..86b637fff--- /dev/null+++ b/plugin/skills/impeccable/scripts/live-completion.mjs@@ -0,0 +1,18 @@+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';+ return 'agent_done';+}++export function completionAckForAcceptResult(eventId, completionType, acceptResult) {+ const ack = { ok: true, type: completionType };+ if (acceptResult?.handled === true && acceptResult?.carbonize === true) {+ ack.final = false;+ ack.requiresComplete = true;+ ack.nextCommand = `live-complete.mjs --id ${eventId}`;+ ack.message = 'Carbonize cleanup must be verified, then the session must be completed explicitly before polling again.';+ }+ return ack;+}diff --git a/plugin/skills/impeccable/scripts/live-inject.mjs b/plugin/skills/impeccable/scripts/live-inject.mjsindex 1d2ae12f7..555c3a36a 100644--- a/plugin/skills/impeccable/scripts/live-inject.mjs+++ b/plugin/skills/impeccable/scripts/live-inject.mjs@@ -2,23 +2,24 @@* CLI helper: insert/remove the live variant mode script tag in the project's* main HTML entry point.*- * On first live run, the agent generates `config.json` in this script's- * directory with the project's insertion target (framework-specific). On+ * On first live run, the agent generates `.impeccable/live/config.json`+ * with the project's insertion target (framework-specific). On* every subsequent run, this script handles insert/remove deterministically* with zero LLM involvement.** Usage:* node live-inject.mjs --port PORT # Insert the live script tag* node live-inject.mjs --remove # Remove the live script tag- * node live-inject.mjs --check # Check whether config.json exists+ * node live-inject.mjs --check # Check whether live config exists*/import fs from 'node:fs';import path from 'node:path';import { fileURLToPath } from 'node:url';+import { resolveLiveConfigPath } from './impeccable-paths.mjs';const __dirname = path.dirname(fileURLToPath(import.meta.url));-const CONFIG_PATH = process.env.IMPECCABLE_LIVE_CONFIG || path.join(__dirname, 'config.json');+const CONFIG_PATH = resolveLiveConfigPath({ cwd: process.cwd(), scriptsDir: __dirname });const MARKER_OPEN_TEXT = 'impeccable-live-start';const MARKER_CLOSE_TEXT = 'impeccable-live-end';@@ -39,12 +40,12 @@ export async function injectCli() {console.log(`Usage: node live-inject.mjs [options]Insert or remove the live mode script tag in the project's HTML entry point.-Reads configuration from config.json (in this same directory).+Reads configuration from .impeccable/live/config.json.Modes:--port PORT Insert script tag pointing at http://localhost:PORT/live.js--remove Remove the script tag (if present)- --check Print whether config.json exists and its content+ --check Print whether .impeccable/live/config.json exists and its contentOutput (JSON):{ ok, file, inserted|removed, config? }`);diff --git a/plugin/skills/impeccable/scripts/live-poll.mjs b/plugin/skills/impeccable/scripts/live-poll.mjsindex eb8f1586a..10d452491 100644--- a/plugin/skills/impeccable/scripts/live-poll.mjs+++ b/plugin/skills/impeccable/scripts/live-poll.mjs@@ -9,10 +9,10 @@*/import { execFileSync } from 'node:child_process';-import fs from 'node:fs';import path from 'node:path';-import os from 'node:os';import { fileURLToPath } from 'node:url';+import { completionAckForAcceptResult, completionTypeForAcceptResult } from './live-completion.mjs';+import { readLiveServerInfo } from './impeccable-paths.mjs';// Node's built-in fetch (undici under the hood) enforces a 300s headers// timeout that can't be lowered per-request. We cap each request below@@ -20,15 +20,29 @@ import { fileURLToPath } from 'node:url';// depending on the standalone undici package.const PER_REQUEST_TIMEOUT_MS = 270_000;-const LIVE_PID_FILE = path.join(process.cwd(), '.impeccable-live.json');-function readServerInfo() {- try {- return JSON.parse(fs.readFileSync(LIVE_PID_FILE, 'utf-8'));- } catch {+ const record = readLiveServerInfo(process.cwd());+ if (!record) {console.error('No running live server found. Start one with: npx impeccable live');process.exit(1);}+ return record.info;+}++export function buildPollReplyPayload(token, { id, type, message, file, data }) {+ return { token, id, type, message, file, data };+}++async function postReply(base, token, reply) {+ const res = await fetch(`${base}/poll`, {+ method: 'POST',+ headers: { 'Content-Type': 'application/json' },+ body: JSON.stringify(buildPollReplyPayload(token, reply)),+ });+ if (!res.ok) {+ const body = await res.json().catch(() => ({}));+ throw new Error(body.error || res.statusText);+ }}export async function pollCli() {@@ -69,23 +83,7 @@ Options:}try {- const res = await fetch(`${base}/poll`, {- method: 'POST',- headers: { 'Content-Type': 'application/json' },- body: JSON.stringify({- token: info.token,- id,- type: status,- message,- file: filePath,- }),- });-- if (!res.ok) {- const body = await res.json().catch(() => ({}));- console.error(`Reply failed (${res.status}):`, body.error || res.statusText);- process.exit(1);- }+ await postReply(base, info.token, { id, type: status, message, file: filePath });// Success — silent exit (agent doesn't need output for replies)} catch (err) {@@ -156,7 +154,23 @@ Options:);event._acceptResult = JSON.parse(out.trim());} catch (err) {- event._acceptResult = { handled: false, error: err.message };+ event._acceptResult = { handled: false, mode: 'error', error: err.message };+ }++ const completionType = completionTypeForAcceptResult(event.type, event._acceptResult);+ try {+ await postReply(base, info.token, {+ id: event.id,+ type: completionType,+ message: event._acceptResult?.error,+ file: event._acceptResult?.file,+ data: event._acceptResult?.carbonize === true ? { carbonize: true } : undefined,+ });+ } catch (err) {+ event._completionAck = { ok: false, error: err.message };+ }+ if (!event._completionAck) {+ event._completionAck = completionAckForAcceptResult(event.id, completionType, event._acceptResult);}}@@ -164,7 +178,7 @@ Options:// JSON but skips nested fields. One line is enough — the full checklist// is in reference/live.md.if (event._acceptResult?.carbonize === true) {- process.stderr.write('\n⚠ Carbonize cleanup REQUIRED before next poll. See reference/live.md "Required after accept".\n\n');+ process.stderr.write('\n⚠ Carbonize cleanup REQUIRED before next poll. After cleanup, run live-complete.mjs --id ' + event.id + '. See reference/live.md "Required after accept".\n\n');}// Print the event as JSON — the agent reads this from stdoutdiff --git a/plugin/skills/impeccable/scripts/live-resume.mjs b/plugin/skills/impeccable/scripts/live-resume.mjsnew file mode 100644index 000000000..a3465c9b5--- /dev/null+++ b/plugin/skills/impeccable/scripts/live-resume.mjs@@ -0,0 +1,48 @@+#!/usr/bin/env node+/**+ * Recover the next agent action from the durable live-session journal.+ */++import { createLiveSessionStore } from './live-session-store.mjs';++function parseArgs(argv) {+ const out = { id: null };+ for (let i = 0; i < argv.length; i++) {+ const arg = argv[i];+ if (arg === '--id') out.id = argv[++i];+ else if (arg.startsWith('--id=')) out.id = arg.slice('--id='.length);+ else if (arg === '--help' || arg === '-h') out.help = true;+ }+ return out;+}++export async function resumeCli() {+ const args = parseArgs(process.argv.slice(2));+ if (args.help) {+ console.log(`Usage: node live-resume.mjs [--id SESSION_ID]\n\nPrint the active durable session checkpoint and the next safe agent action.`);+ return;+ }++ const store = createLiveSessionStore({ cwd: process.cwd(), sessionId: args.id || undefined });+ const snapshot = args.id ? store.getSnapshot(args.id) : store.listActiveSessions()[0] || null;+ if (!snapshot) {+ console.log(JSON.stringify({ active: false, nextAction: 'No active durable live session found.' }, null, 2));+ return;+ }++ const pending = snapshot.pendingEvent || null;+ const nextAction = pending+ ? `Run live-poll.mjs, handle ${pending.type} ${pending.id}, then acknowledge with live-poll.mjs --reply ${pending.id} done.`+ : snapshot.phase === 'carbonize_required'+ ? `Finish carbonize cleanup${snapshot.sourceFile ? ` in ${snapshot.sourceFile}` : ''}, then run live-complete.mjs --id ${snapshot.id}.`+ : snapshot.phase === 'accept_requested'+ ? `Run live-complete.mjs --id ${snapshot.id} after verifying the accepted variant is written.`+ : `Inspect ${snapshot.id}; no pending agent event is currently queued.`;++ console.log(JSON.stringify({ active: true, snapshot, pendingEvent: pending, nextAction }, null, 2));+}++const _running = process.argv[1];+if (_running?.endsWith('live-resume.mjs') || _running?.endsWith('live-resume.mjs/')) {+ resumeCli();+}diff --git a/plugin/skills/impeccable/scripts/live-server.mjs b/plugin/skills/impeccable/scripts/live-server.mjsindex 90614fbf7..53d8f21cb 100644--- a/plugin/skills/impeccable/scripts/live-server.mjs+++ b/plugin/skills/impeccable/scripts/live-server.mjs@@ -22,14 +22,20 @@ import net from 'node:net';import { fileURLToPath } from 'node:url';import { parseDesignMd } from './design-parser.mjs';import { resolveContextDir } from './load-context.mjs';+import { createLiveSessionStore } from './live-session-store.mjs';+import {+ getDesignSidecarPath,+ getLiveAnnotationsDir,+ readLiveServerInfo,+ removeLiveServerInfo,+ resolveDesignSidecarPath,+ writeLiveServerInfo,+} from './impeccable-paths.mjs';const __dirname = path.dirname(fileURLToPath(import.meta.url));-// PID file in the project root so both the server and agent can find it-// predictably (os.tmpdir() varies across platforms).-const LIVE_PID_FILE = path.join(process.cwd(), '.impeccable-live.json');-// PRODUCT.md / DESIGN.md / DESIGN.json live wherever load-context.mjs resolves.-// Keeps live-server in sync with the loader when users keep the docs in-// .agents/context/, docs/, or a path set via IMPECCABLE_CONTEXT_DIR.+// PRODUCT.md / DESIGN.md live wherever load-context.mjs resolves. The generated+// DESIGN sidecar is project-local at .impeccable/design.json, with legacy+// DESIGN.json fallback for existing projects.const CONTEXT_DIR = resolveContextDir(process.cwd());const DEFAULT_POLL_TIMEOUT = 600_000; // 10 min — agent re-polls on timeout anywayconst SSE_HEARTBEAT_INTERVAL = 30_000; // keepalive ping every 30s@@ -57,10 +63,12 @@ const state = {token: null,port: null,sseClients: new Set(), // SSE response objects (server→browser push)- pendingEvents: [], // browser events waiting for agent poll+ pendingEvents: [], // browser events waiting for agent ack ({ event, leaseUntil })pendingPolls: [], // agent poll callbacks waiting for browser eventsexitTimer: null,sessionDir: null, // per-session tmp dir for annotation screenshots+ sessionStore: null,+ leaseTimer: null,};// Cap per-annotation upload size. A full 1920×1080 PNG is typically <1 MB;@@ -68,11 +76,70 @@ const state = {const MAX_ANNOTATION_BYTES = 10 * 1024 * 1024;function enqueueEvent(event) {- if (state.pendingPolls.length > 0) {- state.pendingPolls.shift()(event);- } else {- state.pendingEvents.push(event);+ if (!event || (event.id && state.pendingEvents.some((entry) => entry.event?.id === event.id && entry.event?.type === event.type))) return;+ state.pendingEvents.push({ event, leaseUntil: 0 });+ flushPendingPolls();+}++function restorePendingEventsFromStore() {+ if (!state.sessionStore) return;+ for (const snapshot of state.sessionStore.listActiveSessions()) {+ if (snapshot.pendingEvent) enqueueEvent(snapshot.pendingEvent);+ }+}++function findAvailablePendingEvent(now = Date.now()) {+ return state.pendingEvents.find((entry) => !entry.leaseUntil || entry.leaseUntil <= now);+}++function leaseEvent(entry, leaseMs) {+ if (!entry.event?.id) {+ const idx = state.pendingEvents.indexOf(entry);+ if (idx !== -1) state.pendingEvents.splice(idx, 1);+ return entry.event;}+ entry.leaseUntil = Date.now() + leaseMs;+ return entry.event;+}++function acknowledgePendingEvent(id) {+ if (!id) return false;+ const idx = state.pendingEvents.findIndex((entry) => entry.event?.id === id);+ if (idx === -1) return false;+ state.pendingEvents.splice(idx, 1);+ scheduleLeaseFlush();+ return true;+}++function scheduleLeaseFlush() {+ if (state.leaseTimer) {+ clearTimeout(state.leaseTimer);+ state.leaseTimer = null;+ }+ if (state.pendingPolls.length === 0) return;+ const now = Date.now();+ const nextLeaseUntil = state.pendingEvents+ .map((entry) => entry.leaseUntil || 0)+ .filter((leaseUntil) => leaseUntil > now)+ .sort((a, b) => a - b)[0];+ if (!nextLeaseUntil) return;+ state.leaseTimer = setTimeout(() => {+ state.leaseTimer = null;+ flushPendingPolls();+ }, Math.max(0, nextLeaseUntil - now));+}++function flushPendingPolls() {+ while (state.pendingPolls.length > 0) {+ const entry = findAvailablePendingEvent();+ if (!entry) {+ scheduleLeaseFlush();+ return;+ }+ const poll = state.pendingPolls.shift();+ poll.resolve(leaseEvent(entry, poll.leaseMs));+ }+ scheduleLeaseFlush();}/** Push a message to all connected SSE clients. */@@ -103,13 +170,16 @@ function loadBrowserScripts() {// live-browser.js: DO NOT cache. Return the path so the /live.js handler// can re-read on every request. Editing the browser script during iteration// should land on the next tab reload, not require a server restart.+ const sessionPath = path.join(__dirname, 'live-browser-session.js');const livePath = path.join(__dirname, 'live-browser.js');- if (!fs.existsSync(livePath)) {- process.stderr.write('Error: live-browser.js not found at ' + livePath + '\n');- process.exit(1);+ for (const p of [sessionPath, livePath]) {+ if (!fs.existsSync(p)) {+ process.stderr.write('Error: live browser script not found at ' + p + '\n');+ process.exit(1);+ }}- return { detectScript, livePath };+ return { detectScript, sessionPath, livePath };}function hasProjectContext() {@@ -170,6 +240,13 @@ function validateEvent(msg) {return null;case 'discard':return isValidId(msg.id) ? null : 'discard: missing or malformed id';+ case 'checkpoint':+ if (!isValidId(msg.id)) return 'checkpoint: missing or malformed id';+ if (!Number.isInteger(msg.revision) || msg.revision < 0) return 'checkpoint: revision must be a non-negative integer';+ if (msg.paramValues !== undefined && (typeof msg.paramValues !== 'object' || msg.paramValues === null || Array.isArray(msg.paramValues))) {+ return 'checkpoint: paramValues must be an object';+ }+ return null;case 'exit':return null;case 'prefetch':@@ -184,7 +261,7 @@ function validateEvent(msg) {// HTTP request handler// ----------------------------------------------------------------------------function createRequestHandler({ detectScript, livePath }) {+function createRequestHandler({ detectScript, sessionPath, livePath }) {return (req, res) => {const url = new URL(req.url, `http://localhost:${state.port}`);res.setHeader('Access-Control-Allow-Origin', '*');@@ -200,17 +277,20 @@ function createRequestHandler({ detectScript, livePath }) {// the next tab reload. No-store headers prevent browser caching across// sessions — during iteration, a cached old script silently breaks// every subsequent session.+ let sessionScript;let liveScript;try {+ sessionScript = fs.readFileSync(sessionPath, 'utf-8');liveScript = fs.readFileSync(livePath, 'utf-8');} catch (err) {res.writeHead(500, { 'Content-Type': 'text/plain' });- res.end('Error reading live-browser.js: ' + err.message);+ res.end('Error reading live browser scripts: ' + err.message);return;}const body =`window.__IMPECCABLE_TOKEN__ = '${state.token}';\n` +`window.__IMPECCABLE_PORT__ = ${state.port};\n` ++ sessionScript + '\n' +liveScript;res.writeHead(200, {'Content-Type': 'application/javascript',@@ -305,6 +385,26 @@ function createRequestHandler({ detectScript, livePath }) {}// --- Health ---+ if (p === '/status') {+ const token = url.searchParams.get('token');+ if (token !== state.token) { res.writeHead(401, { 'Content-Type': 'application/json' }); res.end(JSON.stringify({ error: 'Unauthorized' })); return; }+ const sessions = state.sessionStore ? state.sessionStore.listActiveSessions() : [];+ res.writeHead(200, { 'Content-Type': 'application/json' });+ res.end(JSON.stringify({+ status: 'ok',+ port: state.port,+ connectedClients: state.sseClients.size,+ pendingEvents: state.pendingEvents.map((entry) => ({+ id: entry.event?.id,+ type: entry.event?.type,+ leased: !!(entry.leaseUntil && entry.leaseUntil > Date.now()),+ leaseUntil: entry.leaseUntil || null,+ })),+ activeSessions: sessions,+ }));+ return;+ }+if (p === '/health') {res.writeHead(200, { 'Content-Type': 'application/json' });res.end(JSON.stringify({@@ -316,13 +416,13 @@ function createRequestHandler({ detectScript, livePath }) {}// --- Design system (unified v2 response) + raw ---- // /design-system.json returns both parsed DESIGN.md and DESIGN.json+ // /design-system.json returns both parsed DESIGN.md and .impeccable/design.json// sidecar when present. Panel merges them:// { present, parsed, sidecar, hasMd, hasSidecar,// mdNewerThanJson, parseError?, sidecarError? }// - parsed: output of parseDesignMd (frontmatter// + six canonical sections) when DESIGN.md exists.- // - sidecar: DESIGN.json contents when present.+ // - sidecar: .impeccable/design.json contents when present.// Expected shape: schemaVersion 2, carrying// extensions + components + narrative.// /design-system/raw returns DESIGN.md markdown verbatim@@ -331,7 +431,7 @@ function createRequestHandler({ detectScript, livePath }) {if (token !== state.token) { res.writeHead(401); res.end('Unauthorized'); return; }const mdPath = path.join(CONTEXT_DIR, 'DESIGN.md');- const jsonPath = path.join(CONTEXT_DIR, 'DESIGN.json');+ const jsonPath = resolveDesignSidecarPath(process.cwd(), CONTEXT_DIR) || getDesignSidecarPath(process.cwd());const mdStat = statOrNull(mdPath);const jsonStat = statOrNull(jsonPath);@@ -367,7 +467,7 @@ function createRequestHandler({ detectScript, livePath }) {try {response.sidecar = JSON.parse(fs.readFileSync(jsonPath, 'utf-8'));} catch (err) {- response.sidecarError = 'Failed to parse DESIGN.json: ' + err.message;+ response.sidecarError = 'Failed to parse .impeccable/design.json: ' + err.message;}}@@ -449,7 +549,16 @@ function createRequestHandler({ detectScript, livePath }) {res.end(JSON.stringify({ error }));return;}- enqueueEvent(msg);+ if (state.sessionStore && msg.id) {+ try {+ state.sessionStore.appendEvent(msg);+ } catch (err) {+ res.writeHead(500, { 'Content-Type': 'application/json' });+ res.end(JSON.stringify({ error: 'session_store_append_failed', message: err.message }));+ return;+ }+ }+ if (msg.type !== 'checkpoint') enqueueEvent(msg);res.writeHead(200, { 'Content-Type': 'application/json' });res.end(JSON.stringify({ ok: true }));});@@ -492,13 +601,16 @@ function handlePollGet(req, res, url) {return;}const timeout = parseInt(url.searchParams.get('timeout') || DEFAULT_POLL_TIMEOUT, 10);- if (state.pendingEvents.length > 0) {+ const leaseMs = parseInt(url.searchParams.get('leaseMs') || '30000', 10);+ const available = findAvailablePendingEvent();+ if (available) {res.writeHead(200, { 'Content-Type': 'application/json' });- res.end(JSON.stringify(state.pendingEvents.shift()));+ res.end(JSON.stringify(leaseEvent(available, leaseMs)));return;}+ const poll = { resolve, leaseMs };const timer = setTimeout(() => {- const idx = state.pendingPolls.indexOf(resolve);+ const idx = state.pendingPolls.indexOf(poll);if (idx !== -1) state.pendingPolls.splice(idx, 1);res.writeHead(200, { 'Content-Type': 'application/json' });res.end(JSON.stringify({ type: 'timeout' }));@@ -508,10 +620,11 @@ function handlePollGet(req, res, url) {res.writeHead(200, { 'Content-Type': 'application/json' });res.end(JSON.stringify(event));}- state.pendingPolls.push(resolve);+ state.pendingPolls.push(poll);+ scheduleLeaseFlush();req.on('close', () => {clearTimeout(timer);- const idx = state.pendingPolls.indexOf(resolve);+ const idx = state.pendingPolls.indexOf(poll);if (idx !== -1) state.pendingPolls.splice(idx, 1);});}@@ -531,6 +644,26 @@ function handlePollPost(req, res) {res.end(JSON.stringify({ error: 'Unauthorized' }));return;}+ acknowledgePendingEvent(msg.id);+ if (state.sessionStore && msg.id) {+ try {+ const eventType = msg.type === 'discard' || msg.type === 'discarded'+ ? 'discarded'+ : msg.type === 'complete'+ ? 'complete'+ : msg.type === 'error'+ ? 'agent_error'+ : 'agent_done';+ state.sessionStore.appendEvent({+ type: eventType,+ id: msg.id,+ file: msg.file,+ message: msg.message,+ carbonize: msg.data?.carbonize === true,+ });+ } catch { /* keep reply path best-effort; browser still needs SSE */ }+ }+ flushPendingPolls();// Forward the reply to the browser via SSEbroadcast({ type: msg.type || 'done', id: msg.id, message: msg.message, file: msg.file, data: msg.data });res.writeHead(200, { 'Content-Type': 'application/json' });@@ -545,13 +678,15 @@ function handlePollPost(req, res) {let httpServer = null;function shutdown() {- try { fs.unlinkSync(LIVE_PID_FILE); } catch {}+ removeLiveServerInfo(process.cwd());+ if (state.leaseTimer) clearTimeout(state.leaseTimer);+ state.leaseTimer = null;if (state.sessionDir) {try { fs.rmSync(state.sessionDir, { recursive: true, force: true }); } catch {}}for (const res of state.sseClients) { try { res.end(); } catch {} }state.sseClients.clear();- for (const resolve of state.pendingPolls) resolve({ type: 'exit' });+ for (const poll of state.pendingPolls) poll.resolve({ type: 'exit' });state.pendingPolls.length = 0;if (httpServer) httpServer.close();process.exit(0);@@ -587,6 +722,7 @@ Endpoints:/events SSE stream (server→browser) + POST (browser→server)/poll Long-poll for agent CLI/source Raw source file reader (no-HMR fallback)+ /status Durable recovery status (token-protected)/health Health check`);process.exit(0);}@@ -594,7 +730,7 @@ Endpoints:if (args.includes('stop')) {const keepInject = args.includes('--keep-inject');try {- const info = JSON.parse(fs.readFileSync(LIVE_PID_FILE, 'utf-8'));+ const { info } = readLiveServerInfo(process.cwd()) || {};const res = await fetch(`http://localhost:${info.port}/stop?token=${info.token}`);if (res.ok) console.log(`Stopped live server on port ${info.port}.`);} catch {@@ -645,7 +781,7 @@ if (args.includes('--background')) {const deadline = Date.now() + 10_000;while (Date.now() < deadline) {try {- const info = JSON.parse(fs.readFileSync(LIVE_PID_FILE, 'utf-8'));+ const { info } = readLiveServerInfo(process.cwd()) || {};if (info.pid !== process.pid) {// Output JSON so the agent can read port + token from stdout.console.log(JSON.stringify(info));@@ -659,30 +795,36 @@ if (args.includes('--background')) {}// Check for existing session-try {- const existing = JSON.parse(fs.readFileSync(LIVE_PID_FILE, 'utf-8'));- try { process.kill(existing.pid, 0);+const existingRecord = readLiveServerInfo(process.cwd());+if (existingRecord?.info) {+ const existing = existingRecord.info;+ try {+ process.kill(existing.pid, 0);console.error(`Live server already running on port ${existing.port} (pid ${existing.pid}).`);console.error('Stop it first with: node ' + path.basename(fileURLToPath(import.meta.url)) + ' stop');process.exit(1);- } catch { fs.unlinkSync(LIVE_PID_FILE); }-} catch {}+ } catch {+ try { fs.unlinkSync(existingRecord.path); } catch {}+ }+}state.token = randomUUID();+state.sessionStore = createLiveSessionStore({ cwd: process.cwd() });+restorePendingEventsFromStore();const portArg = args.find(a => a.startsWith('--port='));state.port = portArg ? parseInt(portArg.split('=')[1], 10) : await findOpenPort();// Annotation screenshots live in the project root so the agent's Read tool// doesn't trip a per-file permission prompt. Sessioned by token so concurrent// projects (or quick restarts) don't collide.-const annotRoot = path.join(process.cwd(), '.impeccable-live', 'annotations');+const annotRoot = getLiveAnnotationsDir(process.cwd());fs.mkdirSync(annotRoot, { recursive: true });state.sessionDir = fs.mkdtempSync(path.join(annotRoot, 'session-'));-const { detectScript, livePath } = loadBrowserScripts();-httpServer = http.createServer(createRequestHandler({ detectScript, livePath }));+const { detectScript, sessionPath, livePath } = loadBrowserScripts();+httpServer = http.createServer(createRequestHandler({ detectScript, sessionPath, livePath }));httpServer.listen(state.port, '127.0.0.1', () => {- fs.writeFileSync(LIVE_PID_FILE, JSON.stringify({ pid: process.pid, port: state.port, token: state.token }));+ writeLiveServerInfo(process.cwd(), { pid: process.pid, port: state.port, token: state.token });const url = `http://localhost:${state.port}`;console.log(`\nImpeccable live server running on ${url}`);console.log(`Token: ${state.token}\n`);diff --git a/plugin/skills/impeccable/scripts/live-session-store.mjs b/plugin/skills/impeccable/scripts/live-session-store.mjsnew file mode 100644index 000000000..d55ed2d3a--- /dev/null+++ b/plugin/skills/impeccable/scripts/live-session-store.mjs@@ -0,0 +1,254 @@+import fs from 'node:fs';+import path from 'node:path';+import { getLegacyLiveSessionsDir, getLiveSessionsDir } from './impeccable-paths.mjs';++const COMPLETED_PHASES = new Set(['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;+ }++ function getReadableJournalPath(id) {+ const primary = getJournalPath(rootDir, id);+ if (fs.existsSync(primary)) return primary;+ const legacy = getJournalPath(legacyRootDir, id);+ if (fs.existsSync(legacy)) return legacy;+ return primary;+ }++ return {+ rootDir,+ legacyRootDir,+ appendEvent(event) {+ const normalized = normalizeEvent(event, sessionId);+ const journalPath = getJournalPath(rootDir, normalized.id);+ const snapshotPath = getSnapshotPath(rootDir, normalized.id);+ const legacyJournalPath = getJournalPath(legacyRootDir, normalized.id);+ if (!fs.existsSync(journalPath) && fs.existsSync(legacyJournalPath)) {+ fs.copyFileSync(legacyJournalPath, journalPath);+ }+ const prior = loadCachedOrRebuild(normalized.id);+ const seq = prior.nextSeq;+ const entry = {+ seq,+ id: normalized.id,+ type: normalized.type,+ ts: new Date().toISOString(),+ event: normalized,+ };+ 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;+ },+ getSnapshot(id = sessionId, opts = {}) {+ if (!id) throw new Error('session id required');+ 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;+ },+ listActiveSessions() {+ const ids = new Set();+ for (const dir of [legacyRootDir, rootDir]) {+ if (!fs.existsSync(dir)) continue;+ for (const name of fs.readdirSync(dir)) {+ if (name.endsWith('.jsonl')) ids.add(name.slice(0, -'.jsonl'.length));+ }+ }+ return [...ids]+ .sort()+ .map((id) => this.getSnapshot(id))+ .filter(Boolean);+ },+ };+}++function normalizeEvent(event, fallbackId) {+ if (!event || typeof event !== 'object') throw new Error('event object required');+ const id = event.id || fallbackId;+ if (!id || typeof id !== 'string') throw new Error('event id required');+ if (!event.type || typeof event.type !== 'string') throw new Error('event type required');+ return { ...event, id };+}++function getJournalPath(rootDir, id) {+ return path.join(rootDir, safeSessionId(id) + '.jsonl');+}++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,+ phase: 'new',+ pageUrl: null,+ sourceFile: null,+ expectedVariants: 0,+ arrivedVariants: 0,+ visibleVariant: null,+ paramValues: {},+ pendingEventSeq: null,+ pendingEvent: null,+ deliveryLease: null,+ checkpointRevision: 0,+ activeOwner: null,+ sourceMarkers: {},+ fallbackMode: null,+ annotationArtifacts: [],+ diagnostics: [],+ updatedAt: null,+ };+}++function rebuildSnapshotFromJournal(journalPath, id) {+ let snapshot = baseSnapshot(id);+ const diagnostics = [];+ let nextSeq = 1;+ if (!fs.existsSync(journalPath)) return { snapshot, diagnostics, nextSeq };++ const lines = fs.readFileSync(journalPath, 'utf-8').split('\n');+ for (let i = 0; i < lines.length; i++) {+ const line = lines[i];+ if (!line.trim()) continue;+ try {+ const entry = JSON.parse(line);+ if (!entry || typeof entry !== 'object') throw new Error('entry is not object');+ if (Number.isInteger(entry.seq)) nextSeq = Math.max(nextSeq, entry.seq + 1);+ snapshot = applyEvent(snapshot, entry);+ } catch (err) {+ diagnostics.push({+ error: 'journal_parse_failed',+ line: i + 1,+ message: err.message,+ });+ }+ }+ snapshot.diagnostics = [...snapshot.diagnostics, ...diagnostics];+ return { snapshot, diagnostics, nextSeq };+}++function applyEvent(snapshot, entry, inheritedDiagnostics = []) {+ const event = entry.event || entry;+ const next = {+ ...snapshot,+ paramValues: { ...(snapshot.paramValues || {}) },+ sourceMarkers: { ...(snapshot.sourceMarkers || {}) },+ annotationArtifacts: [...(snapshot.annotationArtifacts || [])],+ diagnostics: [...(snapshot.diagnostics || [])],+ updatedAt: entry.ts || new Date().toISOString(),+ };++ if (inheritedDiagnostics.length && next.diagnostics.length === 0) {+ next.diagnostics = [...inheritedDiagnostics];+ }++ switch (event.type) {+ case 'generate':+ next.phase = 'generate_requested';+ next.pageUrl = event.pageUrl ?? next.pageUrl;+ next.expectedVariants = event.count ?? next.expectedVariants;+ next.pendingEventSeq = entry.seq ?? next.pendingEventSeq;+ next.pendingEvent = toPendingEvent(event);+ if (event.screenshotPath) upsertArtifact(next.annotationArtifacts, { type: 'screenshot', path: event.screenshotPath });+ break;+ case 'variants_ready':+ case 'agent_done':+ next.phase = event.carbonize === true ? 'carbonize_required' : 'variants_ready';+ next.sourceFile = event.file ?? next.sourceFile;+ next.arrivedVariants = event.arrivedVariants ?? (next.arrivedVariants ?? next.expectedVariants);+ next.pendingEventSeq = null;+ next.pendingEvent = null;+ if (event.carbonize === true) {+ next.diagnostics.push({+ error: 'carbonize_cleanup_required',+ file: event.file || null,+ message: 'Accepted variant still has carbonize markers that must be folded into source CSS.',+ });+ }+ break;+ case 'checkpoint':+ 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;+ if (event.paramValues) next.paramValues = { ...event.paramValues };+ } else {+ next.diagnostics.push({ error: 'stale_checkpoint_ignored', revision: event.revision });+ }+ break;+ case 'accept':+ case 'accept_intent':+ next.phase = 'accept_requested';+ next.visibleVariant = Number(event.variantId ?? next.visibleVariant);+ if (event.paramValues) next.paramValues = { ...event.paramValues };+ next.pendingEventSeq = entry.seq ?? next.pendingEventSeq;+ next.pendingEvent = toPendingEvent(event);+ break;+ case 'discard':+ next.phase = 'discard_requested';+ next.pendingEventSeq = entry.seq ?? next.pendingEventSeq;+ next.pendingEvent = toPendingEvent(event);+ break;+ case 'discarded':+ next.phase = 'discarded';+ next.pendingEventSeq = null;+ next.pendingEvent = null;+ break;+ case 'complete':+ next.phase = 'completed';+ next.pendingEventSeq = null;+ next.pendingEvent = null;+ break;+ case 'agent_error':+ next.phase = 'agent_error';+ next.pendingEventSeq = null;+ next.pendingEvent = null;+ next.diagnostics.push({ error: 'agent_error', message: event.message || 'unknown agent error' });+ break;+ default:+ next.diagnostics.push({ error: 'unknown_event_type', type: event.type });+ break;+ }+ return next;+}++function toPendingEvent(event) {+ const pending = { ...event };+ delete pending.token;+ return pending;+}++function upsertArtifact(artifacts, artifact) {+ if (!artifacts.some((existing) => existing.path === artifact.path && existing.type === artifact.type)) {+ artifacts.push(artifact);+ }+}++function writeSnapshot(snapshotPath, snapshot) {+ fs.writeFileSync(snapshotPath, JSON.stringify(snapshot, null, 2) + '\n');+}diff --git a/plugin/skills/impeccable/scripts/live-status.mjs b/plugin/skills/impeccable/scripts/live-status.mjsnew file mode 100644index 000000000..dce1fbca2--- /dev/null+++ b/plugin/skills/impeccable/scripts/live-status.mjs@@ -0,0 +1,47 @@+#!/usr/bin/env node+/**+ * Print durable recovery status for Impeccable live sessions.+ */++import { createLiveSessionStore } from './live-session-store.mjs';+import { readLiveServerInfo } from './impeccable-paths.mjs';++function readServerInfo() {+ return readLiveServerInfo(process.cwd())?.info || null;+}++async function fetchServerStatus(info) {+ if (!info) return null;+ try {+ const res = await fetch(`http://localhost:${info.port}/status?token=${info.token}`);+ if (!res.ok) return null;+ return await res.json();+ } catch {+ return null;+ }+}++export async function statusCli() {+ const info = readServerInfo();+ const server = await fetchServerStatus(info);+ const store = createLiveSessionStore({ cwd: process.cwd() });+ const activeSessions = store.listActiveSessions();+ const payload = {+ liveServer: server ? {+ status: server.status,+ port: server.port,+ connectedClients: server.connectedClients,+ pendingEvents: server.pendingEvents,+ } : null,+ activeSessions: server?.activeSessions || activeSessions,+ recoveryHint: 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.',+ };+ console.log(JSON.stringify(payload, null, 2));+}++const _running = process.argv[1];+if (_running?.endsWith('live-status.mjs') || _running?.endsWith('live-status.mjs/')) {+ statusCli();+}diff --git a/plugin/skills/impeccable/scripts/live-wrap.mjs b/plugin/skills/impeccable/scripts/live-wrap.mjsindex a5769a50a..d46328b9f 100644--- a/plugin/skills/impeccable/scripts/live-wrap.mjs+++ b/plugin/skills/impeccable/scripts/live-wrap.mjs@@ -185,6 +185,7 @@ The agent should insert variant HTML at insertLine.`);const { startLine, endLine } = match;const commentSyntax = detectCommentSyntax(targetFile);+ const styleMode = detectStyleMode(targetFile);const isJsx = commentSyntax.open === '{/*';const indent = lines[startLine].match(/^(\s*)/)[1];@@ -269,6 +270,10 @@ The agent should insert variant HTML at insertLine.`);endLine: startLine + wrapperLines.length + (originalLines.length - 1), // 1-indexedinsertLine: insertLine + 1, // 1-indexed: where variants gocommentSyntax: commentSyntax,+ styleMode: styleMode.mode,+ styleTag: styleMode.styleTag,+ cssSelectorPrefixExamples: buildCssSelectorPrefixExamples(styleMode.mode, count),+ cssAuthoring: buildCssAuthoring(styleMode, count),originalLineCount: originalLines.length,}));}@@ -335,6 +340,62 @@ function detectCommentSyntax(filePath) {return { open: '<!--', close: '-->' };}+function detectStyleMode(filePath) {+ const ext = path.extname(filePath).toLowerCase();+ if (ext === '.astro') {+ return {+ mode: 'astro-global-prefixed',+ styleTag: '<style is:inline data-impeccable-css="SESSION_ID">',+ };+ }+ return {+ mode: 'scoped',+ styleTag: '<style data-impeccable-css="SESSION_ID">',+ };+}++function buildCssSelectorPrefixExamples(styleMode, count) {+ if (styleMode !== 'astro-global-prefixed') return [];+ return Array.from({ length: count }, (_, i) => `[data-impeccable-variant="${i + 1}"]`);+}++function buildCssAuthoring(styleMode, count) {+ const variantNumbers = Array.from({ length: count }, (_, i) => i + 1);+ if (styleMode.mode === 'astro-global-prefixed') {+ return {+ mode: styleMode.mode,+ styleTag: styleMode.styleTag,+ strategy: 'global-prefixed',+ rulePattern: '[data-impeccable-variant="N"] > .variant-class { ... }',+ selectorExamples: variantNumbers.map((n) => `[data-impeccable-variant="${n}"] > .variant-class`),+ requirements: [+ 'Use the styleTag exactly; the is:inline attribute is required for this file.',+ 'Prefix every preview selector with the matching [data-impeccable-variant="N"] selector.',+ 'Keep selectors anchored to the generated variant wrapper; do not rely on component CSS scoping for preview rules.',+ ],+ forbidden: [+ 'Do not use @scope for this styleMode.',+ ],+ };+ }+ return {+ mode: styleMode.mode,+ styleTag: styleMode.styleTag,+ strategy: 'scope-rule',+ rulePattern: '@scope ([data-impeccable-variant="N"]) { :scope > .variant-class { ... } }',+ selectorExamples: variantNumbers.map((n) => `@scope ([data-impeccable-variant="${n}"]) { :scope > .variant-class { ... } }`),+ requirements: [+ 'Use @scope blocks keyed to each [data-impeccable-variant="N"] wrapper.',+ 'Inside each @scope block, make :scope rules step into the replacement element with a descendant combinator.',+ 'Use the styleTag exactly; do not add framework-specific style attributes unless this object says to.',+ ],+ forbidden: [+ 'Do not use global [data-impeccable-variant="N"] selector prefixes for this styleMode.',+ 'Do not add is:inline to the style tag for this styleMode.',+ ],+ };+}+/*** Search project files for the query string (class name, ID, etc.)* Returns the first matching file path, or null.diff --git a/plugin/skills/impeccable/scripts/live.mjs b/plugin/skills/impeccable/scripts/live.mjsindex befbdb8ed..cafb0eca9 100644--- a/plugin/skills/impeccable/scripts/live.mjs+++ b/plugin/skills/impeccable/scripts/live.mjs@@ -2,10 +2,10 @@* CLI entry point: prepare everything needed to enter the live variant poll loop.** Does (all in one command):- * 1. Check config.json (returns config_missing if first-ever run)+ * 1. Check .impeccable/live/config.json (returns config_missing if first-ever run)* 2. Start the live server in the background (or reuse a running one)* 3. Inject the browser script tag into the project's entry file- * 4. Read .impeccable.md for design context (if present)+ * 4. Read PRODUCT.md / DESIGN.md for project context* 5. Print a single JSON blob with everything the agent needs** After this, the agent's only remaining steps are:@@ -23,9 +23,9 @@ import path from 'node:path';import { fileURLToPath } from 'node:url';import { loadContext } from './load-context.mjs';import { resolveFiles } from './live-inject.mjs';+import { readLiveServerInfo } from './impeccable-paths.mjs';const __dirname = path.dirname(fileURLToPath(import.meta.url));-const PID_FILE = path.join(process.cwd(), '.impeccable-live.json');async function liveCli() {const args = process.argv.slice(2);@@ -34,10 +34,10 @@ async function liveCli() {console.log(`Usage: node live.mjsPrepare everything for live variant mode in a single command:- - Checks scripts/config.json (required, created once per project)+ - Checks .impeccable/live/config.json (required, created once per project)- Starts (or reuses) the live server in the background- Injects the browser script tag- - Reads .impeccable.md for design context+ - Reads PRODUCT.md / DESIGN.md for project contextOn success, prints a JSON blob with:{ ok, serverPort, serverToken, pageFile, hasContext, context }@@ -223,7 +223,7 @@ function safeParse(out) {function ensureServerRunning() {// Try to reuse an existing servertry {- const existing = JSON.parse(fs.readFileSync(PID_FILE, 'utf-8'));+ const existing = readLiveServerInfo(process.cwd())?.info;if (existing && existing.pid) {try {process.kill(existing.pid, 0); // throws if deaddiff --git a/plugin/skills/impeccable/scripts/load-context.mjs b/plugin/skills/impeccable/scripts/load-context.mjsindex dca23c1f8..dc340bf16 100644--- a/plugin/skills/impeccable/scripts/load-context.mjs+++ b/plugin/skills/impeccable/scripts/load-context.mjs@@ -39,7 +39,7 @@ const LEGACY_NAMES = ['.impeccable.md'];const FALLBACK_DIRS = ['.agents/context', 'docs'];/**- * Resolve the directory that holds PRODUCT.md / DESIGN.md / DESIGN.json for+ * Resolve the directory that holds PRODUCT.md / DESIGN.md for* this project. Exported so other scripts (e.g. live-server.mjs) can read the* design files from the same location the loader uses.*/diff --git a/scripts/build.js b/scripts/build.jsindex e78fdb991..89f09c8e8 100644--- a/scripts/build.js+++ b/scripts/build.js@@ -744,7 +744,7 @@ async function build() {const skillsDest = path.join(ROOT_DIR, configDir, 'skills');if (fs.existsSync(skillsSrc)) {- // Preserve per-project script artifacts (e.g. live-mode config.json)+ // Preserve legacy per-project script artifacts (e.g. live-mode config.json)// across the rm + recopy. The build intentionally doesn't ship them,// so without this the sync destroys local state on every rebuild.const stashed = stashPerProjectArtifacts(skillsDest);diff --git a/scripts/lib/utils.js b/scripts/lib/utils.jsindex 7f14a8c3e..515faed84 100644--- a/scripts/lib/utils.js+++ b/scripts/lib/utils.js@@ -5,9 +5,8 @@ import path from 'path';// belong to the consuming project, not the distributable skill. The build// excludes them from dist, and the harness-sync step preserves them across// the rm+recopy so local state isn't destroyed on every rebuild.-// - config.json: live-mode inject target list for the current project.-// Written by the agent at first /impeccable live; tied to the project's-// filesystem layout. Losing it resets the user's glob + exclusions.+// - config.json: legacy live-mode inject target list for existing projects.+// New installs write project config at .impeccable/live/config.json instead.export const PER_PROJECT_SCRIPT_ARTIFACTS = new Set(['config.json']);// Walk the harness-dir skill tree and return any per-project scriptdiff --git a/source/skills/impeccable/reference/document.md b/source/skills/impeccable/reference/document.mdindex f2bcdb202..abb0a6758 100644--- a/source/skills/impeccable/reference/document.md+++ b/source/skills/impeccable/reference/document.md@@ -237,11 +237,11 @@ Concrete, forceful guardrails. Lead each with "Do" or "Don't". Be specific: incl- **Don't** [...]```-### Step 4b: Write DESIGN.json sidecar (extensions only)+### Step 4b: Write .impeccable/design.json sidecar (extensions only)-The frontmatter owns token primitives (colors, typography, rounded, spacing, components). The sidecar at `DESIGN.json` carries **what Stitch's schema can't hold**: tonal ramps per color, shadow/elevation tokens, motion tokens, breakpoints, full component HTML/CSS snippets (the panel renders these into a shadow DOM), and narrative (north star, rules, do's/don'ts). It extends the frontmatter, it doesn't duplicate it.+The frontmatter owns token primitives (colors, typography, rounded, spacing, components). The sidecar at `.impeccable/design.json` carries **what Stitch's schema can't hold**: tonal ramps per color, shadow/elevation tokens, motion tokens, breakpoints, full component HTML/CSS snippets (the panel renders these into a shadow DOM), and narrative (north star, rules, do's/don'ts). It extends the frontmatter, it doesn't duplicate it.-Regenerate the sidecar whenever you regenerate DESIGN.md. If the user only asks to refresh the sidecar (e.g., from the live panel's stale-hint), preserve DESIGN.md and write only DESIGN.json.+Regenerate the sidecar whenever you regenerate root `DESIGN.md`. If the user only asks to refresh the sidecar (e.g., from the live panel's stale-hint), preserve `DESIGN.md` and write only `.impeccable/design.json`.#### Schema@@ -310,7 +310,7 @@ Aim for a tight set of **5-10 components** that best represent the visual system- **Signature components (include if distinctive):** hero CTA, featured card, filter pill, any custom pattern the user mentioned as important in PRODUCT.md.- **Skip the rest.** Utility components, form building blocks, wrapper layouts: not worth documenting unless visually distinctive.-If the project has **no component library yet** (bare landing page, new project), synthesize canonical primitives from the tokens using best-practice defaults consistent with the DESIGN.md's rules. Every DESIGN.json has *something* to render, even on day zero.+If the project has **no component library yet** (bare landing page, new project), synthesize canonical primitives from the tokens using best-practice defaults consistent with the DESIGN.md's rules. Every `.impeccable/design.json` has *something* to render, even on day zero.#### Tonal ramps@@ -331,7 +331,7 @@ Do not reword. The panel shows these as secondary collapsible context; the same### Step 5: Confirm, refine, and refresh session cache1. Show the user the full DESIGN.md you wrote. Briefly highlight the non-obvious creative choices (descriptive color names, atmosphere language, named rules).-2. Mention that `DESIGN.json` was also written alongside; the live panel will now render this project's actual button/input/nav primitives instead of generic approximations.+2. Mention that `.impeccable/design.json` was also written alongside; the live panel will now render this project's actual button/input/nav primitives instead of generic approximations.3. Offer to refine any section: "Want me to revise a section, add component patterns I missed, or adjust the atmosphere language?"4. **Refresh the session cache.** Run `node {{scripts_path}}/load-context.mjs` one final time so the newly-written DESIGN.md lands in conversation. Subsequent commands in this session will use the fresh version automatically without re-reading.@@ -392,7 +392,7 @@ Per-section guidance in seed mode:- **Components**: omit entirely; no components exist yet.- **Do's and Don'ts**: carry PRODUCT.md's anti-references directly plus the anti-reference named in Q5.-Seed mode writes a minimal frontmatter with `name` and `description` only; no colors, typography, rounded, spacing, or components yet. Real tokens land on the next Scan-mode run. Skip the `DESIGN.json` sidecar in seed mode for the same reason: nothing to render.+Seed mode writes a minimal frontmatter with `name` and `description` only; no colors, typography, rounded, spacing, or components yet. Real tokens land on the next Scan-mode run. Skip the `.impeccable/design.json` sidecar in seed mode for the same reason: nothing to render.### Step 4: Confirm and refresh session cachediff --git a/source/skills/impeccable/reference/live.md b/source/skills/impeccable/reference/live.mdindex c4b63b865..261345920 100644--- a/source/skills/impeccable/reference/live.md+++ b/source/skills/impeccable/reference/live.md@@ -12,8 +12,9 @@ Execute in order. No step skipped, no step reordered.2. Navigate to the URL that serves `pageFile` (infer from `package.json`, docs, terminal output, or an open tab). If you can't infer it confidently, tell the user once to open their dev/preview URL. Never use `serverPort` as that URL; it's the helper, not the app.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=`.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.-5. On `accept` / `discard`: the poll script already cleaned up; just poll again.-6. On `exit`: run the cleanup at the bottom.+5. 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. If interrupted, run `live-status.mjs` or `live-resume.mjs` before guessing. The durable journal replays unacknowledged work after helper restart.+7. 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.@@ -43,13 +44,31 @@ LOOP:Read JSON; dispatch on "type""generate" → Handle Generate; reply done; LOOP- "accept" → Handle Accept; LOOP+ "accept" → Handle Accept; complete carbonize cleanup if required; LOOP"discard" → Handle Discard; LOOP"prefetch" → Handle Prefetch; LOOP"timeout" → LOOP"exit" → break → Cleanup```+## Recovery commands++The live helper persists an append-only journal under `.impeccable/live/sessions/`. Browser checkpoints are advisory but durable; the journal is canonical. This is local durable recovery state, not project source.++Use these commands when the chat was interrupted, polling was missed, the helper restarted, or the browser reloaded:++```bash+node {{scripts_path}}/live-status.mjs+node {{scripts_path}}/live-resume.mjs --id SESSION_ID+node {{scripts_path}}/live-complete.mjs --id SESSION_ID+```++- `live-status.mjs` prints connected helper state, active durable sessions, and queued pending events. It works even when the helper is down by reading the journal directly.+- `live-resume.mjs` prints the active snapshot, pending event, checkpoint phase, visible variant, parameter values, and the next safe agent action.+- `live-complete.mjs` is the canonical manual final acknowledgement. Use it after carbonize/manual cleanup is verified and no further poll acknowledgement will happen automatically.++Server restart rule: start `live-server.mjs` again, then poll. Startup requeues unacknowledged pending events from the journal, so do not ask the user to click Go again unless `live-resume.mjs` says no active session exists.+## Handle `generate`Event: `{id, action, freeformPrompt?, count, pageUrl, element, screenshotPath?, comments?, strokes?}`.@@ -88,7 +107,14 @@ The helper searches ID first, then classes, then tag + class combo. If `event.paIf `--text` matches multiple candidates equally well, wrap exits with `{ error: "element_ambiguous", candidates: [...] }` and `fallback: "agent-driven"`: read the candidate line ranges, decide which one matches the picked element from page context, and write the wrapper manually per the fallback flow.-Output on success: `{ file, insertLine, commentSyntax }`.+Output on success: `{ file, insertLine, commentSyntax, styleMode, styleTag, cssSelectorPrefixExamples, cssAuthoring }`.++`styleMode` controls how preview CSS must be authored. Treat it as a detected capability mode, not a framework guess:++- `scoped`: use `@scope ([data-impeccable-variant="N"])` rules.+- `astro-global-prefixed`: use explicit `[data-impeccable-variant="N"]` selector prefixes and the exact `styleTag` returned by the tool.++Use `cssAuthoring` as the source of truth for the current file. It includes the exact `styleTag`, selector strategy, selector examples, requirements, and forbidden patterns. Do not apply a framework-specific exception unless the returned `styleMode` / `cssAuthoring.mode` says to.**Fallback errors.** Wrap only writes into files it judges to be source (tracked by git, not marked GENERATED, not listed in config's `generatedFiles`). If it can't land on a source file, it errors without writing; accepting a variant into a generated file is silent data loss. Three shapes:@@ -208,13 +234,14 @@ When the prompt and PRODUCT.md anti-references conflict (the prompt asks for X,Complete 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 scoped 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).+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).++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:```html<!-- Variants: insert below this line --><style data-impeccable-css="SESSION_ID">- @scope ([data-impeccable-variant="1"]) { ... }- @scope ([data-impeccable-variant="2"]) { ... }+ /* rules matching cssAuthoring.rulePattern */</style><div data-impeccable-variant="1"><!-- variant 1: full element replacement (single top-level element) -->@@ -229,11 +256,11 @@ Write CSS + all variants in ONE edit at the `insertLine` reported by `wrap`. Col**Each variant div contains exactly one top-level element: the full replacement for the original.** Use the same tag as the original (e.g. `<section>` if the user picked a `<section>`). Loose siblings (heading + paragraph + div as direct children of the variant div) break the outline tracking and the accept flow, which both assume one child.-The first variant has no `display: none` (visible by default). All others do. If variants use only inline styles and no scoped CSS, omit the `<style>` tag entirely. Use `@scope` for CSS isolation (Chrome 118+ / Firefox 128+ / Safari 17.4+).+The 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.-**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 rule starts `:scope > ...`.+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 > ...`.**JSX / TSX target files.** Wrap `<style>` content in a template literal so the CSS `{` / `}` aren't parsed as JSX expressions, and use `className=` / `style={{…}}` on every variant element. Keep `data-impeccable-*` attributes as-is; they're plain strings:@@ -369,10 +396,11 @@ Remove the wrapper you inserted in Step 2. Nothing else to do.## Handle `accept`-Event: `{id, variantId, _acceptResult}`. The poll script already ran `live-accept.mjs` to handle the file operation deterministically; the browser DOM is already updated.+Event: `{id, variantId, _acceptResult, _completionAck}`. The poll script already ran `live-accept.mjs` to handle the file operation deterministically, then acknowledged event delivery to the helper. The browser DOM is already updated.+- `_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 and a stderr banner both list the steps explicitly; neither is decorative.+- `_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: 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` without `mode`: manual cleanup: read file, find markers, edit.@@ -388,13 +416,13 @@ Do these five steps in the current thread, synchronously, before the next poll.4. **Unwrap the accepted content.** Delete the `<div data-impeccable-variant="N" style="display: contents">` that wraps it. Drop `data-impeccable-params` and any `data-p-*` attributes from it; 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.-Then poll again.+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.## Handle `discard`-Event: `{id, _acceptResult}`. The poll script already restored the original and removed all variant markers. Nothing to do. Poll again.+Event: `{id, _acceptResult, _completionAck}`. The poll script already restored the original, removed all variant markers, and acknowledged `discarded` durable completion. Nothing to do unless `_completionAck.ok !== true`; in that case run `live-complete.mjs --id EVENT_ID --discarded`, then poll again.## Handle `prefetch`@@ -424,7 +452,7 @@ When the poll returns `exit`, proceed to cleanup. If the poll is still running anode {{scripts_path}}/live-server.mjs stop```-Stops the HTTP server and runs `live-inject.mjs --remove` to strip `localhost:…/live.js` from the HTML entry. To stop the server but keep the inject tag (for a quick restart), use `stop --keep-inject`. `config.json` persists for future sessions.+Stops the HTTP server and runs `live-inject.mjs --remove` to strip `localhost:…/live.js` from the HTML entry. To stop the server but keep the inject tag (for a quick restart), use `stop --keep-inject`. `.impeccable/live/config.json` persists as project config for future sessions.Then:- Remove any leftover variant wrappers (search for `impeccable-variants-start` markers).@@ -432,7 +460,7 @@ Then:## First-time setup (config missing or invalid)-If `live.mjs` outputs `{ ok: false, error: "config_missing" | "config_invalid", path }`, write `config.json` at the reported path.+If `live.mjs` outputs `{ ok: false, error: "config_missing" | "config_invalid", path }`, write the live config at the reported path. By default this is `.impeccable/live/config.json`.Schema:@@ -512,7 +540,7 @@ node {{scripts_path}}/detect-csp.mjsOutput: `{ shape, signals }` where `shape` is one of `append-arrays`, `append-string`, `middleware`, `meta-tag`, or `null`. The shape is named by *patch mechanism*, so one template covers many frameworks.-- **`null`**: no CSP; skip to writing `config.json` with `cspChecked: true`.+- **`null`**: no CSP; skip to writing `.impeccable/live/config.json` with `cspChecked: true`.- **`append-arrays`**: CSP defined as structured directive arrays. Auto-patchable. See *append-arrays* below. Covers:- Monorepo helpers with `additionalScriptSrc` / `additionalConnectSrc` options (Next.js + shared config package)- SvelteKit `kit.csp.directives`@@ -589,6 +617,6 @@ Reference outputs:### Troubleshooting-If a user says "no" to the CSP patch at setup time and later complains that live doesn't work: their dev CSP blocks `http://localhost:8400`. Fix: delete `cspChecked` from `config.json` and re-run `live.mjs`: setup will ask again.+If a user says "no" to the CSP patch at setup time and later complains that live doesn't work: their dev CSP blocks `http://localhost:8400`. Fix: delete `cspChecked` from `.impeccable/live/config.json` and re-run `live.mjs`: setup will ask again.Then re-run `live.mjs`.diff --git a/source/skills/impeccable/reference/teach.md b/source/skills/impeccable/reference/teach.mdindex a422f9ecf..474fce7d6 100644--- a/source/skills/impeccable/reference/teach.md+++ b/source/skills/impeccable/reference/teach.md@@ -2,8 +2,8 @@Gathers design context for a project and writes two complementary files at the project root:-- **PRODUCT.md** (strategic): register, target users, product purpose, brand personality, anti-references, strategic design principles. Answers "who/what/why".-- **DESIGN.md** (visual): visual theme, color palette, typography, components, layout. Follows the [Google Stitch DESIGN.md format](https://stitch.withgoogle.com/docs/design-md/format/). Answers "how it looks".+- **PRODUCT.md** (strategic): root project file for register, target users, product purpose, brand personality, anti-references, strategic design principles. Answers "who/what/why".+- **DESIGN.md** (visual): root project file for visual theme, color palette, typography, components, layout. Follows the [Google Stitch DESIGN.md format](https://stitch.withgoogle.com/docs/design-md/format/). Answers "how it looks".Every other impeccable command reads these files before doing any work.diff --git a/source/skills/impeccable/scripts/impeccable-paths.mjs b/source/skills/impeccable/scripts/impeccable-paths.mjsnew file mode 100644index 000000000..ba852bae9--- /dev/null+++ b/source/skills/impeccable/scripts/impeccable-paths.mjs@@ -0,0 +1,105 @@+import fs from 'node:fs';+import path from 'node:path';++export const IMPECCABLE_DIR = '.impeccable';+export const LIVE_DIR = 'live';++export function getImpeccableDir(cwd = process.cwd()) {+ return path.join(cwd, IMPECCABLE_DIR);+}++export function getDesignSidecarPath(cwd = process.cwd()) {+ return path.join(getImpeccableDir(cwd), 'design.json');+}++export function getDesignSidecarCandidates(cwd = process.cwd(), contextDir = cwd) {+ const candidates = [+ getDesignSidecarPath(cwd),+ path.join(cwd, 'DESIGN.json'),+ ];+ const contextLegacy = path.join(contextDir, 'DESIGN.json');+ if (!candidates.includes(contextLegacy)) candidates.push(contextLegacy);+ return candidates;+}++export function resolveDesignSidecarPath(cwd = process.cwd(), contextDir = cwd) {+ return firstExisting(getDesignSidecarCandidates(cwd, contextDir));+}++export function getLiveDir(cwd = process.cwd()) {+ return path.join(getImpeccableDir(cwd), LIVE_DIR);+}++export function getLiveConfigPath(cwd = process.cwd()) {+ return path.join(getLiveDir(cwd), 'config.json');+}++export function getLegacyLiveConfigPath(scriptsDir) {+ return path.join(scriptsDir, 'config.json');+}++export function resolveLiveConfigPath({ cwd = process.cwd(), scriptsDir, env = process.env } = {}) {+ if (env.IMPECCABLE_LIVE_CONFIG && env.IMPECCABLE_LIVE_CONFIG.trim()) {+ const configured = env.IMPECCABLE_LIVE_CONFIG.trim();+ return path.isAbsolute(configured) ? configured : path.resolve(cwd, configured);+ }+ const primary = getLiveConfigPath(cwd);+ if (fs.existsSync(primary)) return primary;+ if (scriptsDir) {+ const legacy = getLegacyLiveConfigPath(scriptsDir);+ if (fs.existsSync(legacy)) return legacy;+ }+ return primary;+}++export function getLiveServerPath(cwd = process.cwd()) {+ return path.join(getLiveDir(cwd), 'server.json');+}++export function getLegacyLiveServerPath(cwd = process.cwd()) {+ return path.join(cwd, '.impeccable-live.json');+}++export function readLiveServerInfo(cwd = process.cwd()) {+ for (const filePath of [getLiveServerPath(cwd), getLegacyLiveServerPath(cwd)]) {+ try {+ return { info: JSON.parse(fs.readFileSync(filePath, 'utf-8')), path: filePath };+ } catch {+ /* try next */+ }+ }+ return null;+}++export function writeLiveServerInfo(cwd = process.cwd(), info) {+ const filePath = getLiveServerPath(cwd);+ fs.mkdirSync(path.dirname(filePath), { recursive: true });+ fs.writeFileSync(filePath, JSON.stringify(info));+ return filePath;+}++export function removeLiveServerInfo(cwd = process.cwd()) {+ for (const filePath of [getLiveServerPath(cwd), getLegacyLiveServerPath(cwd)]) {+ try { fs.unlinkSync(filePath); } catch {}+ }+}++export function getLiveSessionsDir(cwd = process.cwd()) {+ return path.join(getLiveDir(cwd), 'sessions');+}++export function getLegacyLiveSessionsDir(cwd = process.cwd()) {+ return path.join(cwd, '.impeccable-live', 'sessions');+}++export function getLiveAnnotationsDir(cwd = process.cwd()) {+ return path.join(getLiveDir(cwd), 'annotations');+}++export function getLegacyLiveAnnotationsDir(cwd = process.cwd()) {+ return path.join(cwd, '.impeccable-live', 'annotations');+}++function firstExisting(paths) {+ return paths.find((filePath) => fs.existsSync(filePath)) || null;+}diff --git a/source/skills/impeccable/scripts/live-browser-session.js b/source/skills/impeccable/scripts/live-browser-session.jsnew file mode 100644index 000000000..0e362d6be--- /dev/null+++ b/source/skills/impeccable/scripts/live-browser-session.js@@ -0,0 +1,123 @@+/**+ * Browser-side durable session helpers for Impeccable live mode.+ *+ * Kept separate from live-browser.js so recovery state can be tested without+ * booting the full overlay UI. Served before live-browser.js and attached to+ * window.__IMPECCABLE_LIVE_SESSION__.+ */+(function (root) {+ 'use strict';++ function createLiveBrowserSessionState({ prefix, storage, idFactory }) {+ if (!prefix) throw new Error('prefix required');+ const store = storage || root.localStorage;+ const makeId = idFactory || function () { return Math.random().toString(16).slice(2, 10); };+ const sessionKey = prefix + '-session';+ const handledKey = sessionKey + '-handled';+ const scrollKey = sessionKey + '-scroll';+ let checkpointRevision = 0;+ const owner = makeId();++ function safeRead(key) {+ try { return store.getItem(key); } catch { return null; }+ }++ function safeWrite(key, value) {+ try { store.setItem(key, value); } catch { /* quota exceeded or private mode */ }+ }++ function safeRemove(key) {+ try { store.removeItem(key); } catch { /* unavailable storage */ }+ }++ function loadSession() {+ try {+ const raw = safeRead(sessionKey);+ if (!raw) return null;+ const parsed = JSON.parse(raw);+ if (Number.isInteger(parsed.checkpointRevision)) {+ checkpointRevision = Math.max(checkpointRevision, parsed.checkpointRevision);+ }+ return parsed;+ } catch { return null; }+ }++ function saveSession(session) {+ if (!session || !session.id) return;+ const payload = {+ ...session,+ checkpointRevision,+ };+ safeWrite(sessionKey, JSON.stringify(payload));+ }++ function clearSession() {+ safeRemove(sessionKey);+ }++ function nextCheckpointRevision() {+ checkpointRevision += 1;+ const existing = loadSession();+ if (existing?.id) saveSession(existing);+ return checkpointRevision;+ }++ function seedCheckpointRevision(value) {+ if (Number.isInteger(value)) checkpointRevision = Math.max(checkpointRevision, value);+ return checkpointRevision;+ }++ function currentCheckpointRevision() {+ return checkpointRevision;+ }++ function markHandled(id) {+ if (!id) return;+ safeWrite(handledKey, id);+ }++ function isHandled(id) {+ return !!id && safeRead(handledKey) === id;+ }++ function clearHandled() {+ safeRemove(handledKey);+ }++ function writeScrollY(y) {+ safeWrite(scrollKey, String(y));+ }++ function readScrollY() {+ const raw = safeRead(scrollKey);+ if (raw == null) return null;+ const n = parseFloat(raw);+ return isFinite(n) ? n : null;+ }++ function clearScrollY() {+ safeRemove(scrollKey);+ }++ return {+ owner,+ sessionKey,+ handledKey,+ scrollKey,+ saveSession,+ loadSession,+ clearSession,+ nextCheckpointRevision,+ seedCheckpointRevision,+ currentCheckpointRevision,+ markHandled,+ isHandled,+ clearHandled,+ writeScrollY,+ readScrollY,+ clearScrollY,+ };+ }++ root.__IMPECCABLE_LIVE_SESSION__ = { createLiveBrowserSessionState };+})(typeof window !== 'undefined' ? window : globalThis);diff --git a/source/skills/impeccable/scripts/live-browser.js b/source/skills/impeccable/scripts/live-browser.jsindex 3da76bb96..e67cd01ed 100644--- a/source/skills/impeccable/scripts/live-browser.js+++ b/source/skills/impeccable/scripts/live-browser.js@@ -50,6 +50,16 @@const Z = { highlight: 100001, bar: 100005, picker: 100007, toast: 100010 };const EASE = 'cubic-bezier(0.22, 1, 0.36, 1)'; // ease-out-quintconst PREFIX = 'impeccable-live';+ const sessionState = window.__IMPECCABLE_LIVE_SESSION__?.createLiveBrowserSessionState({+ prefix: PREFIX,+ storage: localStorage,+ idFactory: () => crypto.randomUUID().replace(/-/g, '').slice(0, 8),+ });+ if (!sessionState) {+ console.error('[impeccable] live-browser-session.js was not loaded. Live mode cannot start safely.');+ window.__IMPECCABLE_LIVE_INIT__ = false;+ return;+ }const HIGHLIGHT_TRANSITION ='top 140ms ' + EASE +', left 140ms ' + EASE +@@ -112,6 +122,8 @@let hasProjectContext = false;let selectedAction = 'impeccable';let selectedCount = 3;+ const browserOwner = sessionState.owner;+ let checkpointTimer = null;// Scroll lock — holds window.scrollY at a fixed value while the session is// active, so HMR DOM patches and variant swaps can't drift the page. See@@ -126,21 +138,9 @@// (Previously: saveSession wrote scrollY alongside state, so every call// during resume overwrote the pre-reload value with whatever the browser// had landed on, typically 0.)- const SCROLL_KEY_SUFFIX = '-scroll';- function writeScrollY(y) {- try { localStorage.setItem(LS_KEY + SCROLL_KEY_SUFFIX, String(y)); } catch {}- }- function readScrollY() {- try {- const raw = localStorage.getItem(LS_KEY + SCROLL_KEY_SUFFIX);- if (raw == null) return null;- const n = parseFloat(raw);- return isFinite(n) ? n : null;- } catch { return null; }- }- function clearScrollY() {- try { localStorage.removeItem(LS_KEY + SCROLL_KEY_SUFFIX); } catch {}- }+ function writeScrollY(y) { sessionState.writeScrollY(y); }+ function readScrollY() { return sessionState.readScrollY(); }+ function clearScrollY() { sessionState.clearScrollY(); }// Pre-empt the browser: apply manual scroll restoration and jump to the// saved scrollY at script-parse time. Retries on fonts.ready and load@@ -1585,6 +1585,7 @@paramsCurrentValues[p.id] = v;readout.textContent = formatRangeValue(input);applyParamValue(variantEl, p, v);+ queueCheckpoint('param_changed');});row.appendChild(input);} else if (p.kind === 'toggle') {@@ -1615,6 +1616,7 @@knob.style.left = next ? '18px' : '2px';readout.textContent = next ? 'On' : 'Off';applyParamValue(variantEl, p, next);+ queueCheckpoint('param_changed');});row.appendChild(track);} else if (p.kind === 'steps') {@@ -1651,6 +1653,7 @@btn.style.color = on ? 'oklch(98% 0 0)' : P.text;});applyParamValue(variantEl, p, o.value);+ queueCheckpoint('param_changed');});segRow.appendChild(b);segBtns.push({ btn: b, val: o.value });@@ -1872,19 +1875,26 @@return;}+ const previousVisibleVariant = currentSessionId === sessionId ? visibleVariant : 0;+// Replace the live element with the full wrapper from sourceconst wrapper = srcWrapper.cloneNode(true);liveEl.parentElement.replaceChild(wrapper, liveEl);- // Update state: count variants, show the first one+ // Update state: count variants, preserving the user's current variant+ // when a late HMR/source reinjection lands after they have cycled.const variants = wrapper.querySelectorAll('[data-impeccable-variant]:not([data-impeccable-variant="original"])');arrivedVariants = variants.length;expectedVariants = parseInt(wrapper.dataset.impeccableVariantCount || arrivedVariants);- visibleVariant = 1;- showVariantInDOM(sessionId, 1);+ const saved = loadSession();+ const savedVisibleVariant = saved && saved.id === sessionId ? saved.visible : 0;+ visibleVariant = previousVisibleVariant > 0 && previousVisibleVariant <= arrivedVariants+ ? previousVisibleVariant+ : (savedVisibleVariant > 0 && savedVisibleVariant <= arrivedVariants ? savedVisibleVariant : 1);+ showVariantInDOM(sessionId, visibleVariant);// Update selectedElement to the visible variant's content- selectedElement = pickVariantContent(wrapper, 1) || wrapper.parentElement;+ selectedElement = pickVariantContent(wrapper, visibleVariant) || wrapper.parentElement;state = 'CYCLING';hideShaderOverlay();@@ -1907,6 +1917,7 @@updateSelectedElement();updateBarContent('cycling');saveSession();+ queueCheckpoint('variant_changed');}function updateSelectedElement() {@@ -1917,6 +1928,18 @@if (visEl) selectedElement = visEl;}+ function readVisibleVariantFromDOM(sessionId) {+ const wrapper = document.querySelector('[data-impeccable-variants="' + sessionId + '"]');+ if (!wrapper) return 0;+ const variants = wrapper.querySelectorAll('[data-impeccable-variant]:not([data-impeccable-variant="original"])');+ for (const variant of variants) {+ if (variant.style.display === 'none') continue;+ const idx = parseInt(variant.dataset.impeccableVariant || '0', 10);+ if (idx > 0) return idx;+ }+ return 0;+ }+// Resolve the element that represents the variant's visible content.// Contract: each variant div should contain exactly one top-level element// (the full replacement). In practice a model may ship loose siblings or@@ -2107,8 +2130,10 @@updating = true;arrivedVariants = count;if (visibleVariant === 0 && arrivedVariants > 0) {- visibleVariant = 1;- showVariantInDOM(sessionId, 1);+ const saved = loadSession();+ const savedVisibleVariant = saved && saved.id === sessionId ? saved.visible : 0;+ visibleVariant = savedVisibleVariant > 0 && savedVisibleVariant <= arrivedVariants ? savedVisibleVariant : 1;+ showVariantInDOM(sessionId, visibleVariant);// showVariantInDOM hid the original (display:none); if we were still// anchored to the original's content, its boundingRect is now zero// and the bar snaps to (0,0). Re-point at the visible variant instead.@@ -2128,6 +2153,7 @@updateBarContent('generating');}saveSession();+ queueCheckpoint(state === 'CYCLING' ? 'variants_ready' : 'variants_progress');updating = false;});@@ -2236,6 +2262,7 @@/** Server died or became unreachable. Reset UI to a clean state. */function handleServerLost() {+ const recoveryState = currentSessionId ? state : 'IDLE';if (state === 'GENERATING' || state === 'CYCLING' || state === 'SAVING') {showToast('Live server disconnected. Session ended.', 5000);}@@ -2246,21 +2273,61 @@stopScrollTracking();if (variantObserver) { variantObserver.disconnect(); variantObserver = null; }stopScrollLock();- clearScrollY();- clearSession();+ // Preserve local session state on server loss. The durable journal is the+ // source of truth, but localStorage plus the variant wrapper lets the UI+ // resume after a helper restart or page reload instead of treating a+ // transient disconnect as an explicit discard.selectedElement = null;- currentSessionId = null;selectedAction = 'impeccable';- state = 'IDLE';+ state = recoveryState;+ if (currentSessionId) saveSession();}- function sendEvent(msg) {+ function sendEvent(msg, opts) {msg.token = TOKEN;- fetch('http://localhost:' + PORT + '/events', {+ function handleFailure(err) {+ console.error('[impeccable] Failed to send event:', err);+ if (opts && opts.throwOnError) throw err;+ return null;+ }+ return fetch('http://localhost:' + PORT + '/events', {method: 'POST',headers: { 'Content-Type': 'application/json' },body: JSON.stringify(msg),- }).catch(err => console.error('[impeccable] Failed to send event:', err));+ }).then(res => {+ if (res.ok) return res;+ return handleFailure(new Error('HTTP ' + res.status + ' ' + res.statusText));+ }).catch(handleFailure);+ }++ function checkpointPayload(reason) {+ return {+ type: 'checkpoint',+ id: currentSessionId,+ revision: sessionState.nextCheckpointRevision(),+ owner: browserOwner,+ phase: String(state || '').toLowerCase(),+ reason,+ pageUrl: location.pathname,+ expectedVariants,+ arrivedVariants,+ visibleVariant,+ paramValues: { ...paramsCurrentValues },+ };+ }++ function sendCheckpoint(reason) {+ if (!currentSessionId) return Promise.resolve(null);+ return sendEvent(checkpointPayload(reason)).catch(() => null);+ }++ function queueCheckpoint(reason) {+ if (!currentSessionId) return;+ if (checkpointTimer) clearTimeout(checkpointTimer);+ checkpointTimer = setTimeout(() => {+ checkpointTimer = null;+ sendCheckpoint(reason);+ }, 120);}// ---------------------------------------------------------------------------@@ -2496,6 +2563,7 @@state = 'GENERATING';showBar('generating');saveSession();+ sendCheckpoint('generate_started');writeScrollY(window.scrollY);if (variantObserver) variantObserver.disconnect();variantObserver = startVariantObserver(currentSessionId);@@ -2920,13 +2988,12 @@ void main() {function handleAccept() {if (!currentSessionId || arrivedVariants === 0) return;+ const domVisibleVariant = readVisibleVariantFromDOM(currentSessionId);+ if (domVisibleVariant > 0) visibleVariant = domVisibleVariant;const acceptPayload = { type: 'accept', id: currentSessionId, variantId: String(visibleVariant) };if (Object.keys(paramsCurrentValues).length > 0) {acceptPayload.paramValues = { ...paramsCurrentValues };}- sendEvent(acceptPayload);- markSessionHandled();-// The accepted variant is already the only visible child of the wrapper// (all other variants are display:none). HMR from the source rewrite will// replace the wrapper imminently. Don't eagerly replaceChild here — React@@ -2936,9 +3003,28 @@ void main() {const acceptedSessionId = currentSessionId;const acceptedVariant = visibleVariant;- state = 'CONFIRMED';- updateBarContent('confirmed');- setTimeout(function() {+ state = 'SAVING';+ updateBarContent('saving');++ sendEvent(acceptPayload, { throwOnError: true })+ .then(() => {+ markSessionHandled();+ confirmAcceptAfterReceipt();+ })+ .catch(() => {+ state = 'CYCLING';+ updateBarContent('cycling');+ showToast('Could not confirm accept with the live server. Session kept for recovery; try Accept again.', 5000);+ });++ function confirmAcceptAfterReceipt() {+ state = 'CONFIRMED';+ updateBarContent('confirmed');+ scheduleAcceptCleanup();+ }++ function scheduleAcceptCleanup() {+ setTimeout(function() {hideBar();hideHighlight();stopScrollTracking();@@ -2967,50 +3053,46 @@ void main() {accepted.style.display = 'contents';parent.replaceChild(accepted, wrapper);}- }, 2000);+ }, 2000);+ }}function handleDiscard() {if (!currentSessionId) return;- sendEvent({ type: 'discard', id: currentSessionId });- markSessionHandled();- // Instant DOM restore + fire-and-forget (script handles file cleanup)- cleanup();+ sendEvent({ type: 'discard', id: currentSessionId }, { throwOnError: true })+ .then(() => {+ markSessionHandled();+ cleanup();+ })+ .catch(() => showToast('Could not confirm discard with the live server. Session kept for recovery.', 5000));}// ---------------------------------------------------------------------------- // Session persistence via localStorage+ // Session persistence via live-browser-session.js// ---------------------------------------------------------------------------// Survives page reloads, browser close/reopen, HMR, and accidental refreshes.- const LS_KEY = PREFIX + '-session';-function saveSession() {if (!currentSessionId) return;// NOTE: scrollY is stored under a separate key (writeScrollY). Storing// it here would overwrite the Go-time value every time state changes.- try {- localStorage.setItem(LS_KEY, JSON.stringify({- id: currentSessionId,- state: state,- action: selectedAction,- count: selectedCount,- expected: expectedVariants,- arrived: arrivedVariants,- visible: visibleVariant,- }));- } catch { /* quota exceeded or private mode */ }+ sessionState.saveSession({+ id: currentSessionId,+ state,+ action: selectedAction,+ count: selectedCount,+ expected: expectedVariants,+ arrived: arrivedVariants,+ visible: visibleVariant,+ });}function loadSession() {- try {- const raw = localStorage.getItem(LS_KEY);- return raw ? JSON.parse(raw) : null;- } catch { return null; }+ return sessionState.loadSession();}function clearSession() {- try { localStorage.removeItem(LS_KEY); } catch {}+ sessionState.clearSession();}/** Mark session as handled (accepted/discarded). The agent will clean up@@ -3018,19 +3100,15 @@ void main() {* prevents resumeSession from picking it up again after reload. */function markSessionHandled() {if (!currentSessionId) return;- try {- localStorage.setItem(LS_KEY + '-handled', currentSessionId);- } catch {}+ sessionState.markHandled(currentSessionId);}function isSessionHandled(id) {- try {- return localStorage.getItem(LS_KEY + '-handled') === id;- } catch { return false; }+ return sessionState.isHandled(id);}function clearHandled() {- try { localStorage.removeItem(LS_KEY + '-handled'); } catch {}+ sessionState.clearHandled();}function cleanup() {@@ -3161,6 +3239,7 @@ void main() {// hid. Now that state is CYCLING, re-fire.if (state === 'CYCLING') refreshParamsPanel();saveSession();+ queueCheckpoint('browser_resumed');// Start observing for more variants AFTER initial setupif (variantObserver) variantObserver.disconnect();@@ -3617,7 +3696,7 @@ void main() {}// ---------------------------------------------------------------------------- // Design System Panel — visualizes the project's DESIGN.json sidecar+ // Design System Panel — visualizes the project's .impeccable/design.json sidecar// ---------------------------------------------------------------------------const DESIGN_PREFS_KEY = 'impeccable-live-design-panel';@@ -3629,7 +3708,7 @@ void main() {open: false,tab: 'visual', // 'visual' | 'raw'parsed: null, // parseDesignMd output (frontmatter + body sections)- sidecar: null, // DESIGN.json v2 payload (extensions + components + narrative)+ sidecar: null, // .impeccable/design.json v2 payload (extensions + components + narrative)hasMd: false,hasSidecar: false,present: null, // true/false once fetch resolves@@ -4130,7 +4209,7 @@ void main() {box.className = 'stale';box.innerHTML = `<span class="stale-dot"></span>- <span class="stale-text"><strong>DESIGN.md is newer than DESIGN.json.</strong> Run <code>/impeccable document</code> to refresh the sidecar.</span>+ <span class="stale-text"><strong>DESIGN.md is newer than .impeccable/design.json.</strong> Run <code>/impeccable document</code> to refresh the sidecar.</span>`;return box;}@@ -4138,7 +4217,7 @@ void main() {function renderParsedMdCta() {const box = document.createElement('div');box.className = 'parsed-md-cta';- box.innerHTML = `<strong>Basic view</strong>This panel reads the tokens in your <code>DESIGN.md</code> frontmatter. Running <code>/impeccable document</code> also generates a <code>DESIGN.json</code> sidecar with your project's actual component snippets (button, input, nav) and tonal ramps, rendered live below the tokens.`;+ box.innerHTML = `<strong>Basic view</strong>This panel reads the tokens in your <code>DESIGN.md</code> frontmatter. Running <code>/impeccable document</code> also generates a <code>.impeccable/design.json</code> sidecar with your project's actual component snippets (button, input, nav) and tonal ramps, rendered live below the tokens.`;return box;}@@ -4598,7 +4677,7 @@ void main() {function cssSafe(v) {// Strip anything outside valid CSS value chars to prevent injection via- // DESIGN.json values rendered into inline style strings.+ // .impeccable/design.json values rendered into inline style strings.return String(v).replace(/[<>"'`\n]/g, '');}diff --git a/source/skills/impeccable/scripts/live-complete.mjs b/source/skills/impeccable/scripts/live-complete.mjsnew file mode 100644index 000000000..78155af85--- /dev/null+++ b/source/skills/impeccable/scripts/live-complete.mjs@@ -0,0 +1,75 @@+#!/usr/bin/env node+/**+ * Canonical durable completion acknowledgement for Impeccable live sessions.+ */++import { createLiveSessionStore } from './live-session-store.mjs';+import { readLiveServerInfo } from './impeccable-paths.mjs';++function parseArgs(argv) {+ const out = { status: 'complete' };+ for (let i = 0; i < argv.length; i++) {+ const arg = argv[i];+ if (arg === '--id') out.id = argv[++i];+ else if (arg.startsWith('--id=')) out.id = arg.slice('--id='.length);+ else if (arg === '--discarded' || arg === '--discard') out.status = 'discarded';+ else if (arg === '--error') { out.status = 'agent_error'; out.message = argv[++i] || 'unknown error'; }+ else if (arg.startsWith('--error=')) { out.status = 'agent_error'; out.message = arg.slice('--error='.length); }+ else if (arg === '--help' || arg === '-h') out.help = true;+ }+ return out;+}++export async function completeCli() {+ const args = parseArgs(process.argv.slice(2));+ if (args.help || !args.id) {+ console.log(`Usage: node live-complete.mjs --id SESSION_ID [--discarded|--error MESSAGE]\n\nAppend the final durable session acknowledgement. Use after accept/discard cleanup is verified.`);+ process.exit(args.help ? 0 : 1);+ }++ const serverInfo = readServerInfo();+ const serverResult = serverInfo ? await completeThroughServer(serverInfo, args) : null;+ if (serverResult?.ok) {+ const store = createLiveSessionStore({ cwd: process.cwd(), sessionId: args.id });+ const snapshot = store.getSnapshot(args.id, { includeCompleted: true });+ console.log(JSON.stringify({ ok: true, id: args.id, phase: snapshot?.phase || args.status, snapshot }, null, 2));+ return;+ }++ const store = createLiveSessionStore({ cwd: process.cwd(), sessionId: args.id });+ const event = args.status === 'discarded'+ ? { type: 'discarded', id: args.id }+ : args.status === 'agent_error'+ ? { type: 'agent_error', id: args.id, message: args.message || 'unknown error' }+ : { type: 'complete', id: args.id };+ const snapshot = store.appendEvent(event);+ console.log(JSON.stringify({ ok: true, id: args.id, phase: snapshot.phase, snapshot }, null, 2));+}++function readServerInfo() {+ return readLiveServerInfo(process.cwd())?.info || null;+}++async function completeThroughServer(info, args) {+ const type = args.status === 'discarded'+ ? 'discarded'+ : args.status === 'agent_error'+ ? 'error'+ : 'complete';+ try {+ const res = await fetch(`http://localhost:${info.port}/poll`, {+ method: 'POST',+ headers: { 'Content-Type': 'application/json' },+ body: JSON.stringify({ token: info.token, id: args.id, type, message: args.message }),+ });+ if (!res.ok) return null;+ return await res.json();+ } catch {+ return null;+ }+}++const _running = process.argv[1];+if (_running?.endsWith('live-complete.mjs') || _running?.endsWith('live-complete.mjs/')) {+ completeCli();+}diff --git a/source/skills/impeccable/scripts/live-completion.mjs b/source/skills/impeccable/scripts/live-completion.mjsnew file mode 100644index 000000000..86b637fff--- /dev/null+++ b/source/skills/impeccable/scripts/live-completion.mjs@@ -0,0 +1,18 @@+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';+ return 'agent_done';+}++export function completionAckForAcceptResult(eventId, completionType, acceptResult) {+ const ack = { ok: true, type: completionType };+ if (acceptResult?.handled === true && acceptResult?.carbonize === true) {+ ack.final = false;+ ack.requiresComplete = true;+ ack.nextCommand = `live-complete.mjs --id ${eventId}`;+ ack.message = 'Carbonize cleanup must be verified, then the session must be completed explicitly before polling again.';+ }+ return ack;+}diff --git a/source/skills/impeccable/scripts/live-inject.mjs b/source/skills/impeccable/scripts/live-inject.mjsindex 1d2ae12f7..555c3a36a 100644--- a/source/skills/impeccable/scripts/live-inject.mjs+++ b/source/skills/impeccable/scripts/live-inject.mjs@@ -2,23 +2,24 @@* CLI helper: insert/remove the live variant mode script tag in the project's* main HTML entry point.*- * On first live run, the agent generates `config.json` in this script's- * directory with the project's insertion target (framework-specific). On+ * On first live run, the agent generates `.impeccable/live/config.json`+ * with the project's insertion target (framework-specific). On* every subsequent run, this script handles insert/remove deterministically* with zero LLM involvement.** Usage:* node live-inject.mjs --port PORT # Insert the live script tag* node live-inject.mjs --remove # Remove the live script tag- * node live-inject.mjs --check # Check whether config.json exists+ * node live-inject.mjs --check # Check whether live config exists*/import fs from 'node:fs';import path from 'node:path';import { fileURLToPath } from 'node:url';+import { resolveLiveConfigPath } from './impeccable-paths.mjs';const __dirname = path.dirname(fileURLToPath(import.meta.url));-const CONFIG_PATH = process.env.IMPECCABLE_LIVE_CONFIG || path.join(__dirname, 'config.json');+const CONFIG_PATH = resolveLiveConfigPath({ cwd: process.cwd(), scriptsDir: __dirname });const MARKER_OPEN_TEXT = 'impeccable-live-start';const MARKER_CLOSE_TEXT = 'impeccable-live-end';@@ -39,12 +40,12 @@ export async function injectCli() {console.log(`Usage: node live-inject.mjs [options]Insert or remove the live mode script tag in the project's HTML entry point.-Reads configuration from config.json (in this same directory).+Reads configuration from .impeccable/live/config.json.Modes:--port PORT Insert script tag pointing at http://localhost:PORT/live.js--remove Remove the script tag (if present)- --check Print whether config.json exists and its content+ --check Print whether .impeccable/live/config.json exists and its contentOutput (JSON):{ ok, file, inserted|removed, config? }`);diff --git a/source/skills/impeccable/scripts/live-poll.mjs b/source/skills/impeccable/scripts/live-poll.mjsindex eb8f1586a..10d452491 100644--- a/source/skills/impeccable/scripts/live-poll.mjs+++ b/source/skills/impeccable/scripts/live-poll.mjs@@ -9,10 +9,10 @@*/import { execFileSync } from 'node:child_process';-import fs from 'node:fs';import path from 'node:path';-import os from 'node:os';import { fileURLToPath } from 'node:url';+import { completionAckForAcceptResult, completionTypeForAcceptResult } from './live-completion.mjs';+import { readLiveServerInfo } from './impeccable-paths.mjs';// Node's built-in fetch (undici under the hood) enforces a 300s headers// timeout that can't be lowered per-request. We cap each request below@@ -20,15 +20,29 @@ import { fileURLToPath } from 'node:url';// depending on the standalone undici package.const PER_REQUEST_TIMEOUT_MS = 270_000;-const LIVE_PID_FILE = path.join(process.cwd(), '.impeccable-live.json');-function readServerInfo() {- try {- return JSON.parse(fs.readFileSync(LIVE_PID_FILE, 'utf-8'));- } catch {+ const record = readLiveServerInfo(process.cwd());+ if (!record) {console.error('No running live server found. Start one with: npx impeccable live');process.exit(1);}+ return record.info;+}++export function buildPollReplyPayload(token, { id, type, message, file, data }) {+ return { token, id, type, message, file, data };+}++async function postReply(base, token, reply) {+ const res = await fetch(`${base}/poll`, {+ method: 'POST',+ headers: { 'Content-Type': 'application/json' },+ body: JSON.stringify(buildPollReplyPayload(token, reply)),+ });+ if (!res.ok) {+ const body = await res.json().catch(() => ({}));+ throw new Error(body.error || res.statusText);+ }}export async function pollCli() {@@ -69,23 +83,7 @@ Options:}try {- const res = await fetch(`${base}/poll`, {- method: 'POST',- headers: { 'Content-Type': 'application/json' },- body: JSON.stringify({- token: info.token,- id,- type: status,- message,- file: filePath,- }),- });-- if (!res.ok) {- const body = await res.json().catch(() => ({}));- console.error(`Reply failed (${res.status}):`, body.error || res.statusText);- process.exit(1);- }+ await postReply(base, info.token, { id, type: status, message, file: filePath });// Success — silent exit (agent doesn't need output for replies)} catch (err) {@@ -156,7 +154,23 @@ Options:);event._acceptResult = JSON.parse(out.trim());} catch (err) {- event._acceptResult = { handled: false, error: err.message };+ event._acceptResult = { handled: false, mode: 'error', error: err.message };+ }++ const completionType = completionTypeForAcceptResult(event.type, event._acceptResult);+ try {+ await postReply(base, info.token, {+ id: event.id,+ type: completionType,+ message: event._acceptResult?.error,+ file: event._acceptResult?.file,+ data: event._acceptResult?.carbonize === true ? { carbonize: true } : undefined,+ });+ } catch (err) {+ event._completionAck = { ok: false, error: err.message };+ }+ if (!event._completionAck) {+ event._completionAck = completionAckForAcceptResult(event.id, completionType, event._acceptResult);}}@@ -164,7 +178,7 @@ Options:// JSON but skips nested fields. One line is enough — the full checklist// is in reference/live.md.if (event._acceptResult?.carbonize === true) {- process.stderr.write('\n⚠ Carbonize cleanup REQUIRED before next poll. See reference/live.md "Required after accept".\n\n');+ process.stderr.write('\n⚠ Carbonize cleanup REQUIRED before next poll. After cleanup, run live-complete.mjs --id ' + event.id + '. See reference/live.md "Required after accept".\n\n');}// Print the event as JSON — the agent reads this from stdoutdiff --git a/source/skills/impeccable/scripts/live-resume.mjs b/source/skills/impeccable/scripts/live-resume.mjsnew file mode 100644index 000000000..a3465c9b5--- /dev/null+++ b/source/skills/impeccable/scripts/live-resume.mjs@@ -0,0 +1,48 @@+#!/usr/bin/env node+/**+ * Recover the next agent action from the durable live-session journal.+ */++import { createLiveSessionStore } from './live-session-store.mjs';++function parseArgs(argv) {+ const out = { id: null };+ for (let i = 0; i < argv.length; i++) {+ const arg = argv[i];+ if (arg === '--id') out.id = argv[++i];+ else if (arg.startsWith('--id=')) out.id = arg.slice('--id='.length);+ else if (arg === '--help' || arg === '-h') out.help = true;+ }+ return out;+}++export async function resumeCli() {+ const args = parseArgs(process.argv.slice(2));+ if (args.help) {+ console.log(`Usage: node live-resume.mjs [--id SESSION_ID]\n\nPrint the active durable session checkpoint and the next safe agent action.`);+ return;+ }++ const store = createLiveSessionStore({ cwd: process.cwd(), sessionId: args.id || undefined });+ const snapshot = args.id ? store.getSnapshot(args.id) : store.listActiveSessions()[0] || null;+ if (!snapshot) {+ console.log(JSON.stringify({ active: false, nextAction: 'No active durable live session found.' }, null, 2));+ return;+ }++ const pending = snapshot.pendingEvent || null;+ const nextAction = pending+ ? `Run live-poll.mjs, handle ${pending.type} ${pending.id}, then acknowledge with live-poll.mjs --reply ${pending.id} done.`+ : snapshot.phase === 'carbonize_required'+ ? `Finish carbonize cleanup${snapshot.sourceFile ? ` in ${snapshot.sourceFile}` : ''}, then run live-complete.mjs --id ${snapshot.id}.`+ : snapshot.phase === 'accept_requested'+ ? `Run live-complete.mjs --id ${snapshot.id} after verifying the accepted variant is written.`+ : `Inspect ${snapshot.id}; no pending agent event is currently queued.`;++ console.log(JSON.stringify({ active: true, snapshot, pendingEvent: pending, nextAction }, null, 2));+}++const _running = process.argv[1];+if (_running?.endsWith('live-resume.mjs') || _running?.endsWith('live-resume.mjs/')) {+ resumeCli();+}diff --git a/source/skills/impeccable/scripts/live-server.mjs b/source/skills/impeccable/scripts/live-server.mjsindex 90614fbf7..53d8f21cb 100644--- a/source/skills/impeccable/scripts/live-server.mjs+++ b/source/skills/impeccable/scripts/live-server.mjs@@ -22,14 +22,20 @@ import net from 'node:net';import { fileURLToPath } from 'node:url';import { parseDesignMd } from './design-parser.mjs';import { resolveContextDir } from './load-context.mjs';+import { createLiveSessionStore } from './live-session-store.mjs';+import {+ getDesignSidecarPath,+ getLiveAnnotationsDir,+ readLiveServerInfo,+ removeLiveServerInfo,+ resolveDesignSidecarPath,+ writeLiveServerInfo,+} from './impeccable-paths.mjs';const __dirname = path.dirname(fileURLToPath(import.meta.url));-// PID file in the project root so both the server and agent can find it-// predictably (os.tmpdir() varies across platforms).-const LIVE_PID_FILE = path.join(process.cwd(), '.impeccable-live.json');-// PRODUCT.md / DESIGN.md / DESIGN.json live wherever load-context.mjs resolves.-// Keeps live-server in sync with the loader when users keep the docs in-// .agents/context/, docs/, or a path set via IMPECCABLE_CONTEXT_DIR.+// PRODUCT.md / DESIGN.md live wherever load-context.mjs resolves. The generated+// DESIGN sidecar is project-local at .impeccable/design.json, with legacy+// DESIGN.json fallback for existing projects.const CONTEXT_DIR = resolveContextDir(process.cwd());const DEFAULT_POLL_TIMEOUT = 600_000; // 10 min — agent re-polls on timeout anywayconst SSE_HEARTBEAT_INTERVAL = 30_000; // keepalive ping every 30s@@ -57,10 +63,12 @@ const state = {token: null,port: null,sseClients: new Set(), // SSE response objects (server→browser push)- pendingEvents: [], // browser events waiting for agent poll+ pendingEvents: [], // browser events waiting for agent ack ({ event, leaseUntil })pendingPolls: [], // agent poll callbacks waiting for browser eventsexitTimer: null,sessionDir: null, // per-session tmp dir for annotation screenshots+ sessionStore: null,+ leaseTimer: null,};// Cap per-annotation upload size. A full 1920×1080 PNG is typically <1 MB;@@ -68,11 +76,70 @@ const state = {const MAX_ANNOTATION_BYTES = 10 * 1024 * 1024;function enqueueEvent(event) {- if (state.pendingPolls.length > 0) {- state.pendingPolls.shift()(event);- } else {- state.pendingEvents.push(event);+ if (!event || (event.id && state.pendingEvents.some((entry) => entry.event?.id === event.id && entry.event?.type === event.type))) return;+ state.pendingEvents.push({ event, leaseUntil: 0 });+ flushPendingPolls();+}++function restorePendingEventsFromStore() {+ if (!state.sessionStore) return;+ for (const snapshot of state.sessionStore.listActiveSessions()) {+ if (snapshot.pendingEvent) enqueueEvent(snapshot.pendingEvent);+ }+}++function findAvailablePendingEvent(now = Date.now()) {+ return state.pendingEvents.find((entry) => !entry.leaseUntil || entry.leaseUntil <= now);+}++function leaseEvent(entry, leaseMs) {+ if (!entry.event?.id) {+ const idx = state.pendingEvents.indexOf(entry);+ if (idx !== -1) state.pendingEvents.splice(idx, 1);+ return entry.event;}+ entry.leaseUntil = Date.now() + leaseMs;+ return entry.event;+}++function acknowledgePendingEvent(id) {+ if (!id) return false;+ const idx = state.pendingEvents.findIndex((entry) => entry.event?.id === id);+ if (idx === -1) return false;+ state.pendingEvents.splice(idx, 1);+ scheduleLeaseFlush();+ return true;+}++function scheduleLeaseFlush() {+ if (state.leaseTimer) {+ clearTimeout(state.leaseTimer);+ state.leaseTimer = null;+ }+ if (state.pendingPolls.length === 0) return;+ const now = Date.now();+ const nextLeaseUntil = state.pendingEvents+ .map((entry) => entry.leaseUntil || 0)+ .filter((leaseUntil) => leaseUntil > now)+ .sort((a, b) => a - b)[0];+ if (!nextLeaseUntil) return;+ state.leaseTimer = setTimeout(() => {+ state.leaseTimer = null;+ flushPendingPolls();+ }, Math.max(0, nextLeaseUntil - now));+}++function flushPendingPolls() {+ while (state.pendingPolls.length > 0) {+ const entry = findAvailablePendingEvent();+ if (!entry) {+ scheduleLeaseFlush();+ return;+ }+ const poll = state.pendingPolls.shift();+ poll.resolve(leaseEvent(entry, poll.leaseMs));+ }+ scheduleLeaseFlush();}/** Push a message to all connected SSE clients. */@@ -103,13 +170,16 @@ function loadBrowserScripts() {// live-browser.js: DO NOT cache. Return the path so the /live.js handler// can re-read on every request. Editing the browser script during iteration// should land on the next tab reload, not require a server restart.+ const sessionPath = path.join(__dirname, 'live-browser-session.js');const livePath = path.join(__dirname, 'live-browser.js');- if (!fs.existsSync(livePath)) {- process.stderr.write('Error: live-browser.js not found at ' + livePath + '\n');- process.exit(1);+ for (const p of [sessionPath, livePath]) {+ if (!fs.existsSync(p)) {+ process.stderr.write('Error: live browser script not found at ' + p + '\n');+ process.exit(1);+ }}- return { detectScript, livePath };+ return { detectScript, sessionPath, livePath };}function hasProjectContext() {@@ -170,6 +240,13 @@ function validateEvent(msg) {return null;case 'discard':return isValidId(msg.id) ? null : 'discard: missing or malformed id';+ case 'checkpoint':+ if (!isValidId(msg.id)) return 'checkpoint: missing or malformed id';+ if (!Number.isInteger(msg.revision) || msg.revision < 0) return 'checkpoint: revision must be a non-negative integer';+ if (msg.paramValues !== undefined && (typeof msg.paramValues !== 'object' || msg.paramValues === null || Array.isArray(msg.paramValues))) {+ return 'checkpoint: paramValues must be an object';+ }+ return null;case 'exit':return null;case 'prefetch':@@ -184,7 +261,7 @@ function validateEvent(msg) {// HTTP request handler// ----------------------------------------------------------------------------function createRequestHandler({ detectScript, livePath }) {+function createRequestHandler({ detectScript, sessionPath, livePath }) {return (req, res) => {const url = new URL(req.url, `http://localhost:${state.port}`);res.setHeader('Access-Control-Allow-Origin', '*');@@ -200,17 +277,20 @@ function createRequestHandler({ detectScript, livePath }) {// the next tab reload. No-store headers prevent browser caching across// sessions — during iteration, a cached old script silently breaks// every subsequent session.+ let sessionScript;let liveScript;try {+ sessionScript = fs.readFileSync(sessionPath, 'utf-8');liveScript = fs.readFileSync(livePath, 'utf-8');} catch (err) {res.writeHead(500, { 'Content-Type': 'text/plain' });- res.end('Error reading live-browser.js: ' + err.message);+ res.end('Error reading live browser scripts: ' + err.message);return;}const body =`window.__IMPECCABLE_TOKEN__ = '${state.token}';\n` +`window.__IMPECCABLE_PORT__ = ${state.port};\n` ++ sessionScript + '\n' +liveScript;res.writeHead(200, {'Content-Type': 'application/javascript',@@ -305,6 +385,26 @@ function createRequestHandler({ detectScript, livePath }) {}// --- Health ---+ if (p === '/status') {+ const token = url.searchParams.get('token');+ if (token !== state.token) { res.writeHead(401, { 'Content-Type': 'application/json' }); res.end(JSON.stringify({ error: 'Unauthorized' })); return; }+ const sessions = state.sessionStore ? state.sessionStore.listActiveSessions() : [];+ res.writeHead(200, { 'Content-Type': 'application/json' });+ res.end(JSON.stringify({+ status: 'ok',+ port: state.port,+ connectedClients: state.sseClients.size,+ pendingEvents: state.pendingEvents.map((entry) => ({+ id: entry.event?.id,+ type: entry.event?.type,+ leased: !!(entry.leaseUntil && entry.leaseUntil > Date.now()),+ leaseUntil: entry.leaseUntil || null,+ })),+ activeSessions: sessions,+ }));+ return;+ }+if (p === '/health') {res.writeHead(200, { 'Content-Type': 'application/json' });res.end(JSON.stringify({@@ -316,13 +416,13 @@ function createRequestHandler({ detectScript, livePath }) {}// --- Design system (unified v2 response) + raw ---- // /design-system.json returns both parsed DESIGN.md and DESIGN.json+ // /design-system.json returns both parsed DESIGN.md and .impeccable/design.json// sidecar when present. Panel merges them:// { present, parsed, sidecar, hasMd, hasSidecar,// mdNewerThanJson, parseError?, sidecarError? }// - parsed: output of parseDesignMd (frontmatter// + six canonical sections) when DESIGN.md exists.- // - sidecar: DESIGN.json contents when present.+ // - sidecar: .impeccable/design.json contents when present.// Expected shape: schemaVersion 2, carrying// extensions + components + narrative.// /design-system/raw returns DESIGN.md markdown verbatim@@ -331,7 +431,7 @@ function createRequestHandler({ detectScript, livePath }) {if (token !== state.token) { res.writeHead(401); res.end('Unauthorized'); return; }const mdPath = path.join(CONTEXT_DIR, 'DESIGN.md');- const jsonPath = path.join(CONTEXT_DIR, 'DESIGN.json');+ const jsonPath = resolveDesignSidecarPath(process.cwd(), CONTEXT_DIR) || getDesignSidecarPath(process.cwd());const mdStat = statOrNull(mdPath);const jsonStat = statOrNull(jsonPath);@@ -367,7 +467,7 @@ function createRequestHandler({ detectScript, livePath }) {try {response.sidecar = JSON.parse(fs.readFileSync(jsonPath, 'utf-8'));} catch (err) {- response.sidecarError = 'Failed to parse DESIGN.json: ' + err.message;+ response.sidecarError = 'Failed to parse .impeccable/design.json: ' + err.message;}}@@ -449,7 +549,16 @@ function createRequestHandler({ detectScript, livePath }) {res.end(JSON.stringify({ error }));return;}- enqueueEvent(msg);+ if (state.sessionStore && msg.id) {+ try {+ state.sessionStore.appendEvent(msg);+ } catch (err) {+ res.writeHead(500, { 'Content-Type': 'application/json' });+ res.end(JSON.stringify({ error: 'session_store_append_failed', message: err.message }));+ return;+ }+ }+ if (msg.type !== 'checkpoint') enqueueEvent(msg);res.writeHead(200, { 'Content-Type': 'application/json' });res.end(JSON.stringify({ ok: true }));});@@ -492,13 +601,16 @@ function handlePollGet(req, res, url) {return;}const timeout = parseInt(url.searchParams.get('timeout') || DEFAULT_POLL_TIMEOUT, 10);- if (state.pendingEvents.length > 0) {+ const leaseMs = parseInt(url.searchParams.get('leaseMs') || '30000', 10);+ const available = findAvailablePendingEvent();+ if (available) {res.writeHead(200, { 'Content-Type': 'application/json' });- res.end(JSON.stringify(state.pendingEvents.shift()));+ res.end(JSON.stringify(leaseEvent(available, leaseMs)));return;}+ const poll = { resolve, leaseMs };const timer = setTimeout(() => {- const idx = state.pendingPolls.indexOf(resolve);+ const idx = state.pendingPolls.indexOf(poll);if (idx !== -1) state.pendingPolls.splice(idx, 1);res.writeHead(200, { 'Content-Type': 'application/json' });res.end(JSON.stringify({ type: 'timeout' }));@@ -508,10 +620,11 @@ function handlePollGet(req, res, url) {res.writeHead(200, { 'Content-Type': 'application/json' });res.end(JSON.stringify(event));}- state.pendingPolls.push(resolve);+ state.pendingPolls.push(poll);+ scheduleLeaseFlush();req.on('close', () => {clearTimeout(timer);- const idx = state.pendingPolls.indexOf(resolve);+ const idx = state.pendingPolls.indexOf(poll);if (idx !== -1) state.pendingPolls.splice(idx, 1);});}@@ -531,6 +644,26 @@ function handlePollPost(req, res) {res.end(JSON.stringify({ error: 'Unauthorized' }));return;}+ acknowledgePendingEvent(msg.id);+ if (state.sessionStore && msg.id) {+ try {+ const eventType = msg.type === 'discard' || msg.type === 'discarded'+ ? 'discarded'+ : msg.type === 'complete'+ ? 'complete'+ : msg.type === 'error'+ ? 'agent_error'+ : 'agent_done';+ state.sessionStore.appendEvent({+ type: eventType,+ id: msg.id,+ file: msg.file,+ message: msg.message,+ carbonize: msg.data?.carbonize === true,+ });+ } catch { /* keep reply path best-effort; browser still needs SSE */ }+ }+ flushPendingPolls();// Forward the reply to the browser via SSEbroadcast({ type: msg.type || 'done', id: msg.id, message: msg.message, file: msg.file, data: msg.data });res.writeHead(200, { 'Content-Type': 'application/json' });@@ -545,13 +678,15 @@ function handlePollPost(req, res) {let httpServer = null;function shutdown() {- try { fs.unlinkSync(LIVE_PID_FILE); } catch {}+ removeLiveServerInfo(process.cwd());+ if (state.leaseTimer) clearTimeout(state.leaseTimer);+ state.leaseTimer = null;if (state.sessionDir) {try { fs.rmSync(state.sessionDir, { recursive: true, force: true }); } catch {}}for (const res of state.sseClients) { try { res.end(); } catch {} }state.sseClients.clear();- for (const resolve of state.pendingPolls) resolve({ type: 'exit' });+ for (const poll of state.pendingPolls) poll.resolve({ type: 'exit' });state.pendingPolls.length = 0;if (httpServer) httpServer.close();process.exit(0);@@ -587,6 +722,7 @@ Endpoints:/events SSE stream (server→browser) + POST (browser→server)/poll Long-poll for agent CLI/source Raw source file reader (no-HMR fallback)+ /status Durable recovery status (token-protected)/health Health check`);process.exit(0);}@@ -594,7 +730,7 @@ Endpoints:if (args.includes('stop')) {const keepInject = args.includes('--keep-inject');try {- const info = JSON.parse(fs.readFileSync(LIVE_PID_FILE, 'utf-8'));+ const { info } = readLiveServerInfo(process.cwd()) || {};const res = await fetch(`http://localhost:${info.port}/stop?token=${info.token}`);if (res.ok) console.log(`Stopped live server on port ${info.port}.`);} catch {@@ -645,7 +781,7 @@ if (args.includes('--background')) {const deadline = Date.now() + 10_000;while (Date.now() < deadline) {try {- const info = JSON.parse(fs.readFileSync(LIVE_PID_FILE, 'utf-8'));+ const { info } = readLiveServerInfo(process.cwd()) || {};if (info.pid !== process.pid) {// Output JSON so the agent can read port + token from stdout.console.log(JSON.stringify(info));@@ -659,30 +795,36 @@ if (args.includes('--background')) {}// Check for existing session-try {- const existing = JSON.parse(fs.readFileSync(LIVE_PID_FILE, 'utf-8'));- try { process.kill(existing.pid, 0);+const existingRecord = readLiveServerInfo(process.cwd());+if (existingRecord?.info) {+ const existing = existingRecord.info;+ try {+ process.kill(existing.pid, 0);console.error(`Live server already running on port ${existing.port} (pid ${existing.pid}).`);console.error('Stop it first with: node ' + path.basename(fileURLToPath(import.meta.url)) + ' stop');process.exit(1);- } catch { fs.unlinkSync(LIVE_PID_FILE); }-} catch {}+ } catch {+ try { fs.unlinkSync(existingRecord.path); } catch {}+ }+}state.token = randomUUID();+state.sessionStore = createLiveSessionStore({ cwd: process.cwd() });+restorePendingEventsFromStore();const portArg = args.find(a => a.startsWith('--port='));state.port = portArg ? parseInt(portArg.split('=')[1], 10) : await findOpenPort();// Annotation screenshots live in the project root so the agent's Read tool// doesn't trip a per-file permission prompt. Sessioned by token so concurrent// projects (or quick restarts) don't collide.-const annotRoot = path.join(process.cwd(), '.impeccable-live', 'annotations');+const annotRoot = getLiveAnnotationsDir(process.cwd());fs.mkdirSync(annotRoot, { recursive: true });state.sessionDir = fs.mkdtempSync(path.join(annotRoot, 'session-'));-const { detectScript, livePath } = loadBrowserScripts();-httpServer = http.createServer(createRequestHandler({ detectScript, livePath }));+const { detectScript, sessionPath, livePath } = loadBrowserScripts();+httpServer = http.createServer(createRequestHandler({ detectScript, sessionPath, livePath }));httpServer.listen(state.port, '127.0.0.1', () => {- fs.writeFileSync(LIVE_PID_FILE, JSON.stringify({ pid: process.pid, port: state.port, token: state.token }));+ writeLiveServerInfo(process.cwd(), { pid: process.pid, port: state.port, token: state.token });const url = `http://localhost:${state.port}`;console.log(`\nImpeccable live server running on ${url}`);console.log(`Token: ${state.token}\n`);diff --git a/source/skills/impeccable/scripts/live-session-store.mjs b/source/skills/impeccable/scripts/live-session-store.mjsnew file mode 100644index 000000000..d55ed2d3a--- /dev/null+++ b/source/skills/impeccable/scripts/live-session-store.mjs@@ -0,0 +1,254 @@+import fs from 'node:fs';+import path from 'node:path';+import { getLegacyLiveSessionsDir, getLiveSessionsDir } from './impeccable-paths.mjs';++const COMPLETED_PHASES = new Set(['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;+ }++ function getReadableJournalPath(id) {+ const primary = getJournalPath(rootDir, id);+ if (fs.existsSync(primary)) return primary;+ const legacy = getJournalPath(legacyRootDir, id);+ if (fs.existsSync(legacy)) return legacy;+ return primary;+ }++ return {+ rootDir,+ legacyRootDir,+ appendEvent(event) {+ const normalized = normalizeEvent(event, sessionId);+ const journalPath = getJournalPath(rootDir, normalized.id);+ const snapshotPath = getSnapshotPath(rootDir, normalized.id);+ const legacyJournalPath = getJournalPath(legacyRootDir, normalized.id);+ if (!fs.existsSync(journalPath) && fs.existsSync(legacyJournalPath)) {+ fs.copyFileSync(legacyJournalPath, journalPath);+ }+ const prior = loadCachedOrRebuild(normalized.id);+ const seq = prior.nextSeq;+ const entry = {+ seq,+ id: normalized.id,+ type: normalized.type,+ ts: new Date().toISOString(),+ event: normalized,+ };+ 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;+ },+ getSnapshot(id = sessionId, opts = {}) {+ if (!id) throw new Error('session id required');+ 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;+ },+ listActiveSessions() {+ const ids = new Set();+ for (const dir of [legacyRootDir, rootDir]) {+ if (!fs.existsSync(dir)) continue;+ for (const name of fs.readdirSync(dir)) {+ if (name.endsWith('.jsonl')) ids.add(name.slice(0, -'.jsonl'.length));+ }+ }+ return [...ids]+ .sort()+ .map((id) => this.getSnapshot(id))+ .filter(Boolean);+ },+ };+}++function normalizeEvent(event, fallbackId) {+ if (!event || typeof event !== 'object') throw new Error('event object required');+ const id = event.id || fallbackId;+ if (!id || typeof id !== 'string') throw new Error('event id required');+ if (!event.type || typeof event.type !== 'string') throw new Error('event type required');+ return { ...event, id };+}++function getJournalPath(rootDir, id) {+ return path.join(rootDir, safeSessionId(id) + '.jsonl');+}++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,+ phase: 'new',+ pageUrl: null,+ sourceFile: null,+ expectedVariants: 0,+ arrivedVariants: 0,+ visibleVariant: null,+ paramValues: {},+ pendingEventSeq: null,+ pendingEvent: null,+ deliveryLease: null,+ checkpointRevision: 0,+ activeOwner: null,+ sourceMarkers: {},+ fallbackMode: null,+ annotationArtifacts: [],+ diagnostics: [],+ updatedAt: null,+ };+}++function rebuildSnapshotFromJournal(journalPath, id) {+ let snapshot = baseSnapshot(id);+ const diagnostics = [];+ let nextSeq = 1;+ if (!fs.existsSync(journalPath)) return { snapshot, diagnostics, nextSeq };++ const lines = fs.readFileSync(journalPath, 'utf-8').split('\n');+ for (let i = 0; i < lines.length; i++) {+ const line = lines[i];+ if (!line.trim()) continue;+ try {+ const entry = JSON.parse(line);+ if (!entry || typeof entry !== 'object') throw new Error('entry is not object');+ if (Number.isInteger(entry.seq)) nextSeq = Math.max(nextSeq, entry.seq + 1);+ snapshot = applyEvent(snapshot, entry);+ } catch (err) {+ diagnostics.push({+ error: 'journal_parse_failed',+ line: i + 1,+ message: err.message,+ });+ }+ }+ snapshot.diagnostics = [...snapshot.diagnostics, ...diagnostics];+ return { snapshot, diagnostics, nextSeq };+}++function applyEvent(snapshot, entry, inheritedDiagnostics = []) {+ const event = entry.event || entry;+ const next = {+ ...snapshot,+ paramValues: { ...(snapshot.paramValues || {}) },+ sourceMarkers: { ...(snapshot.sourceMarkers || {}) },+ annotationArtifacts: [...(snapshot.annotationArtifacts || [])],+ diagnostics: [...(snapshot.diagnostics || [])],+ updatedAt: entry.ts || new Date().toISOString(),+ };++ if (inheritedDiagnostics.length && next.diagnostics.length === 0) {+ next.diagnostics = [...inheritedDiagnostics];+ }++ switch (event.type) {+ case 'generate':+ next.phase = 'generate_requested';+ next.pageUrl = event.pageUrl ?? next.pageUrl;+ next.expectedVariants = event.count ?? next.expectedVariants;+ next.pendingEventSeq = entry.seq ?? next.pendingEventSeq;+ next.pendingEvent = toPendingEvent(event);+ if (event.screenshotPath) upsertArtifact(next.annotationArtifacts, { type: 'screenshot', path: event.screenshotPath });+ break;+ case 'variants_ready':+ case 'agent_done':+ next.phase = event.carbonize === true ? 'carbonize_required' : 'variants_ready';+ next.sourceFile = event.file ?? next.sourceFile;+ next.arrivedVariants = event.arrivedVariants ?? (next.arrivedVariants ?? next.expectedVariants);+ next.pendingEventSeq = null;+ next.pendingEvent = null;+ if (event.carbonize === true) {+ next.diagnostics.push({+ error: 'carbonize_cleanup_required',+ file: event.file || null,+ message: 'Accepted variant still has carbonize markers that must be folded into source CSS.',+ });+ }+ break;+ case 'checkpoint':+ 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;+ if (event.paramValues) next.paramValues = { ...event.paramValues };+ } else {+ next.diagnostics.push({ error: 'stale_checkpoint_ignored', revision: event.revision });+ }+ break;+ case 'accept':+ case 'accept_intent':+ next.phase = 'accept_requested';+ next.visibleVariant = Number(event.variantId ?? next.visibleVariant);+ if (event.paramValues) next.paramValues = { ...event.paramValues };+ next.pendingEventSeq = entry.seq ?? next.pendingEventSeq;+ next.pendingEvent = toPendingEvent(event);+ break;+ case 'discard':+ next.phase = 'discard_requested';+ next.pendingEventSeq = entry.seq ?? next.pendingEventSeq;+ next.pendingEvent = toPendingEvent(event);+ break;+ case 'discarded':+ next.phase = 'discarded';+ next.pendingEventSeq = null;+ next.pendingEvent = null;+ break;+ case 'complete':+ next.phase = 'completed';+ next.pendingEventSeq = null;+ next.pendingEvent = null;+ break;+ case 'agent_error':+ next.phase = 'agent_error';+ next.pendingEventSeq = null;+ next.pendingEvent = null;+ next.diagnostics.push({ error: 'agent_error', message: event.message || 'unknown agent error' });+ break;+ default:+ next.diagnostics.push({ error: 'unknown_event_type', type: event.type });+ break;+ }+ return next;+}++function toPendingEvent(event) {+ const pending = { ...event };+ delete pending.token;+ return pending;+}++function upsertArtifact(artifacts, artifact) {+ if (!artifacts.some((existing) => existing.path === artifact.path && existing.type === artifact.type)) {+ artifacts.push(artifact);+ }+}++function writeSnapshot(snapshotPath, snapshot) {+ fs.writeFileSync(snapshotPath, JSON.stringify(snapshot, null, 2) + '\n');+}diff --git a/source/skills/impeccable/scripts/live-status.mjs b/source/skills/impeccable/scripts/live-status.mjsnew file mode 100644index 000000000..dce1fbca2--- /dev/null+++ b/source/skills/impeccable/scripts/live-status.mjs@@ -0,0 +1,47 @@+#!/usr/bin/env node+/**+ * Print durable recovery status for Impeccable live sessions.+ */++import { createLiveSessionStore } from './live-session-store.mjs';+import { readLiveServerInfo } from './impeccable-paths.mjs';++function readServerInfo() {+ return readLiveServerInfo(process.cwd())?.info || null;+}++async function fetchServerStatus(info) {+ if (!info) return null;+ try {+ const res = await fetch(`http://localhost:${info.port}/status?token=${info.token}`);+ if (!res.ok) return null;+ return await res.json();+ } catch {+ return null;+ }+}++export async function statusCli() {+ const info = readServerInfo();+ const server = await fetchServerStatus(info);+ const store = createLiveSessionStore({ cwd: process.cwd() });+ const activeSessions = store.listActiveSessions();+ const payload = {+ liveServer: server ? {+ status: server.status,+ port: server.port,+ connectedClients: server.connectedClients,+ pendingEvents: server.pendingEvents,+ } : null,+ activeSessions: server?.activeSessions || activeSessions,+ recoveryHint: 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.',+ };+ console.log(JSON.stringify(payload, null, 2));+}++const _running = process.argv[1];+if (_running?.endsWith('live-status.mjs') || _running?.endsWith('live-status.mjs/')) {+ statusCli();+}diff --git a/source/skills/impeccable/scripts/live-wrap.mjs b/source/skills/impeccable/scripts/live-wrap.mjsindex a5769a50a..d46328b9f 100644--- a/source/skills/impeccable/scripts/live-wrap.mjs+++ b/source/skills/impeccable/scripts/live-wrap.mjs@@ -185,6 +185,7 @@ The agent should insert variant HTML at insertLine.`);const { startLine, endLine } = match;const commentSyntax = detectCommentSyntax(targetFile);+ const styleMode = detectStyleMode(targetFile);const isJsx = commentSyntax.open === '{/*';const indent = lines[startLine].match(/^(\s*)/)[1];@@ -269,6 +270,10 @@ The agent should insert variant HTML at insertLine.`);endLine: startLine + wrapperLines.length + (originalLines.length - 1), // 1-indexedinsertLine: insertLine + 1, // 1-indexed: where variants gocommentSyntax: commentSyntax,+ styleMode: styleMode.mode,+ styleTag: styleMode.styleTag,+ cssSelectorPrefixExamples: buildCssSelectorPrefixExamples(styleMode.mode, count),+ cssAuthoring: buildCssAuthoring(styleMode, count),originalLineCount: originalLines.length,}));}@@ -335,6 +340,62 @@ function detectCommentSyntax(filePath) {return { open: '<!--', close: '-->' };}+function detectStyleMode(filePath) {+ const ext = path.extname(filePath).toLowerCase();+ if (ext === '.astro') {+ return {+ mode: 'astro-global-prefixed',+ styleTag: '<style is:inline data-impeccable-css="SESSION_ID">',+ };+ }+ return {+ mode: 'scoped',+ styleTag: '<style data-impeccable-css="SESSION_ID">',+ };+}++function buildCssSelectorPrefixExamples(styleMode, count) {+ if (styleMode !== 'astro-global-prefixed') return [];+ return Array.from({ length: count }, (_, i) => `[data-impeccable-variant="${i + 1}"]`);+}++function buildCssAuthoring(styleMode, count) {+ const variantNumbers = Array.from({ length: count }, (_, i) => i + 1);+ if (styleMode.mode === 'astro-global-prefixed') {+ return {+ mode: styleMode.mode,+ styleTag: styleMode.styleTag,+ strategy: 'global-prefixed',+ rulePattern: '[data-impeccable-variant="N"] > .variant-class { ... }',+ selectorExamples: variantNumbers.map((n) => `[data-impeccable-variant="${n}"] > .variant-class`),+ requirements: [+ 'Use the styleTag exactly; the is:inline attribute is required for this file.',+ 'Prefix every preview selector with the matching [data-impeccable-variant="N"] selector.',+ 'Keep selectors anchored to the generated variant wrapper; do not rely on component CSS scoping for preview rules.',+ ],+ forbidden: [+ 'Do not use @scope for this styleMode.',+ ],+ };+ }+ return {+ mode: styleMode.mode,+ styleTag: styleMode.styleTag,+ strategy: 'scope-rule',+ rulePattern: '@scope ([data-impeccable-variant="N"]) { :scope > .variant-class { ... } }',+ selectorExamples: variantNumbers.map((n) => `@scope ([data-impeccable-variant="${n}"]) { :scope > .variant-class { ... } }`),+ requirements: [+ 'Use @scope blocks keyed to each [data-impeccable-variant="N"] wrapper.',+ 'Inside each @scope block, make :scope rules step into the replacement element with a descendant combinator.',+ 'Use the styleTag exactly; do not add framework-specific style attributes unless this object says to.',+ ],+ forbidden: [+ 'Do not use global [data-impeccable-variant="N"] selector prefixes for this styleMode.',+ 'Do not add is:inline to the style tag for this styleMode.',+ ],+ };+}+/*** Search project files for the query string (class name, ID, etc.)* Returns the first matching file path, or null.diff --git a/source/skills/impeccable/scripts/live.mjs b/source/skills/impeccable/scripts/live.mjsindex befbdb8ed..cafb0eca9 100644--- a/source/skills/impeccable/scripts/live.mjs+++ b/source/skills/impeccable/scripts/live.mjs@@ -2,10 +2,10 @@* CLI entry point: prepare everything needed to enter the live variant poll loop.** Does (all in one command):- * 1. Check config.json (returns config_missing if first-ever run)+ * 1. Check .impeccable/live/config.json (returns config_missing if first-ever run)* 2. Start the live server in the background (or reuse a running one)* 3. Inject the browser script tag into the project's entry file- * 4. Read .impeccable.md for design context (if present)+ * 4. Read PRODUCT.md / DESIGN.md for project context* 5. Print a single JSON blob with everything the agent needs** After this, the agent's only remaining steps are:@@ -23,9 +23,9 @@ import path from 'node:path';import { fileURLToPath } from 'node:url';import { loadContext } from './load-context.mjs';import { resolveFiles } from './live-inject.mjs';+import { readLiveServerInfo } from './impeccable-paths.mjs';const __dirname = path.dirname(fileURLToPath(import.meta.url));-const PID_FILE = path.join(process.cwd(), '.impeccable-live.json');async function liveCli() {const args = process.argv.slice(2);@@ -34,10 +34,10 @@ async function liveCli() {console.log(`Usage: node live.mjsPrepare everything for live variant mode in a single command:- - Checks scripts/config.json (required, created once per project)+ - Checks .impeccable/live/config.json (required, created once per project)- Starts (or reuses) the live server in the background- Injects the browser script tag- - Reads .impeccable.md for design context+ - Reads PRODUCT.md / DESIGN.md for project contextOn success, prints a JSON blob with:{ ok, serverPort, serverToken, pageFile, hasContext, context }@@ -223,7 +223,7 @@ function safeParse(out) {function ensureServerRunning() {// Try to reuse an existing servertry {- const existing = JSON.parse(fs.readFileSync(PID_FILE, 'utf-8'));+ const existing = readLiveServerInfo(process.cwd())?.info;if (existing && existing.pid) {try {process.kill(existing.pid, 0); // throws if deaddiff --git a/source/skills/impeccable/scripts/load-context.mjs b/source/skills/impeccable/scripts/load-context.mjsindex dca23c1f8..dc340bf16 100644--- a/source/skills/impeccable/scripts/load-context.mjs+++ b/source/skills/impeccable/scripts/load-context.mjs@@ -39,7 +39,7 @@ const LEGACY_NAMES = ['.impeccable.md'];const FALLBACK_DIRS = ['.agents/context', 'docs'];/**- * Resolve the directory that holds PRODUCT.md / DESIGN.md / DESIGN.json for+ * Resolve the directory that holds PRODUCT.md / DESIGN.md for* this project. Exported so other scripts (e.g. live-server.mjs) can read the* design files from the same location the loader uses.*/diff --git a/tests/framework-fixtures.test.mjs b/tests/framework-fixtures.test.mjsindex 84bb699ff..f59fcd2ca 100644--- a/tests/framework-fixtures.test.mjs+++ b/tests/framework-fixtures.test.mjs@@ -12,7 +12,7 @@import { describe, it } from 'node:test';import assert from 'node:assert/strict';import { execFileSync } from 'node:child_process';-import { cpSync, existsSync, mkdtempSync, readdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs';+import { cpSync, existsSync, mkdirSync, mkdtempSync, readdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs';import { tmpdir } from 'node:os';import { join, dirname } from 'node:path';import { fileURLToPath } from 'node:url';@@ -43,7 +43,8 @@ function stageFixture(name) {const tmp = mkdtempSync(join(tmpdir(), 'impeccable-fixture-'));cpSync(join(fixtureRoot, 'files'), tmp, { recursive: true });writeFileSync(join(tmp, '.gitignore'), gitignore);- writeFileSync(join(tmp, 'impeccable-live.config.json'), JSON.stringify(fixture.config));+ mkdirSync(join(tmp, '.impeccable', 'live'), { recursive: true });+ writeFileSync(join(tmp, '.impeccable', 'live', 'config.json'), JSON.stringify(fixture.config));execFileSync('git', ['init', '-q'], { cwd: tmp });execFileSync('git', ['config', 'user.email', '[email protected]'], { cwd: tmp });@@ -109,11 +110,7 @@ for (const name of listFixtures()) {it('live-inject --port adds the script tag to every config file', () => {const { tmp } = stageFixture(name);try {- const configPath = join(tmp, 'impeccable-live.config.json');- const out = runScript('live-inject.mjs', ['--port', '9999'], {- cwd: tmp,- env: { IMPECCABLE_LIVE_CONFIG: configPath },- });+ const out = runScript('live-inject.mjs', ['--port', '9999'], { cwd: tmp });const result = JSON.parse(typeof out === 'string' ? out : out.error);assert.equal(result.ok, true, 'inject succeeded');for (const r of result.results) {@@ -130,15 +127,8 @@ for (const name of listFixtures()) {it('live-inject --remove strips the script tag cleanly', () => {const { tmp } = stageFixture(name);try {- const configPath = join(tmp, 'impeccable-live.config.json');- runScript('live-inject.mjs', ['--port', '9999'], {- cwd: tmp,- env: { IMPECCABLE_LIVE_CONFIG: configPath },- });- const out = runScript('live-inject.mjs', ['--remove'], {- cwd: tmp,- env: { IMPECCABLE_LIVE_CONFIG: configPath },- });+ runScript('live-inject.mjs', ['--port', '9999'], { cwd: tmp });+ const out = runScript('live-inject.mjs', ['--remove'], { cwd: tmp });const result = JSON.parse(typeof out === 'string' ? out : out.error);assert.equal(result.ok, true, 'remove succeeded');for (const r of result.results) {diff --git a/tests/framework-fixtures/README.md b/tests/framework-fixtures/README.mdindex 7f7865fcf..6941b1ba1 100644--- a/tests/framework-fixtures/README.md+++ b/tests/framework-fixtures/README.md@@ -18,7 +18,7 @@ Fixtures can also opt into a **runtime E2E** pass that actually installs depende```json{"name": "human-readable label",- "config": { ...contents for live-inject.mjs config.json ... },+ "config": { ...contents for .impeccable/live/config.json ... },"sourceFiles": ["paths that is-generated should classify as source (false)"],"generatedFiles": ["paths that is-generated should classify as generated (true)"],"wrapCases": [diff --git a/tests/impeccable-paths.test.mjs b/tests/impeccable-paths.test.mjsnew file mode 100644index 000000000..933b99370--- /dev/null+++ b/tests/impeccable-paths.test.mjs@@ -0,0 +1,100 @@+/**+ * Tests for project-local Impeccable path resolution.+ * Run with: node --test tests/impeccable-paths.test.mjs+ */++import { describe, it, beforeEach, afterEach } from 'node:test';+import assert from 'node:assert/strict';+import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs';+import { join } from 'node:path';+import { tmpdir } from 'node:os';++import {+ getDesignSidecarPath,+ getLegacyLiveServerPath,+ getLiveAnnotationsDir,+ getLiveConfigPath,+ getLiveServerPath,+ getLiveSessionsDir,+ readLiveServerInfo,+ resolveDesignSidecarPath,+ resolveLiveConfigPath,+} from '../source/skills/impeccable/scripts/impeccable-paths.mjs';++describe('impeccable project paths', () => {+ let tmp;++ beforeEach(() => {+ tmp = mkdtempSync(join(tmpdir(), 'impeccable-paths-'));+ });++ afterEach(() => {+ rmSync(tmp, { recursive: true, force: true });+ });++ it('resolves the generated design sidecar under .impeccable', () => {+ assert.equal(getDesignSidecarPath(tmp), join(tmp, '.impeccable', 'design.json'));++ mkdirSync(join(tmp, '.impeccable'), { recursive: true });+ writeFileSync(join(tmp, 'DESIGN.json'), '{"source":"legacy"}');+ writeFileSync(getDesignSidecarPath(tmp), '{"source":"new"}');++ assert.equal(resolveDesignSidecarPath(tmp), getDesignSidecarPath(tmp));+ });++ it('falls back to legacy root DESIGN.json when the new sidecar is missing', () => {+ const legacyPath = join(tmp, 'DESIGN.json');+ writeFileSync(legacyPath, '{"source":"legacy"}');++ assert.equal(resolveDesignSidecarPath(tmp), legacyPath);+ });++ it('uses .impeccable/live/config.json as the default live config path', () => {+ assert.equal(resolveLiveConfigPath({ cwd: tmp, scriptsDir: join(tmp, 'scripts'), env: {} }), getLiveConfigPath(tmp));+ });++ it('falls back to legacy scripts/config.json when no new live config exists', () => {+ const scriptsDir = join(tmp, 'skills', 'impeccable', 'scripts');+ mkdirSync(scriptsDir, { recursive: true });+ const legacyConfig = join(scriptsDir, 'config.json');+ writeFileSync(legacyConfig, '{"files":["index.html"]}');++ assert.equal(resolveLiveConfigPath({ cwd: tmp, scriptsDir, env: {} }), legacyConfig);+ });++ it('lets IMPECCABLE_LIVE_CONFIG override both new and legacy config locations', () => {+ const override = join(tmp, 'custom-live-config.json');+ mkdirSync(join(tmp, '.impeccable', 'live'), { recursive: true });+ writeFileSync(getLiveConfigPath(tmp), '{"source":"new"}');+ writeFileSync(override, '{"source":"override"}');++ assert.equal(+ resolveLiveConfigPath({ cwd: tmp, scriptsDir: join(tmp, 'scripts'), env: { IMPECCABLE_LIVE_CONFIG: 'custom-live-config.json' } }),+ override,+ );+ });++ it('places live server, session, and annotation state under .impeccable/live', () => {+ assert.equal(getLiveServerPath(tmp), join(tmp, '.impeccable', 'live', 'server.json'));+ assert.equal(getLiveSessionsDir(tmp), join(tmp, '.impeccable', 'live', 'sessions'));+ assert.equal(getLiveAnnotationsDir(tmp), join(tmp, '.impeccable', 'live', 'annotations'));+ });++ it('reads new live server state before legacy recovery state', () => {+ mkdirSync(join(tmp, '.impeccable', 'live'), { recursive: true });+ writeFileSync(getLiveServerPath(tmp), JSON.stringify({ port: 8401, token: 'new' }));+ writeFileSync(getLegacyLiveServerPath(tmp), JSON.stringify({ port: 8400, token: 'legacy' }));++ const record = readLiveServerInfo(tmp);+ assert.equal(record.path, getLiveServerPath(tmp));+ assert.equal(record.info.token, 'new');+ });++ it('reads legacy live server state when the new state file is absent', () => {+ writeFileSync(getLegacyLiveServerPath(tmp), JSON.stringify({ port: 8400, token: 'legacy' }));++ const record = readLiveServerInfo(tmp);+ assert.equal(record.path, getLegacyLiveServerPath(tmp));+ assert.equal(record.info.token, 'legacy');+ });+});diff --git a/tests/live-browser-regression.test.mjs b/tests/live-browser-regression.test.mjsindex b0130d52d..afb439874 100644--- a/tests/live-browser-regression.test.mjs+++ b/tests/live-browser-regression.test.mjs@@ -55,4 +55,43 @@ describe('live-browser.js regression guards', () => {'detectPageTheme must keep its readOpaque helper that filters out fully-transparent backgrounds before computing luminance',);});++ it('handleServerLost preserves the current recoverable phase', () => {+ assert.doesNotMatch(+ SOURCE,+ /state\s*=\s*currentSessionId\s*\?\s*['"]GENERATING['"]\s*:\s*['"]IDLE['"]/,+ 'event=live_browser.server_lost_phase actor=browser operation=sse_disconnect risk=cycling_or_saving_session_saved_as_generating expected=preserve current phase actual=forced generating',+ );+ assert.match(+ SOURCE,+ /function handleServerLost\(\)[\s\S]{0,300}?const recoveryState = currentSessionId \? state : 'IDLE';[\s\S]{0,1200}?state = recoveryState;[\s\S]{0,120}?if \(currentSessionId\) saveSession\(\);/,+ 'server-lost cleanup should keep the current session phase in local recovery state instead of rewriting it to GENERATING',+ );+ });++ it('source reinjection preserves the visible variant after cycling', () => {+ assert.doesNotMatch(+ SOURCE,+ /Replace the live element[\s\S]{0,900}?visibleVariant\s*=\s*1;\s*showVariantInDOM\(sessionId,\s*1\);/,+ 'event=live_browser.visible_variant_reset actor=browser operation=hmr_source_reinject risk=late_hmr_accepts_variant_1_after_user_cycles expected=preserve visible variant actual=reset_to_first',+ );+ assert.match(+ SOURCE,+ /previousVisibleVariant[\s\S]{0,900}?savedVisibleVariant[\s\S]{0,500}?showVariantInDOM\(sessionId, visibleVariant\);/,+ 'source reinjection should preserve the in-memory or saved visible variant instead of always showing variant 1',+ );+ });++ it('handleAccept reads the visible DOM variant before sending accept', () => {+ assert.match(+ SOURCE,+ /function readVisibleVariantFromDOM\(sessionId\)[\s\S]{0,900}?variant\.style\.display === 'none'[\s\S]{0,500}?return idx;/,+ 'live-browser should be able to derive the accepted variant from the currently visible DOM node',+ );+ assert.match(+ SOURCE,+ /function handleAccept\(\)[\s\S]{0,180}?const domVisibleVariant = readVisibleVariantFromDOM\(currentSessionId\);[\s\S]{0,120}?if \(domVisibleVariant > 0\) visibleVariant = domVisibleVariant;[\s\S]{0,160}?variantId: String\(visibleVariant\)/,+ 'event=live_browser.accept_stale_visible_variant actor=browser operation=accept_after_hmr risk=accept_sends_variant_1_after_user_cycles_to_2 expected=read_dom_visible_variant actual=stale_state_variable',+ );+ });});diff --git a/tests/live-browser-session.test.mjs b/tests/live-browser-session.test.mjsnew file mode 100644index 000000000..f5201da23--- /dev/null+++ b/tests/live-browser-session.test.mjs@@ -0,0 +1,64 @@+import { describe, it } from 'node:test';+import assert from 'node:assert/strict';+import { readFileSync } from 'node:fs';+import { join } from 'node:path';+import vm from 'node:vm';++const REPO_ROOT = process.cwd();+const SCRIPT = join(REPO_ROOT, 'source/skills/impeccable/scripts/live-browser-session.js');++function createMemoryStorage() {+ const values = new Map();+ return {+ getItem(key) { return values.has(key) ? values.get(key) : null; },+ setItem(key, value) { values.set(key, String(value)); },+ removeItem(key) { values.delete(key); },+ };+}++function loadFactory() {+ const context = { window: {}, globalThis: {}, console };+ context.window = context;+ context.globalThis = context;+ vm.createContext(context);+ vm.runInContext(readFileSync(SCRIPT, 'utf-8'), context, { filename: SCRIPT });+ return context.__IMPECCABLE_LIVE_SESSION__.createLiveBrowserSessionState;+}++describe('live-browser-session state helper', () => {+ it('persists session, handled state, and scroll independently', () => {+ const createState = loadFactory();+ const storage = createMemoryStorage();+ const state = createState({ prefix: 'impeccable-live', storage, idFactory: () => 'owner-a' });++ state.writeScrollY(420);+ state.saveSession({ id: 'session-a', state: 'CYCLING', visible: 2 });+ state.markHandled('session-a');++ assert.equal(state.readScrollY(), 420);+ assert.equal(state.loadSession().visible, 2);+ assert.equal(state.isHandled('session-a'), true);++ state.clearSession();+ assert.equal(state.loadSession(), null);+ assert.equal(state.readScrollY(), 420, 'scroll key is deliberately independent from session key');+ });++ it('carries checkpoint revision across reload-equivalent helper instances', () => {+ const createState = loadFactory();+ const storage = createMemoryStorage();+ const first = createState({ prefix: 'impeccable-live', storage, idFactory: () => 'owner-a' });+ first.saveSession({ id: 'session-b', state: 'CYCLING', visible: 1 });+ assert.equal(first.nextCheckpointRevision(), 1);+ assert.equal(first.nextCheckpointRevision(), 2);++ const second = createState({ prefix: 'impeccable-live', storage, idFactory: () => 'owner-b' });+ const restored = second.loadSession();+ assert.equal(restored.checkpointRevision, 2);+ assert.equal(+ second.nextCheckpointRevision(),+ 3,+ 'event=live_browser_session.revision_resume actor=browser operation=reload_checkpoint risk=durable_store_ignores_stale_checkpoint expected=3 actual=' + second.currentCheckpointRevision(),+ );+ });+});diff --git a/tests/live-browser-source.test.mjs b/tests/live-browser-source.test.mjsnew file mode 100644index 000000000..f69c59a0c--- /dev/null+++ b/tests/live-browser-source.test.mjs@@ -0,0 +1,24 @@+import { describe, it } from 'node:test';+import assert from 'node:assert/strict';+import { readFileSync } from 'node:fs';+import { join } from 'node:path';++const SOURCE = readFileSync(join(process.cwd(), 'source/skills/impeccable/scripts/live-browser.js'), 'utf-8');++describe('live-browser source contracts', () => {+ it('keeps sendEvent fire-and-forget by default while accept/discard opt into rejection', () => {+ assert.match(+ SOURCE,+ /function sendEvent\(msg, opts\)[\s\S]*if \(opts && opts\.throwOnError\) throw err;[\s\S]*return null;/,+ 'event=live_browser.send_event_contract actor=browser operation=send_event_failure risk=fire_and_forget_callers_get_unhandled_rejections expected=default swallow with opt-in throw actual=missing',+ );+ assert.match(SOURCE, /if \(res\.ok\) return res;[\s\S]*handleFailure\(new Error\('HTTP ' \+ res\.status \+ ' ' \+ res\.statusText\)\)/);+ assert.match(+ SOURCE,+ /\.then\(res => \{[\s\S]*if \(res\.ok\) return res;[\s\S]*\}\)\.catch\(handleFailure\)/,+ 'event=live_browser.http_error_contract actor=browser operation=accept_discard_ack risk=http_500_clears_local_state_without_durable_receipt expected=non-ok response handled before then-success actual=missing',+ );+ assert.match(SOURCE, /sendEvent\(acceptPayload, \{ throwOnError: true \}\)/);+ assert.match(SOURCE, /sendEvent\(\{ type: 'discard', id: currentSessionId \}, \{ throwOnError: true \}\)/);+ });+});diff --git a/tests/live-completion.test.mjs b/tests/live-completion.test.mjsnew file mode 100644index 000000000..aded3fda1--- /dev/null+++ b/tests/live-completion.test.mjs@@ -0,0 +1,61 @@+import { describe, it } from 'node:test';+import assert from 'node:assert/strict';++import {+ completionAckForAcceptResult,+ completionTypeForAcceptResult,+} from '../source/skills/impeccable/scripts/live-completion.mjs';++describe('live completion type classification', () => {+ it('treats generated-file fallback accept as normal agent handoff, not error', () => {+ assert.equal(+ completionTypeForAcceptResult('accept', { handled: false, mode: 'fallback' }),+ 'agent_done',+ 'event=live_poll.fallback_completion actor=agent operation=accept_generated_file risk=fallback_handoff_recorded_as_agent_error expected=agent_done actual=error',+ );+ });++ it('treats unhandled non-error accept as normal manual agent handoff', () => {+ assert.equal(+ completionTypeForAcceptResult('accept', { handled: false, error: 'Session markers not found' }),+ 'agent_done',+ 'event=live_poll.manual_accept_completion actor=agent operation=accept_manual_cleanup risk=manual_handoff_recorded_as_agent_error expected=agent_done actual=error',+ );+ });++ it('keeps carbonize-required accepts recoverable until cleanup is completed', () => {+ assert.equal(+ completionTypeForAcceptResult('accept', { handled: true, carbonize: true }),+ 'agent_done',+ 'event=live_poll.carbonize_completion actor=agent operation=accept_with_carbonize risk=carbonize_session_marked_completed_before_cleanup expected=agent_done actual=complete',+ );+ });++ it('marks carbonize acknowledgements as non-final and requiring explicit completion', () => {+ assert.deepEqual(+ completionAckForAcceptResult('carbonize-1', 'agent_done', { handled: true, carbonize: true }),+ {+ ok: true,+ type: 'agent_done',+ final: false,+ requiresComplete: true,+ nextCommand: 'live-complete.mjs --id carbonize-1',+ message: 'Carbonize cleanup must be verified, then the session must be completed explicitly before polling again.',+ },+ 'event=live_poll.carbonize_ack actor=agent operation=accept_with_carbonize risk=active_session_never_completed expected=explicit_complete_required actual=missing_requires_complete',+ );+ });++ it('keeps normal handled accepts terminal', () => {+ assert.deepEqual(+ completionAckForAcceptResult('done-1', 'complete', { handled: true, carbonize: false }),+ { ok: true, type: 'complete' },+ );+ });++ it('classifies handled accept/discard and real failures explicitly', () => {+ assert.equal(completionTypeForAcceptResult('accept', { handled: true }), 'complete');+ assert.equal(completionTypeForAcceptResult('discard', { handled: true }), 'discarded');+ assert.equal(completionTypeForAcceptResult('accept', { handled: false, mode: 'error', error: 'boom' }), 'error');+ });+});diff --git a/tests/live-e2e.test.mjs b/tests/live-e2e.test.mjsindex de4929c54..8596df514 100644--- a/tests/live-e2e.test.mjs+++ b/tests/live-e2e.test.mjs@@ -174,10 +174,12 @@ for (const { name, fixture } of fixtures) {//// The first-pass timeout has to be long enough to cover the agent's// generate latency before declaring "state was lost, retrace." A- // fake agent finishes in <100ms; an LLM agent typically lands in- // 3-8s. Scale the gate accordingly.+ // fake agent finishes in <100ms. The real LLM path usually lands+ // quickly too, but full-matrix runs can see minute-scale API or+ // install pressure, so keep this gate patient enough that we do+ // not retrace while the agent is still writing the variants.t.diagnostic(`Waiting for CYCLING state with ${expectedCount} variants`);- const firstPassTimeoutMs = agentMode === 'llm' ? 25_000 : 5_000;+ const firstPassTimeoutMs = agentMode === 'llm' ? 90_000 : 5_000;let cyclingReached = false;if (fixture.runtime.preActions) {try {@@ -190,9 +192,9 @@ for (const { name, fixture } of fixtures) {}try {if (!cyclingReached) {- // Default 30s; LLM mode bumps to 60s to absorb API latency on+ // Default 30s; LLM mode bumps to 90s to absorb API latency on// top of HMR settle time.- const finalTimeoutMs = agentMode === 'llm' ? 60_000 : 30_000;+ const finalTimeoutMs = agentMode === 'llm' ? 90_000 : 30_000;await waitForCycling(page, expectedCount, { timeout: finalTimeoutMs });}} catch (err) {@@ -224,10 +226,20 @@ for (const { name, fixture } of fixtures) {const sourceFile = await locateSessionFile(tmp);const after = readFileSync(sourceFile, 'utf-8');assert.match(after, /data-impeccable-variants="/, 'wrapper inserted');- assert.match(after, /<style data-impeccable-css="/, 'colocated <style> block present');- assert.match(after, /@scope \(\[data-impeccable-variant="1"\]\)/, 'scoped CSS for variant 1');- assert.match(after, /@scope \(\[data-impeccable-variant="2"\]\)/, 'scoped CSS for variant 2');- assert.match(after, /@scope \(\[data-impeccable-variant="3"\]\)/, 'scoped CSS for variant 3');+ if (sourceFile.endsWith('.astro')) {+ assert.match(after, /<style is:inline data-impeccable-css="/, 'Astro live CSS uses an inline compiler-bypassing style block');+ assert.match(+ after,+ /\[data-impeccable-variant="1"\]\s*>\s*(?:h1|\.[\w-]+)/,+ 'event=live_e2e.astro_css_prefix actor=agent operation=write_variants risk=astro_scopes_preview_css_away expected=variant-prefixed global selector actual=missing suggestion=inspect fake agent styleMode handling',+ );+ assert.doesNotMatch(after, /@scope \(\[data-impeccable-variant="1"\]\)/, 'Astro live CSS does not use raw @scope');+ } else {+ assert.match(after, /<style data-impeccable-css="/, 'colocated <style> block present');+ assert.match(after, /@scope \(\[data-impeccable-variant="1"\]\)/, 'scoped CSS for variant 1');+ assert.match(after, /@scope \(\[data-impeccable-variant="2"\]\)/, 'scoped CSS for variant 2');+ assert.match(after, /@scope \(\[data-impeccable-variant="3"\]\)/, 'scoped CSS for variant 3');+ }// Param manifest assertions are scoped to fake-agent mode. The fake// agent deterministically emits one param per variant covering all// three kinds; the LLM agent is non-deterministic and may legitimately@@ -244,10 +256,25 @@ for (const { name, fixture } of fixtures) {await clickNext(page);const visible = await getVisibleVariant(page);assert.equal(visible, 2, 'variant 2 visible after one Next');+ if (agentMode === 'fake') {+ await page.waitForFunction(() => {+ const h1 = document.querySelector('[data-impeccable-variant="2"] > h1');+ return h1 && getComputedStyle(h1).fontWeight === '900';+ }, null, { timeout: 5_000 }).catch(() => {});+ const variantWeight = await page.evaluate(() => {+ const h1 = document.querySelector('[data-impeccable-variant="2"] > h1');+ return h1 ? getComputedStyle(h1).fontWeight : null;+ });+ assert.equal(+ variantWeight,+ '900',+ 'event=live_e2e.variant_css_applied actor=browser operation=render_visible_variant risk=unstyled_live_preview expected=font-weight 900 actual=' + variantWeight + ' suggestion=inspect live CSS style mode and selector shape',+ );+ }// 7. Accept variant 2t.diagnostic('Accepting variant 2');- await clickAccept(page);+ await clickAccept(page, { expectedVariant: 2 });// 8. Wait for live-accept + the agent's carbonize cleanup to land.// File-side: wrapper, all variants, and carbonize markers gone;@@ -367,11 +394,17 @@ async function runPreActions(page, actions) {const wasActive = pickerToggle? await pickerToggle.evaluate((el) => el.dataset.active === 'true'): false;- if (wasActive) await page.locator(PICK_TOGGLE).click();+ if (wasActive) await clickPickToggle(page, PICK_TOGGLE);try {- for (const a of actions) {+ for (let i = 0; i < actions.length; i++) {+ const a = actions[i];if (a.type === 'click') {+ const next = actions[i + 1];+ if (next?.type === 'wait') {+ const alreadyVisible = await page.locator(next.selector).first().isVisible().catch(() => false);+ if (alreadyVisible) continue;+ }const loc = page.locator(a.selector);await loc.first().waitFor({ state: 'visible', timeout: 5_000 });await loc.first().click();@@ -395,12 +428,27 @@ async function runPreActions(page, actions) {const after = await page.$(PICK_TOGGLE);if (after) {const isActive = await after.evaluate((el) => el.dataset.active === 'true');- if (!isActive) await page.locator(PICK_TOGGLE).click();+ if (!isActive) await clickPickToggle(page, PICK_TOGGLE);}}}}+async function clickPickToggle(page, selector) {+ try {+ await page.locator(selector).click({ timeout: 5_000 });+ return;+ } catch (err) {+ const clicked = await page.evaluate((sel) => {+ const btn = document.querySelector(sel);+ if (!btn) return false;+ btn.click();+ return true;+ }, selector);+ if (!clicked) throw err;+ }+}+/*** Poll the file until carbonize cleanup has landed: no variants wrapper, no* carbonize markers, no leftover variant divs. Returns the final contents.diff --git a/tests/live-e2e/agent.mjs b/tests/live-e2e/agent.mjsindex 097f908c1..9bd0c4013 100644--- a/tests/live-e2e/agent.mjs+++ b/tests/live-e2e/agent.mjs@@ -73,9 +73,10 @@ const execFileP = promisify(execFile);export function createFakeAgent() {return {/** @type {VariantAgent['generateVariants']} */- async generateVariants(event /*, context */) {+ async generateVariants(event, context = {}) {const text = extractText(event.element?.outerHTML) || 'Title';const cls = 'hero-title';+ const useAstroGlobalCss = context.wrapInfo?.styleMode === 'astro-global-prefixed';// Variant 1 — red color, with a `range` param tuning hue lightness.const variant1 = {@@ -124,24 +125,36 @@ export function createFakeAgent() {],};- // Scoped CSS — `@scope ([data-impeccable-variant="N"])` per variant,- // wired against the params declared above.- const scopedCss = [- '@scope ([data-impeccable-variant="1"]) {',- ' :scope > h1 {',- ' color: oklch(var(--p-lightness, 0.5) 0.25 25);',- ' }',- '}',- '@scope ([data-impeccable-variant="2"]) {',- ' :scope > h1 { font-weight: 900; }',- ' :scope[data-p-face="serif"] > h1 { font-family: ui-serif, serif; }',- ' :scope[data-p-face="mono"] > h1 { font-family: ui-monospace, monospace; }',- '}',- '@scope ([data-impeccable-variant="3"]) {',- ' :scope > h1 { text-transform: uppercase; letter-spacing: 0.04em; }',- ' :scope[data-p-italic] > h1 { font-style: italic; }',- '}',- ].join('\n');+ // Scoped CSS for most frameworks. Astro component styles are transformed+ // and scoped by the compiler, so live preview CSS must use a global style+ // tag plus explicit variant prefixes instead of raw @scope rules.+ const scopedCss = useAstroGlobalCss+ ? [+ '[data-impeccable-variant="1"] > h1 {',+ ' color: oklch(var(--p-lightness, 0.5) 0.25 25);',+ '}',+ '[data-impeccable-variant="2"] > h1 { font-weight: 900; }',+ '[data-impeccable-variant="2"][data-p-face="serif"] > h1 { font-family: ui-serif, serif; }',+ '[data-impeccable-variant="2"][data-p-face="mono"] > h1 { font-family: ui-monospace, monospace; }',+ '[data-impeccable-variant="3"] > h1 { text-transform: uppercase; letter-spacing: 0.04em; }',+ '[data-impeccable-variant="3"][data-p-italic] > h1 { font-style: italic; }',+ ].join('\n')+ : [+ '@scope ([data-impeccable-variant="1"]) {',+ ' :scope > h1 {',+ ' color: oklch(var(--p-lightness, 0.5) 0.25 25);',+ ' }',+ '}',+ '@scope ([data-impeccable-variant="2"]) {',+ ' :scope > h1 { font-weight: 900; }',+ ' :scope[data-p-face="serif"] > h1 { font-family: ui-serif, serif; }',+ ' :scope[data-p-face="mono"] > h1 { font-family: ui-monospace, monospace; }',+ '}',+ '@scope ([data-impeccable-variant="3"]) {',+ ' :scope > h1 { text-transform: uppercase; letter-spacing: 0.04em; }',+ ' :scope[data-p-italic] > h1 { font-style: italic; }',+ '}',+ ].join('\n');return {scopedCss,@@ -192,9 +205,10 @@ function htmlToJsx(html) {* - inner element class= becomes className=* - data-impeccable-params stays a single-quoted JSON string (JSX-legal)*/-function renderVariantsBlock({ sessionId, indent, output, commentSyntax, file }) {+function renderVariantsBlock({ sessionId, indent, output, commentSyntax, file, styleMode }) {const isJsx = commentSyntax.open === '{/*';const isSvelte = !!file && file.endsWith('.svelte');+ const isAstroGlobalCss = styleMode === 'astro-global-prefixed';const styleLines = isJsx? [@@ -203,7 +217,7 @@ function renderVariantsBlock({ sessionId, indent, output, commentSyntax, file })indent + ' `}</style>',]: [- indent + ' <style data-impeccable-css="' + sessionId + '">',+ indent + ' <style' + (isAstroGlobalCss ? ' is:inline' : '') + ' data-impeccable-css="' + sessionId + '">',...output.scopedCss.split('\n').map((l) => indent + ' ' + l),indent + ' </style>',];@@ -258,6 +272,7 @@ async function spliceVariantsIntoWrapper({ tmp, wrapInfo, sessionId, output }) {output,commentSyntax: wrapInfo.commentSyntax,file: wrapInfo.file,+ styleMode: wrapInfo.styleMode,});const next = [@@ -338,7 +353,7 @@ export async function runAgentLoop({log(`wrapped: ${wrapInfo.file} insertLine=${wrapInfo.insertLine}`);// 2. Agent generates variant content (LLM-pluggable seam)- const output = await agent.generateVariants(event, { wrapTarget });+ const output = await agent.generateVariants(event, { wrapTarget, wrapInfo });if (output.variants.length !== event.count) {log(`warning: agent returned ${output.variants.length} variants, expected ${event.count}`);}diff --git a/tests/live-e2e/agents/llm-agent.mjs b/tests/live-e2e/agents/llm-agent.mjsindex 97cd93873..31b96c738 100644--- a/tests/live-e2e/agents/llm-agent.mjs+++ b/tests/live-e2e/agents/llm-agent.mjs@@ -46,7 +46,7 @@ const SYSTEM_INSTRUCTIONS = ['OUTPUT CONTRACT — return ONLY a JSON object with this exact shape. No prose, no code fences, no commentary:','','{',- ' "scopedCss": "string — contents of a <style data-impeccable-css> block, with @scope ([data-impeccable-variant=\\"N\\"]) rules per variant",',+ ' "scopedCss": "string — contents of the preview CSS block, authored according to wrapInfo.cssAuthoring",',' "variants": [',' {',' "innerHtml": "string — single top-level HTML element matching the picked element\'s tag, e.g. <h1 class=\\"hero-title\\">Title</h1>",',@@ -65,7 +65,8 @@ const SYSTEM_INSTRUCTIONS = ['- PRESERVE the original element\'s className verbatim. If the picked element\'s outerHTML contains class="hero-title", every variant\'s innerHtml MUST contain the same class="hero-title" string (you may add additional class names alongside, never remove or rename the original). This is a hard requirement — automated harnesses verify the original class survives across the variant set.','- Generate exactly event.count variants — no more, no fewer.','- Mix the param kinds across the variant set: include at least one range, one steps, and one toggle when count >= 3.',- '- The scopedCss should declare @scope ([data-impeccable-variant="N"]) rules wired against the params you emit (CSS vars for range/toggle, attribute selectors for steps/toggle).',+ '- The scopedCss must follow wrapInfo.cssAuthoring exactly: use its selector strategy, rulePattern, requirements, and forbidden patterns.',+ '- Wire scopedCss rules against the params you emit (CSS vars for range/toggle, attribute selectors for steps/toggle).','- Use HTML attribute syntax in innerHtml (class=, not className=). The orchestrator translates per file syntax.','- Do NOT emit the wrapping <div data-impeccable-variant="N">. The orchestrator wraps your content.','- Do NOT emit the outer <style data-impeccable-css> tag. Only its contents go in scopedCss.',@@ -96,7 +97,7 @@ export async function createLlmAgent(opts = {}) {const client = new Anthropic({ apiKey });return {- async generateVariants(event /*, context */) {+ async generateVariants(event, context = {}) {const userMessage = ['Produce variants for the following pick. Reply with the JSON object only — no prose.','',@@ -112,6 +113,11 @@ export async function createLlmAgent(opts = {}) {className: event.element?.className,textContent: event.element?.textContent?.slice(0, 200),},+ wrapInfo: {+ styleMode: context.wrapInfo?.styleMode,+ styleTag: context.wrapInfo?.styleTag,+ cssAuthoring: context.wrapInfo?.cssAuthoring,+ },},null,2,diff --git a/tests/live-e2e/session.mjs b/tests/live-e2e/session.mjsindex 743922aea..a7140218a 100644--- a/tests/live-e2e/session.mjs+++ b/tests/live-e2e/session.mjs@@ -14,7 +14,7 @@*/import { execFileSync, spawn } from 'node:child_process';-import { cpSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs';+import { cpSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs';import { tmpdir } from 'node:os';import { join, dirname } from 'node:path';import { fileURLToPath } from 'node:url';@@ -39,7 +39,8 @@ export function stageFixture(name, fixture) {const tmp = mkdtempSync(join(tmpdir(), 'impeccable-e2e-'));cpSync(join(fixtureRoot, 'files'), tmp, { recursive: true });writeFileSync(join(tmp, '.gitignore'), gitignore);- writeFileSync(join(tmp, 'impeccable-live.config.json'), JSON.stringify(fixture.config));+ mkdirSync(join(tmp, '.impeccable', 'live'), { recursive: true });+ writeFileSync(join(tmp, '.impeccable', 'live', 'config.json'), JSON.stringify(fixture.config));execFileSync('git', ['init', '-q'], { cwd: tmp });execFileSync('git', ['config', 'user.email', '[email protected]'], { cwd: tmp });@@ -90,7 +91,7 @@ export function runInject(tmp, port) {{cwd: tmp,encoding: 'utf-8',- env: { ...process.env, IMPECCABLE_LIVE_CONFIG: join(tmp, 'impeccable-live.config.json') },+ env: { ...process.env },},);const last = out.trim().split('\n').filter(Boolean).pop();diff --git a/tests/live-e2e/ui.mjs b/tests/live-e2e/ui.mjsindex 8eeebbb88..5ddd5fe6c 100644--- a/tests/live-e2e/ui.mjs+++ b/tests/live-e2e/ui.mjs@@ -99,18 +99,7 @@ export async function setCount(page, count) {* fail the test.*/export async function clickGo(page) {- const go = page.locator(`${BAR_ID} button`, { hasText: /Go\b/ });- let lastErr;- for (let attempt = 0; attempt < 3; attempt++) {- try {- await go.click({ timeout: 5_000 });- return;- } catch (err) {- lastErr = err;- await page.waitForTimeout(500);- }- }- throw lastErr;+ await clickBarButton(page, /Go\b/);}/**@@ -141,11 +130,54 @@ export async function waitForCycling(page, expectedCount, { timeout = 30_000 } =* Click the next variant button (right arrow).*/export async function clickNext(page) {- await page.locator(`${BAR_ID} button`, { hasText: '→' }).click();+ await clickBarButton(page, '→');}export async function clickPrev(page) {- await page.locator(`${BAR_ID} button`, { hasText: '←' }).click();+ await clickBarButton(page, '←');+}++async function clickBarButton(page, label) {+ const button = page.locator(`${BAR_ID} button`, { hasText: label });+ const textMatch = label instanceof RegExp+ ? { kind: 'regex', source: label.source, flags: label.flags }+ : { kind: 'text', value: String(label) };+ let lastErr;+ for (let attempt = 0; attempt < 3; attempt++) {+ try {+ await button.click({ timeout: 5_000 });+ return;+ } catch (err) {+ lastErr = err;+ await page.waitForTimeout(500);+ }+ }+ // Real-LLM fixtures can leave Vite/Tailwind HMR settling for longer than a+ // human-visible click target stays Playwright-stable. Dispatch the click on+ // the current button if normal user-like clicks lost the remount race.+ const clicked = await page.evaluate(findAndClickBarButton, { barSel: BAR_ID, textMatch });+ if (!clicked) throw lastErr;+}++async function dispatchBarButton(page, label) {+ const textMatch = label instanceof RegExp+ ? { kind: 'regex', source: label.source, flags: label.flags }+ : { kind: 'text', value: String(label) };+ return page.evaluate(findAndClickBarButton, { barSel: BAR_ID, textMatch });+}++function findAndClickBarButton({ barSel, textMatch }) {+ const bar = document.querySelector(barSel);+ if (!bar) return false;+ const btn = [...bar.querySelectorAll('button')]+ .find((candidate) => {+ const text = candidate.textContent || '';+ if (textMatch.kind === 'regex') return new RegExp(textMatch.source, textMatch.flags).test(text);+ return text.includes(textMatch.value);+ });+ if (!btn) return false;+ btn.click();+ return true;}/**@@ -153,6 +185,13 @@ export async function clickPrev(page) {*/export async function getVisibleVariant(page) {return page.evaluate((barSel) => {+ const wrapper = document.querySelector('[data-impeccable-variants]');+ if (wrapper) {+ const variants = [...wrapper.querySelectorAll('[data-impeccable-variant]:not([data-impeccable-variant="original"])')];+ const visible = variants.find((variant) => variant.style.display !== 'none');+ const idx = visible ? parseInt(visible.dataset.impeccableVariant || '0', 10) : 0;+ if (idx > 0) return idx;+ }const bar = document.querySelector(barSel);if (!bar) return null;const m = (bar.textContent || '').match(/(\d+)\s*\/\s*(\d+)/);@@ -164,8 +203,29 @@ export async function getVisibleVariant(page) {* Click Accept — sends accept event with current variantId + paramValues.* The bar transitions to a "Saving..." spinner, then a green confirmed row.*/-export async function clickAccept(page) {- await page.locator(`${BAR_ID} button`, { hasText: /Accept/ }).click();+export async function clickAccept(page, { expectedVariant } = {}) {+ if (expectedVariant != null) {+ await ensureVisibleVariant(page, expectedVariant);+ }+ if (await dispatchBarButton(page, /Accept/)) return;+ await clickBarButton(page, /Accept/);+}++async function ensureVisibleVariant(page, expectedVariant) {+ for (let attempt = 0; attempt < 5; attempt++) {+ const current = await getVisibleVariant(page);+ if (current === expectedVariant) return;+ if (current == null) {+ await page.waitForTimeout(300);+ continue;+ }+ await clickBarButton(page, current < expectedVariant ? '→' : '←');+ await page.waitForTimeout(300);+ }+ const current = await getVisibleVariant(page);+ if (current !== expectedVariant) {+ throw new Error(`expected visible variant ${expectedVariant} before accept, got ${current}`);+ }}/**diff --git a/tests/live-inject.test.mjs b/tests/live-inject.test.mjsindex b42694df4..3b0dfb210 100644--- a/tests/live-inject.test.mjs+++ b/tests/live-inject.test.mjs@@ -5,7 +5,7 @@import { describe, it, beforeEach, afterEach } from 'node:test';import assert from 'node:assert/strict';-import { mkdtempSync, writeFileSync, readFileSync, rmSync } from 'node:fs';+import { mkdirSync, mkdtempSync, writeFileSync, readFileSync, realpathSync, rmSync } from 'node:fs';import { dirname, join, resolve } from 'node:path';import { tmpdir } from 'node:os';import { fileURLToPath } from 'node:url';@@ -29,11 +29,59 @@ function runInject(cwd, configPath, args) {}}+function runInjectDefault(cwd, args) {+ try {+ const out = execFileSync('node', [INJECT, ...args], {+ cwd,+ encoding: 'utf-8',+ env: { ...process.env, IMPECCABLE_LIVE_CONFIG: '' },+ stdio: ['ignore', 'pipe', 'pipe'],+ });+ return JSON.parse(out.trim());+ } catch (err) {+ const body = err.stdout?.toString().trim() || err.stderr?.toString().trim() || '';+ return JSON.parse(body || '{}');+ }+}+describe('live-inject — insert/remove round-trip preserves file bytes', () => {let tmp;beforeEach(() => { tmp = mkdtempSync(join(tmpdir(), 'impeccable-inject-test-')); });afterEach(() => { rmSync(tmp, { recursive: true, force: true }); });+ it('reports .impeccable/live/config.json as the default missing config path', () => {+ const result = runInjectDefault(tmp, ['--check']);++ assert.equal(result.ok, false);+ assert.equal(result.error, 'config_missing');+ assert.equal(result.path, join(realpathSync(tmp), '.impeccable', 'live', 'config.json'));+ });++ it('uses .impeccable/live/config.json without an environment override', () => {+ const original = `<html>+ <body>+ <p>Content</p>+ </body>+</html>+`;+ writeFileSync(join(tmp, 'index.html'), original);+ const configDir = join(tmp, '.impeccable', 'live');+ mkdirSync(configDir, { recursive: true });+ writeFileSync(join(configDir, 'config.json'), JSON.stringify({+ files: ['index.html'],+ insertBefore: '</body>',+ commentSyntax: 'html',+ }));++ const inserted = runInjectDefault(tmp, ['--port', '8400']);+ assert.equal(inserted.ok, true);+ assert.match(readFileSync(join(tmp, 'index.html'), 'utf-8'), /localhost:8400\/live\.js/);++ const removed = runInjectDefault(tmp, ['--remove']);+ assert.equal(removed.ok, true);+ assert.equal(readFileSync(join(tmp, 'index.html'), 'utf-8'), original);+ });+it('round-trips an HTML file without mangling indentation', () => {const original = `<!DOCTYPE html><html>diff --git a/tests/live-poll.test.mjs b/tests/live-poll.test.mjsnew file mode 100644index 000000000..effeee49c--- /dev/null+++ b/tests/live-poll.test.mjs@@ -0,0 +1,21 @@+import { describe, it } from 'node:test';+import assert from 'node:assert/strict';++import { buildPollReplyPayload } from '../source/skills/impeccable/scripts/live-poll.mjs';++describe('live-poll reply payloads', () => {+ it('preserves structured data for durable carbonize recovery acknowledgements', () => {+ const payload = buildPollReplyPayload('token-1', {+ id: 'carbonize-reply-1',+ type: 'agent_done',+ file: 'src/App.jsx',+ data: { carbonize: true },+ });++ assert.deepEqual(+ payload.data,+ { carbonize: true },+ 'event=live_poll.reply_data actor=agent operation=completion_ack risk=carbonize_flag_dropped_before_server_journal expected={"carbonize":true} actual=' + JSON.stringify(payload.data),+ );+ });+});diff --git a/tests/live-recovery-commands.test.mjs b/tests/live-recovery-commands.test.mjsnew file mode 100644index 000000000..dd4749ec6--- /dev/null+++ b/tests/live-recovery-commands.test.mjs@@ -0,0 +1,77 @@+import { describe, it } from 'node:test';+import assert from 'node:assert/strict';+import { mkdtempSync, rmSync } from 'node:fs';+import { join } from 'node:path';+import { tmpdir } from 'node:os';+import { execFileSync } from 'node:child_process';+import { createLiveSessionStore } from '../source/skills/impeccable/scripts/live-session-store.mjs';++const REPO_ROOT = process.cwd();+const STATUS_SCRIPT = join(REPO_ROOT, 'source/skills/impeccable/scripts/live-status.mjs');+const RESUME_SCRIPT = join(REPO_ROOT, 'source/skills/impeccable/scripts/live-resume.mjs');+const COMPLETE_SCRIPT = join(REPO_ROOT, 'source/skills/impeccable/scripts/live-complete.mjs');++function withTempProject(fn) {+ const cwd = mkdtempSync(join(tmpdir(), 'impeccable-live-recovery-'));+ try { return fn(cwd); }+ finally { rmSync(cwd, { recursive: true, force: true }); }+}++function runJson(script, args, cwd) {+ const out = execFileSync(process.execPath, [script, ...args], { cwd, encoding: 'utf-8' });+ return JSON.parse(out);+}++describe('live recovery CLI commands', () => {+ it('prints active durable session status without a running helper server', () => withTempProject((cwd) => {+ const store = createLiveSessionStore({ cwd });+ store.appendEvent({ type: 'generate', id: 'cli-recover-1', action: 'impeccable', count: 3, pageUrl: '/', element: { outerHTML: '<button>Go</button>' } });++ const status = runJson(STATUS_SCRIPT, [], cwd);+ assert.equal(status.liveServer, null);+ assert.equal(status.activeSessions.length, 1);+ assert.equal(status.activeSessions[0].id, 'cli-recover-1');+ assert.match(status.recoveryHint, /Start live-server/);+ }));++ it('resumes the pending event and reports the next safe agent action', () => withTempProject((cwd) => {+ const store = createLiveSessionStore({ cwd });+ store.appendEvent({ type: 'generate', id: 'cli-recover-2', action: 'impeccable', count: 2, pageUrl: '/', element: { outerHTML: '<section>Hero</section>' } });++ const resume = runJson(RESUME_SCRIPT, ['--id', 'cli-recover-2'], cwd);+ assert.equal(resume.active, true);+ assert.equal(resume.pendingEvent.type, 'generate');+ assert.match(+ resume.nextAction,+ /live-poll\.mjs/,+ 'event=live_resume.next_action actor=agent operation=recover_session risk=agent_has_state_but_no_next_step expected=live-poll.mjs actual=' + resume.nextAction,+ );+ }));++ it('resumes carbonize-required sessions with a cleanup-specific next action', () => withTempProject((cwd) => {+ const store = createLiveSessionStore({ cwd });+ store.appendEvent({ type: 'accept', id: 'cli-carbonize-1', variantId: '1' });+ store.appendEvent({ type: 'agent_done', id: 'cli-carbonize-1', file: 'src/App.jsx', carbonize: true });++ const resume = runJson(RESUME_SCRIPT, ['--id', 'cli-carbonize-1'], cwd);+ assert.equal(resume.active, true);+ assert.equal(resume.snapshot.phase, 'carbonize_required');+ assert.match(+ resume.nextAction,+ /Finish carbonize cleanup in src\/App\.jsx/,+ 'event=live_resume.carbonize_next_action actor=agent operation=recover_carbonize risk=carbonize_cleanup_hidden_after_accept expected=cleanup-specific action actual=' + resume.nextAction,+ );+ }));++ it('marks a session completed through the canonical completion command', () => withTempProject((cwd) => {+ const store = createLiveSessionStore({ cwd });+ store.appendEvent({ type: 'generate', id: 'cli-recover-3', action: 'impeccable', count: 1, pageUrl: '/', element: { outerHTML: '<p>Copy</p>' } });++ const completed = runJson(COMPLETE_SCRIPT, ['--id', 'cli-recover-3'], cwd);+ assert.equal(completed.ok, true);+ assert.equal(completed.phase, 'completed');++ const status = runJson(STATUS_SCRIPT, [], cwd);+ assert.deepEqual(status.activeSessions, []);+ }));+});diff --git a/tests/live-reference.test.mjs b/tests/live-reference.test.mjsnew file mode 100644index 000000000..84241bb76--- /dev/null+++ b/tests/live-reference.test.mjs@@ -0,0 +1,48 @@+import { describe, it } from 'node:test';+import assert from 'node:assert/strict';+import { readFileSync } from 'node:fs';+import { join } from 'node:path';++const ROOT = process.cwd();++describe('live reference authoring contract', () => {+ it('keeps live preview CSS guidance capability-mode driven', () => {+ const liveMd = readFileSync(join(ROOT, 'source/skills/impeccable/reference/live.md'), 'utf-8');++ assert.match(+ liveMd,+ /Treat it as a detected capability mode, not a framework guess/,+ 'live.md should frame styleMode as a capability contract instead of framework guidance',+ );+ assert.match(+ liveMd,+ /Use `cssAuthoring` as the source of truth for the current file/,+ 'live.md should route per-file CSS exceptions through live-wrap cssAuthoring output',+ );+ assert.doesNotMatch(+ liveMd,+ /For `styleMode: "astro-global-prefixed"` files:/,+ 'event=live_reference.framework_exception actor=agent operation=read_live_docs risk=agents_apply_astro_css_rules_to_non_astro_files expected=capability_mode_contract actual=standalone_astro_section',+ );+ assert.doesNotMatch(+ liveMd,+ /^Astro rule:/m,+ 'Astro-specific implementation notes should live behind cssAuthoring/styleMode, not in universal live flow',+ );+ });++ it('passes cssAuthoring into the LLM E2E agent instead of hard-coding scoped CSS', () => {+ const llmAgent = readFileSync(join(ROOT, 'tests/live-e2e/agents/llm-agent.mjs'), 'utf-8');++ assert.match(+ llmAgent,+ /wrapInfo\.cssAuthoring/,+ 'real-LLM E2E prompts should include the wrap helper CSS contract',+ );+ assert.doesNotMatch(+ llmAgent,+ /with @scope \(\[data-impeccable-variant=/,+ 'real-LLM E2E prompt should not hard-code @scope as the universal CSS contract',+ );+ });+});diff --git a/tests/live-server.test.mjs b/tests/live-server.test.mjsindex 88dd1a792..da219c526 100644--- a/tests/live-server.test.mjs+++ b/tests/live-server.test.mjs@@ -5,21 +5,29 @@import { describe, it, before, after } from 'node:test';import assert from 'node:assert/strict';-import { readFileSync, writeFileSync, mkdirSync, rmSync } from 'node:fs';+import { existsSync, mkdtempSync, readFileSync, writeFileSync, mkdirSync, rmSync } from 'node:fs';import { join } from 'node:path';-import { execSync, spawn } from 'node:child_process';--const SERVER_SCRIPT = 'source/skills/impeccable/scripts/live-server.mjs';-// Matches LIVE_PID_FILE in live-server.mjs: project root, not tmpdir().-const PID_FILE = join(process.cwd(), '.impeccable-live.json');-+import { tmpdir } from 'node:os';+import { execFileSync, execSync, spawn } from 'node:child_process';+import {+ getDesignSidecarPath,+ getLegacyLiveServerPath,+ getLegacyLiveSessionsDir,+ getLiveServerPath,+ getLiveSessionsDir,+} from '../source/skills/impeccable/scripts/impeccable-paths.mjs';++const REPO_ROOT = process.cwd();+const SERVER_SCRIPT = join(REPO_ROOT, 'source/skills/impeccable/scripts/live-server.mjs');+const COMPLETE_SCRIPT = join(REPO_ROOT, 'source/skills/impeccable/scripts/live-complete.mjs');// ---------------------------------------------------------------------------// Helper: start/stop server for integration tests// ----------------------------------------------------------------------------function startServer(port = 8499) {+function startServer(port = 8499, { cwd = REPO_ROOT } = {}) {return new Promise((resolve, reject) => {const proc = spawn('node', [SERVER_SCRIPT, '--port=' + port], {+ cwd,stdio: ['ignore', 'pipe', 'pipe'],env: { ...process.env },});@@ -29,8 +37,8 @@ function startServer(port = 8499) {if (output.includes('running on')) {// Read token from PID filetry {- const info = JSON.parse(readFileSync(PID_FILE, 'utf-8'));- resolve({ proc, port: info.port, token: info.token });+ const info = JSON.parse(readFileSync(getLiveServerPath(cwd), 'utf-8'));+ resolve({ proc, port: info.port, token: info.token, cwd });} catch {reject(new Error('Server started but PID file not readable'));}@@ -48,6 +56,21 @@ async function stopServer(port, token) {} catch { /* server already gone */ }}+async function drainPolls(server) {+ let drained;+ do {+ const r = await fetch(`http://localhost:${server.port}/poll?token=${server.token}&timeout=50&leaseMs=1`);+ drained = await r.json();+ if (drained.id) {+ await fetch(`http://localhost:${server.port}/poll`, {+ method: 'POST',+ headers: { 'Content-Type': 'application/json' },+ body: JSON.stringify({ token: server.token, id: drained.id, type: 'done' }),+ });+ }+ } while (drained.type !== 'timeout');+}+// ---------------------------------------------------------------------------// Server integration tests// ---------------------------------------------------------------------------@@ -56,6 +79,10 @@ describe('live-server integration', () => {let server;before(async () => {+ rmSync(getLiveSessionsDir(REPO_ROOT), { recursive: true, force: true });+ rmSync(getLegacyLiveSessionsDir(REPO_ROOT), { recursive: true, force: true });+ rmSync(getLiveServerPath(REPO_ROOT), { force: true });+ rmSync(getLegacyLiveServerPath(REPO_ROOT), { force: true });server = await startServer(8499);});@@ -77,6 +104,33 @@ describe('live-server integration', () => {assert.equal(data.connectedClients, 0);});+ it('/status returns durable recovery state', async () => {+ await drainPolls(server);+ const eventRes = await fetch(`http://localhost:${server.port}/events`, {+ method: 'POST',+ headers: { 'Content-Type': 'application/json' },+ body: JSON.stringify({+ token: server.token,+ type: 'generate',+ id: 'a1b2c3d5',+ action: 'impeccable',+ count: 1,+ pageUrl: '/',+ element: { outerHTML: '<button>Book</button>' },+ }),+ });+ assert.equal(eventRes.status, 200);++ const res = await fetch(`http://localhost:${server.port}/status?token=${server.token}`);+ assert.equal(res.status, 200);+ const data = await res.json();+ assert.equal(data.status, 'ok');+ assert.equal(data.activeSessions.some((s) => s.id === 'a1b2c3d5'), true);+ assert.equal(data.pendingEvents.some((e) => e.id === 'a1b2c3d5' && e.type === 'generate'), true);++ await drainPolls(server);+ });+it('/live.js serves script with token injected', async () => {const res = await fetch(`http://localhost:${server.port}/live.js`);assert.equal(res.status, 200);@@ -85,6 +139,80 @@ describe('live-server integration', () => {assert.ok(text.includes('__IMPECCABLE_TOKEN__'));assert.ok(text.includes(server.token));assert.ok(text.includes('__IMPECCABLE_PORT__'));+ const sessionHelperIndex = text.indexOf('__IMPECCABLE_LIVE_SESSION__');+ const browserInitIndex = text.indexOf('__IMPECCABLE_LIVE_INIT__');+ assert.ok(sessionHelperIndex !== -1);+ assert.ok(browserInitIndex !== -1);+ assert.ok(+ sessionHelperIndex < browserInitIndex,+ 'event=live_server.browser_helper_order actor=browser operation=load_live_js risk=session_helper_missing_before_browser_init expected=session helper before live init actual=' + sessionHelperIndex + ':' + browserInitIndex,+ );+ });++ it('/design-system.json reads DESIGN.md plus .impeccable/design.json', async () => {+ const tmp = mkdtempSync(join(tmpdir(), 'impeccable-design-system-'));+ let designServer;+ try {+ writeFileSync(join(tmp, 'DESIGN.md'), `---+name: Temp System+description: Temporary design context+colors: {}+---++# Temp System+`);+ const sidecarPath = getDesignSidecarPath(tmp);+ mkdirSync(join(tmp, '.impeccable'), { recursive: true });+ writeFileSync(sidecarPath, JSON.stringify({ version: 2, source: 'new-sidecar' }));++ designServer = await startServer(8520, { cwd: tmp });+ const res = await fetch(`http://localhost:${designServer.port}/design-system.json?token=${designServer.token}`);+ const data = await res.json();++ assert.equal(res.status, 200);+ assert.equal(data.hasMd, true);+ assert.equal(data.hasSidecar, true);+ assert.equal(data.parsed.frontmatter.name, 'Temp System');+ assert.equal(data.sidecar.source, 'new-sidecar');+ } finally {+ if (designServer) {+ await stopServer(designServer.port, designServer.token);+ designServer.proc.kill();+ }+ rmSync(tmp, { recursive: true, force: true });+ }+ });++ it('/design-system.json falls back to legacy root DESIGN.json', async () => {+ const tmp = mkdtempSync(join(tmpdir(), 'impeccable-design-system-legacy-'));+ let designServer;+ try {+ writeFileSync(join(tmp, 'DESIGN.md'), `---+name: Legacy System+description: Legacy design context+colors: {}+---++# Legacy System+`);+ writeFileSync(join(tmp, 'DESIGN.json'), JSON.stringify({ version: 2, source: 'legacy-sidecar' }));++ designServer = await startServer(8521, { cwd: tmp });+ const res = await fetch(`http://localhost:${designServer.port}/design-system.json?token=${designServer.token}`);+ const data = await res.json();++ assert.equal(res.status, 200);+ assert.equal(data.hasMd, true);+ assert.equal(data.hasSidecar, true);+ assert.equal(data.parsed.frontmatter.name, 'Legacy System');+ assert.equal(data.sidecar.source, 'legacy-sidecar');+ } finally {+ if (designServer) {+ await stopServer(designServer.port, designServer.token);+ designServer.proc.kill();+ }+ rmSync(tmp, { recursive: true, force: true });+ }});it('/detect.js serves the detection overlay', async () => {@@ -189,11 +317,7 @@ describe('live-server integration', () => {it('events flow from browser POST to agent poll', async () => {// Drain any queued events from previous tests- let drained;- do {- const r = await fetch(`http://localhost:${server.port}/poll?token=${server.token}&timeout=100`);- drained = await r.json();- } while (drained.type !== 'timeout');+ await drainPolls(server);// Start a poll (will block until event arrives or timeout)const pollPromise = fetch(`http://localhost:${server.port}/poll?token=${server.token}&timeout=5000`)@@ -223,6 +347,263 @@ describe('live-server integration', () => {assert.equal(event.id, 'a1b2c3d4');assert.equal(event.action, 'bolder');assert.equal(event.count, 2);++ await fetch(`http://localhost:${server.port}/poll`, {+ method: 'POST',+ headers: { 'Content-Type': 'application/json' },+ body: JSON.stringify({ token: server.token, id: 'test-e2e-1', type: 'done' }),+ });+ });++ it('persists browser events to the durable session journal before poll delivery', async () => {+ await drainPolls(server);+ const journalPath = join(getLiveSessionsDir(REPO_ROOT), 'a1b2c3d6.jsonl');+ rmSync(journalPath, { force: true });++ const postRes = await fetch(`http://localhost:${server.port}/events`, {+ method: 'POST',+ headers: { 'Content-Type': 'application/json' },+ body: JSON.stringify({+ token: server.token,+ type: 'generate',+ id: 'a1b2c3d6',+ action: 'layout',+ count: 3,+ pageUrl: 'http://localhost:4321/',+ element: { outerHTML: '<section>persist</section>', tagName: 'section' },+ }),+ });+ assert.equal(postRes.status, 200);++ assert.equal(+ existsSync(journalPath),+ true,+ 'event=live_server.journal_before_poll actor=browser operation=post_generate risk=server_restart_loses_unpolled_event expected=journal exists before agent poll actual=missing suggestion=append to live-session-store before enqueueing event',+ );+ const journal = readFileSync(journalPath, 'utf-8');+ assert.match(journal, /"type":"generate"/);++ await fetch(`http://localhost:${server.port}/poll`, {+ method: 'POST',+ headers: { 'Content-Type': 'application/json' },+ body: JSON.stringify({ token: server.token, id: 'a1b2c3d6', type: 'done' }),+ });+ });++ it('accepts checkpoint events without exposing them as agent poll work', async () => {+ await drainPolls(server);+ const res = await fetch(`http://localhost:${server.port}/events`, {+ method: 'POST',+ headers: { 'Content-Type': 'application/json' },+ body: JSON.stringify({+ token: server.token,+ type: 'checkpoint',+ id: 'a1b2c3d7',+ phase: 'cycling',+ revision: 2,+ owner: 'browser-a',+ arrivedVariants: 3,+ visibleVariant: 2,+ paramValues: { density: 'packed' },+ }),+ });+ assert.equal(res.status, 200);++ const polled = await fetch(`http://localhost:${server.port}/poll?token=${server.token}&timeout=50`).then(r => r.json());+ assert.equal(+ polled.type,+ 'timeout',+ 'event=live_server.checkpoint_not_polled actor=browser operation=checkpoint risk=checkpoint_starves_agent_queue expected=timeout actual=' + polled.type + ' suggestion=journal checkpoint without enqueueing agent work',+ );++ const snapshot = JSON.parse(readFileSync(join(getLiveSessionsDir(REPO_ROOT), 'a1b2c3d7.snapshot.json'), 'utf-8'));+ assert.equal(snapshot.visibleVariant, 2);+ assert.deepEqual(snapshot.paramValues, { density: 'packed' });+ });++ it('redelivers an unacknowledged browser event after helper server restart', async () => {+ const tmp = mkdtempSync(join(tmpdir(), 'impeccable-server-restart-'));+ let firstServer;+ let restarted;+ try {+ firstServer = await startServer(8519, { cwd: tmp });+ const postRes = await fetch(`http://localhost:${firstServer.port}/events`, {+ method: 'POST',+ headers: { 'Content-Type': 'application/json' },+ body: JSON.stringify({+ token: firstServer.token,+ type: 'generate',+ id: 'a1b2c3d8',+ action: 'polish',+ count: 2,+ pageUrl: 'http://localhost:4321/',+ element: { outerHTML: '<section>restart</section>', tagName: 'section' },+ }),+ });+ assert.equal(postRes.status, 200);++ await stopServer(firstServer.port, firstServer.token);+ firstServer.proc.kill();+ firstServer = null;++ restarted = await startServer(8519, { cwd: tmp });+ const replayed = await fetch(`http://localhost:${restarted.port}/poll?token=${restarted.token}&timeout=250&leaseMs=50`).then(r => r.json());++ assert.equal(+ replayed.id,+ 'a1b2c3d8',+ 'event=live_server.restart_replay actor=agent operation=poll_after_helper_restart risk=server_restart_loses_unpolled_event expected=a1b2c3d8 actual=' + replayed.id + ' suggestion=rebuild pending poll queue from live-session-store active snapshots on startup',+ );+ assert.equal(replayed.type, 'generate');+ } finally {+ if (firstServer) {+ await stopServer(firstServer.port, firstServer.token);+ firstServer.proc.kill();+ }+ if (restarted) {+ await stopServer(restarted.port, restarted.token);+ restarted.proc.kill();+ }+ rmSync(tmp, { recursive: true, force: true });+ }+ });++ it('records explicit completion acknowledgements as completed durable sessions', async () => {+ await drainPolls(server);+ await fetch(`http://localhost:${server.port}/events`, {+ method: 'POST',+ headers: { 'Content-Type': 'application/json' },+ body: JSON.stringify({+ token: server.token,+ type: 'generate',+ id: 'a1b2c3d9',+ action: 'impeccable',+ count: 1,+ pageUrl: '/',+ element: { outerHTML: '<button>Done</button>' },+ }),+ });+ const polled = await fetch(`http://localhost:${server.port}/poll?token=${server.token}&timeout=50`).then(r => r.json());+ assert.equal(polled.id, 'a1b2c3d9');+ const ack = await fetch(`http://localhost:${server.port}/poll`, {+ method: 'POST',+ headers: { 'Content-Type': 'application/json' },+ body: JSON.stringify({ token: server.token, id: 'a1b2c3d9', type: 'complete' }),+ });+ assert.equal(ack.status, 200);+ const snapshot = JSON.parse(readFileSync(join(getLiveSessionsDir(REPO_ROOT), 'a1b2c3d9.snapshot.json'), 'utf-8'));+ assert.equal(snapshot.phase, 'completed');+ });++ it('manual live-complete acknowledges the running helper queue before writing fallback journal state', async () => {+ await drainPolls(server);+ await fetch(`http://localhost:${server.port}/events`, {+ method: 'POST',+ headers: { 'Content-Type': 'application/json' },+ body: JSON.stringify({+ token: server.token,+ type: 'generate',+ id: 'a1b2c3dc',+ action: 'impeccable',+ count: 1,+ pageUrl: '/',+ element: { outerHTML: '<button>Manual</button>' },+ }),+ });+ const polled = await fetch(`http://localhost:${server.port}/poll?token=${server.token}&timeout=50&leaseMs=50`).then(r => r.json());+ assert.equal(polled.id, 'a1b2c3dc');++ const completed = JSON.parse(execFileSync(process.execPath, [COMPLETE_SCRIPT, '--id', 'a1b2c3dc'], { cwd: REPO_ROOT, encoding: 'utf-8' }));+ assert.equal(completed.phase, 'completed');++ await new Promise(r => setTimeout(r, 75));+ const stale = await fetch(`http://localhost:${server.port}/poll?token=${server.token}&timeout=50&leaseMs=50`).then(r => r.json());+ assert.equal(+ stale.type,+ 'timeout',+ 'event=live_complete.running_server_ack actor=agent operation=manual_complete risk=completed_session_redelivered_from_memory expected=timeout actual=' + stale.id,+ );+ });++ it('does not drop polled events until the agent acknowledges them', async () => {+ await drainPolls(server);++ const postRes = await fetch(`http://localhost:${server.port}/events`, {+ method: 'POST',+ headers: { 'Content-Type': 'application/json' },+ body: JSON.stringify({+ token: server.token,+ type: 'generate',+ id: 'a1b2c3da',+ action: 'polish',+ count: 2,+ element: { outerHTML: '<section>lease</section>', tagName: 'section' },+ }),+ });+ assert.equal(postRes.status, 200);++ const first = await fetch(`http://localhost:${server.port}/poll?token=${server.token}&timeout=100&leaseMs=50`).then(r => r.json());+ assert.equal(first.id, 'a1b2c3da');++ const leased = await fetch(`http://localhost:${server.port}/poll?token=${server.token}&timeout=25&leaseMs=50`).then(r => r.json());+ assert.equal(leased.type, 'timeout', 'leased event should not be redelivered before lease expiry');++ await new Promise(r => setTimeout(r, 75));+ const redelivered = await fetch(`http://localhost:${server.port}/poll?token=${server.token}&timeout=100&leaseMs=50`).then(r => r.json());+ assert.equal(+ redelivered.id,+ 'a1b2c3da',+ 'event=live_poll.lease_redelivery actor=agent operation=poll_after_missed_ack risk=agent_missed_event_loses_live_state expected=same event redelivered after lease expiry actual=' + redelivered.id + ' suggestion=inspect pending event lease bookkeeping',+ );++ await fetch(`http://localhost:${server.port}/poll`, {+ method: 'POST',+ headers: { 'Content-Type': 'application/json' },+ body: JSON.stringify({ token: server.token, id: 'a1b2c3da', type: 'done' }),+ });+ const acked = await fetch(`http://localhost:${server.port}/poll?token=${server.token}&timeout=50&leaseMs=50`).then(r => r.json());+ assert.equal(acked.type, 'timeout', 'acked event should be removed from the poll queue');+ });++ it('wakes a parked poll as soon as a missed-ack lease expires', async () => {+ await drainPolls(server);++ const postRes = await fetch(`http://localhost:${server.port}/events`, {+ method: 'POST',+ headers: { 'Content-Type': 'application/json' },+ body: JSON.stringify({+ token: server.token,+ type: 'generate',+ id: 'a1b2c3db',+ action: 'polish',+ count: 1,+ element: { outerHTML: '<section>wakeup</section>', tagName: 'section' },+ }),+ });+ assert.equal(postRes.status, 200);++ const first = await fetch(`http://localhost:${server.port}/poll?token=${server.token}&timeout=100&leaseMs=60`).then(r => r.json());+ assert.equal(first.id, 'a1b2c3db');++ const startedAt = Date.now();+ const redelivered = await fetch(`http://localhost:${server.port}/poll?token=${server.token}&timeout=500&leaseMs=60`).then(r => r.json());+ const elapsed = Date.now() - startedAt;++ assert.equal(+ redelivered.id,+ 'a1b2c3db',+ 'event=live_poll.lease_expiry_wakeup actor=agent operation=poll_before_lease_expiry risk=parked_poll_waits_full_timeout expected=a1b2c3db actual=' + redelivered.id,+ );+ assert.ok(+ elapsed < 250,+ 'event=live_poll.lease_expiry_latency actor=agent operation=poll_before_lease_expiry risk=redelivery_waits_full_timeout expected=<250 actual=' + elapsed,+ );++ await fetch(`http://localhost:${server.port}/poll`, {+ method: 'POST',+ headers: { 'Content-Type': 'application/json' },+ body: JSON.stringify({ token: server.token, id: 'a1b2c3db', type: 'done' }),+ });});it('agent reply is forwarded via SSE to browser', async () => {diff --git a/tests/live-session-store.test.mjs b/tests/live-session-store.test.mjsnew file mode 100644index 000000000..f0fac4d68--- /dev/null+++ b/tests/live-session-store.test.mjs@@ -0,0 +1,287 @@+/**+ * Tests for durable live-session state.+ * Run with: node --test tests/live-session-store.test.mjs+ */++import { describe, it, beforeEach, afterEach } from 'node:test';+import assert from 'node:assert/strict';+import { mkdirSync, mkdtempSync, rmSync, appendFileSync, readFileSync } from 'node:fs';+import { join } from 'node:path';+import { tmpdir } from 'node:os';++import { createLiveSessionStore } from '../source/skills/impeccable/scripts/live-session-store.mjs';+import {+ getLegacyLiveSessionsDir,+ getLiveAnnotationsDir,+ getLiveSessionsDir,+} from '../source/skills/impeccable/scripts/impeccable-paths.mjs';++describe('live-session-store', () => {+ let tmp;++ beforeEach(() => {+ tmp = mkdtempSync(join(tmpdir(), 'impeccable-session-store-'));+ });++ afterEach(() => {+ rmSync(tmp, { recursive: true, force: true });+ });++ it('rebuilds an active snapshot from an append-only journal after process restart', () => {+ const store = createLiveSessionStore({ cwd: tmp, sessionId: 'session-a' });+ store.appendEvent({+ type: 'generate',+ id: 'session-a',+ action: 'polish',+ count: 3,+ pageUrl: 'http://localhost:4321/',+ element: { outerHTML: '<section class="hero">Hero</section>', tagName: 'section' },+ screenshotPath: join(getLiveAnnotationsDir(tmp), 'session-a.png'),+ });+ store.appendEvent({ type: 'variants_ready', id: 'session-a', file: 'src/pages/index.astro', arrivedVariants: 3 });+ store.appendEvent({ type: 'accept_intent', id: 'session-a', variantId: 2, paramValues: { density: 'packed' } });++ const restarted = createLiveSessionStore({ cwd: tmp, sessionId: 'session-a' });+ const snapshot = restarted.getSnapshot('session-a');++ assert.equal(snapshot.id, 'session-a');+ assert.equal(snapshot.phase, 'accept_requested');+ assert.equal(snapshot.expectedVariants, 3);+ assert.equal(snapshot.arrivedVariants, 3);+ assert.equal(snapshot.sourceFile, 'src/pages/index.astro');+ assert.equal(snapshot.visibleVariant, 2);+ assert.deepEqual(snapshot.paramValues, { density: 'packed' });+ assert.equal(snapshot.annotationArtifacts[0].path.endsWith('session-a.png'), true);++ const active = restarted.listActiveSessions();+ assert.equal(+ active.length,+ 1,+ 'event=live_session_store.active_restart actor=agent operation=list_active_sessions risk=server_restart_loses_live_state expected=one active session actual=' + active.length + ' suggestion=inspect journal replay and completed phase filtering',+ );+ assert.equal(active[0].id, 'session-a');+ });++ it('reports corrupted journal lines while preserving valid prior events', () => {+ const store = createLiveSessionStore({ cwd: tmp, sessionId: 'corrupt-session' });+ store.appendEvent({+ type: 'generate',+ id: 'corrupt-session',+ action: 'layout',+ count: 2,+ element: { outerHTML: '<div>Card</div>', tagName: 'div' },+ });++ appendFileSync(join(getLiveSessionsDir(tmp), 'corrupt-session.jsonl'), '{not json}\n');++ const restarted = createLiveSessionStore({ cwd: tmp, sessionId: 'corrupt-session' });+ const snapshot = restarted.getSnapshot('corrupt-session');++ assert.equal(snapshot.phase, 'generate_requested');+ assert.equal(snapshot.expectedVariants, 2);+ assert.equal(snapshot.diagnostics.length, 1);+ assert.match(snapshot.diagnostics[0].error, /journal_parse_failed/);+ });++ it('does not duplicate parse diagnostics when valid entries follow a corrupted journal line', () => {+ const dir = getLiveSessionsDir(tmp);+ mkdirSync(dir, { recursive: true });+ appendFileSync(join(dir, 'corrupt-then-valid.jsonl'), '{not json}\n');+ appendFileSync(join(dir, 'corrupt-then-valid.jsonl'), JSON.stringify({+ seq: 1,+ id: 'corrupt-then-valid',+ type: 'generate',+ ts: new Date().toISOString(),+ event: {+ type: 'generate',+ id: 'corrupt-then-valid',+ action: 'polish',+ count: 2,+ element: { outerHTML: '<h1>Title</h1>', tagName: 'h1' },+ },+ }) + '\n');++ const store = createLiveSessionStore({ cwd: tmp, sessionId: 'corrupt-then-valid' });+ const snapshot = store.getSnapshot('corrupt-then-valid');+ const parseDiagnostics = snapshot.diagnostics.filter((d) => d.error === 'journal_parse_failed');++ assert.equal(snapshot.phase, 'generate_requested');+ assert.equal(+ parseDiagnostics.length,+ 1,+ 'event=live_session_store.duplicate_parse_diagnostic actor=store operation=journal_replay risk=duplicate_status_noise expected=1 actual=' + parseDiagnostics.length,+ );+ });++ it('preserves zero-valued checkpoint revisions and empty explicit fields', () => {+ const store = createLiveSessionStore({ cwd: tmp, sessionId: 'zero-checkpoint' });+ store.appendEvent({+ type: 'checkpoint',+ id: 'zero-checkpoint',+ revision: 0,+ phase: '',+ owner: '',+ arrivedVariants: 0,+ visibleVariant: 0,+ paramValues: { density: 0 },+ });++ const snapshot = store.getSnapshot('zero-checkpoint');+ assert.equal(+ snapshot.checkpointRevision,+ 0,+ 'event=live_session_store.zero_checkpoint_revision actor=browser operation=checkpoint_replay risk=zero_revision_dropped expected=0 actual=' + snapshot.checkpointRevision,+ );+ assert.equal(snapshot.phase, '');+ assert.equal(snapshot.activeOwner, '');+ assert.equal(snapshot.visibleVariant, 0);+ assert.deepEqual(snapshot.paramValues, { density: 0 });+ });++ it('ignores stale checkpoints and keeps the newest browser state', () => {+ const store = createLiveSessionStore({ cwd: tmp, sessionId: 'checkpoint-session' });+ store.appendEvent({+ type: 'generate',+ id: 'checkpoint-session',+ action: 'layout',+ count: 3,+ element: { outerHTML: '<section>Hero</section>', tagName: 'section' },+ });+ store.appendEvent({ type: 'checkpoint', id: 'checkpoint-session', revision: 5, phase: 'cycling', visibleVariant: 3, paramValues: { density: 'packed' } });+ store.appendEvent({ type: 'checkpoint', id: 'checkpoint-session', revision: 2, phase: 'cycling', visibleVariant: 1, paramValues: { density: 'airy' } });++ const snapshot = store.getSnapshot('checkpoint-session');+ assert.equal(snapshot.checkpointRevision, 5);+ assert.equal(snapshot.visibleVariant, 3);+ assert.deepEqual(snapshot.paramValues, { density: 'packed' });+ assert.equal(+ snapshot.diagnostics.some((d) => d.error === 'stale_checkpoint_ignored' && d.revision === 2),+ true,+ 'event=live_session_store.stale_checkpoint actor=browser operation=checkpoint_replay risk=old_browser_state_overwrites_newer_choice expected=stale diagnostic actual=' + JSON.stringify(snapshot.diagnostics),+ );+ });++ it('keeps carbonize-required accepted sessions active until explicit completion', () => {+ const store = createLiveSessionStore({ cwd: tmp, sessionId: 'carbonize-session' });+ store.appendEvent({+ type: 'accept',+ id: 'carbonize-session',+ variantId: '2',+ paramValues: { tone: 'sharp' },+ });+ store.appendEvent({ type: 'agent_done', id: 'carbonize-session', file: 'src/App.jsx', carbonize: true });++ const snapshot = store.getSnapshot('carbonize-session');+ assert.equal(+ snapshot.phase,+ 'carbonize_required',+ 'event=live_session_store.carbonize_required actor=agent operation=accept_ack risk=carbonize_session_hidden_from_recovery expected=carbonize_required actual=' + snapshot.phase,+ );+ assert.equal(snapshot.sourceFile, 'src/App.jsx');+ assert.equal(snapshot.pendingEvent, null);+ assert.equal(store.listActiveSessions().some((s) => s.id === 'carbonize-session'), true);++ store.appendEvent({ type: 'complete', id: 'carbonize-session' });+ const completed = store.getSnapshot('carbonize-session', { includeCompleted: true });+ assert.equal(completed.phase, 'completed');+ assert.equal(store.listActiveSessions().some((s) => s.id === 'carbonize-session'), false);+ });++ it('clears pending events when an agent error is acknowledged', () => {+ const store = createLiveSessionStore({ cwd: tmp, sessionId: 'error-session' });+ store.appendEvent({+ type: 'generate',+ id: 'error-session',+ action: 'polish',+ count: 1,+ element: { outerHTML: '<button>Try</button>', tagName: 'button' },+ });+ store.appendEvent({ type: 'agent_error', id: 'error-session', message: 'accept failed' });++ const snapshot = store.getSnapshot('error-session');+ assert.equal(snapshot.phase, 'agent_error');+ assert.equal(snapshot.pendingEvent, null);+ assert.equal(snapshot.pendingEventSeq, null);+ assert.equal(+ store.listActiveSessions()[0].pendingEvent,+ null,+ 'event=live_session_store.agent_error_ack actor=agent operation=restart_replay risk=acknowledged_error_event_redelivered expected=null actual=' + JSON.stringify(store.listActiveSessions()[0].pendingEvent),+ );+ });++ it('keeps completed sessions auditable but excludes them from active sessions by default', () => {+ const store = createLiveSessionStore({ cwd: tmp, sessionId: 'done-session' });+ store.appendEvent({+ type: 'generate',+ id: 'done-session',+ action: 'bolder',+ count: 1,+ element: { outerHTML: '<h1>Title</h1>', tagName: 'h1' },+ });+ store.appendEvent({ type: 'agent_done', id: 'done-session', file: 'src/pages/index.astro' });+ store.appendEvent({ type: 'complete', id: 'done-session' });++ const active = store.listActiveSessions();+ const completed = store.getSnapshot('done-session', { includeCompleted: true });++ assert.equal(active.length, 0);+ assert.equal(completed.phase, 'completed');+ assert.equal(completed.sourceFile, 'src/pages/index.astro');+ });++ it('writes a rebuildable snapshot cache without making it authoritative', () => {+ const store = createLiveSessionStore({ cwd: tmp, sessionId: 'cache-session' });+ store.appendEvent({+ type: 'generate',+ id: 'cache-session',+ action: 'colorize',+ count: 2,+ element: { outerHTML: '<div>Palette</div>', tagName: 'div' },+ });++ const snapshotPath = join(getLiveSessionsDir(tmp), 'cache-session.snapshot.json');+ const cached = JSON.parse(readFileSync(snapshotPath, 'utf-8'));+ assert.equal(cached.phase, 'generate_requested');++ // Simulate stale snapshot cache. Restart must prefer journal truth and repair cache.+ appendFileSync(snapshotPath, '');+ const restarted = createLiveSessionStore({ cwd: tmp, sessionId: 'cache-session' });+ restarted.appendEvent({ type: 'agent_done', id: 'cache-session', file: 'src/pages/index.astro' });+ const repaired = JSON.parse(readFileSync(snapshotPath, 'utf-8'));++ assert.equal(repaired.phase, 'variants_ready');+ assert.equal(repaired.sourceFile, 'src/pages/index.astro');+ });++ it('recovers legacy journals from .impeccable-live/sessions', () => {+ const legacyDir = getLegacyLiveSessionsDir(tmp);+ mkdirSync(legacyDir, { recursive: true });+ appendFileSync(join(legacyDir, 'legacy-session.jsonl'), JSON.stringify({+ seq: 1,+ id: 'legacy-session',+ type: 'generate',+ ts: new Date().toISOString(),+ event: {+ type: 'generate',+ id: 'legacy-session',+ action: 'polish',+ count: 2,+ element: { outerHTML: '<section>Legacy</section>', tagName: 'section' },+ },+ }) + '\n');++ const store = createLiveSessionStore({ cwd: tmp, sessionId: 'legacy-session' });+ const snapshot = store.getSnapshot('legacy-session');++ assert.equal(snapshot.phase, 'generate_requested');+ assert.equal(snapshot.expectedVariants, 2);+ assert.equal(store.listActiveSessions().some((s) => s.id === 'legacy-session'), true);++ store.appendEvent({ type: 'agent_done', id: 'legacy-session', file: 'src/App.jsx' });+ const restarted = createLiveSessionStore({ cwd: tmp, sessionId: 'legacy-session' });+ const migratedSnapshot = restarted.getSnapshot('legacy-session');+ assert.equal(migratedSnapshot.phase, 'variants_ready');+ assert.equal(migratedSnapshot.expectedVariants, 2);+ assert.equal(migratedSnapshot.sourceFile, 'src/App.jsx');+ });+});diff --git a/tests/live-wrap.test.mjs b/tests/live-wrap.test.mjsindex 70b6eed18..f70367665 100644--- a/tests/live-wrap.test.mjs+++ b/tests/live-wrap.test.mjs@@ -322,6 +322,62 @@ describe('wrapCli integration', () => {assert.ok(modified.includes('class="after"'));assert.ok(modified.includes('data-impeccable-variants="pres123"'));});++ it('reports scoped CSS authoring as the default live style contract', () => {+ const html = `<section class="hero-shell">+ <h1>Plain title</h1>+</section>`;+ writeFileSync(join(tmp, 'plain.html'), html);++ const result = JSON.parse(execSync(+ `node source/skills/impeccable/scripts/live-wrap.mjs --id scopedCss --count 2 --classes "hero-shell" --tag "section" --file "${join(tmp, 'plain.html')}"`,+ { cwd: process.cwd(), encoding: 'utf-8' }+ ));++ assert.equal(result.styleMode, 'scoped');+ assert.equal(result.cssAuthoring.mode, 'scoped');+ assert.equal(result.cssAuthoring.strategy, 'scope-rule');+ assert.equal(result.cssAuthoring.styleTag, '<style data-impeccable-css="SESSION_ID">');+ assert.match(result.cssAuthoring.rulePattern, /@scope/);+ assert.ok(+ result.cssAuthoring.forbidden.some((item) => item.includes('is:inline')),+ 'scoped mode should explicitly reject file-specific style tag attributes',+ );+ });++ it('reports Astro files need global prefixed live CSS instead of raw @scope', () => {+ const astro = `---+const title = 'Astro title';+---+<section class="hero-shell">+ <h1>{title}</h1>+</section>`;+ writeFileSync(join(tmp, 'Hero.astro'), astro);++ const result = JSON.parse(execSync(+ `node source/skills/impeccable/scripts/live-wrap.mjs --id astroCss --count 3 --classes "hero-shell" --tag "section" --file "${join(tmp, 'Hero.astro')}"`,+ { cwd: process.cwd(), encoding: 'utf-8' }+ ));++ assert.equal(+ result.styleMode,+ 'astro-global-prefixed',+ 'event=live_wrap.astro_css_mode actor=agent operation=wrap_astro_file risk=astro_scopes_preview_css_away expected=styleMode astro-global-prefixed actual=' + result.styleMode + ' suggestion=inspect live-wrap output metadata for .astro files'+ );+ assert.deepEqual(result.cssSelectorPrefixExamples, [+ '[data-impeccable-variant="1"]',+ '[data-impeccable-variant="2"]',+ '[data-impeccable-variant="3"]',+ ]);+ assert.equal(result.cssAuthoring.mode, 'astro-global-prefixed');+ assert.equal(result.cssAuthoring.strategy, 'global-prefixed');+ assert.equal(result.cssAuthoring.styleTag, '<style is:inline data-impeccable-css="SESSION_ID">');+ assert.match(result.cssAuthoring.rulePattern, /^\[data-impeccable-variant="N"\]/);+ assert.ok(+ result.cssAuthoring.forbidden.some((item) => item.includes('@scope')),+ 'Astro-prefixed mode should explicitly reject @scope',+ );+ });});// ---------------------------------------------------------------------------