Skip to content

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

JavaScript

Replace WebSocket with SSE, move live scripts into skill (self-contained)

Paul Bakaus5bad08723d20
diff --git a/.agents/skills/impeccable/reference/live.md b/.agents/skills/impeccable/reference/live.md
index 53b64a21a..ba0e9b0c5 100644
--- a/.agents/skills/impeccable/reference/live.md
+++ b/.agents/skills/impeccable/reference/live.md
@@ -10,7 +10,7 @@ Launch interactive live variant mode: select elements in the browser, pick a des
1. Read `.impeccable.md` if it exists. Keep the design context in mind for variant generation.
2. Start the live variant server:
```bash
- npx impeccable live &
+ node {{scripts_path}}/live-server.mjs &
```
3. Note the **port** and **token** printed to stdout.
@@ -53,7 +53,7 @@ Run a blocking poll loop. On each iteration, wait for a browser event and respon
```
LOOP:
- Run: npx impeccable poll
+ Run: node {{scripts_path}}/live-poll.mjs
Read the JSON output. Dispatch based on the "type" field:
TYPE "generate":
@@ -85,7 +85,7 @@ The event contains: `{id, action, freeformPrompt, count, pageUrl, element}`.
Use the `wrap` helper to find the element and create the variant container:
```bash
-npx impeccable wrap --id EVENT_ID --count EVENT_COUNT --element-id "ELEMENT_ID" --classes "class1,class2" --tag "div"
+node {{scripts_path}}/live-wrap.mjs --id EVENT_ID --count EVENT_COUNT --element-id "ELEMENT_ID" --classes "class1,class2" --tag "div"
```
Pass the element's id (`event.element.id`), classes (`event.element.classes` joined with commas), and tag name. The command searches in priority order: ID match first, then class names, then tag+class combo. If `event.pageUrl` hints at the file (e.g., `/` is usually `index.html`), pass `--file PATH` to skip the search.
@@ -136,10 +136,14 @@ The first variant should NOT have `style="display: none"` (it should be visible
### Step 3: Signal completion
+Include `--file` so the browser can fetch variants directly if the dev server lacks HMR:
+
```bash
-npx impeccable poll --reply EVENT_ID done
+node {{scripts_path}}/live-poll.mjs --reply EVENT_ID done --file RELATIVE_PATH
```
+The file path should be relative to the project root (e.g., `public/index.html`, `src/App.tsx`).
+
## Handle Accept
The event contains: `{id, variantId}`.
@@ -151,7 +155,7 @@ The user accepted a specific variant. For v1 (inspection mode):
4. Remove any scoped CSS blocks (between `impeccable-variants-css-start` and `impeccable-variants-css-end` markers).
5. Reply:
```bash
- npx impeccable poll --reply SESSION_ID done
+ node {{scripts_path}}/live-poll.mjs --reply SESSION_ID done
```
## Handle Discard
@@ -163,7 +167,7 @@ The event contains: `{id}`.
3. Remove any scoped CSS blocks for this session.
4. Reply:
```bash
- npx impeccable poll --reply SESSION_ID done
+ node {{scripts_path}}/live-poll.mjs --reply SESSION_ID done
```
## Cleanup (on exit)
@@ -174,7 +178,7 @@ When the loop ends:
2. **Remove any leftover variant wrappers** (search for `impeccable-variants-start` markers and clean up).
3. **Stop the server**:
```bash
- npx impeccable live stop
+ node {{scripts_path}}/live-server.mjs stop
```
## Variant Generation Guidelines
diff --git a/.agents/skills/impeccable/scripts/live-browser.js b/.agents/skills/impeccable/scripts/live-browser.js
new file mode 100644
index 000000000..7a26c9829
--- /dev/null
+++ b/.agents/skills/impeccable/scripts/live-browser.js
@@ -0,0 +1,1220 @@
+/**
+ * Impeccable Live Variant Mode — Browser Script
+ *
+ * Injected into the user's page via <script src="http://localhost:PORT/live.js">.
+ * The server prepends window.__IMPECCABLE_TOKEN__ and window.__IMPECCABLE_PORT__
+ * before this code.
+ *
+ * UI: a single floating bar that morphs between three states —
+ * configure (pick action + go), generating (progressive dots), and cycling
+ * (prev/next + accept/discard). Feels like Spotlight, not a modal.
+ */
+(function () {
+ 'use strict';
+ if (typeof window === 'undefined') return;
+
+ // Guard against double-init. Bun's HTML loader may process the <script> tag
+ // and create a bundled copy alongside the external load, or HMR may re-execute.
+ // Check BEFORE reading token/port to catch all cases.
+ if (window.__IMPECCABLE_LIVE_INIT__) return;
+ window.__IMPECCABLE_LIVE_INIT__ = true;
+
+ const TOKEN = window.__IMPECCABLE_TOKEN__;
+ const PORT = window.__IMPECCABLE_PORT__;
+ if (!TOKEN || !PORT) {
+ window.__IMPECCABLE_LIVE_INIT__ = false; // reset so the real load can init
+ return;
+ }
+
+ // ---------------------------------------------------------------------------
+ // Design tokens
+ // ---------------------------------------------------------------------------
+
+ const C = {
+ brand: 'oklch(55% 0.25 350)',
+ brandHov: 'oklch(48% 0.25 350)',
+ brandSoft: 'oklch(55% 0.25 350 / 0.12)',
+ ink: 'oklch(15% 0.01 350)',
+ ash: 'oklch(55% 0 0)',
+ paper: 'oklch(98% 0.005 350 / 0.92)',
+ paperSolid:'oklch(98% 0.005 350)',
+ mist: 'oklch(90% 0.01 350 / 0.6)',
+ white: 'oklch(99% 0 0)',
+ };
+ const FONT = 'system-ui, -apple-system, sans-serif';
+ const MONO = 'ui-monospace, SFMono-Regular, Menlo, monospace';
+ const Z = { highlight: 99990, bar: 99995, picker: 99997, toast: 99999 };
+ const EASE = 'cubic-bezier(0.22, 1, 0.36, 1)'; // ease-out-quint
+ const PREFIX = 'impeccable-live';
+
+ const SKIP_TAGS = new Set([
+ 'html', 'head', 'body', 'script', 'style', 'link', 'meta', 'noscript', 'br', 'wbr',
+ ]);
+
+ const ACTIONS = [
+ { value: 'impeccable', label: 'Freeform' },
+ { value: 'bolder', label: 'Bolder' },
+ { value: 'quieter', label: 'Quieter' },
+ { value: 'distill', label: 'Distill' },
+ { value: 'polish', label: 'Polish' },
+ { value: 'typeset', label: 'Typeset' },
+ { value: 'colorize', label: 'Colorize' },
+ { value: 'layout', label: 'Layout' },
+ { value: 'adapt', label: 'Adapt' },
+ { value: 'animate', label: 'Animate' },
+ { value: 'delight', label: 'Delight' },
+ { value: 'overdrive', label: 'Overdrive' },
+ ];
+
+ // ---------------------------------------------------------------------------
+ // State
+ // ---------------------------------------------------------------------------
+
+ let state = 'IDLE';
+ let hoveredElement = null;
+ let selectedElement = null;
+ let currentSessionId = null;
+ let expectedVariants = 0;
+ let arrivedVariants = 0;
+ let visibleVariant = 0;
+ let variantObserver = null;
+ let hasProjectContext = false;
+ let selectedAction = 'impeccable';
+ let selectedCount = 3;
+
+ // UI refs
+ let highlightEl = null;
+ let tooltipEl = null;
+ let barEl = null;
+ let pickerEl = null;
+ let toastEl = null;
+ let scrollRaf = null;
+
+ // ---------------------------------------------------------------------------
+ // Helpers
+ // ---------------------------------------------------------------------------
+
+ function own(el) {
+ return el && (el.id?.startsWith(PREFIX) || el.closest?.('[id^="' + PREFIX + '"]'));
+ }
+
+ function pickable(el) {
+ if (!el || el.nodeType !== 1) return false;
+ if (SKIP_TAGS.has(el.tagName.toLowerCase())) return false;
+ if (own(el)) return false;
+ const r = el.getBoundingClientRect();
+ return r.width >= 20 && r.height >= 20;
+ }
+
+ function desc(el) {
+ if (!el) return '';
+ let s = el.tagName.toLowerCase();
+ if (el.id) s += '#' + el.id;
+ else if (el.classList.length) s += '.' + [...el.classList].slice(0, 2).join('.');
+ return s;
+ }
+
+ function id8() { return crypto.randomUUID().replace(/-/g, '').slice(0, 8); }
+
+ // ---------------------------------------------------------------------------
+ // Highlight overlay
+ // ---------------------------------------------------------------------------
+
+ function initHighlight() {
+ highlightEl = document.createElement('div');
+ highlightEl.id = PREFIX + '-highlight';
+ Object.assign(highlightEl.style, {
+ position: 'fixed', top: '0', left: '0', width: '0', height: '0',
+ border: '2px solid ' + C.brand, borderRadius: '3px',
+ pointerEvents: 'none', zIndex: Z.highlight, boxSizing: 'border-box',
+ transition: 'top 0.08s ease, left 0.08s ease, width 0.08s ease, height 0.08s ease, opacity 0.15s ease',
+ display: 'none', opacity: '0',
+ });
+ document.body.appendChild(highlightEl);
+
+ tooltipEl = document.createElement('div');
+ tooltipEl.id = PREFIX + '-tooltip';
+ Object.assign(tooltipEl.style, {
+ position: 'fixed',
+ background: C.ink, color: C.white,
+ fontFamily: MONO, fontSize: '10px', fontWeight: '500',
+ padding: '2px 6px', borderRadius: '3px',
+ zIndex: Z.highlight + 1, pointerEvents: 'none',
+ whiteSpace: 'nowrap', display: 'none',
+ letterSpacing: '0.02em',
+ });
+ document.body.appendChild(tooltipEl);
+ }
+
+ function showHighlight(el) {
+ if (!el || !highlightEl) return;
+ const r = el.getBoundingClientRect();
+ Object.assign(highlightEl.style, {
+ top: (r.top - 2) + 'px', left: (r.left - 2) + 'px',
+ width: (r.width + 4) + 'px', height: (r.height + 4) + 'px',
+ display: 'block', opacity: '1',
+ });
+ tooltipEl.textContent = desc(el);
+ const tipTop = r.top - 20;
+ Object.assign(tooltipEl.style, {
+ top: (tipTop < 4 ? r.bottom + 4 : tipTop) + 'px',
+ left: Math.max(4, r.left) + 'px', display: 'block',
+ });
+ }
+
+ function hideHighlight() {
+ if (highlightEl) { highlightEl.style.opacity = '0'; highlightEl.style.display = 'none'; }
+ if (tooltipEl) tooltipEl.style.display = 'none';
+ }
+
+ // ---------------------------------------------------------------------------
+ // Element context extraction
+ // ---------------------------------------------------------------------------
+
+ function extractContext(el) {
+ const cs = getComputedStyle(el);
+ const r = el.getBoundingClientRect();
+ const props = {};
+ for (const sheet of document.styleSheets) {
+ try {
+ for (const rule of sheet.cssRules) {
+ if (rule.style) for (let i = 0; i < rule.style.length; i++) {
+ const p = rule.style[i];
+ if (p.startsWith('--') && !props[p]) {
+ const v = cs.getPropertyValue(p).trim();
+ if (v) props[p] = v;
+ }
+ }
+ }
+ } catch { /* cross-origin */ }
+ }
+ return {
+ tagName: el.tagName.toLowerCase(), id: el.id || null,
+ classes: [...el.classList],
+ textContent: (el.textContent || '').slice(0, 500),
+ outerHTML: el.outerHTML.slice(0, 10000),
+ computedStyles: {
+ 'font-family': cs.fontFamily, 'font-size': cs.fontSize,
+ 'font-weight': cs.fontWeight, 'line-height': cs.lineHeight,
+ 'color': cs.color, 'background': cs.background,
+ 'background-color': cs.backgroundColor,
+ 'padding': cs.padding, 'margin': cs.margin,
+ 'display': cs.display, 'position': cs.position,
+ 'gap': cs.gap, 'border-radius': cs.borderRadius,
+ 'box-shadow': cs.boxShadow,
+ },
+ cssCustomProperties: props,
+ parentContext: el.parentElement
+ ? '<' + el.parentElement.tagName.toLowerCase()
+ + (el.parentElement.id ? ' id="' + el.parentElement.id + '"' : '')
+ + (el.parentElement.className ? ' class="' + el.parentElement.className + '"' : '')
+ + '>'
+ : null,
+ boundingRect: { width: Math.round(r.width), height: Math.round(r.height) },
+ };
+ }
+
+ // ---------------------------------------------------------------------------
+ // The Bar — one floating element, three modes
+ // ---------------------------------------------------------------------------
+
+ function initBar() {
+ barEl = document.createElement('div');
+ barEl.id = PREFIX + '-bar';
+ Object.assign(barEl.style, {
+ position: 'fixed', zIndex: Z.bar,
+ display: 'none', opacity: '0',
+ transform: 'translateY(6px)',
+ transition: 'opacity 0.25s ' + EASE + ', transform 0.3s ' + EASE,
+ // Visual
+ background: C.paper,
+ backdropFilter: 'blur(16px)', WebkitBackdropFilter: 'blur(16px)',
+ border: '1px solid ' + C.mist,
+ borderRadius: '10px',
+ boxShadow: '0 4px 20px oklch(0% 0 0 / 0.08), 0 1px 3px oklch(0% 0 0 / 0.06)',
+ fontFamily: FONT, fontSize: '13px', color: C.ink,
+ padding: '6px',
+ maxWidth: '460px', minWidth: '320px',
+ });
+ document.body.appendChild(barEl);
+ }
+
+ function positionBar() {
+ if (!barEl || !selectedElement) return;
+ const r = selectedElement.getBoundingClientRect();
+ const barH = barEl.offsetHeight || 44;
+ const barW = barEl.offsetWidth || 380;
+ let top = r.bottom + 8;
+ let left = r.left + (r.width - barW) / 2;
+ // Keep in viewport
+ if (top + barH + 8 > window.innerHeight) top = r.top - barH - 8;
+ if (top < 8) top = 8;
+ if (left < 8) left = 8;
+ if (left + barW > window.innerWidth - 8) left = window.innerWidth - barW - 8;
+ Object.assign(barEl.style, { top: top + 'px', left: left + 'px' });
+ }
+
+ function showBar(mode) {
+ barEl.innerHTML = '';
+ if (mode === 'configure') barEl.appendChild(buildConfigureRow());
+ else if (mode === 'generating') barEl.appendChild(buildGeneratingRow());
+ else if (mode === 'cycling') barEl.appendChild(buildCyclingRow());
+ barEl.style.display = 'block';
+ positionBar();
+ requestAnimationFrame(() => {
+ barEl.style.opacity = '1';
+ barEl.style.transform = 'translateY(0)';
+ });
+ }
+
+ function hideBar() {
+ if (!barEl) return;
+ barEl.style.opacity = '0';
+ barEl.style.transform = 'translateY(6px)';
+ setTimeout(() => { if (barEl) barEl.style.display = 'none'; }, 250);
+ hideActionPicker();
+ }
+
+ function updateBarContent(mode) {
+ if (!barEl || barEl.style.display === 'none') return;
+ barEl.innerHTML = '';
+ // Reset bar styling
+ barEl.style.background = C.paper;
+ barEl.style.border = '1px solid ' + C.mist;
+ if (mode === 'configure') barEl.appendChild(buildConfigureRow());
+ else if (mode === 'generating') barEl.appendChild(buildGeneratingRow());
+ else if (mode === 'cycling') barEl.appendChild(buildCyclingRow());
+ else if (mode === 'saving') barEl.appendChild(buildSavingRow());
+ else if (mode === 'confirmed') {
+ barEl.appendChild(buildConfirmedRow());
+ barEl.style.background = 'oklch(95% 0.05 145)';
+ barEl.style.border = '1px solid oklch(75% 0.12 145 / 0.4)';
+ }
+ }
+
+ // --- Configure row ---
+
+ function buildConfigureRow() {
+ const row = el('div', {
+ display: 'flex', alignItems: 'center', gap: '4px',
+ });
+
+ // Action pill
+ const pill = el('button', {
+ display: 'inline-flex', alignItems: 'center', gap: '4px',
+ padding: '5px 10px', borderRadius: '6px',
+ background: C.ink, color: C.white,
+ fontFamily: FONT, fontSize: '12px', fontWeight: '500',
+ border: 'none', cursor: 'pointer',
+ transition: 'background 0.12s ease, transform 0.1s ease',
+ whiteSpace: 'nowrap', flexShrink: '0',
+ });
+ pill.textContent = actionLabel() + ' \u25BE';
+ pill.addEventListener('mouseenter', () => pill.style.background = C.brandHov);
+ pill.addEventListener('mouseleave', () => pill.style.background = C.ink);
+ pill.addEventListener('mousedown', () => pill.style.transform = 'scale(0.97)');
+ pill.addEventListener('mouseup', () => pill.style.transform = 'scale(1)');
+ pill.addEventListener('click', (e) => { e.stopPropagation(); toggleActionPicker(); });
+ row.appendChild(pill);
+
+ // Freeform input
+ const input = document.createElement('input');
+ input.id = PREFIX + '-input';
+ input.type = 'text';
+ input.placeholder = selectedAction === 'impeccable' ? 'describe what you want...' : 'refine further (optional)...';
+ Object.assign(input.style, {
+ flex: '1', minWidth: '0',
+ padding: '5px 8px', borderRadius: '6px',
+ border: '1px solid transparent', background: 'transparent',
+ fontFamily: FONT, fontSize: '12px', color: C.ink,
+ outline: 'none',
+ transition: 'border-color 0.15s ease, background 0.15s ease',
+ });
+ input.addEventListener('focus', () => {
+ input.style.borderColor = C.mist;
+ input.style.background = C.white;
+ });
+ input.addEventListener('blur', () => {
+ input.style.borderColor = 'transparent';
+ input.style.background = 'transparent';
+ });
+ input.addEventListener('keydown', (e) => {
+ e.stopPropagation(); // Don't trigger element picker keyboard nav
+ if (e.key === 'Enter') { e.preventDefault(); handleGo(); }
+ if (e.key === 'Escape') { e.preventDefault(); input.blur(); hideBar(); state = 'PICKING'; }
+ });
+ row.appendChild(input);
+
+ // Variant count toggle
+ const count = el('button', {
+ padding: '4px 6px', borderRadius: '5px',
+ border: '1px solid ' + C.mist, background: 'transparent',
+ fontFamily: MONO, fontSize: '11px', fontWeight: '600',
+ color: C.ash, cursor: 'pointer',
+ transition: 'color 0.12s ease, border-color 0.12s ease',
+ flexShrink: '0', whiteSpace: 'nowrap',
+ });
+ count.textContent = '\u00D7' + selectedCount;
+ count.title = 'Variants: click to change';
+ count.addEventListener('mouseenter', () => { count.style.color = C.ink; count.style.borderColor = C.ink; });
+ count.addEventListener('mouseleave', () => { count.style.color = C.ash; count.style.borderColor = C.mist; });
+ count.addEventListener('click', (e) => {
+ e.stopPropagation();
+ selectedCount = selectedCount >= 4 ? 2 : selectedCount + 1;
+ count.textContent = '\u00D7' + selectedCount;
+ });
+ row.appendChild(count);
+
+ // Go button
+ const go = el('button', {
+ padding: '5px 12px', borderRadius: '6px',
+ border: 'none', background: C.brand, color: C.white,
+ fontFamily: FONT, fontSize: '12px', fontWeight: '600',
+ cursor: 'pointer',
+ transition: 'background 0.12s ease, transform 0.1s ease',
+ flexShrink: '0', whiteSpace: 'nowrap',
+ });
+ go.textContent = 'Go \u2192';
+ go.addEventListener('mouseenter', () => go.style.background = C.brandHov);
+ go.addEventListener('mouseleave', () => go.style.background = C.brand);
+ go.addEventListener('mousedown', () => go.style.transform = 'scale(0.97)');
+ go.addEventListener('mouseup', () => go.style.transform = 'scale(1)');
+ go.addEventListener('click', (e) => { e.stopPropagation(); handleGo(); });
+ row.appendChild(go);
+
+ // Auto-focus input after a beat
+ setTimeout(() => input.focus(), 60);
+ return row;
+ }
+
+ // --- Generating row ---
+
+ function buildGeneratingRow() {
+ const row = el('div', {
+ display: 'flex', alignItems: 'center', gap: '8px',
+ padding: '2px 4px',
+ });
+
+ // Action label
+ const label = el('span', {
+ fontWeight: '600', fontSize: '12px', color: C.ink,
+ flexShrink: '0', whiteSpace: 'nowrap',
+ });
+ label.textContent = actionLabel();
+ row.appendChild(label);
+
+ // Dots
+ row.appendChild(buildDots(false));
+
+ // Status
+ const status = el('span', {
+ fontSize: '11px', color: C.ash, whiteSpace: 'nowrap',
+ marginLeft: 'auto',
+ });
+ status.textContent = arrivedVariants < expectedVariants
+ ? 'Generating ' + (arrivedVariants + 1) + ' of ' + expectedVariants + '...'
+ : 'Done';
+ row.appendChild(status);
+
+ return row;
+ }
+
+ // --- Cycling row ---
+
+ function buildCyclingRow() {
+ const row = el('div', {
+ display: 'flex', alignItems: 'center', gap: '6px',
+ padding: '1px 2px',
+ });
+
+ // Prev
+ const prev = navBtn('\u2190');
+ prev.addEventListener('click', (e) => { e.stopPropagation(); cycleVariant(-1); });
+ if (visibleVariant <= 1) prev.style.opacity = '0.3';
+ row.appendChild(prev);
+
+ // Dots (clickable)
+ row.appendChild(buildDots(true));
+
+ // Counter
+ const counter = el('span', {
+ fontFamily: MONO, fontSize: '11px', fontWeight: '500',
+ color: C.ash, minWidth: '24px', textAlign: 'center',
+ });
+ counter.textContent = visibleVariant + '/' + arrivedVariants;
+ row.appendChild(counter);
+
+ // Next
+ const next = navBtn('\u2192');
+ next.addEventListener('click', (e) => { e.stopPropagation(); cycleVariant(1); });
+ if (visibleVariant >= arrivedVariants) next.style.opacity = '0.3';
+ row.appendChild(next);
+
+ // Spacer
+ row.appendChild(el('div', { flex: '1' }));
+
+ // Accept
+ const accept = el('button', {
+ padding: '4px 10px', borderRadius: '5px',
+ border: 'none', background: C.ink, color: C.white,
+ fontFamily: FONT, fontSize: '11px', fontWeight: '600',
+ cursor: 'pointer', transition: 'background 0.12s ease',
+ whiteSpace: 'nowrap',
+ });
+ accept.textContent = '\u2713 Accept';
+ accept.addEventListener('mouseenter', () => accept.style.background = C.brand);
+ accept.addEventListener('mouseleave', () => accept.style.background = C.ink);
+ accept.addEventListener('click', (e) => { e.stopPropagation(); handleAccept(); });
+ if (arrivedVariants === 0) { accept.style.opacity = '0.3'; accept.style.pointerEvents = 'none'; }
+ row.appendChild(accept);
+
+ // Discard
+ const discard = el('button', {
+ padding: '4px 6px', borderRadius: '5px',
+ border: '1px solid ' + C.mist, background: 'transparent',
+ fontFamily: FONT, fontSize: '11px', color: C.ash,
+ cursor: 'pointer', transition: 'color 0.12s ease, border-color 0.12s ease',
+ });
+ discard.textContent = '\u2715';
+ discard.title = 'Discard all variants';
+ discard.addEventListener('mouseenter', () => { discard.style.color = C.ink; discard.style.borderColor = C.ink; });
+ discard.addEventListener('mouseleave', () => { discard.style.color = C.ash; discard.style.borderColor = C.mist; });
+ discard.addEventListener('click', (e) => { e.stopPropagation(); handleDiscard(); });
+ row.appendChild(discard);
+
+ return row;
+ }
+
+ // --- Shared UI builders ---
+
+ // --- Saving row (waiting for agent to process accept/discard) ---
+
+ function buildSavingRow() {
+ const row = el('div', {
+ display: 'flex', alignItems: 'center', gap: '8px',
+ padding: '2px 8px',
+ });
+ const spinner = el('div', {
+ width: '14px', height: '14px', borderRadius: '50%',
+ border: '2px solid ' + C.mist,
+ borderTopColor: C.brand,
+ animation: 'impeccable-spin 0.6s linear infinite',
+ flexShrink: '0',
+ });
+ row.appendChild(spinner);
+ const label = el('span', {
+ fontSize: '12px', color: C.ash, fontWeight: '500',
+ });
+ label.textContent = 'Applying variant...';
+ row.appendChild(label);
+
+ // Inject the keyframes if not already present
+ if (!document.getElementById(PREFIX + '-keyframes')) {
+ const style = document.createElement('style');
+ style.id = PREFIX + '-keyframes';
+ style.textContent = '@keyframes impeccable-spin { to { transform: rotate(360deg); } }';
+ document.head.appendChild(style);
+ }
+ return row;
+ }
+
+ // --- Confirmed row (green success, auto-dismisses) ---
+
+ function buildConfirmedRow() {
+ const row = el('div', {
+ display: 'flex', alignItems: 'center', gap: '8px',
+ padding: '2px 8px',
+ });
+ const check = el('span', {
+ fontSize: '15px', lineHeight: '1', flexShrink: '0',
+ color: 'oklch(45% 0.15 145)',
+ });
+ check.textContent = '\u2713';
+ row.appendChild(check);
+ const label = el('span', {
+ fontSize: '12px', color: 'oklch(35% 0.1 145)', fontWeight: '600',
+ });
+ label.textContent = 'Variant applied';
+ row.appendChild(label);
+ return row;
+ }
+
+ // --- Shared UI builders ---
+
+ function buildDots(clickable) {
+ const container = el('div', {
+ display: 'flex', alignItems: 'center', gap: '4px',
+ });
+ for (let i = 1; i <= expectedVariants; i++) {
+ const arrived = i <= arrivedVariants;
+ const active = i === visibleVariant;
+ const dot = el('div', {
+ width: '7px', height: '7px', borderRadius: '50%',
+ background: active ? C.brand : (arrived ? C.ash : 'transparent'),
+ border: '1.5px solid ' + (arrived ? C.brand : C.mist),
+ transition: 'all 0.2s ' + EASE,
+ cursor: (clickable && arrived) ? 'pointer' : 'default',
+ transform: arrived ? 'scale(1)' : 'scale(0.6)',
+ opacity: arrived ? '1' : '0.4',
+ });
+ if (clickable && arrived) {
+ const idx = i;
+ dot.addEventListener('click', (e) => {
+ e.stopPropagation();
+ visibleVariant = idx;
+ showVariantInDOM(currentSessionId, idx);
+ updateSelectedElement();
+ updateBarContent('cycling');
+ });
+ }
+ container.appendChild(dot);
+ }
+ return container;
+ }
+
+ function navBtn(text) {
+ const b = el('button', {
+ width: '26px', height: '26px', borderRadius: '5px',
+ border: '1px solid ' + C.mist, background: 'transparent',
+ color: C.ink, fontFamily: FONT, fontSize: '13px',
+ cursor: 'pointer', display: 'flex', alignItems: 'center', justifyContent: 'center',
+ transition: 'border-color 0.12s ease, background 0.12s ease',
+ padding: '0', lineHeight: '1',
+ });
+ b.textContent = text;
+ b.addEventListener('mouseenter', () => { b.style.borderColor = C.ink; });
+ b.addEventListener('mouseleave', () => { b.style.borderColor = C.mist; });
+ return b;
+ }
+
+ function actionLabel() {
+ const a = ACTIONS.find(a => a.value === selectedAction);
+ return a ? a.label : 'Freeform';
+ }
+
+ function el(tag, styles) {
+ const e = document.createElement(tag);
+ if (styles) Object.assign(e.style, styles);
+ return e;
+ }
+
+ // ---------------------------------------------------------------------------
+ // Action picker popover
+ // ---------------------------------------------------------------------------
+
+ function initActionPicker() {
+ pickerEl = document.createElement('div');
+ pickerEl.id = PREFIX + '-picker';
+ Object.assign(pickerEl.style, {
+ position: 'fixed', zIndex: Z.picker,
+ display: 'none', opacity: '0',
+ transform: 'scale(0.96) translateY(4px)',
+ transformOrigin: 'bottom left',
+ transition: 'opacity 0.18s ' + EASE + ', transform 0.2s ' + EASE,
+ background: C.paperSolid,
+ border: '1px solid ' + C.mist,
+ borderRadius: '10px',
+ boxShadow: '0 8px 30px oklch(0% 0 0 / 0.10), 0 2px 6px oklch(0% 0 0 / 0.06)',
+ padding: '6px',
+ fontFamily: FONT,
+ });
+
+ // Build the chip grid
+ const grid = el('div', {
+ display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', gap: '3px',
+ });
+
+ ACTIONS.forEach(action => {
+ const chip = el('button', {
+ padding: '6px 8px', borderRadius: '6px',
+ border: 'none',
+ background: action.value === selectedAction ? C.brandSoft : 'transparent',
+ color: action.value === selectedAction ? C.brand : C.ink,
+ fontFamily: FONT, fontSize: '11px', fontWeight: '500',
+ cursor: 'pointer',
+ transition: 'background 0.1s ease, color 0.1s ease',
+ textAlign: 'center', whiteSpace: 'nowrap',
+ });
+ chip.textContent = action.label;
+ chip.dataset.action = action.value;
+ chip.addEventListener('mouseenter', () => {
+ if (action.value !== selectedAction) chip.style.background = C.brandSoft;
+ });
+ chip.addEventListener('mouseleave', () => {
+ chip.style.background = action.value === selectedAction ? C.brandSoft : 'transparent';
+ });
+ chip.addEventListener('click', (e) => {
+ e.stopPropagation();
+ selectedAction = action.value;
+ hideActionPicker();
+ updateBarContent('configure');
+ });
+ grid.appendChild(chip);
+ });
+
+ pickerEl.appendChild(grid);
+ document.body.appendChild(pickerEl);
+ }
+
+ function toggleActionPicker() {
+ if (pickerEl.style.display !== 'none') { hideActionPicker(); return; }
+ // Rebuild chips to reflect current selection
+ pickerEl.querySelectorAll('button').forEach(chip => {
+ const isActive = chip.dataset.action === selectedAction;
+ chip.style.background = isActive ? C.brandSoft : 'transparent';
+ chip.style.color = isActive ? C.brand : C.ink;
+ });
+ // Position above the bar
+ const barRect = barEl.getBoundingClientRect();
+ const pickerH = 90; // approximate
+ let top = barRect.top - pickerH - 6;
+ if (top < 8) top = barRect.bottom + 6;
+ Object.assign(pickerEl.style, {
+ top: top + 'px', left: barRect.left + 'px',
+ display: 'block',
+ });
+ requestAnimationFrame(() => {
+ pickerEl.style.opacity = '1';
+ pickerEl.style.transform = 'scale(1) translateY(0)';
+ });
+ }
+
+ function hideActionPicker() {
+ if (!pickerEl) return;
+ pickerEl.style.opacity = '0';
+ pickerEl.style.transform = 'scale(0.96) translateY(4px)';
+ setTimeout(() => { if (pickerEl) pickerEl.style.display = 'none'; }, 180);
+ }
+
+ // ---------------------------------------------------------------------------
+ // Variant cycling in DOM
+ // ---------------------------------------------------------------------------
+
+ function showVariantInDOM(sessionId, num) {
+ const wrapper = document.querySelector('[data-impeccable-variants="' + sessionId + '"]');
+ if (!wrapper) return;
+ for (const child of wrapper.children) {
+ const v = child.dataset ? child.dataset.impeccableVariant : null;
+ if (!v) continue;
+ child.style.display = (v === String(num)) ? '' : 'none';
+ }
+ }
+
+ /**
+ * No-HMR fallback: fetch the raw source file from the live server,
+ * parse it, extract the variant wrapper, and inject it into the live DOM.
+ * This works even when the dev server caches HTML (Bun, static servers).
+ */
+ function injectVariantsFromSource(filePath, sessionId) {
+ const url = 'http://localhost:' + PORT + '/source?token=' + TOKEN + '&path=' + encodeURIComponent(filePath);
+ fetch(url)
+ .then(r => { if (!r.ok) throw new Error(r.status); return r.text(); })
+ .then(html => {
+ // Parse the raw source HTML
+ const parser = new DOMParser();
+ const doc = parser.parseFromString(html, 'text/html');
+ const srcWrapper = doc.querySelector('[data-impeccable-variants="' + sessionId + '"]');
+ if (!srcWrapper) {
+ console.error('[impeccable] Variant wrapper not found in source file.');
+ return;
+ }
+
+ // Find the original element in the live DOM.
+ // The original is inside the wrapper in the source. We find the
+ // corresponding element in the live DOM by matching the first child's
+ // tag + classes from the original snapshot.
+ const origContent = srcWrapper.querySelector('[data-impeccable-variant="original"] > :first-child');
+ if (!origContent) return;
+
+ const tag = origContent.tagName.toLowerCase();
+ const cls = origContent.className;
+ let liveEl = null;
+ if (origContent.id) {
+ liveEl = document.getElementById(origContent.id);
+ } else if (cls) {
+ // Find by tag + exact class match
+ const candidates = document.querySelectorAll(tag + '.' + cls.split(' ')[0]);
+ for (const c of candidates) {
+ if (c.className === cls && !own(c)) { liveEl = c; break; }
+ }
+ }
+
+ if (!liveEl) {
+ console.error('[impeccable] Could not find original element in live DOM.');
+ return;
+ }
+
+ // Replace the live element with the full wrapper from source
+ const wrapper = srcWrapper.cloneNode(true);
+ liveEl.parentElement.replaceChild(wrapper, liveEl);
+
+ // Update state: count variants, show the first one
+ 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);
+
+ // Update selectedElement to the visible variant's content
+ const visEl = wrapper.querySelector('[data-impeccable-variant="1"] > :first-child');
+ selectedElement = visEl || wrapper.parentElement;
+
+ state = 'CYCLING';
+ updateBarContent('cycling');
+ saveSession();
+ console.log('[impeccable] Injected ' + arrivedVariants + ' variants from source file.');
+ })
+ .catch(err => {
+ console.error('[impeccable] Failed to fetch source:', err);
+ showToast('Could not load variants. Try refreshing the page.', 5000);
+ });
+ }
+
+ function cycleVariant(dir) {
+ const next = visibleVariant + dir;
+ if (next < 1 || next > arrivedVariants) return;
+ visibleVariant = next;
+ showVariantInDOM(currentSessionId, next);
+ updateSelectedElement();
+ updateBarContent('cycling');
+ saveSession();
+ }
+
+ function updateSelectedElement() {
+ if (!currentSessionId) return;
+ const wrapper = document.querySelector('[data-impeccable-variants="' + currentSessionId + '"]');
+ if (!wrapper) return;
+ const visEl = wrapper.querySelector('[data-impeccable-variant="' + visibleVariant + '"] > :first-child');
+ if (visEl) selectedElement = visEl;
+ }
+
+ // ---------------------------------------------------------------------------
+ // MutationObserver for progressive variant reveal
+ // ---------------------------------------------------------------------------
+
+ function startVariantObserver(sessionId) {
+ let updating = false; // re-entrancy guard
+
+ const obs = new MutationObserver((mutations) => {
+ if (updating) return;
+
+ // Only react to mutations that add nodes with data-impeccable-variant,
+ // or mutations inside the variant wrapper. Ignore our own bar/UI changes.
+ let dominated = false;
+ for (const m of mutations) {
+ if (m.target.closest?.('[data-impeccable-variants]')) { dominated = true; break; }
+ for (const n of m.addedNodes) {
+ if (n.nodeType === 1 && (n.dataset?.impeccableVariants || n.dataset?.impeccableVariant)) {
+ dominated = true; break;
+ }
+ }
+ if (dominated) break;
+ }
+ if (!dominated) return;
+
+ const wrapper = document.querySelector('[data-impeccable-variants="' + sessionId + '"]');
+ if (!wrapper) return;
+
+ const variants = wrapper.querySelectorAll('[data-impeccable-variant]:not([data-impeccable-variant="original"])');
+ const count = variants.length;
+
+ // Nothing new
+ if (count <= arrivedVariants) return;
+
+ updating = true;
+ arrivedVariants = count;
+ if (visibleVariant === 0 && arrivedVariants > 0) {
+ visibleVariant = 1;
+ showVariantInDOM(sessionId, 1);
+ }
+
+ const expected = parseInt(wrapper.dataset.impeccableVariantCount || '0');
+ if (expected > 0) expectedVariants = expected;
+
+ if (arrivedVariants >= expectedVariants && expectedVariants > 0) {
+ state = 'CYCLING';
+ updateBarContent('cycling');
+ } else if (state === 'GENERATING') {
+ updateBarContent('generating');
+ }
+ saveSession();
+ updating = false;
+ });
+
+ obs.observe(document.body, { childList: true, subtree: true });
+ return obs;
+ }
+
+ // ---------------------------------------------------------------------------
+ // Bar scroll tracking
+ // ---------------------------------------------------------------------------
+
+ function startScrollTracking() {
+ function tick() {
+ if (state === 'CONFIGURING' || state === 'GENERATING' || state === 'CYCLING') {
+ positionBar();
+ showHighlight(selectedElement);
+ }
+ scrollRaf = requestAnimationFrame(tick);
+ }
+ scrollRaf = requestAnimationFrame(tick);
+ }
+
+ function stopScrollTracking() {
+ if (scrollRaf) { cancelAnimationFrame(scrollRaf); scrollRaf = null; }
+ }
+
+ // ---------------------------------------------------------------------------
+ // SSE (server→browser) + fetch POST (browser→server)
+ // Zero-dependency replacement for WebSocket.
+ // ---------------------------------------------------------------------------
+
+ let evtSource = null;
+
+ function connectSSE() {
+ evtSource = new EventSource('http://localhost:' + PORT + '/events?token=' + TOKEN);
+
+ evtSource.onmessage = (e) => {
+ let msg; try { msg = JSON.parse(e.data); } catch { return; }
+ switch (msg.type) {
+ case 'connected':
+ hasProjectContext = !!msg.hasProjectContext;
+ if (!hasProjectContext) showToast('No .impeccable.md found. Variants will be brand-agnostic.', 6000);
+ console.log('[impeccable] Live mode connected.');
+ if (state === 'IDLE') state = 'PICKING';
+ break;
+ case 'done':
+ if (state === 'SAVING') {
+ state = 'CONFIRMED';
+ updateBarContent('confirmed');
+ setTimeout(() => {
+ hideBar();
+ hideHighlight();
+ stopScrollTracking();
+ if (variantObserver) { variantObserver.disconnect(); variantObserver = null; }
+ clearSession();
+ selectedElement = null;
+ currentSessionId = null;
+ selectedAction = 'impeccable';
+ state = 'PICKING';
+ }, 1800);
+ return;
+ }
+ if (arrivedVariants === 0 && expectedVariants > 0 && msg.file) {
+ console.log('[impeccable] No HMR detected. Fetching variants from source file...');
+ injectVariantsFromSource(msg.file, currentSessionId);
+ return;
+ }
+ state = 'CYCLING';
+ updateBarContent('cycling');
+ break;
+ case 'error':
+ console.error('[impeccable] Error:', msg.message);
+ showToast('Error: ' + msg.message, 5000);
+ hideBar();
+ state = 'PICKING';
+ break;
+ }
+ };
+
+ evtSource.onerror = () => {
+ // EventSource auto-reconnects. Log once.
+ console.log('[impeccable] SSE connection lost. Reconnecting...');
+ };
+ }
+
+ function sendEvent(msg) {
+ msg.token = TOKEN;
+ 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));
+ }
+
+ // ---------------------------------------------------------------------------
+ // Event handlers
+ // ---------------------------------------------------------------------------
+
+ function handleMouseMove(e) {
+ if (state !== 'PICKING') return;
+ const target = document.elementFromPoint(e.clientX, e.clientY);
+ if (!target || !pickable(target) || target === hoveredElement) return;
+ hoveredElement = target;
+ showHighlight(target);
+ }
+
+ function handleClick(e) {
+ // Close action picker on any outside click
+ if (pickerEl?.style.display !== 'none' && !own(e.target)) {
+ hideActionPicker();
+ }
+ if (state !== 'PICKING') return;
+ if (own(e.target)) return;
+ if (!hoveredElement || !pickable(hoveredElement)) return;
+ e.preventDefault();
+ e.stopPropagation();
+ selectedElement = hoveredElement;
+ state = 'CONFIGURING';
+ showHighlight(selectedElement);
+ showBar('configure');
+ startScrollTracking();
+ }
+
+ function handleKeyDown(e) {
+ if (e.key === 'Escape') {
+ e.preventDefault();
+ if (pickerEl?.style.display !== 'none') { hideActionPicker(); return; }
+ if (state === 'CONFIGURING') { hideBar(); stopScrollTracking(); state = 'PICKING'; return; }
+ if (state === 'CYCLING') { handleDiscard(); return; }
+ if (state === 'SAVING' || state === 'CONFIRMED') return; // don't interrupt
+ if (state === 'PICKING') { hideHighlight(); state = 'IDLE'; return; }
+ }
+
+ if (state === 'PICKING' && hoveredElement) {
+ let next = null;
+ if (e.key === 'ArrowDown' && !e.shiftKey) {
+ next = hoveredElement.nextElementSibling;
+ while (next && !pickable(next)) next = next.nextElementSibling;
+ } else if (e.key === 'ArrowUp' && !e.shiftKey) {
+ next = hoveredElement.previousElementSibling;
+ while (next && !pickable(next)) next = next.previousElementSibling;
+ } else if (e.key === 'ArrowUp' && e.shiftKey) {
+ next = hoveredElement.parentElement;
+ if (next && !pickable(next)) next = null;
+ } else if (e.key === 'ArrowDown' && e.shiftKey) {
+ next = hoveredElement.firstElementChild;
+ while (next && !pickable(next)) next = next.nextElementSibling;
+ } else if (e.key === 'Enter') {
+ e.preventDefault();
+ selectedElement = hoveredElement;
+ state = 'CONFIGURING';
+ showHighlight(selectedElement);
+ showBar('configure');
+ startScrollTracking();
+ return;
+ }
+ if (next) {
+ e.preventDefault();
+ hoveredElement = next;
+ showHighlight(next);
+ next.scrollIntoView({ block: 'nearest', behavior: 'smooth' });
+ }
+ return;
+ }
+
+ if (state === 'CYCLING') {
+ if (e.key === 'ArrowLeft') { e.preventDefault(); cycleVariant(-1); }
+ if (e.key === 'ArrowRight') { e.preventDefault(); cycleVariant(1); }
+ if (e.key === 'Enter') { e.preventDefault(); handleAccept(); }
+ }
+ }
+
+ function handleGo() {
+ if (!selectedElement || state !== 'CONFIGURING') return;
+ const input = document.getElementById(PREFIX + '-input');
+ const prompt = input ? input.value.trim() : '';
+
+ currentSessionId = id8();
+ expectedVariants = selectedCount;
+ arrivedVariants = 0;
+ visibleVariant = 0;
+
+ sendEvent({
+ type: 'generate', id: currentSessionId,
+ action: selectedAction,
+ freeformPrompt: prompt || undefined,
+ count: selectedCount,
+ pageUrl: location.pathname,
+ element: extractContext(selectedElement),
+ });
+
+ state = 'GENERATING';
+ showBar('generating');
+ saveSession();
+ if (variantObserver) variantObserver.disconnect();
+ variantObserver = startVariantObserver(currentSessionId);
+ }
+
+ function handleAccept() {
+ if (!currentSessionId || arrivedVariants === 0) return;
+ sendEvent({ type: 'accept', id: currentSessionId, variantId: String(visibleVariant) });
+ markSessionHandled();
+ state = 'SAVING';
+ updateBarContent('saving');
+ // Don't cleanup yet — wait for the "done" WS message to show confirmation
+ }
+
+ function handleDiscard() {
+ if (!currentSessionId) return;
+ sendEvent({ type: 'discard', id: currentSessionId });
+ markSessionHandled();
+ state = 'SAVING';
+ updateBarContent('saving');
+ // Wait for "done" WS message to show confirmation and dismiss
+ }
+
+ // ---------------------------------------------------------------------------
+ // Session persistence via localStorage
+ // ---------------------------------------------------------------------------
+ // Survives page reloads, browser close/reopen, HMR, and accidental refreshes.
+
+ const LS_KEY = PREFIX + '-session';
+
+ function saveSession() {
+ if (!currentSessionId) return;
+ 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 */ }
+ }
+
+ function loadSession() {
+ try {
+ const raw = localStorage.getItem(LS_KEY);
+ return raw ? JSON.parse(raw) : null;
+ } catch { return null; }
+ }
+
+ function clearSession() {
+ try { localStorage.removeItem(LS_KEY); } catch {}
+ }
+
+ /** Mark session as handled (accepted/discarded). The agent will clean up
+ * the source, but until it does the wrapper is still in the HTML. This
+ * prevents resumeSession from picking it up again after reload. */
+ function markSessionHandled() {
+ if (!currentSessionId) return;
+ try {
+ localStorage.setItem(LS_KEY + '-handled', currentSessionId);
+ } catch {}
+ }
+
+ function isSessionHandled(id) {
+ try {
+ return localStorage.getItem(LS_KEY + '-handled') === id;
+ } catch { return false; }
+ }
+
+ function clearHandled() {
+ try { localStorage.removeItem(LS_KEY + '-handled'); } catch {}
+ }
+
+ function cleanup() {
+ hideBar();
+ hideHighlight();
+ stopScrollTracking();
+ if (variantObserver) { variantObserver.disconnect(); variantObserver = null; }
+ clearSession();
+ selectedElement = null;
+ currentSessionId = null;
+ selectedAction = 'impeccable';
+ state = 'PICKING';
+ }
+
+ // ---------------------------------------------------------------------------
+ // Toast
+ // ---------------------------------------------------------------------------
+
+ function showToast(message, duration) {
+ if (toastEl) toastEl.remove();
+ toastEl = el('div', {
+ position: 'fixed', bottom: '16px', left: '50%',
+ transform: 'translateX(-50%) translateY(8px)',
+ background: C.ink, color: C.white,
+ fontFamily: FONT, fontSize: '12px',
+ padding: '8px 16px', borderRadius: '8px',
+ zIndex: Z.toast, opacity: '0',
+ transition: 'opacity 0.25s ' + EASE + ', transform 0.25s ' + EASE,
+ pointerEvents: 'none', maxWidth: '420px', textAlign: 'center',
+ });
+ toastEl.id = PREFIX + '-toast';
+ toastEl.textContent = message;
+ document.body.appendChild(toastEl);
+ requestAnimationFrame(() => {
+ toastEl.style.opacity = '1';
+ toastEl.style.transform = 'translateX(-50%) translateY(0)';
+ });
+ setTimeout(() => {
+ if (toastEl) {
+ toastEl.style.opacity = '0';
+ toastEl.style.transform = 'translateX(-50%) translateY(8px)';
+ setTimeout(() => { if (toastEl) { toastEl.remove(); toastEl = null; } }, 250);
+ }
+ }, duration);
+ }
+
+ // ---------------------------------------------------------------------------
+ // Init
+ // ---------------------------------------------------------------------------
+
+ // Resume an active variant session after HMR/page reload.
+ // If a [data-impeccable-variants] wrapper exists in the DOM, the agent wrote
+ // variants before HMR fired. Pick up where we left off.
+ function resumeSession() {
+ const wrapper = document.querySelector('[data-impeccable-variants]');
+ if (!wrapper) { clearSession(); clearHandled(); return false; }
+
+ const sessionId = wrapper.dataset.impeccableVariants;
+
+ // Don't resume if this session was already accepted/discarded
+ if (isSessionHandled(sessionId)) return false;
+
+ currentSessionId = sessionId;
+ expectedVariants = parseInt(wrapper.dataset.impeccableVariantCount || '0');
+ const variants = wrapper.querySelectorAll('[data-impeccable-variant]:not([data-impeccable-variant="original"])');
+ arrivedVariants = variants.length;
+
+ // Restore visible variant from localStorage if available, else default to 1
+ const saved = loadSession();
+ visibleVariant = (saved && saved.id === sessionId && saved.visible > 0 && saved.visible <= arrivedVariants)
+ ? saved.visible : (arrivedVariants > 0 ? 1 : 0);
+
+ // Find the visible variant's content element for highlight positioning
+ const visEl = wrapper.querySelector('[data-impeccable-variant="' + visibleVariant + '"] > :first-child');
+ selectedElement = visEl || wrapper.parentElement;
+
+ // Set display state BEFORE starting observer (avoid triggering it)
+ if (visibleVariant > 0) showVariantInDOM(currentSessionId, visibleVariant);
+
+ state = arrivedVariants >= expectedVariants ? 'CYCLING' : 'GENERATING';
+ showBar(state === 'CYCLING' ? 'cycling' : 'generating');
+ startScrollTracking();
+ saveSession();
+
+ // Start observing for more variants AFTER initial setup
+ if (variantObserver) variantObserver.disconnect();
+ variantObserver = startVariantObserver(currentSessionId);
+ return true;
+ }
+
+ function init() {
+ initHighlight();
+ initBar();
+ initActionPicker();
+ document.addEventListener('mousemove', handleMouseMove, true);
+ document.addEventListener('click', handleClick, true);
+ document.addEventListener('keydown', handleKeyDown, true);
+ connectSSE();
+
+ // Check for an active session to resume (variant wrapper already in DOM after HMR)
+ if (!resumeSession()) {
+ console.log('[impeccable] Live variant mode ready. Hover over elements to pick one.');
+ } else {
+ console.log('[impeccable] Resumed active variant session ' + currentSessionId + ' (' + arrivedVariants + '/' + expectedVariants + ' variants).');
+ }
+ }
+
+ if (document.readyState === 'loading') {
+ document.addEventListener('DOMContentLoaded', init);
+ } else {
+ init();
+ }
+})();
diff --git a/.agents/skills/impeccable/scripts/live-poll.mjs b/.agents/skills/impeccable/scripts/live-poll.mjs
new file mode 100644
index 000000000..52859416c
--- /dev/null
+++ b/.agents/skills/impeccable/scripts/live-poll.mjs
@@ -0,0 +1,123 @@
+/**
+ * CLI client for the live variant mode poll/reply protocol.
+ *
+ * Usage:
+ * npx impeccable poll # Block until browser event, print JSON
+ * npx impeccable poll --timeout=60000 # Custom timeout (ms)
+ * npx impeccable poll --reply <id> done # Reply "done" to event <id>
+ * npx impeccable poll --reply <id> error "msg" # Reply with error
+ */
+
+import fs from 'node:fs';
+import path from 'node:path';
+import os from 'node:os';
+
+const LIVE_PID_FILE = path.join(os.tmpdir(), 'impeccable-live.json');
+
+function readServerInfo() {
+ try {
+ return JSON.parse(fs.readFileSync(LIVE_PID_FILE, 'utf-8'));
+ } catch {
+ console.error('No running live server found. Start one with: npx impeccable live');
+ process.exit(1);
+ }
+}
+
+export async function pollCli() {
+ const args = process.argv.slice(2);
+
+ if (args.includes('--help') || args.includes('-h')) {
+ console.log(`Usage: impeccable poll [options]
+
+Wait for a browser event from the live variant server, or reply to one.
+
+Modes:
+ poll Block until a browser event arrives, print JSON
+ poll --reply <id> done Reply "done" to event <id>
+ poll --reply <id> error "msg" Reply with an error message
+
+Options:
+ --timeout=MS Poll timeout in milliseconds (default: 120000)
+ --help Show this help message`);
+ process.exit(0);
+ }
+
+ const info = readServerInfo();
+ const base = `http://localhost:${info.port}`;
+
+ // Reply mode: npx impeccable poll --reply <id> <status> [--file path] [message]
+ const replyIdx = args.indexOf('--reply');
+ if (replyIdx !== -1) {
+ const id = args[replyIdx + 1];
+ const status = args[replyIdx + 2] || 'done';
+ const fileIdx = args.indexOf('--file');
+ const filePath = fileIdx !== -1 && fileIdx + 1 < args.length ? args[fileIdx + 1] : undefined;
+ // Message is any remaining positional arg that isn't a flag
+ const message = args.find((a, i) => i > replyIdx + 2 && !a.startsWith('--') && i !== fileIdx + 1) || undefined;
+
+ if (!id) {
+ console.error('Usage: npx impeccable poll --reply <id> <status> [--file path] [message]');
+ process.exit(1);
+ }
+
+ 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);
+ }
+
+ // Success — silent exit (agent doesn't need output for replies)
+ } catch (err) {
+ if (err.cause?.code === 'ECONNREFUSED') {
+ console.error('Live server not running. Start one with: npx impeccable live');
+ } else {
+ console.error('Reply failed:', err.message);
+ }
+ process.exit(1);
+ }
+ return;
+ }
+
+ // Poll mode: block until browser event
+ const timeoutArg = args.find(a => a.startsWith('--timeout='));
+ const timeout = timeoutArg ? parseInt(timeoutArg.split('=')[1], 10) : 120000;
+
+ try {
+ const res = await fetch(`${base}/poll?token=${info.token}&timeout=${timeout}`);
+
+ if (res.status === 401) {
+ console.error('Authentication failed. The server token may have changed.');
+ console.error('Try restarting: npx impeccable live stop && npx impeccable live');
+ process.exit(1);
+ }
+
+ if (!res.ok) {
+ console.error(`Poll failed: ${res.status} ${res.statusText}`);
+ process.exit(1);
+ }
+
+ const event = await res.json();
+ // Print the event as JSON — the agent reads this from stdout
+ console.log(JSON.stringify(event));
+ } catch (err) {
+ if (err.cause?.code === 'ECONNREFUSED') {
+ console.error('Live server not running. Start one with: npx impeccable live');
+ } else {
+ console.error('Poll failed:', err.message);
+ }
+ process.exit(1);
+ }
+}
diff --git a/.agents/skills/impeccable/scripts/live-server.mjs b/.agents/skills/impeccable/scripts/live-server.mjs
new file mode 100644
index 000000000..d436bad58
--- /dev/null
+++ b/.agents/skills/impeccable/scripts/live-server.mjs
@@ -0,0 +1,416 @@
+#!/usr/bin/env node
+/**
+ * Live variant mode server (self-contained, zero dependencies).
+ *
+ * Serves the browser script (/live.js), the detection overlay (/detect.js),
+ * uses Server-Sent Events (SSE) for server→browser push, and HTTP POST for
+ * browser→server events. Agent communicates via HTTP long-poll (/poll).
+ *
+ * Usage:
+ * node <scripts_path>/live-server.mjs # start
+ * node <scripts_path>/live-server.mjs stop # stop
+ * node <scripts_path>/live-server.mjs --help
+ */
+
+import http from 'node:http';
+import { randomUUID } from 'node:crypto';
+import fs from 'node:fs';
+import path from 'node:path';
+import os from 'node:os';
+import net from 'node:net';
+import { fileURLToPath } from 'node:url';
+
+const __dirname = path.dirname(fileURLToPath(import.meta.url));
+const LIVE_PID_FILE = path.join(os.tmpdir(), 'impeccable-live.json');
+const DEFAULT_POLL_TIMEOUT = 120_000;
+
+// ---------------------------------------------------------------------------
+// Port detection
+// ---------------------------------------------------------------------------
+
+async function findOpenPort(start = 8400) {
+ return new Promise((resolve) => {
+ const srv = net.createServer();
+ srv.listen(start, '127.0.0.1', () => {
+ const port = srv.address().port;
+ srv.close(() => resolve(port));
+ });
+ srv.on('error', () => resolve(findOpenPort(start + 1)));
+ });
+}
+
+// ---------------------------------------------------------------------------
+// Session state
+// ---------------------------------------------------------------------------
+
+const state = {
+ token: null,
+ port: null,
+ sseClients: new Set(), // SSE response objects (server→browser push)
+ pendingEvents: [], // browser events waiting for agent poll
+ pendingPolls: [], // agent poll callbacks waiting for browser events
+ exitTimer: null,
+};
+
+function enqueueEvent(event) {
+ if (state.pendingPolls.length > 0) {
+ state.pendingPolls.shift()(event);
+ } else {
+ state.pendingEvents.push(event);
+ }
+}
+
+/** Push a message to all connected SSE clients. */
+function broadcast(msg) {
+ const data = 'data: ' + JSON.stringify(msg) + '\n\n';
+ for (const res of state.sseClients) {
+ try { res.write(data); } catch { /* client gone */ }
+ }
+}
+
+// ---------------------------------------------------------------------------
+// Load scripts
+// ---------------------------------------------------------------------------
+
+function loadBrowserScripts() {
+ // Detection script: look relative to the skill scripts dir, then fall back
+ // to the npm package location (src/detect-antipatterns-browser.js)
+ const detectPaths = [
+ path.join(__dirname, '..', '..', '..', '..', 'src', 'detect-antipatterns-browser.js'),
+ path.join(process.cwd(), 'node_modules', 'impeccable', 'src', 'detect-antipatterns-browser.js'),
+ ];
+ let detectScript = '';
+ for (const p of detectPaths) {
+ try { detectScript = fs.readFileSync(p, 'utf-8'); break; } catch { /* try next */ }
+ }
+
+ const livePath = path.join(__dirname, 'live-browser.js');
+ let liveScript = '';
+ try {
+ liveScript = fs.readFileSync(livePath, 'utf-8');
+ } catch {
+ process.stderr.write('Error: live-browser.js not found at ' + livePath + '\n');
+ process.exit(1);
+ }
+
+ return { detectScript, liveScript };
+}
+
+function hasProjectContext() {
+ try {
+ fs.accessSync(path.join(process.cwd(), '.impeccable.md'), fs.constants.R_OK);
+ return true;
+ } catch { return false; }
+}
+
+// ---------------------------------------------------------------------------
+// Validation (inline — no external import needed for self-contained script)
+// ---------------------------------------------------------------------------
+
+const VISUAL_ACTIONS = [
+ 'impeccable', 'bolder', 'quieter', 'distill', 'polish', 'typeset',
+ 'colorize', 'layout', 'adapt', 'animate', 'delight', 'overdrive',
+];
+
+function validateEvent(msg) {
+ if (!msg || typeof msg !== 'object' || !msg.type) return 'Missing or invalid message';
+ switch (msg.type) {
+ case 'generate':
+ if (!msg.id || typeof msg.id !== 'string') return 'generate: missing id';
+ if (!msg.action || !VISUAL_ACTIONS.includes(msg.action)) return 'generate: invalid action';
+ if (!Number.isInteger(msg.count) || msg.count < 1 || msg.count > 8) return 'generate: count must be 1-8';
+ if (!msg.element || !msg.element.outerHTML) return 'generate: missing element context';
+ return null;
+ case 'accept':
+ if (!msg.id) return 'accept: missing id';
+ if (!msg.variantId) return 'accept: missing variantId';
+ return null;
+ case 'discard':
+ return msg.id ? null : 'discard: missing id';
+ case 'exit':
+ return null;
+ default:
+ return 'Unknown event type: ' + msg.type;
+ }
+}
+
+// ---------------------------------------------------------------------------
+// HTTP request handler
+// ---------------------------------------------------------------------------
+
+function createRequestHandler({ detectScript, liveScriptWithToken }) {
+ return (req, res) => {
+ const url = new URL(req.url, `http://localhost:${state.port}`);
+ res.setHeader('Access-Control-Allow-Origin', '*');
+ res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS');
+ res.setHeader('Access-Control-Allow-Headers', 'Content-Type');
+ if (req.method === 'OPTIONS') { res.writeHead(204); res.end(); return; }
+
+ const p = url.pathname;
+
+ // --- Scripts ---
+ if (p === '/live.js') {
+ res.writeHead(200, { 'Content-Type': 'application/javascript' });
+ res.end(liveScriptWithToken);
+ return;
+ }
+ if (p === '/detect.js' || p === '/') {
+ if (!detectScript) { res.writeHead(404); res.end('Not available'); return; }
+ res.writeHead(200, { 'Content-Type': 'application/javascript' });
+ res.end(detectScript);
+ return;
+ }
+
+ // --- Health ---
+ if (p === '/health') {
+ res.writeHead(200, { 'Content-Type': 'application/json' });
+ res.end(JSON.stringify({
+ status: 'ok', port: state.port, mode: 'variant',
+ hasProjectContext: hasProjectContext(),
+ connectedClients: state.sseClients.size,
+ }));
+ return;
+ }
+
+ // --- Source file (no-HMR fallback) ---
+ if (p === '/source') {
+ const token = url.searchParams.get('token');
+ if (token !== state.token) { res.writeHead(401); res.end('Unauthorized'); return; }
+ const filePath = url.searchParams.get('path');
+ if (!filePath || filePath.includes('..')) { res.writeHead(400); res.end('Bad path'); return; }
+ const absPath = path.resolve(process.cwd(), filePath);
+ if (!absPath.startsWith(process.cwd())) { res.writeHead(403); res.end('Forbidden'); return; }
+ try {
+ res.writeHead(200, { 'Content-Type': 'text/html; charset=utf-8' });
+ res.end(fs.readFileSync(absPath, 'utf-8'));
+ } catch { res.writeHead(404); res.end('File not found'); }
+ return;
+ }
+
+ // --- SSE: server→browser push (replaces WebSocket) ---
+ if (p === '/events' && req.method === 'GET') {
+ const token = url.searchParams.get('token');
+ if (token !== state.token) { res.writeHead(401); res.end('Unauthorized'); return; }
+ res.writeHead(200, {
+ 'Content-Type': 'text/event-stream',
+ 'Cache-Control': 'no-cache',
+ 'Connection': 'keep-alive',
+ });
+ res.write('data: ' + JSON.stringify({
+ type: 'connected',
+ hasProjectContext: hasProjectContext(),
+ }) + '\n\n');
+
+ state.sseClients.add(res);
+ clearTimeout(state.exitTimer);
+
+ req.on('close', () => {
+ state.sseClients.delete(res);
+ if (state.sseClients.size === 0) {
+ clearTimeout(state.exitTimer);
+ state.exitTimer = setTimeout(() => {
+ if (state.sseClients.size === 0) enqueueEvent({ type: 'exit' });
+ }, 8000);
+ }
+ });
+ return;
+ }
+
+ // --- Browser→server events (replaces WebSocket messages) ---
+ if (p === '/events' && req.method === 'POST') {
+ let body = '';
+ req.on('data', (c) => { body += c; });
+ req.on('end', () => {
+ let msg;
+ try { msg = JSON.parse(body); } catch {
+ res.writeHead(400, { 'Content-Type': 'application/json' });
+ res.end(JSON.stringify({ error: 'Invalid JSON' }));
+ return;
+ }
+ if (msg.token !== state.token) {
+ res.writeHead(401, { 'Content-Type': 'application/json' });
+ res.end(JSON.stringify({ error: 'Unauthorized' }));
+ return;
+ }
+ const error = validateEvent(msg);
+ if (error) {
+ res.writeHead(400, { 'Content-Type': 'application/json' });
+ res.end(JSON.stringify({ error }));
+ return;
+ }
+ enqueueEvent(msg);
+ res.writeHead(200, { 'Content-Type': 'application/json' });
+ res.end(JSON.stringify({ ok: true }));
+ });
+ return;
+ }
+
+ // --- Stop ---
+ if (p === '/stop') {
+ const token = url.searchParams.get('token');
+ if (token !== state.token) { res.writeHead(401); res.end('Unauthorized'); return; }
+ res.writeHead(200, { 'Content-Type': 'text/plain' });
+ res.end('stopping');
+ shutdown();
+ return;
+ }
+
+ // --- Agent poll ---
+ if (p === '/poll' && req.method === 'GET') {
+ handlePollGet(req, res, url);
+ return;
+ }
+ if (p === '/poll' && req.method === 'POST') {
+ handlePollPost(req, res);
+ return;
+ }
+
+ res.writeHead(404); res.end('Not found');
+ };
+}
+
+// ---------------------------------------------------------------------------
+// Agent poll endpoints (unchanged from WS version)
+// ---------------------------------------------------------------------------
+
+function handlePollGet(req, res, url) {
+ 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 timeout = parseInt(url.searchParams.get('timeout') || DEFAULT_POLL_TIMEOUT, 10);
+ if (state.pendingEvents.length > 0) {
+ res.writeHead(200, { 'Content-Type': 'application/json' });
+ res.end(JSON.stringify(state.pendingEvents.shift()));
+ return;
+ }
+ const timer = setTimeout(() => {
+ const idx = state.pendingPolls.indexOf(resolve);
+ if (idx !== -1) state.pendingPolls.splice(idx, 1);
+ res.writeHead(200, { 'Content-Type': 'application/json' });
+ res.end(JSON.stringify({ type: 'timeout' }));
+ }, timeout);
+ function resolve(event) {
+ clearTimeout(timer);
+ res.writeHead(200, { 'Content-Type': 'application/json' });
+ res.end(JSON.stringify(event));
+ }
+ state.pendingPolls.push(resolve);
+ req.on('close', () => {
+ clearTimeout(timer);
+ const idx = state.pendingPolls.indexOf(resolve);
+ if (idx !== -1) state.pendingPolls.splice(idx, 1);
+ });
+}
+
+function handlePollPost(req, res) {
+ let body = '';
+ req.on('data', (c) => { body += c; });
+ req.on('end', () => {
+ let msg;
+ try { msg = JSON.parse(body); } catch {
+ res.writeHead(400, { 'Content-Type': 'application/json' });
+ res.end(JSON.stringify({ error: 'Invalid JSON' }));
+ return;
+ }
+ if (msg.token !== state.token) {
+ res.writeHead(401, { 'Content-Type': 'application/json' });
+ res.end(JSON.stringify({ error: 'Unauthorized' }));
+ return;
+ }
+ // Forward the reply to the browser via SSE
+ broadcast({ type: msg.type || 'done', id: msg.id, message: msg.message, file: msg.file, data: msg.data });
+ res.writeHead(200, { 'Content-Type': 'application/json' });
+ res.end(JSON.stringify({ ok: true }));
+ });
+}
+
+// ---------------------------------------------------------------------------
+// Lifecycle
+// ---------------------------------------------------------------------------
+
+let httpServer = null;
+
+function shutdown() {
+ try { fs.unlinkSync(LIVE_PID_FILE); } catch {}
+ for (const res of state.sseClients) { try { res.end(); } catch {} }
+ state.sseClients.clear();
+ for (const resolve of state.pendingPolls) resolve({ type: 'exit' });
+ state.pendingPolls.length = 0;
+ if (httpServer) httpServer.close();
+ process.exit(0);
+}
+
+// ---------------------------------------------------------------------------
+// Main
+// ---------------------------------------------------------------------------
+
+const args = process.argv.slice(2);
+
+if (args.includes('--help') || args.includes('-h')) {
+ console.log(`Usage: node live-server.mjs [options]
+
+Start the live variant mode server (zero dependencies).
+
+Commands:
+ (default) Start the server
+ stop Stop a running server
+
+Options:
+ --port=PORT Use a specific port (default: auto-detect starting at 8400)
+ --help Show this help
+
+Endpoints:
+ /live.js Browser script (element picker + variant cycling)
+ /detect.js Detection overlay (backwards compatible)
+ /events SSE stream (server→browser) + POST (browser→server)
+ /poll Long-poll for agent CLI
+ /source Raw source file reader (no-HMR fallback)
+ /health Health check`);
+ process.exit(0);
+}
+
+if (args.includes('stop')) {
+ try {
+ const info = JSON.parse(fs.readFileSync(LIVE_PID_FILE, 'utf-8'));
+ 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 { console.log('No running live server found.'); }
+ process.exit(0);
+}
+
+// Check for existing session
+try {
+ const existing = JSON.parse(fs.readFileSync(LIVE_PID_FILE, 'utf-8'));
+ 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 {}
+
+state.token = randomUUID();
+const portArg = args.find(a => a.startsWith('--port='));
+state.port = portArg ? parseInt(portArg.split('=')[1], 10) : await findOpenPort();
+
+const { detectScript, liveScript } = loadBrowserScripts();
+const liveScriptWithToken =
+ `window.__IMPECCABLE_TOKEN__ = '${state.token}';\n` +
+ `window.__IMPECCABLE_PORT__ = ${state.port};\n` +
+ liveScript;
+
+httpServer = http.createServer(createRequestHandler({ detectScript, liveScriptWithToken }));
+
+httpServer.listen(state.port, '127.0.0.1', () => {
+ fs.writeFileSync(LIVE_PID_FILE, JSON.stringify({ 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`);
+ console.log(`Inject: <script src="${url}/live.js"><\/script>`);
+ console.log(`Stop: node ${path.basename(fileURLToPath(import.meta.url))} stop`);
+});
+
+process.on('SIGINT', shutdown);
+process.on('SIGTERM', shutdown);
diff --git a/.agents/skills/impeccable/scripts/live-wrap.mjs b/.agents/skills/impeccable/scripts/live-wrap.mjs
new file mode 100644
index 000000000..f1c838cdd
--- /dev/null
+++ b/.agents/skills/impeccable/scripts/live-wrap.mjs
@@ -0,0 +1,298 @@
+/**
+ * CLI helper: find an element in source and wrap it in a variant container.
+ *
+ * Usage:
+ * npx impeccable wrap --id SESSION_ID --count N --query "hero-combined-left" [--file path]
+ *
+ * Searches project files for the element matching the query (class name, ID, or
+ * text snippet), wraps it with the variant scaffolding, and prints the file path
+ * + line range where the agent should insert variant HTML.
+ *
+ * This replaces 3-4 agent tool calls (grep + read + edit) with a single CLI call.
+ */
+
+import fs from 'node:fs';
+import path from 'node:path';
+
+const EXTENSIONS = ['.html', '.jsx', '.tsx', '.vue', '.svelte', '.astro'];
+
+export async function wrapCli() {
+ const args = process.argv.slice(2);
+
+ if (args.includes('--help') || args.includes('-h')) {
+ console.log(`Usage: impeccable wrap [options]
+
+Find an element in source and wrap it in a variant container.
+
+Required:
+ --id ID Session ID for the variant wrapper
+ --count N Number of expected variants (1-8)
+
+Element identification (at least one required):
+ --element-id ID HTML id attribute of the element
+ --classes A,B,C Comma-separated CSS class names
+ --tag TAG Tag name (div, section, etc.)
+ --query TEXT Fallback: raw text to search for
+
+Optional:
+ --file PATH Source file to search in (skips auto-detection)
+ --help Show this help message
+
+Output (JSON):
+ { file, startLine, endLine, insertLine, commentSyntax }
+
+The agent should insert variant HTML at insertLine.`);
+ process.exit(0);
+ }
+
+ const id = argVal(args, '--id');
+ const count = parseInt(argVal(args, '--count') || '3');
+ const elementId = argVal(args, '--element-id');
+ const classes = argVal(args, '--classes');
+ const tag = argVal(args, '--tag');
+ const query = argVal(args, '--query');
+ const filePath = argVal(args, '--file');
+
+ if (!id) { console.error('Missing --id'); process.exit(1); }
+ if (!elementId && !classes && !query) {
+ console.error('Need at least one of: --element-id, --classes, --query');
+ process.exit(1);
+ }
+
+ // Build search queries in priority order (most specific first)
+ const queries = buildSearchQueries(elementId, classes, tag, query);
+
+ // Find the source file
+ let targetFile = filePath;
+ let matchedQuery = null;
+ if (!targetFile) {
+ for (const q of queries) {
+ targetFile = findFileWithQuery(q, process.cwd());
+ if (targetFile) { matchedQuery = q; break; }
+ }
+ if (!targetFile) {
+ console.error(JSON.stringify({ error: 'Could not find element in project files. Searched for: ' + queries.join(', ') }));
+ process.exit(1);
+ }
+ } else {
+ matchedQuery = queries[0];
+ }
+
+ const content = fs.readFileSync(targetFile, 'utf-8');
+ const lines = content.split('\n');
+
+ // Find the element, trying each query in priority order
+ let match = null;
+ for (const q of queries) {
+ match = findElement(lines, q);
+ if (match) break;
+ }
+ if (!match) {
+ console.error(JSON.stringify({ error: 'Found file but could not locate element in ' + targetFile + '. Searched for: ' + queries.join(', ') }));
+ process.exit(1);
+ }
+
+ const { startLine, endLine } = match;
+ const commentSyntax = detectCommentSyntax(targetFile);
+ const indent = lines[startLine].match(/^(\s*)/)[1];
+
+ // Extract the original element
+ const originalLines = lines.slice(startLine, endLine + 1);
+ const originalIndented = originalLines.map(l => indent + ' ' + l.trimStart()).join('\n');
+
+ // Build the wrapper
+ const wrapperLines = [
+ indent + commentSyntax.open + ' impeccable-variants-start ' + id + ' ' + commentSyntax.close,
+ indent + '<div data-impeccable-variants="' + id + '" data-impeccable-variant-count="' + count + '" style="display: contents">',
+ indent + ' ' + commentSyntax.open + ' Original ' + commentSyntax.close,
+ indent + ' <div data-impeccable-variant="original">',
+ originalIndented,
+ indent + ' </div>',
+ indent + ' ' + commentSyntax.open + ' Variants: insert below this line ' + commentSyntax.close,
+ indent + '</div>',
+ indent + commentSyntax.open + ' impeccable-variants-end ' + id + ' ' + commentSyntax.close,
+ ];
+
+ // Replace the original element with the wrapper
+ const newLines = [
+ ...lines.slice(0, startLine),
+ ...wrapperLines,
+ ...lines.slice(endLine + 1),
+ ];
+ fs.writeFileSync(targetFile, newLines.join('\n'), 'utf-8');
+
+ // Calculate insert line (the "insert below this line" comment)
+ const insertLine = startLine + 6; // 0-indexed in the new file
+
+ console.log(JSON.stringify({
+ file: path.relative(process.cwd(), targetFile),
+ startLine: startLine + 1, // 1-indexed for the agent
+ endLine: startLine + wrapperLines.length, // 1-indexed
+ insertLine: insertLine + 1, // 1-indexed: where variants go
+ commentSyntax: commentSyntax,
+ originalLineCount: originalLines.length,
+ }));
+}
+
+// ---------------------------------------------------------------------------
+// Helpers
+// ---------------------------------------------------------------------------
+
+function argVal(args, flag) {
+ const idx = args.indexOf(flag);
+ return idx !== -1 && idx + 1 < args.length ? args[idx + 1] : null;
+}
+
+/**
+ * Build search query strings in priority order (most specific first).
+ * ID is most reliable, then specific class combos, then single classes, then raw query.
+ */
+function buildSearchQueries(elementId, classes, tag, query) {
+ const queries = [];
+
+ // 1. ID is the most specific
+ if (elementId) {
+ queries.push('id="' + elementId + '"');
+ }
+
+ // 2. Full class attribute match (for elements with distinctive multi-class combos)
+ if (classes) {
+ const classList = classes.split(',').map(c => c.trim()).filter(Boolean);
+ if (classList.length > 1) {
+ // Try the most distinctive class first (longest, most specific)
+ const sorted = [...classList].sort((a, b) => b.length - a.length);
+ queries.push('class="' + classList.join(' ') + '"'); // exact full match
+ queries.push(sorted[0]); // most distinctive single class
+ } else if (classList.length === 1) {
+ queries.push(classList[0]);
+ }
+ }
+
+ // 3. Tag + class combo (e.g., <section class="hero">)
+ if (tag && classes) {
+ const firstClass = classes.split(',')[0].trim();
+ queries.push('<' + tag + ' class="' + firstClass);
+ }
+
+ // 4. Raw fallback query
+ if (query) {
+ queries.push(query);
+ }
+
+ return queries;
+}
+
+function detectCommentSyntax(filePath) {
+ const ext = path.extname(filePath).toLowerCase();
+ if (ext === '.jsx' || ext === '.tsx') {
+ return { open: '{/*', close: '*/}' };
+ }
+ // HTML, Vue, Svelte, Astro all use HTML comments
+ return { open: '<!--', close: '-->' };
+}
+
+/**
+ * Search project files for the query string (class name, ID, etc.)
+ * Returns the first matching file path, or null.
+ */
+function findFileWithQuery(query, cwd) {
+ const searchDirs = ['src', 'app', 'pages', 'components', 'public', 'views', 'templates', '.'];
+ const seen = new Set();
+
+ for (const dir of searchDirs) {
+ const absDir = path.join(cwd, dir);
+ if (!fs.existsSync(absDir)) continue;
+ const result = searchDir(absDir, query, seen, 0);
+ if (result) return result;
+ }
+ return null;
+}
+
+function searchDir(dir, query, seen, depth) {
+ if (depth > 5) return null; // don't go too deep
+ const realDir = fs.realpathSync(dir);
+ if (seen.has(realDir)) return null;
+ seen.add(realDir);
+
+ let entries;
+ try { entries = fs.readdirSync(dir, { withFileTypes: true }); }
+ catch { return null; }
+
+ // Check files first
+ for (const entry of entries) {
+ if (!entry.isFile()) continue;
+ const ext = path.extname(entry.name).toLowerCase();
+ if (!EXTENSIONS.includes(ext)) continue;
+
+ const filePath = path.join(dir, entry.name);
+ try {
+ const content = fs.readFileSync(filePath, 'utf-8');
+ if (content.includes(query)) return filePath;
+ } catch { /* skip unreadable files */ }
+ }
+
+ // Then recurse into directories
+ for (const entry of entries) {
+ if (!entry.isDirectory()) continue;
+ if (entry.name === 'node_modules' || entry.name === '.git' || entry.name === 'dist' || entry.name === 'build') continue;
+ const result = searchDir(path.join(dir, entry.name), query, seen, depth + 1);
+ if (result) return result;
+ }
+
+ return null;
+}
+
+/**
+ * Find the element's start and end line in the file.
+ * The query is a class name, ID, or text snippet.
+ * We find the line containing the query, then find the matching closing tag.
+ */
+function findElement(lines, query) {
+ // Find the line containing the query
+ let startLine = -1;
+ for (let i = 0; i < lines.length; i++) {
+ if (lines[i].includes(query)) {
+ // Make sure this looks like a tag opening, not a comment or string
+ const line = lines[i].trim();
+ if (line.startsWith('<!--') || line.startsWith('{/*') || line.startsWith('//')) continue;
+ // Skip lines inside data-impeccable-variant containers (already wrapped)
+ if (lines[i].includes('data-impeccable-variant')) continue;
+ startLine = i;
+ break;
+ }
+ }
+
+ if (startLine === -1) return null;
+
+ // Find the end of this element by counting open/close tags
+ const endLine = findClosingLine(lines, startLine);
+ return { startLine, endLine };
+}
+
+/**
+ * Starting from a line with an opening tag, find the line with the matching
+ * closing tag by counting tag nesting depth.
+ */
+function findClosingLine(lines, start) {
+ // Extract the tag name from the opening line
+ const openMatch = lines[start].match(/<(\w+)[\s>]/);
+ if (!openMatch) return start; // self-closing or text-only line
+
+ const tagName = openMatch[1];
+ let depth = 0;
+
+ for (let i = start; i < lines.length; i++) {
+ const line = lines[i];
+ // Count opening tags (not self-closing)
+ const opens = (line.match(new RegExp('<' + tagName + '[\\s>]', 'g')) || []).length;
+ const selfCloses = (line.match(new RegExp('<' + tagName + '[^>]*/>', 'g')) || []).length;
+ const closes = (line.match(new RegExp('</' + tagName + '\\s*>', 'g')) || []).length;
+
+ depth += opens - selfCloses - closes;
+
+ if (depth <= 0) return i;
+ }
+
+ // If we can't find the close, return a reasonable guess
+ return Math.min(start + 50, lines.length - 1);
+}
diff --git a/.claude/skills/impeccable/reference/live.md b/.claude/skills/impeccable/reference/live.md
index 53b64a21a..ba0e9b0c5 100644
--- a/.claude/skills/impeccable/reference/live.md
+++ b/.claude/skills/impeccable/reference/live.md
@@ -10,7 +10,7 @@ Launch interactive live variant mode: select elements in the browser, pick a des
1. Read `.impeccable.md` if it exists. Keep the design context in mind for variant generation.
2. Start the live variant server:
```bash
- npx impeccable live &
+ node {{scripts_path}}/live-server.mjs &
```
3. Note the **port** and **token** printed to stdout.
@@ -53,7 +53,7 @@ Run a blocking poll loop. On each iteration, wait for a browser event and respon
```
LOOP:
- Run: npx impeccable poll
+ Run: node {{scripts_path}}/live-poll.mjs
Read the JSON output. Dispatch based on the "type" field:
TYPE "generate":
@@ -85,7 +85,7 @@ The event contains: `{id, action, freeformPrompt, count, pageUrl, element}`.
Use the `wrap` helper to find the element and create the variant container:
```bash
-npx impeccable wrap --id EVENT_ID --count EVENT_COUNT --element-id "ELEMENT_ID" --classes "class1,class2" --tag "div"
+node {{scripts_path}}/live-wrap.mjs --id EVENT_ID --count EVENT_COUNT --element-id "ELEMENT_ID" --classes "class1,class2" --tag "div"
```
Pass the element's id (`event.element.id`), classes (`event.element.classes` joined with commas), and tag name. The command searches in priority order: ID match first, then class names, then tag+class combo. If `event.pageUrl` hints at the file (e.g., `/` is usually `index.html`), pass `--file PATH` to skip the search.
@@ -136,10 +136,14 @@ The first variant should NOT have `style="display: none"` (it should be visible
### Step 3: Signal completion
+Include `--file` so the browser can fetch variants directly if the dev server lacks HMR:
+
```bash
-npx impeccable poll --reply EVENT_ID done
+node {{scripts_path}}/live-poll.mjs --reply EVENT_ID done --file RELATIVE_PATH
```
+The file path should be relative to the project root (e.g., `public/index.html`, `src/App.tsx`).
+
## Handle Accept
The event contains: `{id, variantId}`.
@@ -151,7 +155,7 @@ The user accepted a specific variant. For v1 (inspection mode):
4. Remove any scoped CSS blocks (between `impeccable-variants-css-start` and `impeccable-variants-css-end` markers).
5. Reply:
```bash
- npx impeccable poll --reply SESSION_ID done
+ node {{scripts_path}}/live-poll.mjs --reply SESSION_ID done
```
## Handle Discard
@@ -163,7 +167,7 @@ The event contains: `{id}`.
3. Remove any scoped CSS blocks for this session.
4. Reply:
```bash
- npx impeccable poll --reply SESSION_ID done
+ node {{scripts_path}}/live-poll.mjs --reply SESSION_ID done
```
## Cleanup (on exit)
@@ -174,7 +178,7 @@ When the loop ends:
2. **Remove any leftover variant wrappers** (search for `impeccable-variants-start` markers and clean up).
3. **Stop the server**:
```bash
- npx impeccable live stop
+ node {{scripts_path}}/live-server.mjs stop
```
## Variant Generation Guidelines
diff --git a/.claude/skills/impeccable/scripts/live-browser.js b/.claude/skills/impeccable/scripts/live-browser.js
new file mode 100644
index 000000000..7a26c9829
--- /dev/null
+++ b/.claude/skills/impeccable/scripts/live-browser.js
@@ -0,0 +1,1220 @@
+/**
+ * Impeccable Live Variant Mode — Browser Script
+ *
+ * Injected into the user's page via <script src="http://localhost:PORT/live.js">.
+ * The server prepends window.__IMPECCABLE_TOKEN__ and window.__IMPECCABLE_PORT__
+ * before this code.
+ *
+ * UI: a single floating bar that morphs between three states —
+ * configure (pick action + go), generating (progressive dots), and cycling
+ * (prev/next + accept/discard). Feels like Spotlight, not a modal.
+ */
+(function () {
+ 'use strict';
+ if (typeof window === 'undefined') return;
+
+ // Guard against double-init. Bun's HTML loader may process the <script> tag
+ // and create a bundled copy alongside the external load, or HMR may re-execute.
+ // Check BEFORE reading token/port to catch all cases.
+ if (window.__IMPECCABLE_LIVE_INIT__) return;
+ window.__IMPECCABLE_LIVE_INIT__ = true;
+
+ const TOKEN = window.__IMPECCABLE_TOKEN__;
+ const PORT = window.__IMPECCABLE_PORT__;
+ if (!TOKEN || !PORT) {
+ window.__IMPECCABLE_LIVE_INIT__ = false; // reset so the real load can init
+ return;
+ }
+
+ // ---------------------------------------------------------------------------
+ // Design tokens
+ // ---------------------------------------------------------------------------
+
+ const C = {
+ brand: 'oklch(55% 0.25 350)',
+ brandHov: 'oklch(48% 0.25 350)',
+ brandSoft: 'oklch(55% 0.25 350 / 0.12)',
+ ink: 'oklch(15% 0.01 350)',
+ ash: 'oklch(55% 0 0)',
+ paper: 'oklch(98% 0.005 350 / 0.92)',
+ paperSolid:'oklch(98% 0.005 350)',
+ mist: 'oklch(90% 0.01 350 / 0.6)',
+ white: 'oklch(99% 0 0)',
+ };
+ const FONT = 'system-ui, -apple-system, sans-serif';
+ const MONO = 'ui-monospace, SFMono-Regular, Menlo, monospace';
+ const Z = { highlight: 99990, bar: 99995, picker: 99997, toast: 99999 };
+ const EASE = 'cubic-bezier(0.22, 1, 0.36, 1)'; // ease-out-quint
+ const PREFIX = 'impeccable-live';
+
+ const SKIP_TAGS = new Set([
+ 'html', 'head', 'body', 'script', 'style', 'link', 'meta', 'noscript', 'br', 'wbr',
+ ]);
+
+ const ACTIONS = [
+ { value: 'impeccable', label: 'Freeform' },
+ { value: 'bolder', label: 'Bolder' },
+ { value: 'quieter', label: 'Quieter' },
+ { value: 'distill', label: 'Distill' },
+ { value: 'polish', label: 'Polish' },
+ { value: 'typeset', label: 'Typeset' },
+ { value: 'colorize', label: 'Colorize' },
+ { value: 'layout', label: 'Layout' },
+ { value: 'adapt', label: 'Adapt' },
+ { value: 'animate', label: 'Animate' },
+ { value: 'delight', label: 'Delight' },
+ { value: 'overdrive', label: 'Overdrive' },
+ ];
+
+ // ---------------------------------------------------------------------------
+ // State
+ // ---------------------------------------------------------------------------
+
+ let state = 'IDLE';
+ let hoveredElement = null;
+ let selectedElement = null;
+ let currentSessionId = null;
+ let expectedVariants = 0;
+ let arrivedVariants = 0;
+ let visibleVariant = 0;
+ let variantObserver = null;
+ let hasProjectContext = false;
+ let selectedAction = 'impeccable';
+ let selectedCount = 3;
+
+ // UI refs
+ let highlightEl = null;
+ let tooltipEl = null;
+ let barEl = null;
+ let pickerEl = null;
+ let toastEl = null;
+ let scrollRaf = null;
+
+ // ---------------------------------------------------------------------------
+ // Helpers
+ // ---------------------------------------------------------------------------
+
+ function own(el) {
+ return el && (el.id?.startsWith(PREFIX) || el.closest?.('[id^="' + PREFIX + '"]'));
+ }
+
+ function pickable(el) {
+ if (!el || el.nodeType !== 1) return false;
+ if (SKIP_TAGS.has(el.tagName.toLowerCase())) return false;
+ if (own(el)) return false;
+ const r = el.getBoundingClientRect();
+ return r.width >= 20 && r.height >= 20;
+ }
+
+ function desc(el) {
+ if (!el) return '';
+ let s = el.tagName.toLowerCase();
+ if (el.id) s += '#' + el.id;
+ else if (el.classList.length) s += '.' + [...el.classList].slice(0, 2).join('.');
+ return s;
+ }
+
+ function id8() { return crypto.randomUUID().replace(/-/g, '').slice(0, 8); }
+
+ // ---------------------------------------------------------------------------
+ // Highlight overlay
+ // ---------------------------------------------------------------------------
+
+ function initHighlight() {
+ highlightEl = document.createElement('div');
+ highlightEl.id = PREFIX + '-highlight';
+ Object.assign(highlightEl.style, {
+ position: 'fixed', top: '0', left: '0', width: '0', height: '0',
+ border: '2px solid ' + C.brand, borderRadius: '3px',
+ pointerEvents: 'none', zIndex: Z.highlight, boxSizing: 'border-box',
+ transition: 'top 0.08s ease, left 0.08s ease, width 0.08s ease, height 0.08s ease, opacity 0.15s ease',
+ display: 'none', opacity: '0',
+ });
+ document.body.appendChild(highlightEl);
+
+ tooltipEl = document.createElement('div');
+ tooltipEl.id = PREFIX + '-tooltip';
+ Object.assign(tooltipEl.style, {
+ position: 'fixed',
+ background: C.ink, color: C.white,
+ fontFamily: MONO, fontSize: '10px', fontWeight: '500',
+ padding: '2px 6px', borderRadius: '3px',
+ zIndex: Z.highlight + 1, pointerEvents: 'none',
+ whiteSpace: 'nowrap', display: 'none',
+ letterSpacing: '0.02em',
+ });
+ document.body.appendChild(tooltipEl);
+ }
+
+ function showHighlight(el) {
+ if (!el || !highlightEl) return;
+ const r = el.getBoundingClientRect();
+ Object.assign(highlightEl.style, {
+ top: (r.top - 2) + 'px', left: (r.left - 2) + 'px',
+ width: (r.width + 4) + 'px', height: (r.height + 4) + 'px',
+ display: 'block', opacity: '1',
+ });
+ tooltipEl.textContent = desc(el);
+ const tipTop = r.top - 20;
+ Object.assign(tooltipEl.style, {
+ top: (tipTop < 4 ? r.bottom + 4 : tipTop) + 'px',
+ left: Math.max(4, r.left) + 'px', display: 'block',
+ });
+ }
+
+ function hideHighlight() {
+ if (highlightEl) { highlightEl.style.opacity = '0'; highlightEl.style.display = 'none'; }
+ if (tooltipEl) tooltipEl.style.display = 'none';
+ }
+
+ // ---------------------------------------------------------------------------
+ // Element context extraction
+ // ---------------------------------------------------------------------------
+
+ function extractContext(el) {
+ const cs = getComputedStyle(el);
+ const r = el.getBoundingClientRect();
+ const props = {};
+ for (const sheet of document.styleSheets) {
+ try {
+ for (const rule of sheet.cssRules) {
+ if (rule.style) for (let i = 0; i < rule.style.length; i++) {
+ const p = rule.style[i];
+ if (p.startsWith('--') && !props[p]) {
+ const v = cs.getPropertyValue(p).trim();
+ if (v) props[p] = v;
+ }
+ }
+ }
+ } catch { /* cross-origin */ }
+ }
+ return {
+ tagName: el.tagName.toLowerCase(), id: el.id || null,
+ classes: [...el.classList],
+ textContent: (el.textContent || '').slice(0, 500),
+ outerHTML: el.outerHTML.slice(0, 10000),
+ computedStyles: {
+ 'font-family': cs.fontFamily, 'font-size': cs.fontSize,
+ 'font-weight': cs.fontWeight, 'line-height': cs.lineHeight,
+ 'color': cs.color, 'background': cs.background,
+ 'background-color': cs.backgroundColor,
+ 'padding': cs.padding, 'margin': cs.margin,
+ 'display': cs.display, 'position': cs.position,
+ 'gap': cs.gap, 'border-radius': cs.borderRadius,
+ 'box-shadow': cs.boxShadow,
+ },
+ cssCustomProperties: props,
+ parentContext: el.parentElement
+ ? '<' + el.parentElement.tagName.toLowerCase()
+ + (el.parentElement.id ? ' id="' + el.parentElement.id + '"' : '')
+ + (el.parentElement.className ? ' class="' + el.parentElement.className + '"' : '')
+ + '>'
+ : null,
+ boundingRect: { width: Math.round(r.width), height: Math.round(r.height) },
+ };
+ }
+
+ // ---------------------------------------------------------------------------
+ // The Bar — one floating element, three modes
+ // ---------------------------------------------------------------------------
+
+ function initBar() {
+ barEl = document.createElement('div');
+ barEl.id = PREFIX + '-bar';
+ Object.assign(barEl.style, {
+ position: 'fixed', zIndex: Z.bar,
+ display: 'none', opacity: '0',
+ transform: 'translateY(6px)',
+ transition: 'opacity 0.25s ' + EASE + ', transform 0.3s ' + EASE,
+ // Visual
+ background: C.paper,
+ backdropFilter: 'blur(16px)', WebkitBackdropFilter: 'blur(16px)',
+ border: '1px solid ' + C.mist,
+ borderRadius: '10px',
+ boxShadow: '0 4px 20px oklch(0% 0 0 / 0.08), 0 1px 3px oklch(0% 0 0 / 0.06)',
+ fontFamily: FONT, fontSize: '13px', color: C.ink,
+ padding: '6px',
+ maxWidth: '460px', minWidth: '320px',
+ });
+ document.body.appendChild(barEl);
+ }
+
+ function positionBar() {
+ if (!barEl || !selectedElement) return;
+ const r = selectedElement.getBoundingClientRect();
+ const barH = barEl.offsetHeight || 44;
+ const barW = barEl.offsetWidth || 380;
+ let top = r.bottom + 8;
+ let left = r.left + (r.width - barW) / 2;
+ // Keep in viewport
+ if (top + barH + 8 > window.innerHeight) top = r.top - barH - 8;
+ if (top < 8) top = 8;
+ if (left < 8) left = 8;
+ if (left + barW > window.innerWidth - 8) left = window.innerWidth - barW - 8;
+ Object.assign(barEl.style, { top: top + 'px', left: left + 'px' });
+ }
+
+ function showBar(mode) {
+ barEl.innerHTML = '';
+ if (mode === 'configure') barEl.appendChild(buildConfigureRow());
+ else if (mode === 'generating') barEl.appendChild(buildGeneratingRow());
+ else if (mode === 'cycling') barEl.appendChild(buildCyclingRow());
+ barEl.style.display = 'block';
+ positionBar();
+ requestAnimationFrame(() => {
+ barEl.style.opacity = '1';
+ barEl.style.transform = 'translateY(0)';
+ });
+ }
+
+ function hideBar() {
+ if (!barEl) return;
+ barEl.style.opacity = '0';
+ barEl.style.transform = 'translateY(6px)';
+ setTimeout(() => { if (barEl) barEl.style.display = 'none'; }, 250);
+ hideActionPicker();
+ }
+
+ function updateBarContent(mode) {
+ if (!barEl || barEl.style.display === 'none') return;
+ barEl.innerHTML = '';
+ // Reset bar styling
+ barEl.style.background = C.paper;
+ barEl.style.border = '1px solid ' + C.mist;
+ if (mode === 'configure') barEl.appendChild(buildConfigureRow());
+ else if (mode === 'generating') barEl.appendChild(buildGeneratingRow());
+ else if (mode === 'cycling') barEl.appendChild(buildCyclingRow());
+ else if (mode === 'saving') barEl.appendChild(buildSavingRow());
+ else if (mode === 'confirmed') {
+ barEl.appendChild(buildConfirmedRow());
+ barEl.style.background = 'oklch(95% 0.05 145)';
+ barEl.style.border = '1px solid oklch(75% 0.12 145 / 0.4)';
+ }
+ }
+
+ // --- Configure row ---
+
+ function buildConfigureRow() {
+ const row = el('div', {
+ display: 'flex', alignItems: 'center', gap: '4px',
+ });
+
+ // Action pill
+ const pill = el('button', {
+ display: 'inline-flex', alignItems: 'center', gap: '4px',
+ padding: '5px 10px', borderRadius: '6px',
+ background: C.ink, color: C.white,
+ fontFamily: FONT, fontSize: '12px', fontWeight: '500',
+ border: 'none', cursor: 'pointer',
+ transition: 'background 0.12s ease, transform 0.1s ease',
+ whiteSpace: 'nowrap', flexShrink: '0',
+ });
+ pill.textContent = actionLabel() + ' \u25BE';
+ pill.addEventListener('mouseenter', () => pill.style.background = C.brandHov);
+ pill.addEventListener('mouseleave', () => pill.style.background = C.ink);
+ pill.addEventListener('mousedown', () => pill.style.transform = 'scale(0.97)');
+ pill.addEventListener('mouseup', () => pill.style.transform = 'scale(1)');
+ pill.addEventListener('click', (e) => { e.stopPropagation(); toggleActionPicker(); });
+ row.appendChild(pill);
+
+ // Freeform input
+ const input = document.createElement('input');
+ input.id = PREFIX + '-input';
+ input.type = 'text';
+ input.placeholder = selectedAction === 'impeccable' ? 'describe what you want...' : 'refine further (optional)...';
+ Object.assign(input.style, {
+ flex: '1', minWidth: '0',
+ padding: '5px 8px', borderRadius: '6px',
+ border: '1px solid transparent', background: 'transparent',
+ fontFamily: FONT, fontSize: '12px', color: C.ink,
+ outline: 'none',
+ transition: 'border-color 0.15s ease, background 0.15s ease',
+ });
+ input.addEventListener('focus', () => {
+ input.style.borderColor = C.mist;
+ input.style.background = C.white;
+ });
+ input.addEventListener('blur', () => {
+ input.style.borderColor = 'transparent';
+ input.style.background = 'transparent';
+ });
+ input.addEventListener('keydown', (e) => {
+ e.stopPropagation(); // Don't trigger element picker keyboard nav
+ if (e.key === 'Enter') { e.preventDefault(); handleGo(); }
+ if (e.key === 'Escape') { e.preventDefault(); input.blur(); hideBar(); state = 'PICKING'; }
+ });
+ row.appendChild(input);
+
+ // Variant count toggle
+ const count = el('button', {
+ padding: '4px 6px', borderRadius: '5px',
+ border: '1px solid ' + C.mist, background: 'transparent',
+ fontFamily: MONO, fontSize: '11px', fontWeight: '600',
+ color: C.ash, cursor: 'pointer',
+ transition: 'color 0.12s ease, border-color 0.12s ease',
+ flexShrink: '0', whiteSpace: 'nowrap',
+ });
+ count.textContent = '\u00D7' + selectedCount;
+ count.title = 'Variants: click to change';
+ count.addEventListener('mouseenter', () => { count.style.color = C.ink; count.style.borderColor = C.ink; });
+ count.addEventListener('mouseleave', () => { count.style.color = C.ash; count.style.borderColor = C.mist; });
+ count.addEventListener('click', (e) => {
+ e.stopPropagation();
+ selectedCount = selectedCount >= 4 ? 2 : selectedCount + 1;
+ count.textContent = '\u00D7' + selectedCount;
+ });
+ row.appendChild(count);
+
+ // Go button
+ const go = el('button', {
+ padding: '5px 12px', borderRadius: '6px',
+ border: 'none', background: C.brand, color: C.white,
+ fontFamily: FONT, fontSize: '12px', fontWeight: '600',
+ cursor: 'pointer',
+ transition: 'background 0.12s ease, transform 0.1s ease',
+ flexShrink: '0', whiteSpace: 'nowrap',
+ });
+ go.textContent = 'Go \u2192';
+ go.addEventListener('mouseenter', () => go.style.background = C.brandHov);
+ go.addEventListener('mouseleave', () => go.style.background = C.brand);
+ go.addEventListener('mousedown', () => go.style.transform = 'scale(0.97)');
+ go.addEventListener('mouseup', () => go.style.transform = 'scale(1)');
+ go.addEventListener('click', (e) => { e.stopPropagation(); handleGo(); });
+ row.appendChild(go);
+
+ // Auto-focus input after a beat
+ setTimeout(() => input.focus(), 60);
+ return row;
+ }
+
+ // --- Generating row ---
+
+ function buildGeneratingRow() {
+ const row = el('div', {
+ display: 'flex', alignItems: 'center', gap: '8px',
+ padding: '2px 4px',
+ });
+
+ // Action label
+ const label = el('span', {
+ fontWeight: '600', fontSize: '12px', color: C.ink,
+ flexShrink: '0', whiteSpace: 'nowrap',
+ });
+ label.textContent = actionLabel();
+ row.appendChild(label);
+
+ // Dots
+ row.appendChild(buildDots(false));
+
+ // Status
+ const status = el('span', {
+ fontSize: '11px', color: C.ash, whiteSpace: 'nowrap',
+ marginLeft: 'auto',
+ });
+ status.textContent = arrivedVariants < expectedVariants
+ ? 'Generating ' + (arrivedVariants + 1) + ' of ' + expectedVariants + '...'
+ : 'Done';
+ row.appendChild(status);
+
+ return row;
+ }
+
+ // --- Cycling row ---
+
+ function buildCyclingRow() {
+ const row = el('div', {
+ display: 'flex', alignItems: 'center', gap: '6px',
+ padding: '1px 2px',
+ });
+
+ // Prev
+ const prev = navBtn('\u2190');
+ prev.addEventListener('click', (e) => { e.stopPropagation(); cycleVariant(-1); });
+ if (visibleVariant <= 1) prev.style.opacity = '0.3';
+ row.appendChild(prev);
+
+ // Dots (clickable)
+ row.appendChild(buildDots(true));
+
+ // Counter
+ const counter = el('span', {
+ fontFamily: MONO, fontSize: '11px', fontWeight: '500',
+ color: C.ash, minWidth: '24px', textAlign: 'center',
+ });
+ counter.textContent = visibleVariant + '/' + arrivedVariants;
+ row.appendChild(counter);
+
+ // Next
+ const next = navBtn('\u2192');
+ next.addEventListener('click', (e) => { e.stopPropagation(); cycleVariant(1); });
+ if (visibleVariant >= arrivedVariants) next.style.opacity = '0.3';
+ row.appendChild(next);
+
+ // Spacer
+ row.appendChild(el('div', { flex: '1' }));
+
+ // Accept
+ const accept = el('button', {
+ padding: '4px 10px', borderRadius: '5px',
+ border: 'none', background: C.ink, color: C.white,
+ fontFamily: FONT, fontSize: '11px', fontWeight: '600',
+ cursor: 'pointer', transition: 'background 0.12s ease',
+ whiteSpace: 'nowrap',
+ });
+ accept.textContent = '\u2713 Accept';
+ accept.addEventListener('mouseenter', () => accept.style.background = C.brand);
+ accept.addEventListener('mouseleave', () => accept.style.background = C.ink);
+ accept.addEventListener('click', (e) => { e.stopPropagation(); handleAccept(); });
+ if (arrivedVariants === 0) { accept.style.opacity = '0.3'; accept.style.pointerEvents = 'none'; }
+ row.appendChild(accept);
+
+ // Discard
+ const discard = el('button', {
+ padding: '4px 6px', borderRadius: '5px',
+ border: '1px solid ' + C.mist, background: 'transparent',
+ fontFamily: FONT, fontSize: '11px', color: C.ash,
+ cursor: 'pointer', transition: 'color 0.12s ease, border-color 0.12s ease',
+ });
+ discard.textContent = '\u2715';
+ discard.title = 'Discard all variants';
+ discard.addEventListener('mouseenter', () => { discard.style.color = C.ink; discard.style.borderColor = C.ink; });
+ discard.addEventListener('mouseleave', () => { discard.style.color = C.ash; discard.style.borderColor = C.mist; });
+ discard.addEventListener('click', (e) => { e.stopPropagation(); handleDiscard(); });
+ row.appendChild(discard);
+
+ return row;
+ }
+
+ // --- Shared UI builders ---
+
+ // --- Saving row (waiting for agent to process accept/discard) ---
+
+ function buildSavingRow() {
+ const row = el('div', {
+ display: 'flex', alignItems: 'center', gap: '8px',
+ padding: '2px 8px',
+ });
+ const spinner = el('div', {
+ width: '14px', height: '14px', borderRadius: '50%',
+ border: '2px solid ' + C.mist,
+ borderTopColor: C.brand,
+ animation: 'impeccable-spin 0.6s linear infinite',
+ flexShrink: '0',
+ });
+ row.appendChild(spinner);
+ const label = el('span', {
+ fontSize: '12px', color: C.ash, fontWeight: '500',
+ });
+ label.textContent = 'Applying variant...';
+ row.appendChild(label);
+
+ // Inject the keyframes if not already present
+ if (!document.getElementById(PREFIX + '-keyframes')) {
+ const style = document.createElement('style');
+ style.id = PREFIX + '-keyframes';
+ style.textContent = '@keyframes impeccable-spin { to { transform: rotate(360deg); } }';
+ document.head.appendChild(style);
+ }
+ return row;
+ }
+
+ // --- Confirmed row (green success, auto-dismisses) ---
+
+ function buildConfirmedRow() {
+ const row = el('div', {
+ display: 'flex', alignItems: 'center', gap: '8px',
+ padding: '2px 8px',
+ });
+ const check = el('span', {
+ fontSize: '15px', lineHeight: '1', flexShrink: '0',
+ color: 'oklch(45% 0.15 145)',
+ });
+ check.textContent = '\u2713';
+ row.appendChild(check);
+ const label = el('span', {
+ fontSize: '12px', color: 'oklch(35% 0.1 145)', fontWeight: '600',
+ });
+ label.textContent = 'Variant applied';
+ row.appendChild(label);
+ return row;
+ }
+
+ // --- Shared UI builders ---
+
+ function buildDots(clickable) {
+ const container = el('div', {
+ display: 'flex', alignItems: 'center', gap: '4px',
+ });
+ for (let i = 1; i <= expectedVariants; i++) {
+ const arrived = i <= arrivedVariants;
+ const active = i === visibleVariant;
+ const dot = el('div', {
+ width: '7px', height: '7px', borderRadius: '50%',
+ background: active ? C.brand : (arrived ? C.ash : 'transparent'),
+ border: '1.5px solid ' + (arrived ? C.brand : C.mist),
+ transition: 'all 0.2s ' + EASE,
+ cursor: (clickable && arrived) ? 'pointer' : 'default',
+ transform: arrived ? 'scale(1)' : 'scale(0.6)',
+ opacity: arrived ? '1' : '0.4',
+ });
+ if (clickable && arrived) {
+ const idx = i;
+ dot.addEventListener('click', (e) => {
+ e.stopPropagation();
+ visibleVariant = idx;
+ showVariantInDOM(currentSessionId, idx);
+ updateSelectedElement();
+ updateBarContent('cycling');
+ });
+ }
+ container.appendChild(dot);
+ }
+ return container;
+ }
+
+ function navBtn(text) {
+ const b = el('button', {
+ width: '26px', height: '26px', borderRadius: '5px',
+ border: '1px solid ' + C.mist, background: 'transparent',
+ color: C.ink, fontFamily: FONT, fontSize: '13px',
+ cursor: 'pointer', display: 'flex', alignItems: 'center', justifyContent: 'center',
+ transition: 'border-color 0.12s ease, background 0.12s ease',
+ padding: '0', lineHeight: '1',
+ });
+ b.textContent = text;
+ b.addEventListener('mouseenter', () => { b.style.borderColor = C.ink; });
+ b.addEventListener('mouseleave', () => { b.style.borderColor = C.mist; });
+ return b;
+ }
+
+ function actionLabel() {
+ const a = ACTIONS.find(a => a.value === selectedAction);
+ return a ? a.label : 'Freeform';
+ }
+
+ function el(tag, styles) {
+ const e = document.createElement(tag);
+ if (styles) Object.assign(e.style, styles);
+ return e;
+ }
+
+ // ---------------------------------------------------------------------------
+ // Action picker popover
+ // ---------------------------------------------------------------------------
+
+ function initActionPicker() {
+ pickerEl = document.createElement('div');
+ pickerEl.id = PREFIX + '-picker';
+ Object.assign(pickerEl.style, {
+ position: 'fixed', zIndex: Z.picker,
+ display: 'none', opacity: '0',
+ transform: 'scale(0.96) translateY(4px)',
+ transformOrigin: 'bottom left',
+ transition: 'opacity 0.18s ' + EASE + ', transform 0.2s ' + EASE,
+ background: C.paperSolid,
+ border: '1px solid ' + C.mist,
+ borderRadius: '10px',
+ boxShadow: '0 8px 30px oklch(0% 0 0 / 0.10), 0 2px 6px oklch(0% 0 0 / 0.06)',
+ padding: '6px',
+ fontFamily: FONT,
+ });
+
+ // Build the chip grid
+ const grid = el('div', {
+ display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', gap: '3px',
+ });
+
+ ACTIONS.forEach(action => {
+ const chip = el('button', {
+ padding: '6px 8px', borderRadius: '6px',
+ border: 'none',
+ background: action.value === selectedAction ? C.brandSoft : 'transparent',
+ color: action.value === selectedAction ? C.brand : C.ink,
+ fontFamily: FONT, fontSize: '11px', fontWeight: '500',
+ cursor: 'pointer',
+ transition: 'background 0.1s ease, color 0.1s ease',
+ textAlign: 'center', whiteSpace: 'nowrap',
+ });
+ chip.textContent = action.label;
+ chip.dataset.action = action.value;
+ chip.addEventListener('mouseenter', () => {
+ if (action.value !== selectedAction) chip.style.background = C.brandSoft;
+ });
+ chip.addEventListener('mouseleave', () => {
+ chip.style.background = action.value === selectedAction ? C.brandSoft : 'transparent';
+ });
+ chip.addEventListener('click', (e) => {
+ e.stopPropagation();
+ selectedAction = action.value;
+ hideActionPicker();
+ updateBarContent('configure');
+ });
+ grid.appendChild(chip);
+ });
+
+ pickerEl.appendChild(grid);
+ document.body.appendChild(pickerEl);
+ }
+
+ function toggleActionPicker() {
+ if (pickerEl.style.display !== 'none') { hideActionPicker(); return; }
+ // Rebuild chips to reflect current selection
+ pickerEl.querySelectorAll('button').forEach(chip => {
+ const isActive = chip.dataset.action === selectedAction;
+ chip.style.background = isActive ? C.brandSoft : 'transparent';
+ chip.style.color = isActive ? C.brand : C.ink;
+ });
+ // Position above the bar
+ const barRect = barEl.getBoundingClientRect();
+ const pickerH = 90; // approximate
+ let top = barRect.top - pickerH - 6;
+ if (top < 8) top = barRect.bottom + 6;
+ Object.assign(pickerEl.style, {
+ top: top + 'px', left: barRect.left + 'px',
+ display: 'block',
+ });
+ requestAnimationFrame(() => {
+ pickerEl.style.opacity = '1';
+ pickerEl.style.transform = 'scale(1) translateY(0)';
+ });
+ }
+
+ function hideActionPicker() {
+ if (!pickerEl) return;
+ pickerEl.style.opacity = '0';
+ pickerEl.style.transform = 'scale(0.96) translateY(4px)';
+ setTimeout(() => { if (pickerEl) pickerEl.style.display = 'none'; }, 180);
+ }
+
+ // ---------------------------------------------------------------------------
+ // Variant cycling in DOM
+ // ---------------------------------------------------------------------------
+
+ function showVariantInDOM(sessionId, num) {
+ const wrapper = document.querySelector('[data-impeccable-variants="' + sessionId + '"]');
+ if (!wrapper) return;
+ for (const child of wrapper.children) {
+ const v = child.dataset ? child.dataset.impeccableVariant : null;
+ if (!v) continue;
+ child.style.display = (v === String(num)) ? '' : 'none';
+ }
+ }
+
+ /**
+ * No-HMR fallback: fetch the raw source file from the live server,
+ * parse it, extract the variant wrapper, and inject it into the live DOM.
+ * This works even when the dev server caches HTML (Bun, static servers).
+ */
+ function injectVariantsFromSource(filePath, sessionId) {
+ const url = 'http://localhost:' + PORT + '/source?token=' + TOKEN + '&path=' + encodeURIComponent(filePath);
+ fetch(url)
+ .then(r => { if (!r.ok) throw new Error(r.status); return r.text(); })
+ .then(html => {
+ // Parse the raw source HTML
+ const parser = new DOMParser();
+ const doc = parser.parseFromString(html, 'text/html');
+ const srcWrapper = doc.querySelector('[data-impeccable-variants="' + sessionId + '"]');
+ if (!srcWrapper) {
+ console.error('[impeccable] Variant wrapper not found in source file.');
+ return;
+ }
+
+ // Find the original element in the live DOM.
+ // The original is inside the wrapper in the source. We find the
+ // corresponding element in the live DOM by matching the first child's
+ // tag + classes from the original snapshot.
+ const origContent = srcWrapper.querySelector('[data-impeccable-variant="original"] > :first-child');
+ if (!origContent) return;
+
+ const tag = origContent.tagName.toLowerCase();
+ const cls = origContent.className;
+ let liveEl = null;
+ if (origContent.id) {
+ liveEl = document.getElementById(origContent.id);
+ } else if (cls) {
+ // Find by tag + exact class match
+ const candidates = document.querySelectorAll(tag + '.' + cls.split(' ')[0]);
+ for (const c of candidates) {
+ if (c.className === cls && !own(c)) { liveEl = c; break; }
+ }
+ }
+
+ if (!liveEl) {
+ console.error('[impeccable] Could not find original element in live DOM.');
+ return;
+ }
+
+ // Replace the live element with the full wrapper from source
+ const wrapper = srcWrapper.cloneNode(true);
+ liveEl.parentElement.replaceChild(wrapper, liveEl);
+
+ // Update state: count variants, show the first one
+ 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);
+
+ // Update selectedElement to the visible variant's content
+ const visEl = wrapper.querySelector('[data-impeccable-variant="1"] > :first-child');
+ selectedElement = visEl || wrapper.parentElement;
+
+ state = 'CYCLING';
+ updateBarContent('cycling');
+ saveSession();
+ console.log('[impeccable] Injected ' + arrivedVariants + ' variants from source file.');
+ })
+ .catch(err => {
+ console.error('[impeccable] Failed to fetch source:', err);
+ showToast('Could not load variants. Try refreshing the page.', 5000);
+ });
+ }
+
+ function cycleVariant(dir) {
+ const next = visibleVariant + dir;
+ if (next < 1 || next > arrivedVariants) return;
+ visibleVariant = next;
+ showVariantInDOM(currentSessionId, next);
+ updateSelectedElement();
+ updateBarContent('cycling');
+ saveSession();
+ }
+
+ function updateSelectedElement() {
+ if (!currentSessionId) return;
+ const wrapper = document.querySelector('[data-impeccable-variants="' + currentSessionId + '"]');
+ if (!wrapper) return;
+ const visEl = wrapper.querySelector('[data-impeccable-variant="' + visibleVariant + '"] > :first-child');
+ if (visEl) selectedElement = visEl;
+ }
+
+ // ---------------------------------------------------------------------------
+ // MutationObserver for progressive variant reveal
+ // ---------------------------------------------------------------------------
+
+ function startVariantObserver(sessionId) {
+ let updating = false; // re-entrancy guard
+
+ const obs = new MutationObserver((mutations) => {
+ if (updating) return;
+
+ // Only react to mutations that add nodes with data-impeccable-variant,
+ // or mutations inside the variant wrapper. Ignore our own bar/UI changes.
+ let dominated = false;
+ for (const m of mutations) {
+ if (m.target.closest?.('[data-impeccable-variants]')) { dominated = true; break; }
+ for (const n of m.addedNodes) {
+ if (n.nodeType === 1 && (n.dataset?.impeccableVariants || n.dataset?.impeccableVariant)) {
+ dominated = true; break;
+ }
+ }
+ if (dominated) break;
+ }
+ if (!dominated) return;
+
+ const wrapper = document.querySelector('[data-impeccable-variants="' + sessionId + '"]');
+ if (!wrapper) return;
+
+ const variants = wrapper.querySelectorAll('[data-impeccable-variant]:not([data-impeccable-variant="original"])');
+ const count = variants.length;
+
+ // Nothing new
+ if (count <= arrivedVariants) return;
+
+ updating = true;
+ arrivedVariants = count;
+ if (visibleVariant === 0 && arrivedVariants > 0) {
+ visibleVariant = 1;
+ showVariantInDOM(sessionId, 1);
+ }
+
+ const expected = parseInt(wrapper.dataset.impeccableVariantCount || '0');
+ if (expected > 0) expectedVariants = expected;
+
+ if (arrivedVariants >= expectedVariants && expectedVariants > 0) {
+ state = 'CYCLING';
+ updateBarContent('cycling');
+ } else if (state === 'GENERATING') {
+ updateBarContent('generating');
+ }
+ saveSession();
+ updating = false;
+ });
+
+ obs.observe(document.body, { childList: true, subtree: true });
+ return obs;
+ }
+
+ // ---------------------------------------------------------------------------
+ // Bar scroll tracking
+ // ---------------------------------------------------------------------------
+
+ function startScrollTracking() {
+ function tick() {
+ if (state === 'CONFIGURING' || state === 'GENERATING' || state === 'CYCLING') {
+ positionBar();
+ showHighlight(selectedElement);
+ }
+ scrollRaf = requestAnimationFrame(tick);
+ }
+ scrollRaf = requestAnimationFrame(tick);
+ }
+
+ function stopScrollTracking() {
+ if (scrollRaf) { cancelAnimationFrame(scrollRaf); scrollRaf = null; }
+ }
+
+ // ---------------------------------------------------------------------------
+ // SSE (server→browser) + fetch POST (browser→server)
+ // Zero-dependency replacement for WebSocket.
+ // ---------------------------------------------------------------------------
+
+ let evtSource = null;
+
+ function connectSSE() {
+ evtSource = new EventSource('http://localhost:' + PORT + '/events?token=' + TOKEN);
+
+ evtSource.onmessage = (e) => {
+ let msg; try { msg = JSON.parse(e.data); } catch { return; }
+ switch (msg.type) {
+ case 'connected':
+ hasProjectContext = !!msg.hasProjectContext;
+ if (!hasProjectContext) showToast('No .impeccable.md found. Variants will be brand-agnostic.', 6000);
+ console.log('[impeccable] Live mode connected.');
+ if (state === 'IDLE') state = 'PICKING';
+ break;
+ case 'done':
+ if (state === 'SAVING') {
+ state = 'CONFIRMED';
+ updateBarContent('confirmed');
+ setTimeout(() => {
+ hideBar();
+ hideHighlight();
+ stopScrollTracking();
+ if (variantObserver) { variantObserver.disconnect(); variantObserver = null; }
+ clearSession();
+ selectedElement = null;
+ currentSessionId = null;
+ selectedAction = 'impeccable';
+ state = 'PICKING';
+ }, 1800);
+ return;
+ }
+ if (arrivedVariants === 0 && expectedVariants > 0 && msg.file) {
+ console.log('[impeccable] No HMR detected. Fetching variants from source file...');
+ injectVariantsFromSource(msg.file, currentSessionId);
+ return;
+ }
+ state = 'CYCLING';
+ updateBarContent('cycling');
+ break;
+ case 'error':
+ console.error('[impeccable] Error:', msg.message);
+ showToast('Error: ' + msg.message, 5000);
+ hideBar();
+ state = 'PICKING';
+ break;
+ }
+ };
+
+ evtSource.onerror = () => {
+ // EventSource auto-reconnects. Log once.
+ console.log('[impeccable] SSE connection lost. Reconnecting...');
+ };
+ }
+
+ function sendEvent(msg) {
+ msg.token = TOKEN;
+ 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));
+ }
+
+ // ---------------------------------------------------------------------------
+ // Event handlers
+ // ---------------------------------------------------------------------------
+
+ function handleMouseMove(e) {
+ if (state !== 'PICKING') return;
+ const target = document.elementFromPoint(e.clientX, e.clientY);
+ if (!target || !pickable(target) || target === hoveredElement) return;
+ hoveredElement = target;
+ showHighlight(target);
+ }
+
+ function handleClick(e) {
+ // Close action picker on any outside click
+ if (pickerEl?.style.display !== 'none' && !own(e.target)) {
+ hideActionPicker();
+ }
+ if (state !== 'PICKING') return;
+ if (own(e.target)) return;
+ if (!hoveredElement || !pickable(hoveredElement)) return;
+ e.preventDefault();
+ e.stopPropagation();
+ selectedElement = hoveredElement;
+ state = 'CONFIGURING';
+ showHighlight(selectedElement);
+ showBar('configure');
+ startScrollTracking();
+ }
+
+ function handleKeyDown(e) {
+ if (e.key === 'Escape') {
+ e.preventDefault();
+ if (pickerEl?.style.display !== 'none') { hideActionPicker(); return; }
+ if (state === 'CONFIGURING') { hideBar(); stopScrollTracking(); state = 'PICKING'; return; }
+ if (state === 'CYCLING') { handleDiscard(); return; }
+ if (state === 'SAVING' || state === 'CONFIRMED') return; // don't interrupt
+ if (state === 'PICKING') { hideHighlight(); state = 'IDLE'; return; }
+ }
+
+ if (state === 'PICKING' && hoveredElement) {
+ let next = null;
+ if (e.key === 'ArrowDown' && !e.shiftKey) {
+ next = hoveredElement.nextElementSibling;
+ while (next && !pickable(next)) next = next.nextElementSibling;
+ } else if (e.key === 'ArrowUp' && !e.shiftKey) {
+ next = hoveredElement.previousElementSibling;
+ while (next && !pickable(next)) next = next.previousElementSibling;
+ } else if (e.key === 'ArrowUp' && e.shiftKey) {
+ next = hoveredElement.parentElement;
+ if (next && !pickable(next)) next = null;
+ } else if (e.key === 'ArrowDown' && e.shiftKey) {
+ next = hoveredElement.firstElementChild;
+ while (next && !pickable(next)) next = next.nextElementSibling;
+ } else if (e.key === 'Enter') {
+ e.preventDefault();
+ selectedElement = hoveredElement;
+ state = 'CONFIGURING';
+ showHighlight(selectedElement);
+ showBar('configure');
+ startScrollTracking();
+ return;
+ }
+ if (next) {
+ e.preventDefault();
+ hoveredElement = next;
+ showHighlight(next);
+ next.scrollIntoView({ block: 'nearest', behavior: 'smooth' });
+ }
+ return;
+ }
+
+ if (state === 'CYCLING') {
+ if (e.key === 'ArrowLeft') { e.preventDefault(); cycleVariant(-1); }
+ if (e.key === 'ArrowRight') { e.preventDefault(); cycleVariant(1); }
+ if (e.key === 'Enter') { e.preventDefault(); handleAccept(); }
+ }
+ }
+
+ function handleGo() {
+ if (!selectedElement || state !== 'CONFIGURING') return;
+ const input = document.getElementById(PREFIX + '-input');
+ const prompt = input ? input.value.trim() : '';
+
+ currentSessionId = id8();
+ expectedVariants = selectedCount;
+ arrivedVariants = 0;
+ visibleVariant = 0;
+
+ sendEvent({
+ type: 'generate', id: currentSessionId,
+ action: selectedAction,
+ freeformPrompt: prompt || undefined,
+ count: selectedCount,
+ pageUrl: location.pathname,
+ element: extractContext(selectedElement),
+ });
+
+ state = 'GENERATING';
+ showBar('generating');
+ saveSession();
+ if (variantObserver) variantObserver.disconnect();
+ variantObserver = startVariantObserver(currentSessionId);
+ }
+
+ function handleAccept() {
+ if (!currentSessionId || arrivedVariants === 0) return;
+ sendEvent({ type: 'accept', id: currentSessionId, variantId: String(visibleVariant) });
+ markSessionHandled();
+ state = 'SAVING';
+ updateBarContent('saving');
+ // Don't cleanup yet — wait for the "done" WS message to show confirmation
+ }
+
+ function handleDiscard() {
+ if (!currentSessionId) return;
+ sendEvent({ type: 'discard', id: currentSessionId });
+ markSessionHandled();
+ state = 'SAVING';
+ updateBarContent('saving');
+ // Wait for "done" WS message to show confirmation and dismiss
+ }
+
+ // ---------------------------------------------------------------------------
+ // Session persistence via localStorage
+ // ---------------------------------------------------------------------------
+ // Survives page reloads, browser close/reopen, HMR, and accidental refreshes.
+
+ const LS_KEY = PREFIX + '-session';
+
+ function saveSession() {
+ if (!currentSessionId) return;
+ 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 */ }
+ }
+
+ function loadSession() {
+ try {
+ const raw = localStorage.getItem(LS_KEY);
+ return raw ? JSON.parse(raw) : null;
+ } catch { return null; }
+ }
+
+ function clearSession() {
+ try { localStorage.removeItem(LS_KEY); } catch {}
+ }
+
+ /** Mark session as handled (accepted/discarded). The agent will clean up
+ * the source, but until it does the wrapper is still in the HTML. This
+ * prevents resumeSession from picking it up again after reload. */
+ function markSessionHandled() {
+ if (!currentSessionId) return;
+ try {
+ localStorage.setItem(LS_KEY + '-handled', currentSessionId);
+ } catch {}
+ }
+
+ function isSessionHandled(id) {
+ try {
+ return localStorage.getItem(LS_KEY + '-handled') === id;
+ } catch { return false; }
+ }
+
+ function clearHandled() {
+ try { localStorage.removeItem(LS_KEY + '-handled'); } catch {}
+ }
+
+ function cleanup() {
+ hideBar();
+ hideHighlight();
+ stopScrollTracking();
+ if (variantObserver) { variantObserver.disconnect(); variantObserver = null; }
+ clearSession();
+ selectedElement = null;
+ currentSessionId = null;
+ selectedAction = 'impeccable';
+ state = 'PICKING';
+ }
+
+ // ---------------------------------------------------------------------------
+ // Toast
+ // ---------------------------------------------------------------------------
+
+ function showToast(message, duration) {
+ if (toastEl) toastEl.remove();
+ toastEl = el('div', {
+ position: 'fixed', bottom: '16px', left: '50%',
+ transform: 'translateX(-50%) translateY(8px)',
+ background: C.ink, color: C.white,
+ fontFamily: FONT, fontSize: '12px',
+ padding: '8px 16px', borderRadius: '8px',
+ zIndex: Z.toast, opacity: '0',
+ transition: 'opacity 0.25s ' + EASE + ', transform 0.25s ' + EASE,
+ pointerEvents: 'none', maxWidth: '420px', textAlign: 'center',
+ });
+ toastEl.id = PREFIX + '-toast';
+ toastEl.textContent = message;
+ document.body.appendChild(toastEl);
+ requestAnimationFrame(() => {
+ toastEl.style.opacity = '1';
+ toastEl.style.transform = 'translateX(-50%) translateY(0)';
+ });
+ setTimeout(() => {
+ if (toastEl) {
+ toastEl.style.opacity = '0';
+ toastEl.style.transform = 'translateX(-50%) translateY(8px)';
+ setTimeout(() => { if (toastEl) { toastEl.remove(); toastEl = null; } }, 250);
+ }
+ }, duration);
+ }
+
+ // ---------------------------------------------------------------------------
+ // Init
+ // ---------------------------------------------------------------------------
+
+ // Resume an active variant session after HMR/page reload.
+ // If a [data-impeccable-variants] wrapper exists in the DOM, the agent wrote
+ // variants before HMR fired. Pick up where we left off.
+ function resumeSession() {
+ const wrapper = document.querySelector('[data-impeccable-variants]');
+ if (!wrapper) { clearSession(); clearHandled(); return false; }
+
+ const sessionId = wrapper.dataset.impeccableVariants;
+
+ // Don't resume if this session was already accepted/discarded
+ if (isSessionHandled(sessionId)) return false;
+
+ currentSessionId = sessionId;
+ expectedVariants = parseInt(wrapper.dataset.impeccableVariantCount || '0');
+ const variants = wrapper.querySelectorAll('[data-impeccable-variant]:not([data-impeccable-variant="original"])');
+ arrivedVariants = variants.length;
+
+ // Restore visible variant from localStorage if available, else default to 1
+ const saved = loadSession();
+ visibleVariant = (saved && saved.id === sessionId && saved.visible > 0 && saved.visible <= arrivedVariants)
+ ? saved.visible : (arrivedVariants > 0 ? 1 : 0);
+
+ // Find the visible variant's content element for highlight positioning
+ const visEl = wrapper.querySelector('[data-impeccable-variant="' + visibleVariant + '"] > :first-child');
+ selectedElement = visEl || wrapper.parentElement;
+
+ // Set display state BEFORE starting observer (avoid triggering it)
+ if (visibleVariant > 0) showVariantInDOM(currentSessionId, visibleVariant);
+
+ state = arrivedVariants >= expectedVariants ? 'CYCLING' : 'GENERATING';
+ showBar(state === 'CYCLING' ? 'cycling' : 'generating');
+ startScrollTracking();
+ saveSession();
+
+ // Start observing for more variants AFTER initial setup
+ if (variantObserver) variantObserver.disconnect();
+ variantObserver = startVariantObserver(currentSessionId);
+ return true;
+ }
+
+ function init() {
+ initHighlight();
+ initBar();
+ initActionPicker();
+ document.addEventListener('mousemove', handleMouseMove, true);
+ document.addEventListener('click', handleClick, true);
+ document.addEventListener('keydown', handleKeyDown, true);
+ connectSSE();
+
+ // Check for an active session to resume (variant wrapper already in DOM after HMR)
+ if (!resumeSession()) {
+ console.log('[impeccable] Live variant mode ready. Hover over elements to pick one.');
+ } else {
+ console.log('[impeccable] Resumed active variant session ' + currentSessionId + ' (' + arrivedVariants + '/' + expectedVariants + ' variants).');
+ }
+ }
+
+ if (document.readyState === 'loading') {
+ document.addEventListener('DOMContentLoaded', init);
+ } else {
+ init();
+ }
+})();
diff --git a/.claude/skills/impeccable/scripts/live-poll.mjs b/.claude/skills/impeccable/scripts/live-poll.mjs
new file mode 100644
index 000000000..52859416c
--- /dev/null
+++ b/.claude/skills/impeccable/scripts/live-poll.mjs
@@ -0,0 +1,123 @@
+/**
+ * CLI client for the live variant mode poll/reply protocol.
+ *
+ * Usage:
+ * npx impeccable poll # Block until browser event, print JSON
+ * npx impeccable poll --timeout=60000 # Custom timeout (ms)
+ * npx impeccable poll --reply <id> done # Reply "done" to event <id>
+ * npx impeccable poll --reply <id> error "msg" # Reply with error
+ */
+
+import fs from 'node:fs';
+import path from 'node:path';
+import os from 'node:os';
+
+const LIVE_PID_FILE = path.join(os.tmpdir(), 'impeccable-live.json');
+
+function readServerInfo() {
+ try {
+ return JSON.parse(fs.readFileSync(LIVE_PID_FILE, 'utf-8'));
+ } catch {
+ console.error('No running live server found. Start one with: npx impeccable live');
+ process.exit(1);
+ }
+}
+
+export async function pollCli() {
+ const args = process.argv.slice(2);
+
+ if (args.includes('--help') || args.includes('-h')) {
+ console.log(`Usage: impeccable poll [options]
+
+Wait for a browser event from the live variant server, or reply to one.
+
+Modes:
+ poll Block until a browser event arrives, print JSON
+ poll --reply <id> done Reply "done" to event <id>
+ poll --reply <id> error "msg" Reply with an error message
+
+Options:
+ --timeout=MS Poll timeout in milliseconds (default: 120000)
+ --help Show this help message`);
+ process.exit(0);
+ }
+
+ const info = readServerInfo();
+ const base = `http://localhost:${info.port}`;
+
+ // Reply mode: npx impeccable poll --reply <id> <status> [--file path] [message]
+ const replyIdx = args.indexOf('--reply');
+ if (replyIdx !== -1) {
+ const id = args[replyIdx + 1];
+ const status = args[replyIdx + 2] || 'done';
+ const fileIdx = args.indexOf('--file');
+ const filePath = fileIdx !== -1 && fileIdx + 1 < args.length ? args[fileIdx + 1] : undefined;
+ // Message is any remaining positional arg that isn't a flag
+ const message = args.find((a, i) => i > replyIdx + 2 && !a.startsWith('--') && i !== fileIdx + 1) || undefined;
+
+ if (!id) {
+ console.error('Usage: npx impeccable poll --reply <id> <status> [--file path] [message]');
+ process.exit(1);
+ }
+
+ 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);
+ }
+
+ // Success — silent exit (agent doesn't need output for replies)
+ } catch (err) {
+ if (err.cause?.code === 'ECONNREFUSED') {
+ console.error('Live server not running. Start one with: npx impeccable live');
+ } else {
+ console.error('Reply failed:', err.message);
+ }
+ process.exit(1);
+ }
+ return;
+ }
+
+ // Poll mode: block until browser event
+ const timeoutArg = args.find(a => a.startsWith('--timeout='));
+ const timeout = timeoutArg ? parseInt(timeoutArg.split('=')[1], 10) : 120000;
+
+ try {
+ const res = await fetch(`${base}/poll?token=${info.token}&timeout=${timeout}`);
+
+ if (res.status === 401) {
+ console.error('Authentication failed. The server token may have changed.');
+ console.error('Try restarting: npx impeccable live stop && npx impeccable live');
+ process.exit(1);
+ }
+
+ if (!res.ok) {
+ console.error(`Poll failed: ${res.status} ${res.statusText}`);
+ process.exit(1);
+ }
+
+ const event = await res.json();
+ // Print the event as JSON — the agent reads this from stdout
+ console.log(JSON.stringify(event));
+ } catch (err) {
+ if (err.cause?.code === 'ECONNREFUSED') {
+ console.error('Live server not running. Start one with: npx impeccable live');
+ } else {
+ console.error('Poll failed:', err.message);
+ }
+ process.exit(1);
+ }
+}
diff --git a/.claude/skills/impeccable/scripts/live-server.mjs b/.claude/skills/impeccable/scripts/live-server.mjs
new file mode 100644
index 000000000..d436bad58
--- /dev/null
+++ b/.claude/skills/impeccable/scripts/live-server.mjs
@@ -0,0 +1,416 @@
+#!/usr/bin/env node
+/**
+ * Live variant mode server (self-contained, zero dependencies).
+ *
+ * Serves the browser script (/live.js), the detection overlay (/detect.js),
+ * uses Server-Sent Events (SSE) for server→browser push, and HTTP POST for
+ * browser→server events. Agent communicates via HTTP long-poll (/poll).
+ *
+ * Usage:
+ * node <scripts_path>/live-server.mjs # start
+ * node <scripts_path>/live-server.mjs stop # stop
+ * node <scripts_path>/live-server.mjs --help
+ */
+
+import http from 'node:http';
+import { randomUUID } from 'node:crypto';
+import fs from 'node:fs';
+import path from 'node:path';
+import os from 'node:os';
+import net from 'node:net';
+import { fileURLToPath } from 'node:url';
+
+const __dirname = path.dirname(fileURLToPath(import.meta.url));
+const LIVE_PID_FILE = path.join(os.tmpdir(), 'impeccable-live.json');
+const DEFAULT_POLL_TIMEOUT = 120_000;
+
+// ---------------------------------------------------------------------------
+// Port detection
+// ---------------------------------------------------------------------------
+
+async function findOpenPort(start = 8400) {
+ return new Promise((resolve) => {
+ const srv = net.createServer();
+ srv.listen(start, '127.0.0.1', () => {
+ const port = srv.address().port;
+ srv.close(() => resolve(port));
+ });
+ srv.on('error', () => resolve(findOpenPort(start + 1)));
+ });
+}
+
+// ---------------------------------------------------------------------------
+// Session state
+// ---------------------------------------------------------------------------
+
+const state = {
+ token: null,
+ port: null,
+ sseClients: new Set(), // SSE response objects (server→browser push)
+ pendingEvents: [], // browser events waiting for agent poll
+ pendingPolls: [], // agent poll callbacks waiting for browser events
+ exitTimer: null,
+};
+
+function enqueueEvent(event) {
+ if (state.pendingPolls.length > 0) {
+ state.pendingPolls.shift()(event);
+ } else {
+ state.pendingEvents.push(event);
+ }
+}
+
+/** Push a message to all connected SSE clients. */
+function broadcast(msg) {
+ const data = 'data: ' + JSON.stringify(msg) + '\n\n';
+ for (const res of state.sseClients) {
+ try { res.write(data); } catch { /* client gone */ }
+ }
+}
+
+// ---------------------------------------------------------------------------
+// Load scripts
+// ---------------------------------------------------------------------------
+
+function loadBrowserScripts() {
+ // Detection script: look relative to the skill scripts dir, then fall back
+ // to the npm package location (src/detect-antipatterns-browser.js)
+ const detectPaths = [
+ path.join(__dirname, '..', '..', '..', '..', 'src', 'detect-antipatterns-browser.js'),
+ path.join(process.cwd(), 'node_modules', 'impeccable', 'src', 'detect-antipatterns-browser.js'),
+ ];
+ let detectScript = '';
+ for (const p of detectPaths) {
+ try { detectScript = fs.readFileSync(p, 'utf-8'); break; } catch { /* try next */ }
+ }
+
+ const livePath = path.join(__dirname, 'live-browser.js');
+ let liveScript = '';
+ try {
+ liveScript = fs.readFileSync(livePath, 'utf-8');
+ } catch {
+ process.stderr.write('Error: live-browser.js not found at ' + livePath + '\n');
+ process.exit(1);
+ }
+
+ return { detectScript, liveScript };
+}
+
+function hasProjectContext() {
+ try {
+ fs.accessSync(path.join(process.cwd(), '.impeccable.md'), fs.constants.R_OK);
+ return true;
+ } catch { return false; }
+}
+
+// ---------------------------------------------------------------------------
+// Validation (inline — no external import needed for self-contained script)
+// ---------------------------------------------------------------------------
+
+const VISUAL_ACTIONS = [
+ 'impeccable', 'bolder', 'quieter', 'distill', 'polish', 'typeset',
+ 'colorize', 'layout', 'adapt', 'animate', 'delight', 'overdrive',
+];
+
+function validateEvent(msg) {
+ if (!msg || typeof msg !== 'object' || !msg.type) return 'Missing or invalid message';
+ switch (msg.type) {
+ case 'generate':
+ if (!msg.id || typeof msg.id !== 'string') return 'generate: missing id';
+ if (!msg.action || !VISUAL_ACTIONS.includes(msg.action)) return 'generate: invalid action';
+ if (!Number.isInteger(msg.count) || msg.count < 1 || msg.count > 8) return 'generate: count must be 1-8';
+ if (!msg.element || !msg.element.outerHTML) return 'generate: missing element context';
+ return null;
+ case 'accept':
+ if (!msg.id) return 'accept: missing id';
+ if (!msg.variantId) return 'accept: missing variantId';
+ return null;
+ case 'discard':
+ return msg.id ? null : 'discard: missing id';
+ case 'exit':
+ return null;
+ default:
+ return 'Unknown event type: ' + msg.type;
+ }
+}
+
+// ---------------------------------------------------------------------------
+// HTTP request handler
+// ---------------------------------------------------------------------------
+
+function createRequestHandler({ detectScript, liveScriptWithToken }) {
+ return (req, res) => {
+ const url = new URL(req.url, `http://localhost:${state.port}`);
+ res.setHeader('Access-Control-Allow-Origin', '*');
+ res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS');
+ res.setHeader('Access-Control-Allow-Headers', 'Content-Type');
+ if (req.method === 'OPTIONS') { res.writeHead(204); res.end(); return; }
+
+ const p = url.pathname;
+
+ // --- Scripts ---
+ if (p === '/live.js') {
+ res.writeHead(200, { 'Content-Type': 'application/javascript' });
+ res.end(liveScriptWithToken);
+ return;
+ }
+ if (p === '/detect.js' || p === '/') {
+ if (!detectScript) { res.writeHead(404); res.end('Not available'); return; }
+ res.writeHead(200, { 'Content-Type': 'application/javascript' });
+ res.end(detectScript);
+ return;
+ }
+
+ // --- Health ---
+ if (p === '/health') {
+ res.writeHead(200, { 'Content-Type': 'application/json' });
+ res.end(JSON.stringify({
+ status: 'ok', port: state.port, mode: 'variant',
+ hasProjectContext: hasProjectContext(),
+ connectedClients: state.sseClients.size,
+ }));
+ return;
+ }
+
+ // --- Source file (no-HMR fallback) ---
+ if (p === '/source') {
+ const token = url.searchParams.get('token');
+ if (token !== state.token) { res.writeHead(401); res.end('Unauthorized'); return; }
+ const filePath = url.searchParams.get('path');
+ if (!filePath || filePath.includes('..')) { res.writeHead(400); res.end('Bad path'); return; }
+ const absPath = path.resolve(process.cwd(), filePath);
+ if (!absPath.startsWith(process.cwd())) { res.writeHead(403); res.end('Forbidden'); return; }
+ try {
+ res.writeHead(200, { 'Content-Type': 'text/html; charset=utf-8' });
+ res.end(fs.readFileSync(absPath, 'utf-8'));
+ } catch { res.writeHead(404); res.end('File not found'); }
+ return;
+ }
+
+ // --- SSE: server→browser push (replaces WebSocket) ---
+ if (p === '/events' && req.method === 'GET') {
+ const token = url.searchParams.get('token');
+ if (token !== state.token) { res.writeHead(401); res.end('Unauthorized'); return; }
+ res.writeHead(200, {
+ 'Content-Type': 'text/event-stream',
+ 'Cache-Control': 'no-cache',
+ 'Connection': 'keep-alive',
+ });
+ res.write('data: ' + JSON.stringify({
+ type: 'connected',
+ hasProjectContext: hasProjectContext(),
+ }) + '\n\n');
+
+ state.sseClients.add(res);
+ clearTimeout(state.exitTimer);
+
+ req.on('close', () => {
+ state.sseClients.delete(res);
+ if (state.sseClients.size === 0) {
+ clearTimeout(state.exitTimer);
+ state.exitTimer = setTimeout(() => {
+ if (state.sseClients.size === 0) enqueueEvent({ type: 'exit' });
+ }, 8000);
+ }
+ });
+ return;
+ }
+
+ // --- Browser→server events (replaces WebSocket messages) ---
+ if (p === '/events' && req.method === 'POST') {
+ let body = '';
+ req.on('data', (c) => { body += c; });
+ req.on('end', () => {
+ let msg;
+ try { msg = JSON.parse(body); } catch {
+ res.writeHead(400, { 'Content-Type': 'application/json' });
+ res.end(JSON.stringify({ error: 'Invalid JSON' }));
+ return;
+ }
+ if (msg.token !== state.token) {
+ res.writeHead(401, { 'Content-Type': 'application/json' });
+ res.end(JSON.stringify({ error: 'Unauthorized' }));
+ return;
+ }
+ const error = validateEvent(msg);
+ if (error) {
+ res.writeHead(400, { 'Content-Type': 'application/json' });
+ res.end(JSON.stringify({ error }));
+ return;
+ }
+ enqueueEvent(msg);
+ res.writeHead(200, { 'Content-Type': 'application/json' });
+ res.end(JSON.stringify({ ok: true }));
+ });
+ return;
+ }
+
+ // --- Stop ---
+ if (p === '/stop') {
+ const token = url.searchParams.get('token');
+ if (token !== state.token) { res.writeHead(401); res.end('Unauthorized'); return; }
+ res.writeHead(200, { 'Content-Type': 'text/plain' });
+ res.end('stopping');
+ shutdown();
+ return;
+ }
+
+ // --- Agent poll ---
+ if (p === '/poll' && req.method === 'GET') {
+ handlePollGet(req, res, url);
+ return;
+ }
+ if (p === '/poll' && req.method === 'POST') {
+ handlePollPost(req, res);
+ return;
+ }
+
+ res.writeHead(404); res.end('Not found');
+ };
+}
+
+// ---------------------------------------------------------------------------
+// Agent poll endpoints (unchanged from WS version)
+// ---------------------------------------------------------------------------
+
+function handlePollGet(req, res, url) {
+ 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 timeout = parseInt(url.searchParams.get('timeout') || DEFAULT_POLL_TIMEOUT, 10);
+ if (state.pendingEvents.length > 0) {
+ res.writeHead(200, { 'Content-Type': 'application/json' });
+ res.end(JSON.stringify(state.pendingEvents.shift()));
+ return;
+ }
+ const timer = setTimeout(() => {
+ const idx = state.pendingPolls.indexOf(resolve);
+ if (idx !== -1) state.pendingPolls.splice(idx, 1);
+ res.writeHead(200, { 'Content-Type': 'application/json' });
+ res.end(JSON.stringify({ type: 'timeout' }));
+ }, timeout);
+ function resolve(event) {
+ clearTimeout(timer);
+ res.writeHead(200, { 'Content-Type': 'application/json' });
+ res.end(JSON.stringify(event));
+ }
+ state.pendingPolls.push(resolve);
+ req.on('close', () => {
+ clearTimeout(timer);
+ const idx = state.pendingPolls.indexOf(resolve);
+ if (idx !== -1) state.pendingPolls.splice(idx, 1);
+ });
+}
+
+function handlePollPost(req, res) {
+ let body = '';
+ req.on('data', (c) => { body += c; });
+ req.on('end', () => {
+ let msg;
+ try { msg = JSON.parse(body); } catch {
+ res.writeHead(400, { 'Content-Type': 'application/json' });
+ res.end(JSON.stringify({ error: 'Invalid JSON' }));
+ return;
+ }
+ if (msg.token !== state.token) {
+ res.writeHead(401, { 'Content-Type': 'application/json' });
+ res.end(JSON.stringify({ error: 'Unauthorized' }));
+ return;
+ }
+ // Forward the reply to the browser via SSE
+ broadcast({ type: msg.type || 'done', id: msg.id, message: msg.message, file: msg.file, data: msg.data });
+ res.writeHead(200, { 'Content-Type': 'application/json' });
+ res.end(JSON.stringify({ ok: true }));
+ });
+}
+
+// ---------------------------------------------------------------------------
+// Lifecycle
+// ---------------------------------------------------------------------------
+
+let httpServer = null;
+
+function shutdown() {
+ try { fs.unlinkSync(LIVE_PID_FILE); } catch {}
+ for (const res of state.sseClients) { try { res.end(); } catch {} }
+ state.sseClients.clear();
+ for (const resolve of state.pendingPolls) resolve({ type: 'exit' });
+ state.pendingPolls.length = 0;
+ if (httpServer) httpServer.close();
+ process.exit(0);
+}
+
+// ---------------------------------------------------------------------------
+// Main
+// ---------------------------------------------------------------------------
+
+const args = process.argv.slice(2);
+
+if (args.includes('--help') || args.includes('-h')) {
+ console.log(`Usage: node live-server.mjs [options]
+
+Start the live variant mode server (zero dependencies).
+
+Commands:
+ (default) Start the server
+ stop Stop a running server
+
+Options:
+ --port=PORT Use a specific port (default: auto-detect starting at 8400)
+ --help Show this help
+
+Endpoints:
+ /live.js Browser script (element picker + variant cycling)
+ /detect.js Detection overlay (backwards compatible)
+ /events SSE stream (server→browser) + POST (browser→server)
+ /poll Long-poll for agent CLI
+ /source Raw source file reader (no-HMR fallback)
+ /health Health check`);
+ process.exit(0);
+}
+
+if (args.includes('stop')) {
+ try {
+ const info = JSON.parse(fs.readFileSync(LIVE_PID_FILE, 'utf-8'));
+ 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 { console.log('No running live server found.'); }
+ process.exit(0);
+}
+
+// Check for existing session
+try {
+ const existing = JSON.parse(fs.readFileSync(LIVE_PID_FILE, 'utf-8'));
+ 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 {}
+
+state.token = randomUUID();
+const portArg = args.find(a => a.startsWith('--port='));
+state.port = portArg ? parseInt(portArg.split('=')[1], 10) : await findOpenPort();
+
+const { detectScript, liveScript } = loadBrowserScripts();
+const liveScriptWithToken =
+ `window.__IMPECCABLE_TOKEN__ = '${state.token}';\n` +
+ `window.__IMPECCABLE_PORT__ = ${state.port};\n` +
+ liveScript;
+
+httpServer = http.createServer(createRequestHandler({ detectScript, liveScriptWithToken }));
+
+httpServer.listen(state.port, '127.0.0.1', () => {
+ fs.writeFileSync(LIVE_PID_FILE, JSON.stringify({ 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`);
+ console.log(`Inject: <script src="${url}/live.js"><\/script>`);
+ console.log(`Stop: node ${path.basename(fileURLToPath(import.meta.url))} stop`);
+});
+
+process.on('SIGINT', shutdown);
+process.on('SIGTERM', shutdown);
diff --git a/.claude/skills/impeccable/scripts/live-wrap.mjs b/.claude/skills/impeccable/scripts/live-wrap.mjs
new file mode 100644
index 000000000..f1c838cdd
--- /dev/null
+++ b/.claude/skills/impeccable/scripts/live-wrap.mjs
@@ -0,0 +1,298 @@
+/**
+ * CLI helper: find an element in source and wrap it in a variant container.
+ *
+ * Usage:
+ * npx impeccable wrap --id SESSION_ID --count N --query "hero-combined-left" [--file path]
+ *
+ * Searches project files for the element matching the query (class name, ID, or
+ * text snippet), wraps it with the variant scaffolding, and prints the file path
+ * + line range where the agent should insert variant HTML.
+ *
+ * This replaces 3-4 agent tool calls (grep + read + edit) with a single CLI call.
+ */
+
+import fs from 'node:fs';
+import path from 'node:path';
+
+const EXTENSIONS = ['.html', '.jsx', '.tsx', '.vue', '.svelte', '.astro'];
+
+export async function wrapCli() {
+ const args = process.argv.slice(2);
+
+ if (args.includes('--help') || args.includes('-h')) {
+ console.log(`Usage: impeccable wrap [options]
+
+Find an element in source and wrap it in a variant container.
+
+Required:
+ --id ID Session ID for the variant wrapper
+ --count N Number of expected variants (1-8)
+
+Element identification (at least one required):
+ --element-id ID HTML id attribute of the element
+ --classes A,B,C Comma-separated CSS class names
+ --tag TAG Tag name (div, section, etc.)
+ --query TEXT Fallback: raw text to search for
+
+Optional:
+ --file PATH Source file to search in (skips auto-detection)
+ --help Show this help message
+
+Output (JSON):
+ { file, startLine, endLine, insertLine, commentSyntax }
+
+The agent should insert variant HTML at insertLine.`);
+ process.exit(0);
+ }
+
+ const id = argVal(args, '--id');
+ const count = parseInt(argVal(args, '--count') || '3');
+ const elementId = argVal(args, '--element-id');
+ const classes = argVal(args, '--classes');
+ const tag = argVal(args, '--tag');
+ const query = argVal(args, '--query');
+ const filePath = argVal(args, '--file');
+
+ if (!id) { console.error('Missing --id'); process.exit(1); }
+ if (!elementId && !classes && !query) {
+ console.error('Need at least one of: --element-id, --classes, --query');
+ process.exit(1);
+ }
+
+ // Build search queries in priority order (most specific first)
+ const queries = buildSearchQueries(elementId, classes, tag, query);
+
+ // Find the source file
+ let targetFile = filePath;
+ let matchedQuery = null;
+ if (!targetFile) {
+ for (const q of queries) {
+ targetFile = findFileWithQuery(q, process.cwd());
+ if (targetFile) { matchedQuery = q; break; }
+ }
+ if (!targetFile) {
+ console.error(JSON.stringify({ error: 'Could not find element in project files. Searched for: ' + queries.join(', ') }));
+ process.exit(1);
+ }
+ } else {
+ matchedQuery = queries[0];
+ }
+
+ const content = fs.readFileSync(targetFile, 'utf-8');
+ const lines = content.split('\n');
+
+ // Find the element, trying each query in priority order
+ let match = null;
+ for (const q of queries) {
+ match = findElement(lines, q);
+ if (match) break;
+ }
+ if (!match) {
+ console.error(JSON.stringify({ error: 'Found file but could not locate element in ' + targetFile + '. Searched for: ' + queries.join(', ') }));
+ process.exit(1);
+ }
+
+ const { startLine, endLine } = match;
+ const commentSyntax = detectCommentSyntax(targetFile);
+ const indent = lines[startLine].match(/^(\s*)/)[1];
+
+ // Extract the original element
+ const originalLines = lines.slice(startLine, endLine + 1);
+ const originalIndented = originalLines.map(l => indent + ' ' + l.trimStart()).join('\n');
+
+ // Build the wrapper
+ const wrapperLines = [
+ indent + commentSyntax.open + ' impeccable-variants-start ' + id + ' ' + commentSyntax.close,
+ indent + '<div data-impeccable-variants="' + id + '" data-impeccable-variant-count="' + count + '" style="display: contents">',
+ indent + ' ' + commentSyntax.open + ' Original ' + commentSyntax.close,
+ indent + ' <div data-impeccable-variant="original">',
+ originalIndented,
+ indent + ' </div>',
+ indent + ' ' + commentSyntax.open + ' Variants: insert below this line ' + commentSyntax.close,
+ indent + '</div>',
+ indent + commentSyntax.open + ' impeccable-variants-end ' + id + ' ' + commentSyntax.close,
+ ];
+
+ // Replace the original element with the wrapper
+ const newLines = [
+ ...lines.slice(0, startLine),
+ ...wrapperLines,
+ ...lines.slice(endLine + 1),
+ ];
+ fs.writeFileSync(targetFile, newLines.join('\n'), 'utf-8');
+
+ // Calculate insert line (the "insert below this line" comment)
+ const insertLine = startLine + 6; // 0-indexed in the new file
+
+ console.log(JSON.stringify({
+ file: path.relative(process.cwd(), targetFile),
+ startLine: startLine + 1, // 1-indexed for the agent
+ endLine: startLine + wrapperLines.length, // 1-indexed
+ insertLine: insertLine + 1, // 1-indexed: where variants go
+ commentSyntax: commentSyntax,
+ originalLineCount: originalLines.length,
+ }));
+}
+
+// ---------------------------------------------------------------------------
+// Helpers
+// ---------------------------------------------------------------------------
+
+function argVal(args, flag) {
+ const idx = args.indexOf(flag);
+ return idx !== -1 && idx + 1 < args.length ? args[idx + 1] : null;
+}
+
+/**
+ * Build search query strings in priority order (most specific first).
+ * ID is most reliable, then specific class combos, then single classes, then raw query.
+ */
+function buildSearchQueries(elementId, classes, tag, query) {
+ const queries = [];
+
+ // 1. ID is the most specific
+ if (elementId) {
+ queries.push('id="' + elementId + '"');
+ }
+
+ // 2. Full class attribute match (for elements with distinctive multi-class combos)
+ if (classes) {
+ const classList = classes.split(',').map(c => c.trim()).filter(Boolean);
+ if (classList.length > 1) {
+ // Try the most distinctive class first (longest, most specific)
+ const sorted = [...classList].sort((a, b) => b.length - a.length);
+ queries.push('class="' + classList.join(' ') + '"'); // exact full match
+ queries.push(sorted[0]); // most distinctive single class
+ } else if (classList.length === 1) {
+ queries.push(classList[0]);
+ }
+ }
+
+ // 3. Tag + class combo (e.g., <section class="hero">)
+ if (tag && classes) {
+ const firstClass = classes.split(',')[0].trim();
+ queries.push('<' + tag + ' class="' + firstClass);
+ }
+
+ // 4. Raw fallback query
+ if (query) {
+ queries.push(query);
+ }
+
+ return queries;
+}
+
+function detectCommentSyntax(filePath) {
+ const ext = path.extname(filePath).toLowerCase();
+ if (ext === '.jsx' || ext === '.tsx') {
+ return { open: '{/*', close: '*/}' };
+ }
+ // HTML, Vue, Svelte, Astro all use HTML comments
+ return { open: '<!--', close: '-->' };
+}
+
+/**
+ * Search project files for the query string (class name, ID, etc.)
+ * Returns the first matching file path, or null.
+ */
+function findFileWithQuery(query, cwd) {
+ const searchDirs = ['src', 'app', 'pages', 'components', 'public', 'views', 'templates', '.'];
+ const seen = new Set();
+
+ for (const dir of searchDirs) {
+ const absDir = path.join(cwd, dir);
+ if (!fs.existsSync(absDir)) continue;
+ const result = searchDir(absDir, query, seen, 0);
+ if (result) return result;
+ }
+ return null;
+}
+
+function searchDir(dir, query, seen, depth) {
+ if (depth > 5) return null; // don't go too deep
+ const realDir = fs.realpathSync(dir);
+ if (seen.has(realDir)) return null;
+ seen.add(realDir);
+
+ let entries;
+ try { entries = fs.readdirSync(dir, { withFileTypes: true }); }
+ catch { return null; }
+
+ // Check files first
+ for (const entry of entries) {
+ if (!entry.isFile()) continue;
+ const ext = path.extname(entry.name).toLowerCase();
+ if (!EXTENSIONS.includes(ext)) continue;
+
+ const filePath = path.join(dir, entry.name);
+ try {
+ const content = fs.readFileSync(filePath, 'utf-8');
+ if (content.includes(query)) return filePath;
+ } catch { /* skip unreadable files */ }
+ }
+
+ // Then recurse into directories
+ for (const entry of entries) {
+ if (!entry.isDirectory()) continue;
+ if (entry.name === 'node_modules' || entry.name === '.git' || entry.name === 'dist' || entry.name === 'build') continue;
+ const result = searchDir(path.join(dir, entry.name), query, seen, depth + 1);
+ if (result) return result;
+ }
+
+ return null;
+}
+
+/**
+ * Find the element's start and end line in the file.
+ * The query is a class name, ID, or text snippet.
+ * We find the line containing the query, then find the matching closing tag.
+ */
+function findElement(lines, query) {
+ // Find the line containing the query
+ let startLine = -1;
+ for (let i = 0; i < lines.length; i++) {
+ if (lines[i].includes(query)) {
+ // Make sure this looks like a tag opening, not a comment or string
+ const line = lines[i].trim();
+ if (line.startsWith('<!--') || line.startsWith('{/*') || line.startsWith('//')) continue;
+ // Skip lines inside data-impeccable-variant containers (already wrapped)
+ if (lines[i].includes('data-impeccable-variant')) continue;
+ startLine = i;
+ break;
+ }
+ }
+
+ if (startLine === -1) return null;
+
+ // Find the end of this element by counting open/close tags
+ const endLine = findClosingLine(lines, startLine);
+ return { startLine, endLine };
+}
+
+/**
+ * Starting from a line with an opening tag, find the line with the matching
+ * closing tag by counting tag nesting depth.
+ */
+function findClosingLine(lines, start) {
+ // Extract the tag name from the opening line
+ const openMatch = lines[start].match(/<(\w+)[\s>]/);
+ if (!openMatch) return start; // self-closing or text-only line
+
+ const tagName = openMatch[1];
+ let depth = 0;
+
+ for (let i = start; i < lines.length; i++) {
+ const line = lines[i];
+ // Count opening tags (not self-closing)
+ const opens = (line.match(new RegExp('<' + tagName + '[\\s>]', 'g')) || []).length;
+ const selfCloses = (line.match(new RegExp('<' + tagName + '[^>]*/>', 'g')) || []).length;
+ const closes = (line.match(new RegExp('</' + tagName + '\\s*>', 'g')) || []).length;
+
+ depth += opens - selfCloses - closes;
+
+ if (depth <= 0) return i;
+ }
+
+ // If we can't find the close, return a reasonable guess
+ return Math.min(start + 50, lines.length - 1);
+}
diff --git a/.codex/skills/impeccable/reference/live.md b/.codex/skills/impeccable/reference/live.md
index 53b64a21a..ba0e9b0c5 100644
--- a/.codex/skills/impeccable/reference/live.md
+++ b/.codex/skills/impeccable/reference/live.md
@@ -10,7 +10,7 @@ Launch interactive live variant mode: select elements in the browser, pick a des
1. Read `.impeccable.md` if it exists. Keep the design context in mind for variant generation.
2. Start the live variant server:
```bash
- npx impeccable live &
+ node {{scripts_path}}/live-server.mjs &
```
3. Note the **port** and **token** printed to stdout.
@@ -53,7 +53,7 @@ Run a blocking poll loop. On each iteration, wait for a browser event and respon
```
LOOP:
- Run: npx impeccable poll
+ Run: node {{scripts_path}}/live-poll.mjs
Read the JSON output. Dispatch based on the "type" field:
TYPE "generate":
@@ -85,7 +85,7 @@ The event contains: `{id, action, freeformPrompt, count, pageUrl, element}`.
Use the `wrap` helper to find the element and create the variant container:
```bash
-npx impeccable wrap --id EVENT_ID --count EVENT_COUNT --element-id "ELEMENT_ID" --classes "class1,class2" --tag "div"
+node {{scripts_path}}/live-wrap.mjs --id EVENT_ID --count EVENT_COUNT --element-id "ELEMENT_ID" --classes "class1,class2" --tag "div"
```
Pass the element's id (`event.element.id`), classes (`event.element.classes` joined with commas), and tag name. The command searches in priority order: ID match first, then class names, then tag+class combo. If `event.pageUrl` hints at the file (e.g., `/` is usually `index.html`), pass `--file PATH` to skip the search.
@@ -136,10 +136,14 @@ The first variant should NOT have `style="display: none"` (it should be visible
### Step 3: Signal completion
+Include `--file` so the browser can fetch variants directly if the dev server lacks HMR:
+
```bash
-npx impeccable poll --reply EVENT_ID done
+node {{scripts_path}}/live-poll.mjs --reply EVENT_ID done --file RELATIVE_PATH
```
+The file path should be relative to the project root (e.g., `public/index.html`, `src/App.tsx`).
+
## Handle Accept
The event contains: `{id, variantId}`.
@@ -151,7 +155,7 @@ The user accepted a specific variant. For v1 (inspection mode):
4. Remove any scoped CSS blocks (between `impeccable-variants-css-start` and `impeccable-variants-css-end` markers).
5. Reply:
```bash
- npx impeccable poll --reply SESSION_ID done
+ node {{scripts_path}}/live-poll.mjs --reply SESSION_ID done
```
## Handle Discard
@@ -163,7 +167,7 @@ The event contains: `{id}`.
3. Remove any scoped CSS blocks for this session.
4. Reply:
```bash
- npx impeccable poll --reply SESSION_ID done
+ node {{scripts_path}}/live-poll.mjs --reply SESSION_ID done
```
## Cleanup (on exit)
@@ -174,7 +178,7 @@ When the loop ends:
2. **Remove any leftover variant wrappers** (search for `impeccable-variants-start` markers and clean up).
3. **Stop the server**:
```bash
- npx impeccable live stop
+ node {{scripts_path}}/live-server.mjs stop
```
## Variant Generation Guidelines
diff --git a/.codex/skills/impeccable/scripts/live-browser.js b/.codex/skills/impeccable/scripts/live-browser.js
new file mode 100644
index 000000000..7a26c9829
--- /dev/null
+++ b/.codex/skills/impeccable/scripts/live-browser.js
@@ -0,0 +1,1220 @@
+/**
+ * Impeccable Live Variant Mode — Browser Script
+ *
+ * Injected into the user's page via <script src="http://localhost:PORT/live.js">.
+ * The server prepends window.__IMPECCABLE_TOKEN__ and window.__IMPECCABLE_PORT__
+ * before this code.
+ *
+ * UI: a single floating bar that morphs between three states —
+ * configure (pick action + go), generating (progressive dots), and cycling
+ * (prev/next + accept/discard). Feels like Spotlight, not a modal.
+ */
+(function () {
+ 'use strict';
+ if (typeof window === 'undefined') return;
+
+ // Guard against double-init. Bun's HTML loader may process the <script> tag
+ // and create a bundled copy alongside the external load, or HMR may re-execute.
+ // Check BEFORE reading token/port to catch all cases.
+ if (window.__IMPECCABLE_LIVE_INIT__) return;
+ window.__IMPECCABLE_LIVE_INIT__ = true;
+
+ const TOKEN = window.__IMPECCABLE_TOKEN__;
+ const PORT = window.__IMPECCABLE_PORT__;
+ if (!TOKEN || !PORT) {
+ window.__IMPECCABLE_LIVE_INIT__ = false; // reset so the real load can init
+ return;
+ }
+
+ // ---------------------------------------------------------------------------
+ // Design tokens
+ // ---------------------------------------------------------------------------
+
+ const C = {
+ brand: 'oklch(55% 0.25 350)',
+ brandHov: 'oklch(48% 0.25 350)',
+ brandSoft: 'oklch(55% 0.25 350 / 0.12)',
+ ink: 'oklch(15% 0.01 350)',
+ ash: 'oklch(55% 0 0)',
+ paper: 'oklch(98% 0.005 350 / 0.92)',
+ paperSolid:'oklch(98% 0.005 350)',
+ mist: 'oklch(90% 0.01 350 / 0.6)',
+ white: 'oklch(99% 0 0)',
+ };
+ const FONT = 'system-ui, -apple-system, sans-serif';
+ const MONO = 'ui-monospace, SFMono-Regular, Menlo, monospace';
+ const Z = { highlight: 99990, bar: 99995, picker: 99997, toast: 99999 };
+ const EASE = 'cubic-bezier(0.22, 1, 0.36, 1)'; // ease-out-quint
+ const PREFIX = 'impeccable-live';
+
+ const SKIP_TAGS = new Set([
+ 'html', 'head', 'body', 'script', 'style', 'link', 'meta', 'noscript', 'br', 'wbr',
+ ]);
+
+ const ACTIONS = [
+ { value: 'impeccable', label: 'Freeform' },
+ { value: 'bolder', label: 'Bolder' },
+ { value: 'quieter', label: 'Quieter' },
+ { value: 'distill', label: 'Distill' },
+ { value: 'polish', label: 'Polish' },
+ { value: 'typeset', label: 'Typeset' },
+ { value: 'colorize', label: 'Colorize' },
+ { value: 'layout', label: 'Layout' },
+ { value: 'adapt', label: 'Adapt' },
+ { value: 'animate', label: 'Animate' },
+ { value: 'delight', label: 'Delight' },
+ { value: 'overdrive', label: 'Overdrive' },
+ ];
+
+ // ---------------------------------------------------------------------------
+ // State
+ // ---------------------------------------------------------------------------
+
+ let state = 'IDLE';
+ let hoveredElement = null;
+ let selectedElement = null;
+ let currentSessionId = null;
+ let expectedVariants = 0;
+ let arrivedVariants = 0;
+ let visibleVariant = 0;
+ let variantObserver = null;
+ let hasProjectContext = false;
+ let selectedAction = 'impeccable';
+ let selectedCount = 3;
+
+ // UI refs
+ let highlightEl = null;
+ let tooltipEl = null;
+ let barEl = null;
+ let pickerEl = null;
+ let toastEl = null;
+ let scrollRaf = null;
+
+ // ---------------------------------------------------------------------------
+ // Helpers
+ // ---------------------------------------------------------------------------
+
+ function own(el) {
+ return el && (el.id?.startsWith(PREFIX) || el.closest?.('[id^="' + PREFIX + '"]'));
+ }
+
+ function pickable(el) {
+ if (!el || el.nodeType !== 1) return false;
+ if (SKIP_TAGS.has(el.tagName.toLowerCase())) return false;
+ if (own(el)) return false;
+ const r = el.getBoundingClientRect();
+ return r.width >= 20 && r.height >= 20;
+ }
+
+ function desc(el) {
+ if (!el) return '';
+ let s = el.tagName.toLowerCase();
+ if (el.id) s += '#' + el.id;
+ else if (el.classList.length) s += '.' + [...el.classList].slice(0, 2).join('.');
+ return s;
+ }
+
+ function id8() { return crypto.randomUUID().replace(/-/g, '').slice(0, 8); }
+
+ // ---------------------------------------------------------------------------
+ // Highlight overlay
+ // ---------------------------------------------------------------------------
+
+ function initHighlight() {
+ highlightEl = document.createElement('div');
+ highlightEl.id = PREFIX + '-highlight';
+ Object.assign(highlightEl.style, {
+ position: 'fixed', top: '0', left: '0', width: '0', height: '0',
+ border: '2px solid ' + C.brand, borderRadius: '3px',
+ pointerEvents: 'none', zIndex: Z.highlight, boxSizing: 'border-box',
+ transition: 'top 0.08s ease, left 0.08s ease, width 0.08s ease, height 0.08s ease, opacity 0.15s ease',
+ display: 'none', opacity: '0',
+ });
+ document.body.appendChild(highlightEl);
+
+ tooltipEl = document.createElement('div');
+ tooltipEl.id = PREFIX + '-tooltip';
+ Object.assign(tooltipEl.style, {
+ position: 'fixed',
+ background: C.ink, color: C.white,
+ fontFamily: MONO, fontSize: '10px', fontWeight: '500',
+ padding: '2px 6px', borderRadius: '3px',
+ zIndex: Z.highlight + 1, pointerEvents: 'none',
+ whiteSpace: 'nowrap', display: 'none',
+ letterSpacing: '0.02em',
+ });
+ document.body.appendChild(tooltipEl);
+ }
+
+ function showHighlight(el) {
+ if (!el || !highlightEl) return;
+ const r = el.getBoundingClientRect();
+ Object.assign(highlightEl.style, {
+ top: (r.top - 2) + 'px', left: (r.left - 2) + 'px',
+ width: (r.width + 4) + 'px', height: (r.height + 4) + 'px',
+ display: 'block', opacity: '1',
+ });
+ tooltipEl.textContent = desc(el);
+ const tipTop = r.top - 20;
+ Object.assign(tooltipEl.style, {
+ top: (tipTop < 4 ? r.bottom + 4 : tipTop) + 'px',
+ left: Math.max(4, r.left) + 'px', display: 'block',
+ });
+ }
+
+ function hideHighlight() {
+ if (highlightEl) { highlightEl.style.opacity = '0'; highlightEl.style.display = 'none'; }
+ if (tooltipEl) tooltipEl.style.display = 'none';
+ }
+
+ // ---------------------------------------------------------------------------
+ // Element context extraction
+ // ---------------------------------------------------------------------------
+
+ function extractContext(el) {
+ const cs = getComputedStyle(el);
+ const r = el.getBoundingClientRect();
+ const props = {};
+ for (const sheet of document.styleSheets) {
+ try {
+ for (const rule of sheet.cssRules) {
+ if (rule.style) for (let i = 0; i < rule.style.length; i++) {
+ const p = rule.style[i];
+ if (p.startsWith('--') && !props[p]) {
+ const v = cs.getPropertyValue(p).trim();
+ if (v) props[p] = v;
+ }
+ }
+ }
+ } catch { /* cross-origin */ }
+ }
+ return {
+ tagName: el.tagName.toLowerCase(), id: el.id || null,
+ classes: [...el.classList],
+ textContent: (el.textContent || '').slice(0, 500),
+ outerHTML: el.outerHTML.slice(0, 10000),
+ computedStyles: {
+ 'font-family': cs.fontFamily, 'font-size': cs.fontSize,
+ 'font-weight': cs.fontWeight, 'line-height': cs.lineHeight,
+ 'color': cs.color, 'background': cs.background,
+ 'background-color': cs.backgroundColor,
+ 'padding': cs.padding, 'margin': cs.margin,
+ 'display': cs.display, 'position': cs.position,
+ 'gap': cs.gap, 'border-radius': cs.borderRadius,
+ 'box-shadow': cs.boxShadow,
+ },
+ cssCustomProperties: props,
+ parentContext: el.parentElement
+ ? '<' + el.parentElement.tagName.toLowerCase()
+ + (el.parentElement.id ? ' id="' + el.parentElement.id + '"' : '')
+ + (el.parentElement.className ? ' class="' + el.parentElement.className + '"' : '')
+ + '>'
+ : null,
+ boundingRect: { width: Math.round(r.width), height: Math.round(r.height) },
+ };
+ }
+
+ // ---------------------------------------------------------------------------
+ // The Bar — one floating element, three modes
+ // ---------------------------------------------------------------------------
+
+ function initBar() {
+ barEl = document.createElement('div');
+ barEl.id = PREFIX + '-bar';
+ Object.assign(barEl.style, {
+ position: 'fixed', zIndex: Z.bar,
+ display: 'none', opacity: '0',
+ transform: 'translateY(6px)',
+ transition: 'opacity 0.25s ' + EASE + ', transform 0.3s ' + EASE,
+ // Visual
+ background: C.paper,
+ backdropFilter: 'blur(16px)', WebkitBackdropFilter: 'blur(16px)',
+ border: '1px solid ' + C.mist,
+ borderRadius: '10px',
+ boxShadow: '0 4px 20px oklch(0% 0 0 / 0.08), 0 1px 3px oklch(0% 0 0 / 0.06)',
+ fontFamily: FONT, fontSize: '13px', color: C.ink,
+ padding: '6px',
+ maxWidth: '460px', minWidth: '320px',
+ });
+ document.body.appendChild(barEl);
+ }
+
+ function positionBar() {
+ if (!barEl || !selectedElement) return;
+ const r = selectedElement.getBoundingClientRect();
+ const barH = barEl.offsetHeight || 44;
+ const barW = barEl.offsetWidth || 380;
+ let top = r.bottom + 8;
+ let left = r.left + (r.width - barW) / 2;
+ // Keep in viewport
+ if (top + barH + 8 > window.innerHeight) top = r.top - barH - 8;
+ if (top < 8) top = 8;
+ if (left < 8) left = 8;
+ if (left + barW > window.innerWidth - 8) left = window.innerWidth - barW - 8;
+ Object.assign(barEl.style, { top: top + 'px', left: left + 'px' });
+ }
+
+ function showBar(mode) {
+ barEl.innerHTML = '';
+ if (mode === 'configure') barEl.appendChild(buildConfigureRow());
+ else if (mode === 'generating') barEl.appendChild(buildGeneratingRow());
+ else if (mode === 'cycling') barEl.appendChild(buildCyclingRow());
+ barEl.style.display = 'block';
+ positionBar();
+ requestAnimationFrame(() => {
+ barEl.style.opacity = '1';
+ barEl.style.transform = 'translateY(0)';
+ });
+ }
+
+ function hideBar() {
+ if (!barEl) return;
+ barEl.style.opacity = '0';
+ barEl.style.transform = 'translateY(6px)';
+ setTimeout(() => { if (barEl) barEl.style.display = 'none'; }, 250);
+ hideActionPicker();
+ }
+
+ function updateBarContent(mode) {
+ if (!barEl || barEl.style.display === 'none') return;
+ barEl.innerHTML = '';
+ // Reset bar styling
+ barEl.style.background = C.paper;
+ barEl.style.border = '1px solid ' + C.mist;
+ if (mode === 'configure') barEl.appendChild(buildConfigureRow());
+ else if (mode === 'generating') barEl.appendChild(buildGeneratingRow());
+ else if (mode === 'cycling') barEl.appendChild(buildCyclingRow());
+ else if (mode === 'saving') barEl.appendChild(buildSavingRow());
+ else if (mode === 'confirmed') {
+ barEl.appendChild(buildConfirmedRow());
+ barEl.style.background = 'oklch(95% 0.05 145)';
+ barEl.style.border = '1px solid oklch(75% 0.12 145 / 0.4)';
+ }
+ }
+
+ // --- Configure row ---
+
+ function buildConfigureRow() {
+ const row = el('div', {
+ display: 'flex', alignItems: 'center', gap: '4px',
+ });
+
+ // Action pill
+ const pill = el('button', {
+ display: 'inline-flex', alignItems: 'center', gap: '4px',
+ padding: '5px 10px', borderRadius: '6px',
+ background: C.ink, color: C.white,
+ fontFamily: FONT, fontSize: '12px', fontWeight: '500',
+ border: 'none', cursor: 'pointer',
+ transition: 'background 0.12s ease, transform 0.1s ease',
+ whiteSpace: 'nowrap', flexShrink: '0',
+ });
+ pill.textContent = actionLabel() + ' \u25BE';
+ pill.addEventListener('mouseenter', () => pill.style.background = C.brandHov);
+ pill.addEventListener('mouseleave', () => pill.style.background = C.ink);
+ pill.addEventListener('mousedown', () => pill.style.transform = 'scale(0.97)');
+ pill.addEventListener('mouseup', () => pill.style.transform = 'scale(1)');
+ pill.addEventListener('click', (e) => { e.stopPropagation(); toggleActionPicker(); });
+ row.appendChild(pill);
+
+ // Freeform input
+ const input = document.createElement('input');
+ input.id = PREFIX + '-input';
+ input.type = 'text';
+ input.placeholder = selectedAction === 'impeccable' ? 'describe what you want...' : 'refine further (optional)...';
+ Object.assign(input.style, {
+ flex: '1', minWidth: '0',
+ padding: '5px 8px', borderRadius: '6px',
+ border: '1px solid transparent', background: 'transparent',
+ fontFamily: FONT, fontSize: '12px', color: C.ink,
+ outline: 'none',
+ transition: 'border-color 0.15s ease, background 0.15s ease',
+ });
+ input.addEventListener('focus', () => {
+ input.style.borderColor = C.mist;
+ input.style.background = C.white;
+ });
+ input.addEventListener('blur', () => {
+ input.style.borderColor = 'transparent';
+ input.style.background = 'transparent';
+ });
+ input.addEventListener('keydown', (e) => {
+ e.stopPropagation(); // Don't trigger element picker keyboard nav
+ if (e.key === 'Enter') { e.preventDefault(); handleGo(); }
+ if (e.key === 'Escape') { e.preventDefault(); input.blur(); hideBar(); state = 'PICKING'; }
+ });
+ row.appendChild(input);
+
+ // Variant count toggle
+ const count = el('button', {
+ padding: '4px 6px', borderRadius: '5px',
+ border: '1px solid ' + C.mist, background: 'transparent',
+ fontFamily: MONO, fontSize: '11px', fontWeight: '600',
+ color: C.ash, cursor: 'pointer',
+ transition: 'color 0.12s ease, border-color 0.12s ease',
+ flexShrink: '0', whiteSpace: 'nowrap',
+ });
+ count.textContent = '\u00D7' + selectedCount;
+ count.title = 'Variants: click to change';
+ count.addEventListener('mouseenter', () => { count.style.color = C.ink; count.style.borderColor = C.ink; });
+ count.addEventListener('mouseleave', () => { count.style.color = C.ash; count.style.borderColor = C.mist; });
+ count.addEventListener('click', (e) => {
+ e.stopPropagation();
+ selectedCount = selectedCount >= 4 ? 2 : selectedCount + 1;
+ count.textContent = '\u00D7' + selectedCount;
+ });
+ row.appendChild(count);
+
+ // Go button
+ const go = el('button', {
+ padding: '5px 12px', borderRadius: '6px',
+ border: 'none', background: C.brand, color: C.white,
+ fontFamily: FONT, fontSize: '12px', fontWeight: '600',
+ cursor: 'pointer',
+ transition: 'background 0.12s ease, transform 0.1s ease',
+ flexShrink: '0', whiteSpace: 'nowrap',
+ });
+ go.textContent = 'Go \u2192';
+ go.addEventListener('mouseenter', () => go.style.background = C.brandHov);
+ go.addEventListener('mouseleave', () => go.style.background = C.brand);
+ go.addEventListener('mousedown', () => go.style.transform = 'scale(0.97)');
+ go.addEventListener('mouseup', () => go.style.transform = 'scale(1)');
+ go.addEventListener('click', (e) => { e.stopPropagation(); handleGo(); });
+ row.appendChild(go);
+
+ // Auto-focus input after a beat
+ setTimeout(() => input.focus(), 60);
+ return row;
+ }
+
+ // --- Generating row ---
+
+ function buildGeneratingRow() {
+ const row = el('div', {
+ display: 'flex', alignItems: 'center', gap: '8px',
+ padding: '2px 4px',
+ });
+
+ // Action label
+ const label = el('span', {
+ fontWeight: '600', fontSize: '12px', color: C.ink,
+ flexShrink: '0', whiteSpace: 'nowrap',
+ });
+ label.textContent = actionLabel();
+ row.appendChild(label);
+
+ // Dots
+ row.appendChild(buildDots(false));
+
+ // Status
+ const status = el('span', {
+ fontSize: '11px', color: C.ash, whiteSpace: 'nowrap',
+ marginLeft: 'auto',
+ });
+ status.textContent = arrivedVariants < expectedVariants
+ ? 'Generating ' + (arrivedVariants + 1) + ' of ' + expectedVariants + '...'
+ : 'Done';
+ row.appendChild(status);
+
+ return row;
+ }
+
+ // --- Cycling row ---
+
+ function buildCyclingRow() {
+ const row = el('div', {
+ display: 'flex', alignItems: 'center', gap: '6px',
+ padding: '1px 2px',
+ });
+
+ // Prev
+ const prev = navBtn('\u2190');
+ prev.addEventListener('click', (e) => { e.stopPropagation(); cycleVariant(-1); });
+ if (visibleVariant <= 1) prev.style.opacity = '0.3';
+ row.appendChild(prev);
+
+ // Dots (clickable)
+ row.appendChild(buildDots(true));
+
+ // Counter
+ const counter = el('span', {
+ fontFamily: MONO, fontSize: '11px', fontWeight: '500',
+ color: C.ash, minWidth: '24px', textAlign: 'center',
+ });
+ counter.textContent = visibleVariant + '/' + arrivedVariants;
+ row.appendChild(counter);
+
+ // Next
+ const next = navBtn('\u2192');
+ next.addEventListener('click', (e) => { e.stopPropagation(); cycleVariant(1); });
+ if (visibleVariant >= arrivedVariants) next.style.opacity = '0.3';
+ row.appendChild(next);
+
+ // Spacer
+ row.appendChild(el('div', { flex: '1' }));
+
+ // Accept
+ const accept = el('button', {
+ padding: '4px 10px', borderRadius: '5px',
+ border: 'none', background: C.ink, color: C.white,
+ fontFamily: FONT, fontSize: '11px', fontWeight: '600',
+ cursor: 'pointer', transition: 'background 0.12s ease',
+ whiteSpace: 'nowrap',
+ });
+ accept.textContent = '\u2713 Accept';
+ accept.addEventListener('mouseenter', () => accept.style.background = C.brand);
+ accept.addEventListener('mouseleave', () => accept.style.background = C.ink);
+ accept.addEventListener('click', (e) => { e.stopPropagation(); handleAccept(); });
+ if (arrivedVariants === 0) { accept.style.opacity = '0.3'; accept.style.pointerEvents = 'none'; }
+ row.appendChild(accept);
+
+ // Discard
+ const discard = el('button', {
+ padding: '4px 6px', borderRadius: '5px',
+ border: '1px solid ' + C.mist, background: 'transparent',
+ fontFamily: FONT, fontSize: '11px', color: C.ash,
+ cursor: 'pointer', transition: 'color 0.12s ease, border-color 0.12s ease',
+ });
+ discard.textContent = '\u2715';
+ discard.title = 'Discard all variants';
+ discard.addEventListener('mouseenter', () => { discard.style.color = C.ink; discard.style.borderColor = C.ink; });
+ discard.addEventListener('mouseleave', () => { discard.style.color = C.ash; discard.style.borderColor = C.mist; });
+ discard.addEventListener('click', (e) => { e.stopPropagation(); handleDiscard(); });
+ row.appendChild(discard);
+
+ return row;
+ }
+
+ // --- Shared UI builders ---
+
+ // --- Saving row (waiting for agent to process accept/discard) ---
+
+ function buildSavingRow() {
+ const row = el('div', {
+ display: 'flex', alignItems: 'center', gap: '8px',
+ padding: '2px 8px',
+ });
+ const spinner = el('div', {
+ width: '14px', height: '14px', borderRadius: '50%',
+ border: '2px solid ' + C.mist,
+ borderTopColor: C.brand,
+ animation: 'impeccable-spin 0.6s linear infinite',
+ flexShrink: '0',
+ });
+ row.appendChild(spinner);
+ const label = el('span', {
+ fontSize: '12px', color: C.ash, fontWeight: '500',
+ });
+ label.textContent = 'Applying variant...';
+ row.appendChild(label);
+
+ // Inject the keyframes if not already present
+ if (!document.getElementById(PREFIX + '-keyframes')) {
+ const style = document.createElement('style');
+ style.id = PREFIX + '-keyframes';
+ style.textContent = '@keyframes impeccable-spin { to { transform: rotate(360deg); } }';
+ document.head.appendChild(style);
+ }
+ return row;
+ }
+
+ // --- Confirmed row (green success, auto-dismisses) ---
+
+ function buildConfirmedRow() {
+ const row = el('div', {
+ display: 'flex', alignItems: 'center', gap: '8px',
+ padding: '2px 8px',
+ });
+ const check = el('span', {
+ fontSize: '15px', lineHeight: '1', flexShrink: '0',
+ color: 'oklch(45% 0.15 145)',
+ });
+ check.textContent = '\u2713';
+ row.appendChild(check);
+ const label = el('span', {
+ fontSize: '12px', color: 'oklch(35% 0.1 145)', fontWeight: '600',
+ });
+ label.textContent = 'Variant applied';
+ row.appendChild(label);
+ return row;
+ }
+
+ // --- Shared UI builders ---
+
+ function buildDots(clickable) {
+ const container = el('div', {
+ display: 'flex', alignItems: 'center', gap: '4px',
+ });
+ for (let i = 1; i <= expectedVariants; i++) {
+ const arrived = i <= arrivedVariants;
+ const active = i === visibleVariant;
+ const dot = el('div', {
+ width: '7px', height: '7px', borderRadius: '50%',
+ background: active ? C.brand : (arrived ? C.ash : 'transparent'),
+ border: '1.5px solid ' + (arrived ? C.brand : C.mist),
+ transition: 'all 0.2s ' + EASE,
+ cursor: (clickable && arrived) ? 'pointer' : 'default',
+ transform: arrived ? 'scale(1)' : 'scale(0.6)',
+ opacity: arrived ? '1' : '0.4',
+ });
+ if (clickable && arrived) {
+ const idx = i;
+ dot.addEventListener('click', (e) => {
+ e.stopPropagation();
+ visibleVariant = idx;
+ showVariantInDOM(currentSessionId, idx);
+ updateSelectedElement();
+ updateBarContent('cycling');
+ });
+ }
+ container.appendChild(dot);
+ }
+ return container;
+ }
+
+ function navBtn(text) {
+ const b = el('button', {
+ width: '26px', height: '26px', borderRadius: '5px',
+ border: '1px solid ' + C.mist, background: 'transparent',
+ color: C.ink, fontFamily: FONT, fontSize: '13px',
+ cursor: 'pointer', display: 'flex', alignItems: 'center', justifyContent: 'center',
+ transition: 'border-color 0.12s ease, background 0.12s ease',
+ padding: '0', lineHeight: '1',
+ });
+ b.textContent = text;
+ b.addEventListener('mouseenter', () => { b.style.borderColor = C.ink; });
+ b.addEventListener('mouseleave', () => { b.style.borderColor = C.mist; });
+ return b;
+ }
+
+ function actionLabel() {
+ const a = ACTIONS.find(a => a.value === selectedAction);
+ return a ? a.label : 'Freeform';
+ }
+
+ function el(tag, styles) {
+ const e = document.createElement(tag);
+ if (styles) Object.assign(e.style, styles);
+ return e;
+ }
+
+ // ---------------------------------------------------------------------------
+ // Action picker popover
+ // ---------------------------------------------------------------------------
+
+ function initActionPicker() {
+ pickerEl = document.createElement('div');
+ pickerEl.id = PREFIX + '-picker';
+ Object.assign(pickerEl.style, {
+ position: 'fixed', zIndex: Z.picker,
+ display: 'none', opacity: '0',
+ transform: 'scale(0.96) translateY(4px)',
+ transformOrigin: 'bottom left',
+ transition: 'opacity 0.18s ' + EASE + ', transform 0.2s ' + EASE,
+ background: C.paperSolid,
+ border: '1px solid ' + C.mist,
+ borderRadius: '10px',
+ boxShadow: '0 8px 30px oklch(0% 0 0 / 0.10), 0 2px 6px oklch(0% 0 0 / 0.06)',
+ padding: '6px',
+ fontFamily: FONT,
+ });
+
+ // Build the chip grid
+ const grid = el('div', {
+ display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', gap: '3px',
+ });
+
+ ACTIONS.forEach(action => {
+ const chip = el('button', {
+ padding: '6px 8px', borderRadius: '6px',
+ border: 'none',
+ background: action.value === selectedAction ? C.brandSoft : 'transparent',
+ color: action.value === selectedAction ? C.brand : C.ink,
+ fontFamily: FONT, fontSize: '11px', fontWeight: '500',
+ cursor: 'pointer',
+ transition: 'background 0.1s ease, color 0.1s ease',
+ textAlign: 'center', whiteSpace: 'nowrap',
+ });
+ chip.textContent = action.label;
+ chip.dataset.action = action.value;
+ chip.addEventListener('mouseenter', () => {
+ if (action.value !== selectedAction) chip.style.background = C.brandSoft;
+ });
+ chip.addEventListener('mouseleave', () => {
+ chip.style.background = action.value === selectedAction ? C.brandSoft : 'transparent';
+ });
+ chip.addEventListener('click', (e) => {
+ e.stopPropagation();
+ selectedAction = action.value;
+ hideActionPicker();
+ updateBarContent('configure');
+ });
+ grid.appendChild(chip);
+ });
+
+ pickerEl.appendChild(grid);
+ document.body.appendChild(pickerEl);
+ }
+
+ function toggleActionPicker() {
+ if (pickerEl.style.display !== 'none') { hideActionPicker(); return; }
+ // Rebuild chips to reflect current selection
+ pickerEl.querySelectorAll('button').forEach(chip => {
+ const isActive = chip.dataset.action === selectedAction;
+ chip.style.background = isActive ? C.brandSoft : 'transparent';
+ chip.style.color = isActive ? C.brand : C.ink;
+ });
+ // Position above the bar
+ const barRect = barEl.getBoundingClientRect();
+ const pickerH = 90; // approximate
+ let top = barRect.top - pickerH - 6;
+ if (top < 8) top = barRect.bottom + 6;
+ Object.assign(pickerEl.style, {
+ top: top + 'px', left: barRect.left + 'px',
+ display: 'block',
+ });
+ requestAnimationFrame(() => {
+ pickerEl.style.opacity = '1';
+ pickerEl.style.transform = 'scale(1) translateY(0)';
+ });
+ }
+
+ function hideActionPicker() {
+ if (!pickerEl) return;
+ pickerEl.style.opacity = '0';
+ pickerEl.style.transform = 'scale(0.96) translateY(4px)';
+ setTimeout(() => { if (pickerEl) pickerEl.style.display = 'none'; }, 180);
+ }
+
+ // ---------------------------------------------------------------------------
+ // Variant cycling in DOM
+ // ---------------------------------------------------------------------------
+
+ function showVariantInDOM(sessionId, num) {
+ const wrapper = document.querySelector('[data-impeccable-variants="' + sessionId + '"]');
+ if (!wrapper) return;
+ for (const child of wrapper.children) {
+ const v = child.dataset ? child.dataset.impeccableVariant : null;
+ if (!v) continue;
+ child.style.display = (v === String(num)) ? '' : 'none';
+ }
+ }
+
+ /**
+ * No-HMR fallback: fetch the raw source file from the live server,
+ * parse it, extract the variant wrapper, and inject it into the live DOM.
+ * This works even when the dev server caches HTML (Bun, static servers).
+ */
+ function injectVariantsFromSource(filePath, sessionId) {
+ const url = 'http://localhost:' + PORT + '/source?token=' + TOKEN + '&path=' + encodeURIComponent(filePath);
+ fetch(url)
+ .then(r => { if (!r.ok) throw new Error(r.status); return r.text(); })
+ .then(html => {
+ // Parse the raw source HTML
+ const parser = new DOMParser();
+ const doc = parser.parseFromString(html, 'text/html');
+ const srcWrapper = doc.querySelector('[data-impeccable-variants="' + sessionId + '"]');
+ if (!srcWrapper) {
+ console.error('[impeccable] Variant wrapper not found in source file.');
+ return;
+ }
+
+ // Find the original element in the live DOM.
+ // The original is inside the wrapper in the source. We find the
+ // corresponding element in the live DOM by matching the first child's
+ // tag + classes from the original snapshot.
+ const origContent = srcWrapper.querySelector('[data-impeccable-variant="original"] > :first-child');
+ if (!origContent) return;
+
+ const tag = origContent.tagName.toLowerCase();
+ const cls = origContent.className;
+ let liveEl = null;
+ if (origContent.id) {
+ liveEl = document.getElementById(origContent.id);
+ } else if (cls) {
+ // Find by tag + exact class match
+ const candidates = document.querySelectorAll(tag + '.' + cls.split(' ')[0]);
+ for (const c of candidates) {
+ if (c.className === cls && !own(c)) { liveEl = c; break; }
+ }
+ }
+
+ if (!liveEl) {
+ console.error('[impeccable] Could not find original element in live DOM.');
+ return;
+ }
+
+ // Replace the live element with the full wrapper from source
+ const wrapper = srcWrapper.cloneNode(true);
+ liveEl.parentElement.replaceChild(wrapper, liveEl);
+
+ // Update state: count variants, show the first one
+ 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);
+
+ // Update selectedElement to the visible variant's content
+ const visEl = wrapper.querySelector('[data-impeccable-variant="1"] > :first-child');
+ selectedElement = visEl || wrapper.parentElement;
+
+ state = 'CYCLING';
+ updateBarContent('cycling');
+ saveSession();
+ console.log('[impeccable] Injected ' + arrivedVariants + ' variants from source file.');
+ })
+ .catch(err => {
+ console.error('[impeccable] Failed to fetch source:', err);
+ showToast('Could not load variants. Try refreshing the page.', 5000);
+ });
+ }
+
+ function cycleVariant(dir) {
+ const next = visibleVariant + dir;
+ if (next < 1 || next > arrivedVariants) return;
+ visibleVariant = next;
+ showVariantInDOM(currentSessionId, next);
+ updateSelectedElement();
+ updateBarContent('cycling');
+ saveSession();
+ }
+
+ function updateSelectedElement() {
+ if (!currentSessionId) return;
+ const wrapper = document.querySelector('[data-impeccable-variants="' + currentSessionId + '"]');
+ if (!wrapper) return;
+ const visEl = wrapper.querySelector('[data-impeccable-variant="' + visibleVariant + '"] > :first-child');
+ if (visEl) selectedElement = visEl;
+ }
+
+ // ---------------------------------------------------------------------------
+ // MutationObserver for progressive variant reveal
+ // ---------------------------------------------------------------------------
+
+ function startVariantObserver(sessionId) {
+ let updating = false; // re-entrancy guard
+
+ const obs = new MutationObserver((mutations) => {
+ if (updating) return;
+
+ // Only react to mutations that add nodes with data-impeccable-variant,
+ // or mutations inside the variant wrapper. Ignore our own bar/UI changes.
+ let dominated = false;
+ for (const m of mutations) {
+ if (m.target.closest?.('[data-impeccable-variants]')) { dominated = true; break; }
+ for (const n of m.addedNodes) {
+ if (n.nodeType === 1 && (n.dataset?.impeccableVariants || n.dataset?.impeccableVariant)) {
+ dominated = true; break;
+ }
+ }
+ if (dominated) break;
+ }
+ if (!dominated) return;
+
+ const wrapper = document.querySelector('[data-impeccable-variants="' + sessionId + '"]');
+ if (!wrapper) return;
+
+ const variants = wrapper.querySelectorAll('[data-impeccable-variant]:not([data-impeccable-variant="original"])');
+ const count = variants.length;
+
+ // Nothing new
+ if (count <= arrivedVariants) return;
+
+ updating = true;
+ arrivedVariants = count;
+ if (visibleVariant === 0 && arrivedVariants > 0) {
+ visibleVariant = 1;
+ showVariantInDOM(sessionId, 1);
+ }
+
+ const expected = parseInt(wrapper.dataset.impeccableVariantCount || '0');
+ if (expected > 0) expectedVariants = expected;
+
+ if (arrivedVariants >= expectedVariants && expectedVariants > 0) {
+ state = 'CYCLING';
+ updateBarContent('cycling');
+ } else if (state === 'GENERATING') {
+ updateBarContent('generating');
+ }
+ saveSession();
+ updating = false;
+ });
+
+ obs.observe(document.body, { childList: true, subtree: true });
+ return obs;
+ }
+
+ // ---------------------------------------------------------------------------
+ // Bar scroll tracking
+ // ---------------------------------------------------------------------------
+
+ function startScrollTracking() {
+ function tick() {
+ if (state === 'CONFIGURING' || state === 'GENERATING' || state === 'CYCLING') {
+ positionBar();
+ showHighlight(selectedElement);
+ }
+ scrollRaf = requestAnimationFrame(tick);
+ }
+ scrollRaf = requestAnimationFrame(tick);
+ }
+
+ function stopScrollTracking() {
+ if (scrollRaf) { cancelAnimationFrame(scrollRaf); scrollRaf = null; }
+ }
+
+ // ---------------------------------------------------------------------------
+ // SSE (server→browser) + fetch POST (browser→server)
+ // Zero-dependency replacement for WebSocket.
+ // ---------------------------------------------------------------------------
+
+ let evtSource = null;
+
+ function connectSSE() {
+ evtSource = new EventSource('http://localhost:' + PORT + '/events?token=' + TOKEN);
+
+ evtSource.onmessage = (e) => {
+ let msg; try { msg = JSON.parse(e.data); } catch { return; }
+ switch (msg.type) {
+ case 'connected':
+ hasProjectContext = !!msg.hasProjectContext;
+ if (!hasProjectContext) showToast('No .impeccable.md found. Variants will be brand-agnostic.', 6000);
+ console.log('[impeccable] Live mode connected.');
+ if (state === 'IDLE') state = 'PICKING';
+ break;
+ case 'done':
+ if (state === 'SAVING') {
+ state = 'CONFIRMED';
+ updateBarContent('confirmed');
+ setTimeout(() => {
+ hideBar();
+ hideHighlight();
+ stopScrollTracking();
+ if (variantObserver) { variantObserver.disconnect(); variantObserver = null; }
+ clearSession();
+ selectedElement = null;
+ currentSessionId = null;
+ selectedAction = 'impeccable';
+ state = 'PICKING';
+ }, 1800);
+ return;
+ }
+ if (arrivedVariants === 0 && expectedVariants > 0 && msg.file) {
+ console.log('[impeccable] No HMR detected. Fetching variants from source file...');
+ injectVariantsFromSource(msg.file, currentSessionId);
+ return;
+ }
+ state = 'CYCLING';
+ updateBarContent('cycling');
+ break;
+ case 'error':
+ console.error('[impeccable] Error:', msg.message);
+ showToast('Error: ' + msg.message, 5000);
+ hideBar();
+ state = 'PICKING';
+ break;
+ }
+ };
+
+ evtSource.onerror = () => {
+ // EventSource auto-reconnects. Log once.
+ console.log('[impeccable] SSE connection lost. Reconnecting...');
+ };
+ }
+
+ function sendEvent(msg) {
+ msg.token = TOKEN;
+ 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));
+ }
+
+ // ---------------------------------------------------------------------------
+ // Event handlers
+ // ---------------------------------------------------------------------------
+
+ function handleMouseMove(e) {
+ if (state !== 'PICKING') return;
+ const target = document.elementFromPoint(e.clientX, e.clientY);
+ if (!target || !pickable(target) || target === hoveredElement) return;
+ hoveredElement = target;
+ showHighlight(target);
+ }
+
+ function handleClick(e) {
+ // Close action picker on any outside click
+ if (pickerEl?.style.display !== 'none' && !own(e.target)) {
+ hideActionPicker();
+ }
+ if (state !== 'PICKING') return;
+ if (own(e.target)) return;
+ if (!hoveredElement || !pickable(hoveredElement)) return;
+ e.preventDefault();
+ e.stopPropagation();
+ selectedElement = hoveredElement;
+ state = 'CONFIGURING';
+ showHighlight(selectedElement);
+ showBar('configure');
+ startScrollTracking();
+ }
+
+ function handleKeyDown(e) {
+ if (e.key === 'Escape') {
+ e.preventDefault();
+ if (pickerEl?.style.display !== 'none') { hideActionPicker(); return; }
+ if (state === 'CONFIGURING') { hideBar(); stopScrollTracking(); state = 'PICKING'; return; }
+ if (state === 'CYCLING') { handleDiscard(); return; }
+ if (state === 'SAVING' || state === 'CONFIRMED') return; // don't interrupt
+ if (state === 'PICKING') { hideHighlight(); state = 'IDLE'; return; }
+ }
+
+ if (state === 'PICKING' && hoveredElement) {
+ let next = null;
+ if (e.key === 'ArrowDown' && !e.shiftKey) {
+ next = hoveredElement.nextElementSibling;
+ while (next && !pickable(next)) next = next.nextElementSibling;
+ } else if (e.key === 'ArrowUp' && !e.shiftKey) {
+ next = hoveredElement.previousElementSibling;
+ while (next && !pickable(next)) next = next.previousElementSibling;
+ } else if (e.key === 'ArrowUp' && e.shiftKey) {
+ next = hoveredElement.parentElement;
+ if (next && !pickable(next)) next = null;
+ } else if (e.key === 'ArrowDown' && e.shiftKey) {
+ next = hoveredElement.firstElementChild;
+ while (next && !pickable(next)) next = next.nextElementSibling;
+ } else if (e.key === 'Enter') {
+ e.preventDefault();
+ selectedElement = hoveredElement;
+ state = 'CONFIGURING';
+ showHighlight(selectedElement);
+ showBar('configure');
+ startScrollTracking();
+ return;
+ }
+ if (next) {
+ e.preventDefault();
+ hoveredElement = next;
+ showHighlight(next);
+ next.scrollIntoView({ block: 'nearest', behavior: 'smooth' });
+ }
+ return;
+ }
+
+ if (state === 'CYCLING') {
+ if (e.key === 'ArrowLeft') { e.preventDefault(); cycleVariant(-1); }
+ if (e.key === 'ArrowRight') { e.preventDefault(); cycleVariant(1); }
+ if (e.key === 'Enter') { e.preventDefault(); handleAccept(); }
+ }
+ }
+
+ function handleGo() {
+ if (!selectedElement || state !== 'CONFIGURING') return;
+ const input = document.getElementById(PREFIX + '-input');
+ const prompt = input ? input.value.trim() : '';
+
+ currentSessionId = id8();
+ expectedVariants = selectedCount;
+ arrivedVariants = 0;
+ visibleVariant = 0;
+
+ sendEvent({
+ type: 'generate', id: currentSessionId,
+ action: selectedAction,
+ freeformPrompt: prompt || undefined,
+ count: selectedCount,
+ pageUrl: location.pathname,
+ element: extractContext(selectedElement),
+ });
+
+ state = 'GENERATING';
+ showBar('generating');
+ saveSession();
+ if (variantObserver) variantObserver.disconnect();
+ variantObserver = startVariantObserver(currentSessionId);
+ }
+
+ function handleAccept() {
+ if (!currentSessionId || arrivedVariants === 0) return;
+ sendEvent({ type: 'accept', id: currentSessionId, variantId: String(visibleVariant) });
+ markSessionHandled();
+ state = 'SAVING';
+ updateBarContent('saving');
+ // Don't cleanup yet — wait for the "done" WS message to show confirmation
+ }
+
+ function handleDiscard() {
+ if (!currentSessionId) return;
+ sendEvent({ type: 'discard', id: currentSessionId });
+ markSessionHandled();
+ state = 'SAVING';
+ updateBarContent('saving');
+ // Wait for "done" WS message to show confirmation and dismiss
+ }
+
+ // ---------------------------------------------------------------------------
+ // Session persistence via localStorage
+ // ---------------------------------------------------------------------------
+ // Survives page reloads, browser close/reopen, HMR, and accidental refreshes.
+
+ const LS_KEY = PREFIX + '-session';
+
+ function saveSession() {
+ if (!currentSessionId) return;
+ 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 */ }
+ }
+
+ function loadSession() {
+ try {
+ const raw = localStorage.getItem(LS_KEY);
+ return raw ? JSON.parse(raw) : null;
+ } catch { return null; }
+ }
+
+ function clearSession() {
+ try { localStorage.removeItem(LS_KEY); } catch {}
+ }
+
+ /** Mark session as handled (accepted/discarded). The agent will clean up
+ * the source, but until it does the wrapper is still in the HTML. This
+ * prevents resumeSession from picking it up again after reload. */
+ function markSessionHandled() {
+ if (!currentSessionId) return;
+ try {
+ localStorage.setItem(LS_KEY + '-handled', currentSessionId);
+ } catch {}
+ }
+
+ function isSessionHandled(id) {
+ try {
+ return localStorage.getItem(LS_KEY + '-handled') === id;
+ } catch { return false; }
+ }
+
+ function clearHandled() {
+ try { localStorage.removeItem(LS_KEY + '-handled'); } catch {}
+ }
+
+ function cleanup() {
+ hideBar();
+ hideHighlight();
+ stopScrollTracking();
+ if (variantObserver) { variantObserver.disconnect(); variantObserver = null; }
+ clearSession();
+ selectedElement = null;
+ currentSessionId = null;
+ selectedAction = 'impeccable';
+ state = 'PICKING';
+ }
+
+ // ---------------------------------------------------------------------------
+ // Toast
+ // ---------------------------------------------------------------------------
+
+ function showToast(message, duration) {
+ if (toastEl) toastEl.remove();
+ toastEl = el('div', {
+ position: 'fixed', bottom: '16px', left: '50%',
+ transform: 'translateX(-50%) translateY(8px)',
+ background: C.ink, color: C.white,
+ fontFamily: FONT, fontSize: '12px',
+ padding: '8px 16px', borderRadius: '8px',
+ zIndex: Z.toast, opacity: '0',
+ transition: 'opacity 0.25s ' + EASE + ', transform 0.25s ' + EASE,
+ pointerEvents: 'none', maxWidth: '420px', textAlign: 'center',
+ });
+ toastEl.id = PREFIX + '-toast';
+ toastEl.textContent = message;
+ document.body.appendChild(toastEl);
+ requestAnimationFrame(() => {
+ toastEl.style.opacity = '1';
+ toastEl.style.transform = 'translateX(-50%) translateY(0)';
+ });
+ setTimeout(() => {
+ if (toastEl) {
+ toastEl.style.opacity = '0';
+ toastEl.style.transform = 'translateX(-50%) translateY(8px)';
+ setTimeout(() => { if (toastEl) { toastEl.remove(); toastEl = null; } }, 250);
+ }
+ }, duration);
+ }
+
+ // ---------------------------------------------------------------------------
+ // Init
+ // ---------------------------------------------------------------------------
+
+ // Resume an active variant session after HMR/page reload.
+ // If a [data-impeccable-variants] wrapper exists in the DOM, the agent wrote
+ // variants before HMR fired. Pick up where we left off.
+ function resumeSession() {
+ const wrapper = document.querySelector('[data-impeccable-variants]');
+ if (!wrapper) { clearSession(); clearHandled(); return false; }
+
+ const sessionId = wrapper.dataset.impeccableVariants;
+
+ // Don't resume if this session was already accepted/discarded
+ if (isSessionHandled(sessionId)) return false;
+
+ currentSessionId = sessionId;
+ expectedVariants = parseInt(wrapper.dataset.impeccableVariantCount || '0');
+ const variants = wrapper.querySelectorAll('[data-impeccable-variant]:not([data-impeccable-variant="original"])');
+ arrivedVariants = variants.length;
+
+ // Restore visible variant from localStorage if available, else default to 1
+ const saved = loadSession();
+ visibleVariant = (saved && saved.id === sessionId && saved.visible > 0 && saved.visible <= arrivedVariants)
+ ? saved.visible : (arrivedVariants > 0 ? 1 : 0);
+
+ // Find the visible variant's content element for highlight positioning
+ const visEl = wrapper.querySelector('[data-impeccable-variant="' + visibleVariant + '"] > :first-child');
+ selectedElement = visEl || wrapper.parentElement;
+
+ // Set display state BEFORE starting observer (avoid triggering it)
+ if (visibleVariant > 0) showVariantInDOM(currentSessionId, visibleVariant);
+
+ state = arrivedVariants >= expectedVariants ? 'CYCLING' : 'GENERATING';
+ showBar(state === 'CYCLING' ? 'cycling' : 'generating');
+ startScrollTracking();
+ saveSession();
+
+ // Start observing for more variants AFTER initial setup
+ if (variantObserver) variantObserver.disconnect();
+ variantObserver = startVariantObserver(currentSessionId);
+ return true;
+ }
+
+ function init() {
+ initHighlight();
+ initBar();
+ initActionPicker();
+ document.addEventListener('mousemove', handleMouseMove, true);
+ document.addEventListener('click', handleClick, true);
+ document.addEventListener('keydown', handleKeyDown, true);
+ connectSSE();
+
+ // Check for an active session to resume (variant wrapper already in DOM after HMR)
+ if (!resumeSession()) {
+ console.log('[impeccable] Live variant mode ready. Hover over elements to pick one.');
+ } else {
+ console.log('[impeccable] Resumed active variant session ' + currentSessionId + ' (' + arrivedVariants + '/' + expectedVariants + ' variants).');
+ }
+ }
+
+ if (document.readyState === 'loading') {
+ document.addEventListener('DOMContentLoaded', init);
+ } else {
+ init();
+ }
+})();
diff --git a/.codex/skills/impeccable/scripts/live-poll.mjs b/.codex/skills/impeccable/scripts/live-poll.mjs
new file mode 100644
index 000000000..52859416c
--- /dev/null
+++ b/.codex/skills/impeccable/scripts/live-poll.mjs
@@ -0,0 +1,123 @@
+/**
+ * CLI client for the live variant mode poll/reply protocol.
+ *
+ * Usage:
+ * npx impeccable poll # Block until browser event, print JSON
+ * npx impeccable poll --timeout=60000 # Custom timeout (ms)
+ * npx impeccable poll --reply <id> done # Reply "done" to event <id>
+ * npx impeccable poll --reply <id> error "msg" # Reply with error
+ */
+
+import fs from 'node:fs';
+import path from 'node:path';
+import os from 'node:os';
+
+const LIVE_PID_FILE = path.join(os.tmpdir(), 'impeccable-live.json');
+
+function readServerInfo() {
+ try {
+ return JSON.parse(fs.readFileSync(LIVE_PID_FILE, 'utf-8'));
+ } catch {
+ console.error('No running live server found. Start one with: npx impeccable live');
+ process.exit(1);
+ }
+}
+
+export async function pollCli() {
+ const args = process.argv.slice(2);
+
+ if (args.includes('--help') || args.includes('-h')) {
+ console.log(`Usage: impeccable poll [options]
+
+Wait for a browser event from the live variant server, or reply to one.
+
+Modes:
+ poll Block until a browser event arrives, print JSON
+ poll --reply <id> done Reply "done" to event <id>
+ poll --reply <id> error "msg" Reply with an error message
+
+Options:
+ --timeout=MS Poll timeout in milliseconds (default: 120000)
+ --help Show this help message`);
+ process.exit(0);
+ }
+
+ const info = readServerInfo();
+ const base = `http://localhost:${info.port}`;
+
+ // Reply mode: npx impeccable poll --reply <id> <status> [--file path] [message]
+ const replyIdx = args.indexOf('--reply');
+ if (replyIdx !== -1) {
+ const id = args[replyIdx + 1];
+ const status = args[replyIdx + 2] || 'done';
+ const fileIdx = args.indexOf('--file');
+ const filePath = fileIdx !== -1 && fileIdx + 1 < args.length ? args[fileIdx + 1] : undefined;
+ // Message is any remaining positional arg that isn't a flag
+ const message = args.find((a, i) => i > replyIdx + 2 && !a.startsWith('--') && i !== fileIdx + 1) || undefined;
+
+ if (!id) {
+ console.error('Usage: npx impeccable poll --reply <id> <status> [--file path] [message]');
+ process.exit(1);
+ }
+
+ 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);
+ }
+
+ // Success — silent exit (agent doesn't need output for replies)
+ } catch (err) {
+ if (err.cause?.code === 'ECONNREFUSED') {
+ console.error('Live server not running. Start one with: npx impeccable live');
+ } else {
+ console.error('Reply failed:', err.message);
+ }
+ process.exit(1);
+ }
+ return;
+ }
+
+ // Poll mode: block until browser event
+ const timeoutArg = args.find(a => a.startsWith('--timeout='));
+ const timeout = timeoutArg ? parseInt(timeoutArg.split('=')[1], 10) : 120000;
+
+ try {
+ const res = await fetch(`${base}/poll?token=${info.token}&timeout=${timeout}`);
+
+ if (res.status === 401) {
+ console.error('Authentication failed. The server token may have changed.');
+ console.error('Try restarting: npx impeccable live stop && npx impeccable live');
+ process.exit(1);
+ }
+
+ if (!res.ok) {
+ console.error(`Poll failed: ${res.status} ${res.statusText}`);
+ process.exit(1);
+ }
+
+ const event = await res.json();
+ // Print the event as JSON — the agent reads this from stdout
+ console.log(JSON.stringify(event));
+ } catch (err) {
+ if (err.cause?.code === 'ECONNREFUSED') {
+ console.error('Live server not running. Start one with: npx impeccable live');
+ } else {
+ console.error('Poll failed:', err.message);
+ }
+ process.exit(1);
+ }
+}
diff --git a/.codex/skills/impeccable/scripts/live-server.mjs b/.codex/skills/impeccable/scripts/live-server.mjs
new file mode 100644
index 000000000..d436bad58
--- /dev/null
+++ b/.codex/skills/impeccable/scripts/live-server.mjs
@@ -0,0 +1,416 @@
+#!/usr/bin/env node
+/**
+ * Live variant mode server (self-contained, zero dependencies).
+ *
+ * Serves the browser script (/live.js), the detection overlay (/detect.js),
+ * uses Server-Sent Events (SSE) for server→browser push, and HTTP POST for
+ * browser→server events. Agent communicates via HTTP long-poll (/poll).
+ *
+ * Usage:
+ * node <scripts_path>/live-server.mjs # start
+ * node <scripts_path>/live-server.mjs stop # stop
+ * node <scripts_path>/live-server.mjs --help
+ */
+
+import http from 'node:http';
+import { randomUUID } from 'node:crypto';
+import fs from 'node:fs';
+import path from 'node:path';
+import os from 'node:os';
+import net from 'node:net';
+import { fileURLToPath } from 'node:url';
+
+const __dirname = path.dirname(fileURLToPath(import.meta.url));
+const LIVE_PID_FILE = path.join(os.tmpdir(), 'impeccable-live.json');
+const DEFAULT_POLL_TIMEOUT = 120_000;
+
+// ---------------------------------------------------------------------------
+// Port detection
+// ---------------------------------------------------------------------------
+
+async function findOpenPort(start = 8400) {
+ return new Promise((resolve) => {
+ const srv = net.createServer();
+ srv.listen(start, '127.0.0.1', () => {
+ const port = srv.address().port;
+ srv.close(() => resolve(port));
+ });
+ srv.on('error', () => resolve(findOpenPort(start + 1)));
+ });
+}
+
+// ---------------------------------------------------------------------------
+// Session state
+// ---------------------------------------------------------------------------
+
+const state = {
+ token: null,
+ port: null,
+ sseClients: new Set(), // SSE response objects (server→browser push)
+ pendingEvents: [], // browser events waiting for agent poll
+ pendingPolls: [], // agent poll callbacks waiting for browser events
+ exitTimer: null,
+};
+
+function enqueueEvent(event) {
+ if (state.pendingPolls.length > 0) {
+ state.pendingPolls.shift()(event);
+ } else {
+ state.pendingEvents.push(event);
+ }
+}
+
+/** Push a message to all connected SSE clients. */
+function broadcast(msg) {
+ const data = 'data: ' + JSON.stringify(msg) + '\n\n';
+ for (const res of state.sseClients) {
+ try { res.write(data); } catch { /* client gone */ }
+ }
+}
+
+// ---------------------------------------------------------------------------
+// Load scripts
+// ---------------------------------------------------------------------------
+
+function loadBrowserScripts() {
+ // Detection script: look relative to the skill scripts dir, then fall back
+ // to the npm package location (src/detect-antipatterns-browser.js)
+ const detectPaths = [
+ path.join(__dirname, '..', '..', '..', '..', 'src', 'detect-antipatterns-browser.js'),
+ path.join(process.cwd(), 'node_modules', 'impeccable', 'src', 'detect-antipatterns-browser.js'),
+ ];
+ let detectScript = '';
+ for (const p of detectPaths) {
+ try { detectScript = fs.readFileSync(p, 'utf-8'); break; } catch { /* try next */ }
+ }
+
+ const livePath = path.join(__dirname, 'live-browser.js');
+ let liveScript = '';
+ try {
+ liveScript = fs.readFileSync(livePath, 'utf-8');
+ } catch {
+ process.stderr.write('Error: live-browser.js not found at ' + livePath + '\n');
+ process.exit(1);
+ }
+
+ return { detectScript, liveScript };
+}
+
+function hasProjectContext() {
+ try {
+ fs.accessSync(path.join(process.cwd(), '.impeccable.md'), fs.constants.R_OK);
+ return true;
+ } catch { return false; }
+}
+
+// ---------------------------------------------------------------------------
+// Validation (inline — no external import needed for self-contained script)
+// ---------------------------------------------------------------------------
+
+const VISUAL_ACTIONS = [
+ 'impeccable', 'bolder', 'quieter', 'distill', 'polish', 'typeset',
+ 'colorize', 'layout', 'adapt', 'animate', 'delight', 'overdrive',
+];
+
+function validateEvent(msg) {
+ if (!msg || typeof msg !== 'object' || !msg.type) return 'Missing or invalid message';
+ switch (msg.type) {
+ case 'generate':
+ if (!msg.id || typeof msg.id !== 'string') return 'generate: missing id';
+ if (!msg.action || !VISUAL_ACTIONS.includes(msg.action)) return 'generate: invalid action';
+ if (!Number.isInteger(msg.count) || msg.count < 1 || msg.count > 8) return 'generate: count must be 1-8';
+ if (!msg.element || !msg.element.outerHTML) return 'generate: missing element context';
+ return null;
+ case 'accept':
+ if (!msg.id) return 'accept: missing id';
+ if (!msg.variantId) return 'accept: missing variantId';
+ return null;
+ case 'discard':
+ return msg.id ? null : 'discard: missing id';
+ case 'exit':
+ return null;
+ default:
+ return 'Unknown event type: ' + msg.type;
+ }
+}
+
+// ---------------------------------------------------------------------------
+// HTTP request handler
+// ---------------------------------------------------------------------------
+
+function createRequestHandler({ detectScript, liveScriptWithToken }) {
+ return (req, res) => {
+ const url = new URL(req.url, `http://localhost:${state.port}`);
+ res.setHeader('Access-Control-Allow-Origin', '*');
+ res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS');
+ res.setHeader('Access-Control-Allow-Headers', 'Content-Type');
+ if (req.method === 'OPTIONS') { res.writeHead(204); res.end(); return; }
+
+ const p = url.pathname;
+
+ // --- Scripts ---
+ if (p === '/live.js') {
+ res.writeHead(200, { 'Content-Type': 'application/javascript' });
+ res.end(liveScriptWithToken);
+ return;
+ }
+ if (p === '/detect.js' || p === '/') {
+ if (!detectScript) { res.writeHead(404); res.end('Not available'); return; }
+ res.writeHead(200, { 'Content-Type': 'application/javascript' });
+ res.end(detectScript);
+ return;
+ }
+
+ // --- Health ---
+ if (p === '/health') {
+ res.writeHead(200, { 'Content-Type': 'application/json' });
+ res.end(JSON.stringify({
+ status: 'ok', port: state.port, mode: 'variant',
+ hasProjectContext: hasProjectContext(),
+ connectedClients: state.sseClients.size,
+ }));
+ return;
+ }
+
+ // --- Source file (no-HMR fallback) ---
+ if (p === '/source') {
+ const token = url.searchParams.get('token');
+ if (token !== state.token) { res.writeHead(401); res.end('Unauthorized'); return; }
+ const filePath = url.searchParams.get('path');
+ if (!filePath || filePath.includes('..')) { res.writeHead(400); res.end('Bad path'); return; }
+ const absPath = path.resolve(process.cwd(), filePath);
+ if (!absPath.startsWith(process.cwd())) { res.writeHead(403); res.end('Forbidden'); return; }
+ try {
+ res.writeHead(200, { 'Content-Type': 'text/html; charset=utf-8' });
+ res.end(fs.readFileSync(absPath, 'utf-8'));
+ } catch { res.writeHead(404); res.end('File not found'); }
+ return;
+ }
+
+ // --- SSE: server→browser push (replaces WebSocket) ---
+ if (p === '/events' && req.method === 'GET') {
+ const token = url.searchParams.get('token');
+ if (token !== state.token) { res.writeHead(401); res.end('Unauthorized'); return; }
+ res.writeHead(200, {
+ 'Content-Type': 'text/event-stream',
+ 'Cache-Control': 'no-cache',
+ 'Connection': 'keep-alive',
+ });
+ res.write('data: ' + JSON.stringify({
+ type: 'connected',
+ hasProjectContext: hasProjectContext(),
+ }) + '\n\n');
+
+ state.sseClients.add(res);
+ clearTimeout(state.exitTimer);
+
+ req.on('close', () => {
+ state.sseClients.delete(res);
+ if (state.sseClients.size === 0) {
+ clearTimeout(state.exitTimer);
+ state.exitTimer = setTimeout(() => {
+ if (state.sseClients.size === 0) enqueueEvent({ type: 'exit' });
+ }, 8000);
+ }
+ });
+ return;
+ }
+
+ // --- Browser→server events (replaces WebSocket messages) ---
+ if (p === '/events' && req.method === 'POST') {
+ let body = '';
+ req.on('data', (c) => { body += c; });
+ req.on('end', () => {
+ let msg;
+ try { msg = JSON.parse(body); } catch {
+ res.writeHead(400, { 'Content-Type': 'application/json' });
+ res.end(JSON.stringify({ error: 'Invalid JSON' }));
+ return;
+ }
+ if (msg.token !== state.token) {
+ res.writeHead(401, { 'Content-Type': 'application/json' });
+ res.end(JSON.stringify({ error: 'Unauthorized' }));
+ return;
+ }
+ const error = validateEvent(msg);
+ if (error) {
+ res.writeHead(400, { 'Content-Type': 'application/json' });
+ res.end(JSON.stringify({ error }));
+ return;
+ }
+ enqueueEvent(msg);
+ res.writeHead(200, { 'Content-Type': 'application/json' });
+ res.end(JSON.stringify({ ok: true }));
+ });
+ return;
+ }
+
+ // --- Stop ---
+ if (p === '/stop') {
+ const token = url.searchParams.get('token');
+ if (token !== state.token) { res.writeHead(401); res.end('Unauthorized'); return; }
+ res.writeHead(200, { 'Content-Type': 'text/plain' });
+ res.end('stopping');
+ shutdown();
+ return;
+ }
+
+ // --- Agent poll ---
+ if (p === '/poll' && req.method === 'GET') {
+ handlePollGet(req, res, url);
+ return;
+ }
+ if (p === '/poll' && req.method === 'POST') {
+ handlePollPost(req, res);
+ return;
+ }
+
+ res.writeHead(404); res.end('Not found');
+ };
+}
+
+// ---------------------------------------------------------------------------
+// Agent poll endpoints (unchanged from WS version)
+// ---------------------------------------------------------------------------
+
+function handlePollGet(req, res, url) {
+ 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 timeout = parseInt(url.searchParams.get('timeout') || DEFAULT_POLL_TIMEOUT, 10);
+ if (state.pendingEvents.length > 0) {
+ res.writeHead(200, { 'Content-Type': 'application/json' });
+ res.end(JSON.stringify(state.pendingEvents.shift()));
+ return;
+ }
+ const timer = setTimeout(() => {
+ const idx = state.pendingPolls.indexOf(resolve);
+ if (idx !== -1) state.pendingPolls.splice(idx, 1);
+ res.writeHead(200, { 'Content-Type': 'application/json' });
+ res.end(JSON.stringify({ type: 'timeout' }));
+ }, timeout);
+ function resolve(event) {
+ clearTimeout(timer);
+ res.writeHead(200, { 'Content-Type': 'application/json' });
+ res.end(JSON.stringify(event));
+ }
+ state.pendingPolls.push(resolve);
+ req.on('close', () => {
+ clearTimeout(timer);
+ const idx = state.pendingPolls.indexOf(resolve);
+ if (idx !== -1) state.pendingPolls.splice(idx, 1);
+ });
+}
+
+function handlePollPost(req, res) {
+ let body = '';
+ req.on('data', (c) => { body += c; });
+ req.on('end', () => {
+ let msg;
+ try { msg = JSON.parse(body); } catch {
+ res.writeHead(400, { 'Content-Type': 'application/json' });
+ res.end(JSON.stringify({ error: 'Invalid JSON' }));
+ return;
+ }
+ if (msg.token !== state.token) {
+ res.writeHead(401, { 'Content-Type': 'application/json' });
+ res.end(JSON.stringify({ error: 'Unauthorized' }));
+ return;
+ }
+ // Forward the reply to the browser via SSE
+ broadcast({ type: msg.type || 'done', id: msg.id, message: msg.message, file: msg.file, data: msg.data });
+ res.writeHead(200, { 'Content-Type': 'application/json' });
+ res.end(JSON.stringify({ ok: true }));
+ });
+}
+
+// ---------------------------------------------------------------------------
+// Lifecycle
+// ---------------------------------------------------------------------------
+
+let httpServer = null;
+
+function shutdown() {
+ try { fs.unlinkSync(LIVE_PID_FILE); } catch {}
+ for (const res of state.sseClients) { try { res.end(); } catch {} }
+ state.sseClients.clear();
+ for (const resolve of state.pendingPolls) resolve({ type: 'exit' });
+ state.pendingPolls.length = 0;
+ if (httpServer) httpServer.close();
+ process.exit(0);
+}
+
+// ---------------------------------------------------------------------------
+// Main
+// ---------------------------------------------------------------------------
+
+const args = process.argv.slice(2);
+
+if (args.includes('--help') || args.includes('-h')) {
+ console.log(`Usage: node live-server.mjs [options]
+
+Start the live variant mode server (zero dependencies).
+
+Commands:
+ (default) Start the server
+ stop Stop a running server
+
+Options:
+ --port=PORT Use a specific port (default: auto-detect starting at 8400)
+ --help Show this help
+
+Endpoints:
+ /live.js Browser script (element picker + variant cycling)
+ /detect.js Detection overlay (backwards compatible)
+ /events SSE stream (server→browser) + POST (browser→server)
+ /poll Long-poll for agent CLI
+ /source Raw source file reader (no-HMR fallback)
+ /health Health check`);
+ process.exit(0);
+}
+
+if (args.includes('stop')) {
+ try {
+ const info = JSON.parse(fs.readFileSync(LIVE_PID_FILE, 'utf-8'));
+ 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 { console.log('No running live server found.'); }
+ process.exit(0);
+}
+
+// Check for existing session
+try {
+ const existing = JSON.parse(fs.readFileSync(LIVE_PID_FILE, 'utf-8'));
+ 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 {}
+
+state.token = randomUUID();
+const portArg = args.find(a => a.startsWith('--port='));
+state.port = portArg ? parseInt(portArg.split('=')[1], 10) : await findOpenPort();
+
+const { detectScript, liveScript } = loadBrowserScripts();
+const liveScriptWithToken =
+ `window.__IMPECCABLE_TOKEN__ = '${state.token}';\n` +
+ `window.__IMPECCABLE_PORT__ = ${state.port};\n` +
+ liveScript;
+
+httpServer = http.createServer(createRequestHandler({ detectScript, liveScriptWithToken }));
+
+httpServer.listen(state.port, '127.0.0.1', () => {
+ fs.writeFileSync(LIVE_PID_FILE, JSON.stringify({ 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`);
+ console.log(`Inject: <script src="${url}/live.js"><\/script>`);
+ console.log(`Stop: node ${path.basename(fileURLToPath(import.meta.url))} stop`);
+});
+
+process.on('SIGINT', shutdown);
+process.on('SIGTERM', shutdown);
diff --git a/.codex/skills/impeccable/scripts/live-wrap.mjs b/.codex/skills/impeccable/scripts/live-wrap.mjs
new file mode 100644
index 000000000..f1c838cdd
--- /dev/null
+++ b/.codex/skills/impeccable/scripts/live-wrap.mjs
@@ -0,0 +1,298 @@
+/**
+ * CLI helper: find an element in source and wrap it in a variant container.
+ *
+ * Usage:
+ * npx impeccable wrap --id SESSION_ID --count N --query "hero-combined-left" [--file path]
+ *
+ * Searches project files for the element matching the query (class name, ID, or
+ * text snippet), wraps it with the variant scaffolding, and prints the file path
+ * + line range where the agent should insert variant HTML.
+ *
+ * This replaces 3-4 agent tool calls (grep + read + edit) with a single CLI call.
+ */
+
+import fs from 'node:fs';
+import path from 'node:path';
+
+const EXTENSIONS = ['.html', '.jsx', '.tsx', '.vue', '.svelte', '.astro'];
+
+export async function wrapCli() {
+ const args = process.argv.slice(2);
+
+ if (args.includes('--help') || args.includes('-h')) {
+ console.log(`Usage: impeccable wrap [options]
+
+Find an element in source and wrap it in a variant container.
+
+Required:
+ --id ID Session ID for the variant wrapper
+ --count N Number of expected variants (1-8)
+
+Element identification (at least one required):
+ --element-id ID HTML id attribute of the element
+ --classes A,B,C Comma-separated CSS class names
+ --tag TAG Tag name (div, section, etc.)
+ --query TEXT Fallback: raw text to search for
+
+Optional:
+ --file PATH Source file to search in (skips auto-detection)
+ --help Show this help message
+
+Output (JSON):
+ { file, startLine, endLine, insertLine, commentSyntax }
+
+The agent should insert variant HTML at insertLine.`);
+ process.exit(0);
+ }
+
+ const id = argVal(args, '--id');
+ const count = parseInt(argVal(args, '--count') || '3');
+ const elementId = argVal(args, '--element-id');
+ const classes = argVal(args, '--classes');
+ const tag = argVal(args, '--tag');
+ const query = argVal(args, '--query');
+ const filePath = argVal(args, '--file');
+
+ if (!id) { console.error('Missing --id'); process.exit(1); }
+ if (!elementId && !classes && !query) {
+ console.error('Need at least one of: --element-id, --classes, --query');
+ process.exit(1);
+ }
+
+ // Build search queries in priority order (most specific first)
+ const queries = buildSearchQueries(elementId, classes, tag, query);
+
+ // Find the source file
+ let targetFile = filePath;
+ let matchedQuery = null;
+ if (!targetFile) {
+ for (const q of queries) {
+ targetFile = findFileWithQuery(q, process.cwd());
+ if (targetFile) { matchedQuery = q; break; }
+ }
+ if (!targetFile) {
+ console.error(JSON.stringify({ error: 'Could not find element in project files. Searched for: ' + queries.join(', ') }));
+ process.exit(1);
+ }
+ } else {
+ matchedQuery = queries[0];
+ }
+
+ const content = fs.readFileSync(targetFile, 'utf-8');
+ const lines = content.split('\n');
+
+ // Find the element, trying each query in priority order
+ let match = null;
+ for (const q of queries) {
+ match = findElement(lines, q);
+ if (match) break;
+ }
+ if (!match) {
+ console.error(JSON.stringify({ error: 'Found file but could not locate element in ' + targetFile + '. Searched for: ' + queries.join(', ') }));
+ process.exit(1);
+ }
+
+ const { startLine, endLine } = match;
+ const commentSyntax = detectCommentSyntax(targetFile);
+ const indent = lines[startLine].match(/^(\s*)/)[1];
+
+ // Extract the original element
+ const originalLines = lines.slice(startLine, endLine + 1);
+ const originalIndented = originalLines.map(l => indent + ' ' + l.trimStart()).join('\n');
+
+ // Build the wrapper
+ const wrapperLines = [
+ indent + commentSyntax.open + ' impeccable-variants-start ' + id + ' ' + commentSyntax.close,
+ indent + '<div data-impeccable-variants="' + id + '" data-impeccable-variant-count="' + count + '" style="display: contents">',
+ indent + ' ' + commentSyntax.open + ' Original ' + commentSyntax.close,
+ indent + ' <div data-impeccable-variant="original">',
+ originalIndented,
+ indent + ' </div>',
+ indent + ' ' + commentSyntax.open + ' Variants: insert below this line ' + commentSyntax.close,
+ indent + '</div>',
+ indent + commentSyntax.open + ' impeccable-variants-end ' + id + ' ' + commentSyntax.close,
+ ];
+
+ // Replace the original element with the wrapper
+ const newLines = [
+ ...lines.slice(0, startLine),
+ ...wrapperLines,
+ ...lines.slice(endLine + 1),
+ ];
+ fs.writeFileSync(targetFile, newLines.join('\n'), 'utf-8');
+
+ // Calculate insert line (the "insert below this line" comment)
+ const insertLine = startLine + 6; // 0-indexed in the new file
+
+ console.log(JSON.stringify({
+ file: path.relative(process.cwd(), targetFile),
+ startLine: startLine + 1, // 1-indexed for the agent
+ endLine: startLine + wrapperLines.length, // 1-indexed
+ insertLine: insertLine + 1, // 1-indexed: where variants go
+ commentSyntax: commentSyntax,
+ originalLineCount: originalLines.length,
+ }));
+}
+
+// ---------------------------------------------------------------------------
+// Helpers
+// ---------------------------------------------------------------------------
+
+function argVal(args, flag) {
+ const idx = args.indexOf(flag);
+ return idx !== -1 && idx + 1 < args.length ? args[idx + 1] : null;
+}
+
+/**
+ * Build search query strings in priority order (most specific first).
+ * ID is most reliable, then specific class combos, then single classes, then raw query.
+ */
+function buildSearchQueries(elementId, classes, tag, query) {
+ const queries = [];
+
+ // 1. ID is the most specific
+ if (elementId) {
+ queries.push('id="' + elementId + '"');
+ }
+
+ // 2. Full class attribute match (for elements with distinctive multi-class combos)
+ if (classes) {
+ const classList = classes.split(',').map(c => c.trim()).filter(Boolean);
+ if (classList.length > 1) {
+ // Try the most distinctive class first (longest, most specific)
+ const sorted = [...classList].sort((a, b) => b.length - a.length);
+ queries.push('class="' + classList.join(' ') + '"'); // exact full match
+ queries.push(sorted[0]); // most distinctive single class
+ } else if (classList.length === 1) {
+ queries.push(classList[0]);
+ }
+ }
+
+ // 3. Tag + class combo (e.g., <section class="hero">)
+ if (tag && classes) {
+ const firstClass = classes.split(',')[0].trim();
+ queries.push('<' + tag + ' class="' + firstClass);
+ }
+
+ // 4. Raw fallback query
+ if (query) {
+ queries.push(query);
+ }
+
+ return queries;
+}
+
+function detectCommentSyntax(filePath) {
+ const ext = path.extname(filePath).toLowerCase();
+ if (ext === '.jsx' || ext === '.tsx') {
+ return { open: '{/*', close: '*/}' };
+ }
+ // HTML, Vue, Svelte, Astro all use HTML comments
+ return { open: '<!--', close: '-->' };
+}
+
+/**
+ * Search project files for the query string (class name, ID, etc.)
+ * Returns the first matching file path, or null.
+ */
+function findFileWithQuery(query, cwd) {
+ const searchDirs = ['src', 'app', 'pages', 'components', 'public', 'views', 'templates', '.'];
+ const seen = new Set();
+
+ for (const dir of searchDirs) {
+ const absDir = path.join(cwd, dir);
+ if (!fs.existsSync(absDir)) continue;
+ const result = searchDir(absDir, query, seen, 0);
+ if (result) return result;
+ }
+ return null;
+}
+
+function searchDir(dir, query, seen, depth) {
+ if (depth > 5) return null; // don't go too deep
+ const realDir = fs.realpathSync(dir);
+ if (seen.has(realDir)) return null;
+ seen.add(realDir);
+
+ let entries;
+ try { entries = fs.readdirSync(dir, { withFileTypes: true }); }
+ catch { return null; }
+
+ // Check files first
+ for (const entry of entries) {
+ if (!entry.isFile()) continue;
+ const ext = path.extname(entry.name).toLowerCase();
+ if (!EXTENSIONS.includes(ext)) continue;
+
+ const filePath = path.join(dir, entry.name);
+ try {
+ const content = fs.readFileSync(filePath, 'utf-8');
+ if (content.includes(query)) return filePath;
+ } catch { /* skip unreadable files */ }
+ }
+
+ // Then recurse into directories
+ for (const entry of entries) {
+ if (!entry.isDirectory()) continue;
+ if (entry.name === 'node_modules' || entry.name === '.git' || entry.name === 'dist' || entry.name === 'build') continue;
+ const result = searchDir(path.join(dir, entry.name), query, seen, depth + 1);
+ if (result) return result;
+ }
+
+ return null;
+}
+
+/**
+ * Find the element's start and end line in the file.
+ * The query is a class name, ID, or text snippet.
+ * We find the line containing the query, then find the matching closing tag.
+ */
+function findElement(lines, query) {
+ // Find the line containing the query
+ let startLine = -1;
+ for (let i = 0; i < lines.length; i++) {
+ if (lines[i].includes(query)) {
+ // Make sure this looks like a tag opening, not a comment or string
+ const line = lines[i].trim();
+ if (line.startsWith('<!--') || line.startsWith('{/*') || line.startsWith('//')) continue;
+ // Skip lines inside data-impeccable-variant containers (already wrapped)
+ if (lines[i].includes('data-impeccable-variant')) continue;
+ startLine = i;
+ break;
+ }
+ }
+
+ if (startLine === -1) return null;
+
+ // Find the end of this element by counting open/close tags
+ const endLine = findClosingLine(lines, startLine);
+ return { startLine, endLine };
+}
+
+/**
+ * Starting from a line with an opening tag, find the line with the matching
+ * closing tag by counting tag nesting depth.
+ */
+function findClosingLine(lines, start) {
+ // Extract the tag name from the opening line
+ const openMatch = lines[start].match(/<(\w+)[\s>]/);
+ if (!openMatch) return start; // self-closing or text-only line
+
+ const tagName = openMatch[1];
+ let depth = 0;
+
+ for (let i = start; i < lines.length; i++) {
+ const line = lines[i];
+ // Count opening tags (not self-closing)
+ const opens = (line.match(new RegExp('<' + tagName + '[\\s>]', 'g')) || []).length;
+ const selfCloses = (line.match(new RegExp('<' + tagName + '[^>]*/>', 'g')) || []).length;
+ const closes = (line.match(new RegExp('</' + tagName + '\\s*>', 'g')) || []).length;
+
+ depth += opens - selfCloses - closes;
+
+ if (depth <= 0) return i;
+ }
+
+ // If we can't find the close, return a reasonable guess
+ return Math.min(start + 50, lines.length - 1);
+}
diff --git a/.cursor/skills/impeccable/reference/live.md b/.cursor/skills/impeccable/reference/live.md
index 53b64a21a..ba0e9b0c5 100644
--- a/.cursor/skills/impeccable/reference/live.md
+++ b/.cursor/skills/impeccable/reference/live.md
@@ -10,7 +10,7 @@ Launch interactive live variant mode: select elements in the browser, pick a des
1. Read `.impeccable.md` if it exists. Keep the design context in mind for variant generation.
2. Start the live variant server:
```bash
- npx impeccable live &
+ node {{scripts_path}}/live-server.mjs &
```
3. Note the **port** and **token** printed to stdout.
@@ -53,7 +53,7 @@ Run a blocking poll loop. On each iteration, wait for a browser event and respon
```
LOOP:
- Run: npx impeccable poll
+ Run: node {{scripts_path}}/live-poll.mjs
Read the JSON output. Dispatch based on the "type" field:
TYPE "generate":
@@ -85,7 +85,7 @@ The event contains: `{id, action, freeformPrompt, count, pageUrl, element}`.
Use the `wrap` helper to find the element and create the variant container:
```bash
-npx impeccable wrap --id EVENT_ID --count EVENT_COUNT --element-id "ELEMENT_ID" --classes "class1,class2" --tag "div"
+node {{scripts_path}}/live-wrap.mjs --id EVENT_ID --count EVENT_COUNT --element-id "ELEMENT_ID" --classes "class1,class2" --tag "div"
```
Pass the element's id (`event.element.id`), classes (`event.element.classes` joined with commas), and tag name. The command searches in priority order: ID match first, then class names, then tag+class combo. If `event.pageUrl` hints at the file (e.g., `/` is usually `index.html`), pass `--file PATH` to skip the search.
@@ -136,10 +136,14 @@ The first variant should NOT have `style="display: none"` (it should be visible
### Step 3: Signal completion
+Include `--file` so the browser can fetch variants directly if the dev server lacks HMR:
+
```bash
-npx impeccable poll --reply EVENT_ID done
+node {{scripts_path}}/live-poll.mjs --reply EVENT_ID done --file RELATIVE_PATH
```
+The file path should be relative to the project root (e.g., `public/index.html`, `src/App.tsx`).
+
## Handle Accept
The event contains: `{id, variantId}`.
@@ -151,7 +155,7 @@ The user accepted a specific variant. For v1 (inspection mode):
4. Remove any scoped CSS blocks (between `impeccable-variants-css-start` and `impeccable-variants-css-end` markers).
5. Reply:
```bash
- npx impeccable poll --reply SESSION_ID done
+ node {{scripts_path}}/live-poll.mjs --reply SESSION_ID done
```
## Handle Discard
@@ -163,7 +167,7 @@ The event contains: `{id}`.
3. Remove any scoped CSS blocks for this session.
4. Reply:
```bash
- npx impeccable poll --reply SESSION_ID done
+ node {{scripts_path}}/live-poll.mjs --reply SESSION_ID done
```
## Cleanup (on exit)
@@ -174,7 +178,7 @@ When the loop ends:
2. **Remove any leftover variant wrappers** (search for `impeccable-variants-start` markers and clean up).
3. **Stop the server**:
```bash
- npx impeccable live stop
+ node {{scripts_path}}/live-server.mjs stop
```
## Variant Generation Guidelines
diff --git a/.cursor/skills/impeccable/scripts/live-browser.js b/.cursor/skills/impeccable/scripts/live-browser.js
new file mode 100644
index 000000000..7a26c9829
--- /dev/null
+++ b/.cursor/skills/impeccable/scripts/live-browser.js
@@ -0,0 +1,1220 @@
+/**
+ * Impeccable Live Variant Mode — Browser Script
+ *
+ * Injected into the user's page via <script src="http://localhost:PORT/live.js">.
+ * The server prepends window.__IMPECCABLE_TOKEN__ and window.__IMPECCABLE_PORT__
+ * before this code.
+ *
+ * UI: a single floating bar that morphs between three states —
+ * configure (pick action + go), generating (progressive dots), and cycling
+ * (prev/next + accept/discard). Feels like Spotlight, not a modal.
+ */
+(function () {
+ 'use strict';
+ if (typeof window === 'undefined') return;
+
+ // Guard against double-init. Bun's HTML loader may process the <script> tag
+ // and create a bundled copy alongside the external load, or HMR may re-execute.
+ // Check BEFORE reading token/port to catch all cases.
+ if (window.__IMPECCABLE_LIVE_INIT__) return;
+ window.__IMPECCABLE_LIVE_INIT__ = true;
+
+ const TOKEN = window.__IMPECCABLE_TOKEN__;
+ const PORT = window.__IMPECCABLE_PORT__;
+ if (!TOKEN || !PORT) {
+ window.__IMPECCABLE_LIVE_INIT__ = false; // reset so the real load can init
+ return;
+ }
+
+ // ---------------------------------------------------------------------------
+ // Design tokens
+ // ---------------------------------------------------------------------------
+
+ const C = {
+ brand: 'oklch(55% 0.25 350)',
+ brandHov: 'oklch(48% 0.25 350)',
+ brandSoft: 'oklch(55% 0.25 350 / 0.12)',
+ ink: 'oklch(15% 0.01 350)',
+ ash: 'oklch(55% 0 0)',
+ paper: 'oklch(98% 0.005 350 / 0.92)',
+ paperSolid:'oklch(98% 0.005 350)',
+ mist: 'oklch(90% 0.01 350 / 0.6)',
+ white: 'oklch(99% 0 0)',
+ };
+ const FONT = 'system-ui, -apple-system, sans-serif';
+ const MONO = 'ui-monospace, SFMono-Regular, Menlo, monospace';
+ const Z = { highlight: 99990, bar: 99995, picker: 99997, toast: 99999 };
+ const EASE = 'cubic-bezier(0.22, 1, 0.36, 1)'; // ease-out-quint
+ const PREFIX = 'impeccable-live';
+
+ const SKIP_TAGS = new Set([
+ 'html', 'head', 'body', 'script', 'style', 'link', 'meta', 'noscript', 'br', 'wbr',
+ ]);
+
+ const ACTIONS = [
+ { value: 'impeccable', label: 'Freeform' },
+ { value: 'bolder', label: 'Bolder' },
+ { value: 'quieter', label: 'Quieter' },
+ { value: 'distill', label: 'Distill' },
+ { value: 'polish', label: 'Polish' },
+ { value: 'typeset', label: 'Typeset' },
+ { value: 'colorize', label: 'Colorize' },
+ { value: 'layout', label: 'Layout' },
+ { value: 'adapt', label: 'Adapt' },
+ { value: 'animate', label: 'Animate' },
+ { value: 'delight', label: 'Delight' },
+ { value: 'overdrive', label: 'Overdrive' },
+ ];
+
+ // ---------------------------------------------------------------------------
+ // State
+ // ---------------------------------------------------------------------------
+
+ let state = 'IDLE';
+ let hoveredElement = null;
+ let selectedElement = null;
+ let currentSessionId = null;
+ let expectedVariants = 0;
+ let arrivedVariants = 0;
+ let visibleVariant = 0;
+ let variantObserver = null;
+ let hasProjectContext = false;
+ let selectedAction = 'impeccable';
+ let selectedCount = 3;
+
+ // UI refs
+ let highlightEl = null;
+ let tooltipEl = null;
+ let barEl = null;
+ let pickerEl = null;
+ let toastEl = null;
+ let scrollRaf = null;
+
+ // ---------------------------------------------------------------------------
+ // Helpers
+ // ---------------------------------------------------------------------------
+
+ function own(el) {
+ return el && (el.id?.startsWith(PREFIX) || el.closest?.('[id^="' + PREFIX + '"]'));
+ }
+
+ function pickable(el) {
+ if (!el || el.nodeType !== 1) return false;
+ if (SKIP_TAGS.has(el.tagName.toLowerCase())) return false;
+ if (own(el)) return false;
+ const r = el.getBoundingClientRect();
+ return r.width >= 20 && r.height >= 20;
+ }
+
+ function desc(el) {
+ if (!el) return '';
+ let s = el.tagName.toLowerCase();
+ if (el.id) s += '#' + el.id;
+ else if (el.classList.length) s += '.' + [...el.classList].slice(0, 2).join('.');
+ return s;
+ }
+
+ function id8() { return crypto.randomUUID().replace(/-/g, '').slice(0, 8); }
+
+ // ---------------------------------------------------------------------------
+ // Highlight overlay
+ // ---------------------------------------------------------------------------
+
+ function initHighlight() {
+ highlightEl = document.createElement('div');
+ highlightEl.id = PREFIX + '-highlight';
+ Object.assign(highlightEl.style, {
+ position: 'fixed', top: '0', left: '0', width: '0', height: '0',
+ border: '2px solid ' + C.brand, borderRadius: '3px',
+ pointerEvents: 'none', zIndex: Z.highlight, boxSizing: 'border-box',
+ transition: 'top 0.08s ease, left 0.08s ease, width 0.08s ease, height 0.08s ease, opacity 0.15s ease',
+ display: 'none', opacity: '0',
+ });
+ document.body.appendChild(highlightEl);
+
+ tooltipEl = document.createElement('div');
+ tooltipEl.id = PREFIX + '-tooltip';
+ Object.assign(tooltipEl.style, {
+ position: 'fixed',
+ background: C.ink, color: C.white,
+ fontFamily: MONO, fontSize: '10px', fontWeight: '500',
+ padding: '2px 6px', borderRadius: '3px',
+ zIndex: Z.highlight + 1, pointerEvents: 'none',
+ whiteSpace: 'nowrap', display: 'none',
+ letterSpacing: '0.02em',
+ });
+ document.body.appendChild(tooltipEl);
+ }
+
+ function showHighlight(el) {
+ if (!el || !highlightEl) return;
+ const r = el.getBoundingClientRect();
+ Object.assign(highlightEl.style, {
+ top: (r.top - 2) + 'px', left: (r.left - 2) + 'px',
+ width: (r.width + 4) + 'px', height: (r.height + 4) + 'px',
+ display: 'block', opacity: '1',
+ });
+ tooltipEl.textContent = desc(el);
+ const tipTop = r.top - 20;
+ Object.assign(tooltipEl.style, {
+ top: (tipTop < 4 ? r.bottom + 4 : tipTop) + 'px',
+ left: Math.max(4, r.left) + 'px', display: 'block',
+ });
+ }
+
+ function hideHighlight() {
+ if (highlightEl) { highlightEl.style.opacity = '0'; highlightEl.style.display = 'none'; }
+ if (tooltipEl) tooltipEl.style.display = 'none';
+ }
+
+ // ---------------------------------------------------------------------------
+ // Element context extraction
+ // ---------------------------------------------------------------------------
+
+ function extractContext(el) {
+ const cs = getComputedStyle(el);
+ const r = el.getBoundingClientRect();
+ const props = {};
+ for (const sheet of document.styleSheets) {
+ try {
+ for (const rule of sheet.cssRules) {
+ if (rule.style) for (let i = 0; i < rule.style.length; i++) {
+ const p = rule.style[i];
+ if (p.startsWith('--') && !props[p]) {
+ const v = cs.getPropertyValue(p).trim();
+ if (v) props[p] = v;
+ }
+ }
+ }
+ } catch { /* cross-origin */ }
+ }
+ return {
+ tagName: el.tagName.toLowerCase(), id: el.id || null,
+ classes: [...el.classList],
+ textContent: (el.textContent || '').slice(0, 500),
+ outerHTML: el.outerHTML.slice(0, 10000),
+ computedStyles: {
+ 'font-family': cs.fontFamily, 'font-size': cs.fontSize,
+ 'font-weight': cs.fontWeight, 'line-height': cs.lineHeight,
+ 'color': cs.color, 'background': cs.background,
+ 'background-color': cs.backgroundColor,
+ 'padding': cs.padding, 'margin': cs.margin,
+ 'display': cs.display, 'position': cs.position,
+ 'gap': cs.gap, 'border-radius': cs.borderRadius,
+ 'box-shadow': cs.boxShadow,
+ },
+ cssCustomProperties: props,
+ parentContext: el.parentElement
+ ? '<' + el.parentElement.tagName.toLowerCase()
+ + (el.parentElement.id ? ' id="' + el.parentElement.id + '"' : '')
+ + (el.parentElement.className ? ' class="' + el.parentElement.className + '"' : '')
+ + '>'
+ : null,
+ boundingRect: { width: Math.round(r.width), height: Math.round(r.height) },
+ };
+ }
+
+ // ---------------------------------------------------------------------------
+ // The Bar — one floating element, three modes
+ // ---------------------------------------------------------------------------
+
+ function initBar() {
+ barEl = document.createElement('div');
+ barEl.id = PREFIX + '-bar';
+ Object.assign(barEl.style, {
+ position: 'fixed', zIndex: Z.bar,
+ display: 'none', opacity: '0',
+ transform: 'translateY(6px)',
+ transition: 'opacity 0.25s ' + EASE + ', transform 0.3s ' + EASE,
+ // Visual
+ background: C.paper,
+ backdropFilter: 'blur(16px)', WebkitBackdropFilter: 'blur(16px)',
+ border: '1px solid ' + C.mist,
+ borderRadius: '10px',
+ boxShadow: '0 4px 20px oklch(0% 0 0 / 0.08), 0 1px 3px oklch(0% 0 0 / 0.06)',
+ fontFamily: FONT, fontSize: '13px', color: C.ink,
+ padding: '6px',
+ maxWidth: '460px', minWidth: '320px',
+ });
+ document.body.appendChild(barEl);
+ }
+
+ function positionBar() {
+ if (!barEl || !selectedElement) return;
+ const r = selectedElement.getBoundingClientRect();
+ const barH = barEl.offsetHeight || 44;
+ const barW = barEl.offsetWidth || 380;
+ let top = r.bottom + 8;
+ let left = r.left + (r.width - barW) / 2;
+ // Keep in viewport
+ if (top + barH + 8 > window.innerHeight) top = r.top - barH - 8;
+ if (top < 8) top = 8;
+ if (left < 8) left = 8;
+ if (left + barW > window.innerWidth - 8) left = window.innerWidth - barW - 8;
+ Object.assign(barEl.style, { top: top + 'px', left: left + 'px' });
+ }
+
+ function showBar(mode) {
+ barEl.innerHTML = '';
+ if (mode === 'configure') barEl.appendChild(buildConfigureRow());
+ else if (mode === 'generating') barEl.appendChild(buildGeneratingRow());
+ else if (mode === 'cycling') barEl.appendChild(buildCyclingRow());
+ barEl.style.display = 'block';
+ positionBar();
+ requestAnimationFrame(() => {
+ barEl.style.opacity = '1';
+ barEl.style.transform = 'translateY(0)';
+ });
+ }
+
+ function hideBar() {
+ if (!barEl) return;
+ barEl.style.opacity = '0';
+ barEl.style.transform = 'translateY(6px)';
+ setTimeout(() => { if (barEl) barEl.style.display = 'none'; }, 250);
+ hideActionPicker();
+ }
+
+ function updateBarContent(mode) {
+ if (!barEl || barEl.style.display === 'none') return;
+ barEl.innerHTML = '';
+ // Reset bar styling
+ barEl.style.background = C.paper;
+ barEl.style.border = '1px solid ' + C.mist;
+ if (mode === 'configure') barEl.appendChild(buildConfigureRow());
+ else if (mode === 'generating') barEl.appendChild(buildGeneratingRow());
+ else if (mode === 'cycling') barEl.appendChild(buildCyclingRow());
+ else if (mode === 'saving') barEl.appendChild(buildSavingRow());
+ else if (mode === 'confirmed') {
+ barEl.appendChild(buildConfirmedRow());
+ barEl.style.background = 'oklch(95% 0.05 145)';
+ barEl.style.border = '1px solid oklch(75% 0.12 145 / 0.4)';
+ }
+ }
+
+ // --- Configure row ---
+
+ function buildConfigureRow() {
+ const row = el('div', {
+ display: 'flex', alignItems: 'center', gap: '4px',
+ });
+
+ // Action pill
+ const pill = el('button', {
+ display: 'inline-flex', alignItems: 'center', gap: '4px',
+ padding: '5px 10px', borderRadius: '6px',
+ background: C.ink, color: C.white,
+ fontFamily: FONT, fontSize: '12px', fontWeight: '500',
+ border: 'none', cursor: 'pointer',
+ transition: 'background 0.12s ease, transform 0.1s ease',
+ whiteSpace: 'nowrap', flexShrink: '0',
+ });
+ pill.textContent = actionLabel() + ' \u25BE';
+ pill.addEventListener('mouseenter', () => pill.style.background = C.brandHov);
+ pill.addEventListener('mouseleave', () => pill.style.background = C.ink);
+ pill.addEventListener('mousedown', () => pill.style.transform = 'scale(0.97)');
+ pill.addEventListener('mouseup', () => pill.style.transform = 'scale(1)');
+ pill.addEventListener('click', (e) => { e.stopPropagation(); toggleActionPicker(); });
+ row.appendChild(pill);
+
+ // Freeform input
+ const input = document.createElement('input');
+ input.id = PREFIX + '-input';
+ input.type = 'text';
+ input.placeholder = selectedAction === 'impeccable' ? 'describe what you want...' : 'refine further (optional)...';
+ Object.assign(input.style, {
+ flex: '1', minWidth: '0',
+ padding: '5px 8px', borderRadius: '6px',
+ border: '1px solid transparent', background: 'transparent',
+ fontFamily: FONT, fontSize: '12px', color: C.ink,
+ outline: 'none',
+ transition: 'border-color 0.15s ease, background 0.15s ease',
+ });
+ input.addEventListener('focus', () => {
+ input.style.borderColor = C.mist;
+ input.style.background = C.white;
+ });
+ input.addEventListener('blur', () => {
+ input.style.borderColor = 'transparent';
+ input.style.background = 'transparent';
+ });
+ input.addEventListener('keydown', (e) => {
+ e.stopPropagation(); // Don't trigger element picker keyboard nav
+ if (e.key === 'Enter') { e.preventDefault(); handleGo(); }
+ if (e.key === 'Escape') { e.preventDefault(); input.blur(); hideBar(); state = 'PICKING'; }
+ });
+ row.appendChild(input);
+
+ // Variant count toggle
+ const count = el('button', {
+ padding: '4px 6px', borderRadius: '5px',
+ border: '1px solid ' + C.mist, background: 'transparent',
+ fontFamily: MONO, fontSize: '11px', fontWeight: '600',
+ color: C.ash, cursor: 'pointer',
+ transition: 'color 0.12s ease, border-color 0.12s ease',
+ flexShrink: '0', whiteSpace: 'nowrap',
+ });
+ count.textContent = '\u00D7' + selectedCount;
+ count.title = 'Variants: click to change';
+ count.addEventListener('mouseenter', () => { count.style.color = C.ink; count.style.borderColor = C.ink; });
+ count.addEventListener('mouseleave', () => { count.style.color = C.ash; count.style.borderColor = C.mist; });
+ count.addEventListener('click', (e) => {
+ e.stopPropagation();
+ selectedCount = selectedCount >= 4 ? 2 : selectedCount + 1;
+ count.textContent = '\u00D7' + selectedCount;
+ });
+ row.appendChild(count);
+
+ // Go button
+ const go = el('button', {
+ padding: '5px 12px', borderRadius: '6px',
+ border: 'none', background: C.brand, color: C.white,
+ fontFamily: FONT, fontSize: '12px', fontWeight: '600',
+ cursor: 'pointer',
+ transition: 'background 0.12s ease, transform 0.1s ease',
+ flexShrink: '0', whiteSpace: 'nowrap',
+ });
+ go.textContent = 'Go \u2192';
+ go.addEventListener('mouseenter', () => go.style.background = C.brandHov);
+ go.addEventListener('mouseleave', () => go.style.background = C.brand);
+ go.addEventListener('mousedown', () => go.style.transform = 'scale(0.97)');
+ go.addEventListener('mouseup', () => go.style.transform = 'scale(1)');
+ go.addEventListener('click', (e) => { e.stopPropagation(); handleGo(); });
+ row.appendChild(go);
+
+ // Auto-focus input after a beat
+ setTimeout(() => input.focus(), 60);
+ return row;
+ }
+
+ // --- Generating row ---
+
+ function buildGeneratingRow() {
+ const row = el('div', {
+ display: 'flex', alignItems: 'center', gap: '8px',
+ padding: '2px 4px',
+ });
+
+ // Action label
+ const label = el('span', {
+ fontWeight: '600', fontSize: '12px', color: C.ink,
+ flexShrink: '0', whiteSpace: 'nowrap',
+ });
+ label.textContent = actionLabel();
+ row.appendChild(label);
+
+ // Dots
+ row.appendChild(buildDots(false));
+
+ // Status
+ const status = el('span', {
+ fontSize: '11px', color: C.ash, whiteSpace: 'nowrap',
+ marginLeft: 'auto',
+ });
+ status.textContent = arrivedVariants < expectedVariants
+ ? 'Generating ' + (arrivedVariants + 1) + ' of ' + expectedVariants + '...'
+ : 'Done';
+ row.appendChild(status);
+
+ return row;
+ }
+
+ // --- Cycling row ---
+
+ function buildCyclingRow() {
+ const row = el('div', {
+ display: 'flex', alignItems: 'center', gap: '6px',
+ padding: '1px 2px',
+ });
+
+ // Prev
+ const prev = navBtn('\u2190');
+ prev.addEventListener('click', (e) => { e.stopPropagation(); cycleVariant(-1); });
+ if (visibleVariant <= 1) prev.style.opacity = '0.3';
+ row.appendChild(prev);
+
+ // Dots (clickable)
+ row.appendChild(buildDots(true));
+
+ // Counter
+ const counter = el('span', {
+ fontFamily: MONO, fontSize: '11px', fontWeight: '500',
+ color: C.ash, minWidth: '24px', textAlign: 'center',
+ });
+ counter.textContent = visibleVariant + '/' + arrivedVariants;
+ row.appendChild(counter);
+
+ // Next
+ const next = navBtn('\u2192');
+ next.addEventListener('click', (e) => { e.stopPropagation(); cycleVariant(1); });
+ if (visibleVariant >= arrivedVariants) next.style.opacity = '0.3';
+ row.appendChild(next);
+
+ // Spacer
+ row.appendChild(el('div', { flex: '1' }));
+
+ // Accept
+ const accept = el('button', {
+ padding: '4px 10px', borderRadius: '5px',
+ border: 'none', background: C.ink, color: C.white,
+ fontFamily: FONT, fontSize: '11px', fontWeight: '600',
+ cursor: 'pointer', transition: 'background 0.12s ease',
+ whiteSpace: 'nowrap',
+ });
+ accept.textContent = '\u2713 Accept';
+ accept.addEventListener('mouseenter', () => accept.style.background = C.brand);
+ accept.addEventListener('mouseleave', () => accept.style.background = C.ink);
+ accept.addEventListener('click', (e) => { e.stopPropagation(); handleAccept(); });
+ if (arrivedVariants === 0) { accept.style.opacity = '0.3'; accept.style.pointerEvents = 'none'; }
+ row.appendChild(accept);
+
+ // Discard
+ const discard = el('button', {
+ padding: '4px 6px', borderRadius: '5px',
+ border: '1px solid ' + C.mist, background: 'transparent',
+ fontFamily: FONT, fontSize: '11px', color: C.ash,
+ cursor: 'pointer', transition: 'color 0.12s ease, border-color 0.12s ease',
+ });
+ discard.textContent = '\u2715';
+ discard.title = 'Discard all variants';
+ discard.addEventListener('mouseenter', () => { discard.style.color = C.ink; discard.style.borderColor = C.ink; });
+ discard.addEventListener('mouseleave', () => { discard.style.color = C.ash; discard.style.borderColor = C.mist; });
+ discard.addEventListener('click', (e) => { e.stopPropagation(); handleDiscard(); });
+ row.appendChild(discard);
+
+ return row;
+ }
+
+ // --- Shared UI builders ---
+
+ // --- Saving row (waiting for agent to process accept/discard) ---
+
+ function buildSavingRow() {
+ const row = el('div', {
+ display: 'flex', alignItems: 'center', gap: '8px',
+ padding: '2px 8px',
+ });
+ const spinner = el('div', {
+ width: '14px', height: '14px', borderRadius: '50%',
+ border: '2px solid ' + C.mist,
+ borderTopColor: C.brand,
+ animation: 'impeccable-spin 0.6s linear infinite',
+ flexShrink: '0',
+ });
+ row.appendChild(spinner);
+ const label = el('span', {
+ fontSize: '12px', color: C.ash, fontWeight: '500',
+ });
+ label.textContent = 'Applying variant...';
+ row.appendChild(label);
+
+ // Inject the keyframes if not already present
+ if (!document.getElementById(PREFIX + '-keyframes')) {
+ const style = document.createElement('style');
+ style.id = PREFIX + '-keyframes';
+ style.textContent = '@keyframes impeccable-spin { to { transform: rotate(360deg); } }';
+ document.head.appendChild(style);
+ }
+ return row;
+ }
+
+ // --- Confirmed row (green success, auto-dismisses) ---
+
+ function buildConfirmedRow() {
+ const row = el('div', {
+ display: 'flex', alignItems: 'center', gap: '8px',
+ padding: '2px 8px',
+ });
+ const check = el('span', {
+ fontSize: '15px', lineHeight: '1', flexShrink: '0',
+ color: 'oklch(45% 0.15 145)',
+ });
+ check.textContent = '\u2713';
+ row.appendChild(check);
+ const label = el('span', {
+ fontSize: '12px', color: 'oklch(35% 0.1 145)', fontWeight: '600',
+ });
+ label.textContent = 'Variant applied';
+ row.appendChild(label);
+ return row;
+ }
+
+ // --- Shared UI builders ---
+
+ function buildDots(clickable) {
+ const container = el('div', {
+ display: 'flex', alignItems: 'center', gap: '4px',
+ });
+ for (let i = 1; i <= expectedVariants; i++) {
+ const arrived = i <= arrivedVariants;
+ const active = i === visibleVariant;
+ const dot = el('div', {
+ width: '7px', height: '7px', borderRadius: '50%',
+ background: active ? C.brand : (arrived ? C.ash : 'transparent'),
+ border: '1.5px solid ' + (arrived ? C.brand : C.mist),
+ transition: 'all 0.2s ' + EASE,
+ cursor: (clickable && arrived) ? 'pointer' : 'default',
+ transform: arrived ? 'scale(1)' : 'scale(0.6)',
+ opacity: arrived ? '1' : '0.4',
+ });
+ if (clickable && arrived) {
+ const idx = i;
+ dot.addEventListener('click', (e) => {
+ e.stopPropagation();
+ visibleVariant = idx;
+ showVariantInDOM(currentSessionId, idx);
+ updateSelectedElement();
+ updateBarContent('cycling');
+ });
+ }
+ container.appendChild(dot);
+ }
+ return container;
+ }
+
+ function navBtn(text) {
+ const b = el('button', {
+ width: '26px', height: '26px', borderRadius: '5px',
+ border: '1px solid ' + C.mist, background: 'transparent',
+ color: C.ink, fontFamily: FONT, fontSize: '13px',
+ cursor: 'pointer', display: 'flex', alignItems: 'center', justifyContent: 'center',
+ transition: 'border-color 0.12s ease, background 0.12s ease',
+ padding: '0', lineHeight: '1',
+ });
+ b.textContent = text;
+ b.addEventListener('mouseenter', () => { b.style.borderColor = C.ink; });
+ b.addEventListener('mouseleave', () => { b.style.borderColor = C.mist; });
+ return b;
+ }
+
+ function actionLabel() {
+ const a = ACTIONS.find(a => a.value === selectedAction);
+ return a ? a.label : 'Freeform';
+ }
+
+ function el(tag, styles) {
+ const e = document.createElement(tag);
+ if (styles) Object.assign(e.style, styles);
+ return e;
+ }
+
+ // ---------------------------------------------------------------------------
+ // Action picker popover
+ // ---------------------------------------------------------------------------
+
+ function initActionPicker() {
+ pickerEl = document.createElement('div');
+ pickerEl.id = PREFIX + '-picker';
+ Object.assign(pickerEl.style, {
+ position: 'fixed', zIndex: Z.picker,
+ display: 'none', opacity: '0',
+ transform: 'scale(0.96) translateY(4px)',
+ transformOrigin: 'bottom left',
+ transition: 'opacity 0.18s ' + EASE + ', transform 0.2s ' + EASE,
+ background: C.paperSolid,
+ border: '1px solid ' + C.mist,
+ borderRadius: '10px',
+ boxShadow: '0 8px 30px oklch(0% 0 0 / 0.10), 0 2px 6px oklch(0% 0 0 / 0.06)',
+ padding: '6px',
+ fontFamily: FONT,
+ });
+
+ // Build the chip grid
+ const grid = el('div', {
+ display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', gap: '3px',
+ });
+
+ ACTIONS.forEach(action => {
+ const chip = el('button', {
+ padding: '6px 8px', borderRadius: '6px',
+ border: 'none',
+ background: action.value === selectedAction ? C.brandSoft : 'transparent',
+ color: action.value === selectedAction ? C.brand : C.ink,
+ fontFamily: FONT, fontSize: '11px', fontWeight: '500',
+ cursor: 'pointer',
+ transition: 'background 0.1s ease, color 0.1s ease',
+ textAlign: 'center', whiteSpace: 'nowrap',
+ });
+ chip.textContent = action.label;
+ chip.dataset.action = action.value;
+ chip.addEventListener('mouseenter', () => {
+ if (action.value !== selectedAction) chip.style.background = C.brandSoft;
+ });
+ chip.addEventListener('mouseleave', () => {
+ chip.style.background = action.value === selectedAction ? C.brandSoft : 'transparent';
+ });
+ chip.addEventListener('click', (e) => {
+ e.stopPropagation();
+ selectedAction = action.value;
+ hideActionPicker();
+ updateBarContent('configure');
+ });
+ grid.appendChild(chip);
+ });
+
+ pickerEl.appendChild(grid);
+ document.body.appendChild(pickerEl);
+ }
+
+ function toggleActionPicker() {
+ if (pickerEl.style.display !== 'none') { hideActionPicker(); return; }
+ // Rebuild chips to reflect current selection
+ pickerEl.querySelectorAll('button').forEach(chip => {
+ const isActive = chip.dataset.action === selectedAction;
+ chip.style.background = isActive ? C.brandSoft : 'transparent';
+ chip.style.color = isActive ? C.brand : C.ink;
+ });
+ // Position above the bar
+ const barRect = barEl.getBoundingClientRect();
+ const pickerH = 90; // approximate
+ let top = barRect.top - pickerH - 6;
+ if (top < 8) top = barRect.bottom + 6;
+ Object.assign(pickerEl.style, {
+ top: top + 'px', left: barRect.left + 'px',
+ display: 'block',
+ });
+ requestAnimationFrame(() => {
+ pickerEl.style.opacity = '1';
+ pickerEl.style.transform = 'scale(1) translateY(0)';
+ });
+ }
+
+ function hideActionPicker() {
+ if (!pickerEl) return;
+ pickerEl.style.opacity = '0';
+ pickerEl.style.transform = 'scale(0.96) translateY(4px)';
+ setTimeout(() => { if (pickerEl) pickerEl.style.display = 'none'; }, 180);
+ }
+
+ // ---------------------------------------------------------------------------
+ // Variant cycling in DOM
+ // ---------------------------------------------------------------------------
+
+ function showVariantInDOM(sessionId, num) {
+ const wrapper = document.querySelector('[data-impeccable-variants="' + sessionId + '"]');
+ if (!wrapper) return;
+ for (const child of wrapper.children) {
+ const v = child.dataset ? child.dataset.impeccableVariant : null;
+ if (!v) continue;
+ child.style.display = (v === String(num)) ? '' : 'none';
+ }
+ }
+
+ /**
+ * No-HMR fallback: fetch the raw source file from the live server,
+ * parse it, extract the variant wrapper, and inject it into the live DOM.
+ * This works even when the dev server caches HTML (Bun, static servers).
+ */
+ function injectVariantsFromSource(filePath, sessionId) {
+ const url = 'http://localhost:' + PORT + '/source?token=' + TOKEN + '&path=' + encodeURIComponent(filePath);
+ fetch(url)
+ .then(r => { if (!r.ok) throw new Error(r.status); return r.text(); })
+ .then(html => {
+ // Parse the raw source HTML
+ const parser = new DOMParser();
+ const doc = parser.parseFromString(html, 'text/html');
+ const srcWrapper = doc.querySelector('[data-impeccable-variants="' + sessionId + '"]');
+ if (!srcWrapper) {
+ console.error('[impeccable] Variant wrapper not found in source file.');
+ return;
+ }
+
+ // Find the original element in the live DOM.
+ // The original is inside the wrapper in the source. We find the
+ // corresponding element in the live DOM by matching the first child's
+ // tag + classes from the original snapshot.
+ const origContent = srcWrapper.querySelector('[data-impeccable-variant="original"] > :first-child');
+ if (!origContent) return;
+
+ const tag = origContent.tagName.toLowerCase();
+ const cls = origContent.className;
+ let liveEl = null;
+ if (origContent.id) {
+ liveEl = document.getElementById(origContent.id);
+ } else if (cls) {
+ // Find by tag + exact class match
+ const candidates = document.querySelectorAll(tag + '.' + cls.split(' ')[0]);
+ for (const c of candidates) {
+ if (c.className === cls && !own(c)) { liveEl = c; break; }
+ }
+ }
+
+ if (!liveEl) {
+ console.error('[impeccable] Could not find original element in live DOM.');
+ return;
+ }
+
+ // Replace the live element with the full wrapper from source
+ const wrapper = srcWrapper.cloneNode(true);
+ liveEl.parentElement.replaceChild(wrapper, liveEl);
+
+ // Update state: count variants, show the first one
+ 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);
+
+ // Update selectedElement to the visible variant's content
+ const visEl = wrapper.querySelector('[data-impeccable-variant="1"] > :first-child');
+ selectedElement = visEl || wrapper.parentElement;
+
+ state = 'CYCLING';
+ updateBarContent('cycling');
+ saveSession();
+ console.log('[impeccable] Injected ' + arrivedVariants + ' variants from source file.');
+ })
+ .catch(err => {
+ console.error('[impeccable] Failed to fetch source:', err);
+ showToast('Could not load variants. Try refreshing the page.', 5000);
+ });
+ }
+
+ function cycleVariant(dir) {
+ const next = visibleVariant + dir;
+ if (next < 1 || next > arrivedVariants) return;
+ visibleVariant = next;
+ showVariantInDOM(currentSessionId, next);
+ updateSelectedElement();
+ updateBarContent('cycling');
+ saveSession();
+ }
+
+ function updateSelectedElement() {
+ if (!currentSessionId) return;
+ const wrapper = document.querySelector('[data-impeccable-variants="' + currentSessionId + '"]');
+ if (!wrapper) return;
+ const visEl = wrapper.querySelector('[data-impeccable-variant="' + visibleVariant + '"] > :first-child');
+ if (visEl) selectedElement = visEl;
+ }
+
+ // ---------------------------------------------------------------------------
+ // MutationObserver for progressive variant reveal
+ // ---------------------------------------------------------------------------
+
+ function startVariantObserver(sessionId) {
+ let updating = false; // re-entrancy guard
+
+ const obs = new MutationObserver((mutations) => {
+ if (updating) return;
+
+ // Only react to mutations that add nodes with data-impeccable-variant,
+ // or mutations inside the variant wrapper. Ignore our own bar/UI changes.
+ let dominated = false;
+ for (const m of mutations) {
+ if (m.target.closest?.('[data-impeccable-variants]')) { dominated = true; break; }
+ for (const n of m.addedNodes) {
+ if (n.nodeType === 1 && (n.dataset?.impeccableVariants || n.dataset?.impeccableVariant)) {
+ dominated = true; break;
+ }
+ }
+ if (dominated) break;
+ }
+ if (!dominated) return;
+
+ const wrapper = document.querySelector('[data-impeccable-variants="' + sessionId + '"]');
+ if (!wrapper) return;
+
+ const variants = wrapper.querySelectorAll('[data-impeccable-variant]:not([data-impeccable-variant="original"])');
+ const count = variants.length;
+
+ // Nothing new
+ if (count <= arrivedVariants) return;
+
+ updating = true;
+ arrivedVariants = count;
+ if (visibleVariant === 0 && arrivedVariants > 0) {
+ visibleVariant = 1;
+ showVariantInDOM(sessionId, 1);
+ }
+
+ const expected = parseInt(wrapper.dataset.impeccableVariantCount || '0');
+ if (expected > 0) expectedVariants = expected;
+
+ if (arrivedVariants >= expectedVariants && expectedVariants > 0) {
+ state = 'CYCLING';
+ updateBarContent('cycling');
+ } else if (state === 'GENERATING') {
+ updateBarContent('generating');
+ }
+ saveSession();
+ updating = false;
+ });
+
+ obs.observe(document.body, { childList: true, subtree: true });
+ return obs;
+ }
+
+ // ---------------------------------------------------------------------------
+ // Bar scroll tracking
+ // ---------------------------------------------------------------------------
+
+ function startScrollTracking() {
+ function tick() {
+ if (state === 'CONFIGURING' || state === 'GENERATING' || state === 'CYCLING') {
+ positionBar();
+ showHighlight(selectedElement);
+ }
+ scrollRaf = requestAnimationFrame(tick);
+ }
+ scrollRaf = requestAnimationFrame(tick);
+ }
+
+ function stopScrollTracking() {
+ if (scrollRaf) { cancelAnimationFrame(scrollRaf); scrollRaf = null; }
+ }
+
+ // ---------------------------------------------------------------------------
+ // SSE (server→browser) + fetch POST (browser→server)
+ // Zero-dependency replacement for WebSocket.
+ // ---------------------------------------------------------------------------
+
+ let evtSource = null;
+
+ function connectSSE() {
+ evtSource = new EventSource('http://localhost:' + PORT + '/events?token=' + TOKEN);
+
+ evtSource.onmessage = (e) => {
+ let msg; try { msg = JSON.parse(e.data); } catch { return; }
+ switch (msg.type) {
+ case 'connected':
+ hasProjectContext = !!msg.hasProjectContext;
+ if (!hasProjectContext) showToast('No .impeccable.md found. Variants will be brand-agnostic.', 6000);
+ console.log('[impeccable] Live mode connected.');
+ if (state === 'IDLE') state = 'PICKING';
+ break;
+ case 'done':
+ if (state === 'SAVING') {
+ state = 'CONFIRMED';
+ updateBarContent('confirmed');
+ setTimeout(() => {
+ hideBar();
+ hideHighlight();
+ stopScrollTracking();
+ if (variantObserver) { variantObserver.disconnect(); variantObserver = null; }
+ clearSession();
+ selectedElement = null;
+ currentSessionId = null;
+ selectedAction = 'impeccable';
+ state = 'PICKING';
+ }, 1800);
+ return;
+ }
+ if (arrivedVariants === 0 && expectedVariants > 0 && msg.file) {
+ console.log('[impeccable] No HMR detected. Fetching variants from source file...');
+ injectVariantsFromSource(msg.file, currentSessionId);
+ return;
+ }
+ state = 'CYCLING';
+ updateBarContent('cycling');
+ break;
+ case 'error':
+ console.error('[impeccable] Error:', msg.message);
+ showToast('Error: ' + msg.message, 5000);
+ hideBar();
+ state = 'PICKING';
+ break;
+ }
+ };
+
+ evtSource.onerror = () => {
+ // EventSource auto-reconnects. Log once.
+ console.log('[impeccable] SSE connection lost. Reconnecting...');
+ };
+ }
+
+ function sendEvent(msg) {
+ msg.token = TOKEN;
+ 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));
+ }
+
+ // ---------------------------------------------------------------------------
+ // Event handlers
+ // ---------------------------------------------------------------------------
+
+ function handleMouseMove(e) {
+ if (state !== 'PICKING') return;
+ const target = document.elementFromPoint(e.clientX, e.clientY);
+ if (!target || !pickable(target) || target === hoveredElement) return;
+ hoveredElement = target;
+ showHighlight(target);
+ }
+
+ function handleClick(e) {
+ // Close action picker on any outside click
+ if (pickerEl?.style.display !== 'none' && !own(e.target)) {
+ hideActionPicker();
+ }
+ if (state !== 'PICKING') return;
+ if (own(e.target)) return;
+ if (!hoveredElement || !pickable(hoveredElement)) return;
+ e.preventDefault();
+ e.stopPropagation();
+ selectedElement = hoveredElement;
+ state = 'CONFIGURING';
+ showHighlight(selectedElement);
+ showBar('configure');
+ startScrollTracking();
+ }
+
+ function handleKeyDown(e) {
+ if (e.key === 'Escape') {
+ e.preventDefault();
+ if (pickerEl?.style.display !== 'none') { hideActionPicker(); return; }
+ if (state === 'CONFIGURING') { hideBar(); stopScrollTracking(); state = 'PICKING'; return; }
+ if (state === 'CYCLING') { handleDiscard(); return; }
+ if (state === 'SAVING' || state === 'CONFIRMED') return; // don't interrupt
+ if (state === 'PICKING') { hideHighlight(); state = 'IDLE'; return; }
+ }
+
+ if (state === 'PICKING' && hoveredElement) {
+ let next = null;
+ if (e.key === 'ArrowDown' && !e.shiftKey) {
+ next = hoveredElement.nextElementSibling;
+ while (next && !pickable(next)) next = next.nextElementSibling;
+ } else if (e.key === 'ArrowUp' && !e.shiftKey) {
+ next = hoveredElement.previousElementSibling;
+ while (next && !pickable(next)) next = next.previousElementSibling;
+ } else if (e.key === 'ArrowUp' && e.shiftKey) {
+ next = hoveredElement.parentElement;
+ if (next && !pickable(next)) next = null;
+ } else if (e.key === 'ArrowDown' && e.shiftKey) {
+ next = hoveredElement.firstElementChild;
+ while (next && !pickable(next)) next = next.nextElementSibling;
+ } else if (e.key === 'Enter') {
+ e.preventDefault();
+ selectedElement = hoveredElement;
+ state = 'CONFIGURING';
+ showHighlight(selectedElement);
+ showBar('configure');
+ startScrollTracking();
+ return;
+ }
+ if (next) {
+ e.preventDefault();
+ hoveredElement = next;
+ showHighlight(next);
+ next.scrollIntoView({ block: 'nearest', behavior: 'smooth' });
+ }
+ return;
+ }
+
+ if (state === 'CYCLING') {
+ if (e.key === 'ArrowLeft') { e.preventDefault(); cycleVariant(-1); }
+ if (e.key === 'ArrowRight') { e.preventDefault(); cycleVariant(1); }
+ if (e.key === 'Enter') { e.preventDefault(); handleAccept(); }
+ }
+ }
+
+ function handleGo() {
+ if (!selectedElement || state !== 'CONFIGURING') return;
+ const input = document.getElementById(PREFIX + '-input');
+ const prompt = input ? input.value.trim() : '';
+
+ currentSessionId = id8();
+ expectedVariants = selectedCount;
+ arrivedVariants = 0;
+ visibleVariant = 0;
+
+ sendEvent({
+ type: 'generate', id: currentSessionId,
+ action: selectedAction,
+ freeformPrompt: prompt || undefined,
+ count: selectedCount,
+ pageUrl: location.pathname,
+ element: extractContext(selectedElement),
+ });
+
+ state = 'GENERATING';
+ showBar('generating');
+ saveSession();
+ if (variantObserver) variantObserver.disconnect();
+ variantObserver = startVariantObserver(currentSessionId);
+ }
+
+ function handleAccept() {
+ if (!currentSessionId || arrivedVariants === 0) return;
+ sendEvent({ type: 'accept', id: currentSessionId, variantId: String(visibleVariant) });
+ markSessionHandled();
+ state = 'SAVING';
+ updateBarContent('saving');
+ // Don't cleanup yet — wait for the "done" WS message to show confirmation
+ }
+
+ function handleDiscard() {
+ if (!currentSessionId) return;
+ sendEvent({ type: 'discard', id: currentSessionId });
+ markSessionHandled();
+ state = 'SAVING';
+ updateBarContent('saving');
+ // Wait for "done" WS message to show confirmation and dismiss
+ }
+
+ // ---------------------------------------------------------------------------
+ // Session persistence via localStorage
+ // ---------------------------------------------------------------------------
+ // Survives page reloads, browser close/reopen, HMR, and accidental refreshes.
+
+ const LS_KEY = PREFIX + '-session';
+
+ function saveSession() {
+ if (!currentSessionId) return;
+ 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 */ }
+ }
+
+ function loadSession() {
+ try {
+ const raw = localStorage.getItem(LS_KEY);
+ return raw ? JSON.parse(raw) : null;
+ } catch { return null; }
+ }
+
+ function clearSession() {
+ try { localStorage.removeItem(LS_KEY); } catch {}
+ }
+
+ /** Mark session as handled (accepted/discarded). The agent will clean up
+ * the source, but until it does the wrapper is still in the HTML. This
+ * prevents resumeSession from picking it up again after reload. */
+ function markSessionHandled() {
+ if (!currentSessionId) return;
+ try {
+ localStorage.setItem(LS_KEY + '-handled', currentSessionId);
+ } catch {}
+ }
+
+ function isSessionHandled(id) {
+ try {
+ return localStorage.getItem(LS_KEY + '-handled') === id;
+ } catch { return false; }
+ }
+
+ function clearHandled() {
+ try { localStorage.removeItem(LS_KEY + '-handled'); } catch {}
+ }
+
+ function cleanup() {
+ hideBar();
+ hideHighlight();
+ stopScrollTracking();
+ if (variantObserver) { variantObserver.disconnect(); variantObserver = null; }
+ clearSession();
+ selectedElement = null;
+ currentSessionId = null;
+ selectedAction = 'impeccable';
+ state = 'PICKING';
+ }
+
+ // ---------------------------------------------------------------------------
+ // Toast
+ // ---------------------------------------------------------------------------
+
+ function showToast(message, duration) {
+ if (toastEl) toastEl.remove();
+ toastEl = el('div', {
+ position: 'fixed', bottom: '16px', left: '50%',
+ transform: 'translateX(-50%) translateY(8px)',
+ background: C.ink, color: C.white,
+ fontFamily: FONT, fontSize: '12px',
+ padding: '8px 16px', borderRadius: '8px',
+ zIndex: Z.toast, opacity: '0',
+ transition: 'opacity 0.25s ' + EASE + ', transform 0.25s ' + EASE,
+ pointerEvents: 'none', maxWidth: '420px', textAlign: 'center',
+ });
+ toastEl.id = PREFIX + '-toast';
+ toastEl.textContent = message;
+ document.body.appendChild(toastEl);
+ requestAnimationFrame(() => {
+ toastEl.style.opacity = '1';
+ toastEl.style.transform = 'translateX(-50%) translateY(0)';
+ });
+ setTimeout(() => {
+ if (toastEl) {
+ toastEl.style.opacity = '0';
+ toastEl.style.transform = 'translateX(-50%) translateY(8px)';
+ setTimeout(() => { if (toastEl) { toastEl.remove(); toastEl = null; } }, 250);
+ }
+ }, duration);
+ }
+
+ // ---------------------------------------------------------------------------
+ // Init
+ // ---------------------------------------------------------------------------
+
+ // Resume an active variant session after HMR/page reload.
+ // If a [data-impeccable-variants] wrapper exists in the DOM, the agent wrote
+ // variants before HMR fired. Pick up where we left off.
+ function resumeSession() {
+ const wrapper = document.querySelector('[data-impeccable-variants]');
+ if (!wrapper) { clearSession(); clearHandled(); return false; }
+
+ const sessionId = wrapper.dataset.impeccableVariants;
+
+ // Don't resume if this session was already accepted/discarded
+ if (isSessionHandled(sessionId)) return false;
+
+ currentSessionId = sessionId;
+ expectedVariants = parseInt(wrapper.dataset.impeccableVariantCount || '0');
+ const variants = wrapper.querySelectorAll('[data-impeccable-variant]:not([data-impeccable-variant="original"])');
+ arrivedVariants = variants.length;
+
+ // Restore visible variant from localStorage if available, else default to 1
+ const saved = loadSession();
+ visibleVariant = (saved && saved.id === sessionId && saved.visible > 0 && saved.visible <= arrivedVariants)
+ ? saved.visible : (arrivedVariants > 0 ? 1 : 0);
+
+ // Find the visible variant's content element for highlight positioning
+ const visEl = wrapper.querySelector('[data-impeccable-variant="' + visibleVariant + '"] > :first-child');
+ selectedElement = visEl || wrapper.parentElement;
+
+ // Set display state BEFORE starting observer (avoid triggering it)
+ if (visibleVariant > 0) showVariantInDOM(currentSessionId, visibleVariant);
+
+ state = arrivedVariants >= expectedVariants ? 'CYCLING' : 'GENERATING';
+ showBar(state === 'CYCLING' ? 'cycling' : 'generating');
+ startScrollTracking();
+ saveSession();
+
+ // Start observing for more variants AFTER initial setup
+ if (variantObserver) variantObserver.disconnect();
+ variantObserver = startVariantObserver(currentSessionId);
+ return true;
+ }
+
+ function init() {
+ initHighlight();
+ initBar();
+ initActionPicker();
+ document.addEventListener('mousemove', handleMouseMove, true);
+ document.addEventListener('click', handleClick, true);
+ document.addEventListener('keydown', handleKeyDown, true);
+ connectSSE();
+
+ // Check for an active session to resume (variant wrapper already in DOM after HMR)
+ if (!resumeSession()) {
+ console.log('[impeccable] Live variant mode ready. Hover over elements to pick one.');
+ } else {
+ console.log('[impeccable] Resumed active variant session ' + currentSessionId + ' (' + arrivedVariants + '/' + expectedVariants + ' variants).');
+ }
+ }
+
+ if (document.readyState === 'loading') {
+ document.addEventListener('DOMContentLoaded', init);
+ } else {
+ init();
+ }
+})();
diff --git a/.cursor/skills/impeccable/scripts/live-poll.mjs b/.cursor/skills/impeccable/scripts/live-poll.mjs
new file mode 100644
index 000000000..52859416c
--- /dev/null
+++ b/.cursor/skills/impeccable/scripts/live-poll.mjs
@@ -0,0 +1,123 @@
+/**
+ * CLI client for the live variant mode poll/reply protocol.
+ *
+ * Usage:
+ * npx impeccable poll # Block until browser event, print JSON
+ * npx impeccable poll --timeout=60000 # Custom timeout (ms)
+ * npx impeccable poll --reply <id> done # Reply "done" to event <id>
+ * npx impeccable poll --reply <id> error "msg" # Reply with error
+ */
+
+import fs from 'node:fs';
+import path from 'node:path';
+import os from 'node:os';
+
+const LIVE_PID_FILE = path.join(os.tmpdir(), 'impeccable-live.json');
+
+function readServerInfo() {
+ try {
+ return JSON.parse(fs.readFileSync(LIVE_PID_FILE, 'utf-8'));
+ } catch {
+ console.error('No running live server found. Start one with: npx impeccable live');
+ process.exit(1);
+ }
+}
+
+export async function pollCli() {
+ const args = process.argv.slice(2);
+
+ if (args.includes('--help') || args.includes('-h')) {
+ console.log(`Usage: impeccable poll [options]
+
+Wait for a browser event from the live variant server, or reply to one.
+
+Modes:
+ poll Block until a browser event arrives, print JSON
+ poll --reply <id> done Reply "done" to event <id>
+ poll --reply <id> error "msg" Reply with an error message
+
+Options:
+ --timeout=MS Poll timeout in milliseconds (default: 120000)
+ --help Show this help message`);
+ process.exit(0);
+ }
+
+ const info = readServerInfo();
+ const base = `http://localhost:${info.port}`;
+
+ // Reply mode: npx impeccable poll --reply <id> <status> [--file path] [message]
+ const replyIdx = args.indexOf('--reply');
+ if (replyIdx !== -1) {
+ const id = args[replyIdx + 1];
+ const status = args[replyIdx + 2] || 'done';
+ const fileIdx = args.indexOf('--file');
+ const filePath = fileIdx !== -1 && fileIdx + 1 < args.length ? args[fileIdx + 1] : undefined;
+ // Message is any remaining positional arg that isn't a flag
+ const message = args.find((a, i) => i > replyIdx + 2 && !a.startsWith('--') && i !== fileIdx + 1) || undefined;
+
+ if (!id) {
+ console.error('Usage: npx impeccable poll --reply <id> <status> [--file path] [message]');
+ process.exit(1);
+ }
+
+ 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);
+ }
+
+ // Success — silent exit (agent doesn't need output for replies)
+ } catch (err) {
+ if (err.cause?.code === 'ECONNREFUSED') {
+ console.error('Live server not running. Start one with: npx impeccable live');
+ } else {
+ console.error('Reply failed:', err.message);
+ }
+ process.exit(1);
+ }
+ return;
+ }
+
+ // Poll mode: block until browser event
+ const timeoutArg = args.find(a => a.startsWith('--timeout='));
+ const timeout = timeoutArg ? parseInt(timeoutArg.split('=')[1], 10) : 120000;
+
+ try {
+ const res = await fetch(`${base}/poll?token=${info.token}&timeout=${timeout}`);
+
+ if (res.status === 401) {
+ console.error('Authentication failed. The server token may have changed.');
+ console.error('Try restarting: npx impeccable live stop && npx impeccable live');
+ process.exit(1);
+ }
+
+ if (!res.ok) {
+ console.error(`Poll failed: ${res.status} ${res.statusText}`);
+ process.exit(1);
+ }
+
+ const event = await res.json();
+ // Print the event as JSON — the agent reads this from stdout
+ console.log(JSON.stringify(event));
+ } catch (err) {
+ if (err.cause?.code === 'ECONNREFUSED') {
+ console.error('Live server not running. Start one with: npx impeccable live');
+ } else {
+ console.error('Poll failed:', err.message);
+ }
+ process.exit(1);
+ }
+}
diff --git a/.cursor/skills/impeccable/scripts/live-server.mjs b/.cursor/skills/impeccable/scripts/live-server.mjs
new file mode 100644
index 000000000..d436bad58
--- /dev/null
+++ b/.cursor/skills/impeccable/scripts/live-server.mjs
@@ -0,0 +1,416 @@
+#!/usr/bin/env node
+/**
+ * Live variant mode server (self-contained, zero dependencies).
+ *
+ * Serves the browser script (/live.js), the detection overlay (/detect.js),
+ * uses Server-Sent Events (SSE) for server→browser push, and HTTP POST for
+ * browser→server events. Agent communicates via HTTP long-poll (/poll).
+ *
+ * Usage:
+ * node <scripts_path>/live-server.mjs # start
+ * node <scripts_path>/live-server.mjs stop # stop
+ * node <scripts_path>/live-server.mjs --help
+ */
+
+import http from 'node:http';
+import { randomUUID } from 'node:crypto';
+import fs from 'node:fs';
+import path from 'node:path';
+import os from 'node:os';
+import net from 'node:net';
+import { fileURLToPath } from 'node:url';
+
+const __dirname = path.dirname(fileURLToPath(import.meta.url));
+const LIVE_PID_FILE = path.join(os.tmpdir(), 'impeccable-live.json');
+const DEFAULT_POLL_TIMEOUT = 120_000;
+
+// ---------------------------------------------------------------------------
+// Port detection
+// ---------------------------------------------------------------------------
+
+async function findOpenPort(start = 8400) {
+ return new Promise((resolve) => {
+ const srv = net.createServer();
+ srv.listen(start, '127.0.0.1', () => {
+ const port = srv.address().port;
+ srv.close(() => resolve(port));
+ });
+ srv.on('error', () => resolve(findOpenPort(start + 1)));
+ });
+}
+
+// ---------------------------------------------------------------------------
+// Session state
+// ---------------------------------------------------------------------------
+
+const state = {
+ token: null,
+ port: null,
+ sseClients: new Set(), // SSE response objects (server→browser push)
+ pendingEvents: [], // browser events waiting for agent poll
+ pendingPolls: [], // agent poll callbacks waiting for browser events
+ exitTimer: null,
+};
+
+function enqueueEvent(event) {
+ if (state.pendingPolls.length > 0) {
+ state.pendingPolls.shift()(event);
+ } else {
+ state.pendingEvents.push(event);
+ }
+}
+
+/** Push a message to all connected SSE clients. */
+function broadcast(msg) {
+ const data = 'data: ' + JSON.stringify(msg) + '\n\n';
+ for (const res of state.sseClients) {
+ try { res.write(data); } catch { /* client gone */ }
+ }
+}
+
+// ---------------------------------------------------------------------------
+// Load scripts
+// ---------------------------------------------------------------------------
+
+function loadBrowserScripts() {
+ // Detection script: look relative to the skill scripts dir, then fall back
+ // to the npm package location (src/detect-antipatterns-browser.js)
+ const detectPaths = [
+ path.join(__dirname, '..', '..', '..', '..', 'src', 'detect-antipatterns-browser.js'),
+ path.join(process.cwd(), 'node_modules', 'impeccable', 'src', 'detect-antipatterns-browser.js'),
+ ];
+ let detectScript = '';
+ for (const p of detectPaths) {
+ try { detectScript = fs.readFileSync(p, 'utf-8'); break; } catch { /* try next */ }
+ }
+
+ const livePath = path.join(__dirname, 'live-browser.js');
+ let liveScript = '';
+ try {
+ liveScript = fs.readFileSync(livePath, 'utf-8');
+ } catch {
+ process.stderr.write('Error: live-browser.js not found at ' + livePath + '\n');
+ process.exit(1);
+ }
+
+ return { detectScript, liveScript };
+}
+
+function hasProjectContext() {
+ try {
+ fs.accessSync(path.join(process.cwd(), '.impeccable.md'), fs.constants.R_OK);
+ return true;
+ } catch { return false; }
+}
+
+// ---------------------------------------------------------------------------
+// Validation (inline — no external import needed for self-contained script)
+// ---------------------------------------------------------------------------
+
+const VISUAL_ACTIONS = [
+ 'impeccable', 'bolder', 'quieter', 'distill', 'polish', 'typeset',
+ 'colorize', 'layout', 'adapt', 'animate', 'delight', 'overdrive',
+];
+
+function validateEvent(msg) {
+ if (!msg || typeof msg !== 'object' || !msg.type) return 'Missing or invalid message';
+ switch (msg.type) {
+ case 'generate':
+ if (!msg.id || typeof msg.id !== 'string') return 'generate: missing id';
+ if (!msg.action || !VISUAL_ACTIONS.includes(msg.action)) return 'generate: invalid action';
+ if (!Number.isInteger(msg.count) || msg.count < 1 || msg.count > 8) return 'generate: count must be 1-8';
+ if (!msg.element || !msg.element.outerHTML) return 'generate: missing element context';
+ return null;
+ case 'accept':
+ if (!msg.id) return 'accept: missing id';
+ if (!msg.variantId) return 'accept: missing variantId';
+ return null;
+ case 'discard':
+ return msg.id ? null : 'discard: missing id';
+ case 'exit':
+ return null;
+ default:
+ return 'Unknown event type: ' + msg.type;
+ }
+}
+
+// ---------------------------------------------------------------------------
+// HTTP request handler
+// ---------------------------------------------------------------------------
+
+function createRequestHandler({ detectScript, liveScriptWithToken }) {
+ return (req, res) => {
+ const url = new URL(req.url, `http://localhost:${state.port}`);
+ res.setHeader('Access-Control-Allow-Origin', '*');
+ res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS');
+ res.setHeader('Access-Control-Allow-Headers', 'Content-Type');
+ if (req.method === 'OPTIONS') { res.writeHead(204); res.end(); return; }
+
+ const p = url.pathname;
+
+ // --- Scripts ---
+ if (p === '/live.js') {
+ res.writeHead(200, { 'Content-Type': 'application/javascript' });
+ res.end(liveScriptWithToken);
+ return;
+ }
+ if (p === '/detect.js' || p === '/') {
+ if (!detectScript) { res.writeHead(404); res.end('Not available'); return; }
+ res.writeHead(200, { 'Content-Type': 'application/javascript' });
+ res.end(detectScript);
+ return;
+ }
+
+ // --- Health ---
+ if (p === '/health') {
+ res.writeHead(200, { 'Content-Type': 'application/json' });
+ res.end(JSON.stringify({
+ status: 'ok', port: state.port, mode: 'variant',
+ hasProjectContext: hasProjectContext(),
+ connectedClients: state.sseClients.size,
+ }));
+ return;
+ }
+
+ // --- Source file (no-HMR fallback) ---
+ if (p === '/source') {
+ const token = url.searchParams.get('token');
+ if (token !== state.token) { res.writeHead(401); res.end('Unauthorized'); return; }
+ const filePath = url.searchParams.get('path');
+ if (!filePath || filePath.includes('..')) { res.writeHead(400); res.end('Bad path'); return; }
+ const absPath = path.resolve(process.cwd(), filePath);
+ if (!absPath.startsWith(process.cwd())) { res.writeHead(403); res.end('Forbidden'); return; }
+ try {
+ res.writeHead(200, { 'Content-Type': 'text/html; charset=utf-8' });
+ res.end(fs.readFileSync(absPath, 'utf-8'));
+ } catch { res.writeHead(404); res.end('File not found'); }
+ return;
+ }
+
+ // --- SSE: server→browser push (replaces WebSocket) ---
+ if (p === '/events' && req.method === 'GET') {
+ const token = url.searchParams.get('token');
+ if (token !== state.token) { res.writeHead(401); res.end('Unauthorized'); return; }
+ res.writeHead(200, {
+ 'Content-Type': 'text/event-stream',
+ 'Cache-Control': 'no-cache',
+ 'Connection': 'keep-alive',
+ });
+ res.write('data: ' + JSON.stringify({
+ type: 'connected',
+ hasProjectContext: hasProjectContext(),
+ }) + '\n\n');
+
+ state.sseClients.add(res);
+ clearTimeout(state.exitTimer);
+
+ req.on('close', () => {
+ state.sseClients.delete(res);
+ if (state.sseClients.size === 0) {
+ clearTimeout(state.exitTimer);
+ state.exitTimer = setTimeout(() => {
+ if (state.sseClients.size === 0) enqueueEvent({ type: 'exit' });
+ }, 8000);
+ }
+ });
+ return;
+ }
+
+ // --- Browser→server events (replaces WebSocket messages) ---
+ if (p === '/events' && req.method === 'POST') {
+ let body = '';
+ req.on('data', (c) => { body += c; });
+ req.on('end', () => {
+ let msg;
+ try { msg = JSON.parse(body); } catch {
+ res.writeHead(400, { 'Content-Type': 'application/json' });
+ res.end(JSON.stringify({ error: 'Invalid JSON' }));
+ return;
+ }
+ if (msg.token !== state.token) {
+ res.writeHead(401, { 'Content-Type': 'application/json' });
+ res.end(JSON.stringify({ error: 'Unauthorized' }));
+ return;
+ }
+ const error = validateEvent(msg);
+ if (error) {
+ res.writeHead(400, { 'Content-Type': 'application/json' });
+ res.end(JSON.stringify({ error }));
+ return;
+ }
+ enqueueEvent(msg);
+ res.writeHead(200, { 'Content-Type': 'application/json' });
+ res.end(JSON.stringify({ ok: true }));
+ });
+ return;
+ }
+
+ // --- Stop ---
+ if (p === '/stop') {
+ const token = url.searchParams.get('token');
+ if (token !== state.token) { res.writeHead(401); res.end('Unauthorized'); return; }
+ res.writeHead(200, { 'Content-Type': 'text/plain' });
+ res.end('stopping');
+ shutdown();
+ return;
+ }
+
+ // --- Agent poll ---
+ if (p === '/poll' && req.method === 'GET') {
+ handlePollGet(req, res, url);
+ return;
+ }
+ if (p === '/poll' && req.method === 'POST') {
+ handlePollPost(req, res);
+ return;
+ }
+
+ res.writeHead(404); res.end('Not found');
+ };
+}
+
+// ---------------------------------------------------------------------------
+// Agent poll endpoints (unchanged from WS version)
+// ---------------------------------------------------------------------------
+
+function handlePollGet(req, res, url) {
+ 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 timeout = parseInt(url.searchParams.get('timeout') || DEFAULT_POLL_TIMEOUT, 10);
+ if (state.pendingEvents.length > 0) {
+ res.writeHead(200, { 'Content-Type': 'application/json' });
+ res.end(JSON.stringify(state.pendingEvents.shift()));
+ return;
+ }
+ const timer = setTimeout(() => {
+ const idx = state.pendingPolls.indexOf(resolve);
+ if (idx !== -1) state.pendingPolls.splice(idx, 1);
+ res.writeHead(200, { 'Content-Type': 'application/json' });
+ res.end(JSON.stringify({ type: 'timeout' }));
+ }, timeout);
+ function resolve(event) {
+ clearTimeout(timer);
+ res.writeHead(200, { 'Content-Type': 'application/json' });
+ res.end(JSON.stringify(event));
+ }
+ state.pendingPolls.push(resolve);
+ req.on('close', () => {
+ clearTimeout(timer);
+ const idx = state.pendingPolls.indexOf(resolve);
+ if (idx !== -1) state.pendingPolls.splice(idx, 1);
+ });
+}
+
+function handlePollPost(req, res) {
+ let body = '';
+ req.on('data', (c) => { body += c; });
+ req.on('end', () => {
+ let msg;
+ try { msg = JSON.parse(body); } catch {
+ res.writeHead(400, { 'Content-Type': 'application/json' });
+ res.end(JSON.stringify({ error: 'Invalid JSON' }));
+ return;
+ }
+ if (msg.token !== state.token) {
+ res.writeHead(401, { 'Content-Type': 'application/json' });
+ res.end(JSON.stringify({ error: 'Unauthorized' }));
+ return;
+ }
+ // Forward the reply to the browser via SSE
+ broadcast({ type: msg.type || 'done', id: msg.id, message: msg.message, file: msg.file, data: msg.data });
+ res.writeHead(200, { 'Content-Type': 'application/json' });
+ res.end(JSON.stringify({ ok: true }));
+ });
+}
+
+// ---------------------------------------------------------------------------
+// Lifecycle
+// ---------------------------------------------------------------------------
+
+let httpServer = null;
+
+function shutdown() {
+ try { fs.unlinkSync(LIVE_PID_FILE); } catch {}
+ for (const res of state.sseClients) { try { res.end(); } catch {} }
+ state.sseClients.clear();
+ for (const resolve of state.pendingPolls) resolve({ type: 'exit' });
+ state.pendingPolls.length = 0;
+ if (httpServer) httpServer.close();
+ process.exit(0);
+}
+
+// ---------------------------------------------------------------------------
+// Main
+// ---------------------------------------------------------------------------
+
+const args = process.argv.slice(2);
+
+if (args.includes('--help') || args.includes('-h')) {
+ console.log(`Usage: node live-server.mjs [options]
+
+Start the live variant mode server (zero dependencies).
+
+Commands:
+ (default) Start the server
+ stop Stop a running server
+
+Options:
+ --port=PORT Use a specific port (default: auto-detect starting at 8400)
+ --help Show this help
+
+Endpoints:
+ /live.js Browser script (element picker + variant cycling)
+ /detect.js Detection overlay (backwards compatible)
+ /events SSE stream (server→browser) + POST (browser→server)
+ /poll Long-poll for agent CLI
+ /source Raw source file reader (no-HMR fallback)
+ /health Health check`);
+ process.exit(0);
+}
+
+if (args.includes('stop')) {
+ try {
+ const info = JSON.parse(fs.readFileSync(LIVE_PID_FILE, 'utf-8'));
+ 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 { console.log('No running live server found.'); }
+ process.exit(0);
+}
+
+// Check for existing session
+try {
+ const existing = JSON.parse(fs.readFileSync(LIVE_PID_FILE, 'utf-8'));
+ 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 {}
+
+state.token = randomUUID();
+const portArg = args.find(a => a.startsWith('--port='));
+state.port = portArg ? parseInt(portArg.split('=')[1], 10) : await findOpenPort();
+
+const { detectScript, liveScript } = loadBrowserScripts();
+const liveScriptWithToken =
+ `window.__IMPECCABLE_TOKEN__ = '${state.token}';\n` +
+ `window.__IMPECCABLE_PORT__ = ${state.port};\n` +
+ liveScript;
+
+httpServer = http.createServer(createRequestHandler({ detectScript, liveScriptWithToken }));
+
+httpServer.listen(state.port, '127.0.0.1', () => {
+ fs.writeFileSync(LIVE_PID_FILE, JSON.stringify({ 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`);
+ console.log(`Inject: <script src="${url}/live.js"><\/script>`);
+ console.log(`Stop: node ${path.basename(fileURLToPath(import.meta.url))} stop`);
+});
+
+process.on('SIGINT', shutdown);
+process.on('SIGTERM', shutdown);
diff --git a/.cursor/skills/impeccable/scripts/live-wrap.mjs b/.cursor/skills/impeccable/scripts/live-wrap.mjs
new file mode 100644
index 000000000..f1c838cdd
--- /dev/null
+++ b/.cursor/skills/impeccable/scripts/live-wrap.mjs
@@ -0,0 +1,298 @@
+/**
+ * CLI helper: find an element in source and wrap it in a variant container.
+ *
+ * Usage:
+ * npx impeccable wrap --id SESSION_ID --count N --query "hero-combined-left" [--file path]
+ *
+ * Searches project files for the element matching the query (class name, ID, or
+ * text snippet), wraps it with the variant scaffolding, and prints the file path
+ * + line range where the agent should insert variant HTML.
+ *
+ * This replaces 3-4 agent tool calls (grep + read + edit) with a single CLI call.
+ */
+
+import fs from 'node:fs';
+import path from 'node:path';
+
+const EXTENSIONS = ['.html', '.jsx', '.tsx', '.vue', '.svelte', '.astro'];
+
+export async function wrapCli() {
+ const args = process.argv.slice(2);
+
+ if (args.includes('--help') || args.includes('-h')) {
+ console.log(`Usage: impeccable wrap [options]
+
+Find an element in source and wrap it in a variant container.
+
+Required:
+ --id ID Session ID for the variant wrapper
+ --count N Number of expected variants (1-8)
+
+Element identification (at least one required):
+ --element-id ID HTML id attribute of the element
+ --classes A,B,C Comma-separated CSS class names
+ --tag TAG Tag name (div, section, etc.)
+ --query TEXT Fallback: raw text to search for
+
+Optional:
+ --file PATH Source file to search in (skips auto-detection)
+ --help Show this help message
+
+Output (JSON):
+ { file, startLine, endLine, insertLine, commentSyntax }
+
+The agent should insert variant HTML at insertLine.`);
+ process.exit(0);
+ }
+
+ const id = argVal(args, '--id');
+ const count = parseInt(argVal(args, '--count') || '3');
+ const elementId = argVal(args, '--element-id');
+ const classes = argVal(args, '--classes');
+ const tag = argVal(args, '--tag');
+ const query = argVal(args, '--query');
+ const filePath = argVal(args, '--file');
+
+ if (!id) { console.error('Missing --id'); process.exit(1); }
+ if (!elementId && !classes && !query) {
+ console.error('Need at least one of: --element-id, --classes, --query');
+ process.exit(1);
+ }
+
+ // Build search queries in priority order (most specific first)
+ const queries = buildSearchQueries(elementId, classes, tag, query);
+
+ // Find the source file
+ let targetFile = filePath;
+ let matchedQuery = null;
+ if (!targetFile) {
+ for (const q of queries) {
+ targetFile = findFileWithQuery(q, process.cwd());
+ if (targetFile) { matchedQuery = q; break; }
+ }
+ if (!targetFile) {
+ console.error(JSON.stringify({ error: 'Could not find element in project files. Searched for: ' + queries.join(', ') }));
+ process.exit(1);
+ }
+ } else {
+ matchedQuery = queries[0];
+ }
+
+ const content = fs.readFileSync(targetFile, 'utf-8');
+ const lines = content.split('\n');
+
+ // Find the element, trying each query in priority order
+ let match = null;
+ for (const q of queries) {
+ match = findElement(lines, q);
+ if (match) break;
+ }
+ if (!match) {
+ console.error(JSON.stringify({ error: 'Found file but could not locate element in ' + targetFile + '. Searched for: ' + queries.join(', ') }));
+ process.exit(1);
+ }
+
+ const { startLine, endLine } = match;
+ const commentSyntax = detectCommentSyntax(targetFile);
+ const indent = lines[startLine].match(/^(\s*)/)[1];
+
+ // Extract the original element
+ const originalLines = lines.slice(startLine, endLine + 1);
+ const originalIndented = originalLines.map(l => indent + ' ' + l.trimStart()).join('\n');
+
+ // Build the wrapper
+ const wrapperLines = [
+ indent + commentSyntax.open + ' impeccable-variants-start ' + id + ' ' + commentSyntax.close,
+ indent + '<div data-impeccable-variants="' + id + '" data-impeccable-variant-count="' + count + '" style="display: contents">',
+ indent + ' ' + commentSyntax.open + ' Original ' + commentSyntax.close,
+ indent + ' <div data-impeccable-variant="original">',
+ originalIndented,
+ indent + ' </div>',
+ indent + ' ' + commentSyntax.open + ' Variants: insert below this line ' + commentSyntax.close,
+ indent + '</div>',
+ indent + commentSyntax.open + ' impeccable-variants-end ' + id + ' ' + commentSyntax.close,
+ ];
+
+ // Replace the original element with the wrapper
+ const newLines = [
+ ...lines.slice(0, startLine),
+ ...wrapperLines,
+ ...lines.slice(endLine + 1),
+ ];
+ fs.writeFileSync(targetFile, newLines.join('\n'), 'utf-8');
+
+ // Calculate insert line (the "insert below this line" comment)
+ const insertLine = startLine + 6; // 0-indexed in the new file
+
+ console.log(JSON.stringify({
+ file: path.relative(process.cwd(), targetFile),
+ startLine: startLine + 1, // 1-indexed for the agent
+ endLine: startLine + wrapperLines.length, // 1-indexed
+ insertLine: insertLine + 1, // 1-indexed: where variants go
+ commentSyntax: commentSyntax,
+ originalLineCount: originalLines.length,
+ }));
+}
+
+// ---------------------------------------------------------------------------
+// Helpers
+// ---------------------------------------------------------------------------
+
+function argVal(args, flag) {
+ const idx = args.indexOf(flag);
+ return idx !== -1 && idx + 1 < args.length ? args[idx + 1] : null;
+}
+
+/**
+ * Build search query strings in priority order (most specific first).
+ * ID is most reliable, then specific class combos, then single classes, then raw query.
+ */
+function buildSearchQueries(elementId, classes, tag, query) {
+ const queries = [];
+
+ // 1. ID is the most specific
+ if (elementId) {
+ queries.push('id="' + elementId + '"');
+ }
+
+ // 2. Full class attribute match (for elements with distinctive multi-class combos)
+ if (classes) {
+ const classList = classes.split(',').map(c => c.trim()).filter(Boolean);
+ if (classList.length > 1) {
+ // Try the most distinctive class first (longest, most specific)
+ const sorted = [...classList].sort((a, b) => b.length - a.length);
+ queries.push('class="' + classList.join(' ') + '"'); // exact full match
+ queries.push(sorted[0]); // most distinctive single class
+ } else if (classList.length === 1) {
+ queries.push(classList[0]);
+ }
+ }
+
+ // 3. Tag + class combo (e.g., <section class="hero">)
+ if (tag && classes) {
+ const firstClass = classes.split(',')[0].trim();
+ queries.push('<' + tag + ' class="' + firstClass);
+ }
+
+ // 4. Raw fallback query
+ if (query) {
+ queries.push(query);
+ }
+
+ return queries;
+}
+
+function detectCommentSyntax(filePath) {
+ const ext = path.extname(filePath).toLowerCase();
+ if (ext === '.jsx' || ext === '.tsx') {
+ return { open: '{/*', close: '*/}' };
+ }
+ // HTML, Vue, Svelte, Astro all use HTML comments
+ return { open: '<!--', close: '-->' };
+}
+
+/**
+ * Search project files for the query string (class name, ID, etc.)
+ * Returns the first matching file path, or null.
+ */
+function findFileWithQuery(query, cwd) {
+ const searchDirs = ['src', 'app', 'pages', 'components', 'public', 'views', 'templates', '.'];
+ const seen = new Set();
+
+ for (const dir of searchDirs) {
+ const absDir = path.join(cwd, dir);
+ if (!fs.existsSync(absDir)) continue;
+ const result = searchDir(absDir, query, seen, 0);
+ if (result) return result;
+ }
+ return null;
+}
+
+function searchDir(dir, query, seen, depth) {
+ if (depth > 5) return null; // don't go too deep
+ const realDir = fs.realpathSync(dir);
+ if (seen.has(realDir)) return null;
+ seen.add(realDir);
+
+ let entries;
+ try { entries = fs.readdirSync(dir, { withFileTypes: true }); }
+ catch { return null; }
+
+ // Check files first
+ for (const entry of entries) {
+ if (!entry.isFile()) continue;
+ const ext = path.extname(entry.name).toLowerCase();
+ if (!EXTENSIONS.includes(ext)) continue;
+
+ const filePath = path.join(dir, entry.name);
+ try {
+ const content = fs.readFileSync(filePath, 'utf-8');
+ if (content.includes(query)) return filePath;
+ } catch { /* skip unreadable files */ }
+ }
+
+ // Then recurse into directories
+ for (const entry of entries) {
+ if (!entry.isDirectory()) continue;
+ if (entry.name === 'node_modules' || entry.name === '.git' || entry.name === 'dist' || entry.name === 'build') continue;
+ const result = searchDir(path.join(dir, entry.name), query, seen, depth + 1);
+ if (result) return result;
+ }
+
+ return null;
+}
+
+/**
+ * Find the element's start and end line in the file.
+ * The query is a class name, ID, or text snippet.
+ * We find the line containing the query, then find the matching closing tag.
+ */
+function findElement(lines, query) {
+ // Find the line containing the query
+ let startLine = -1;
+ for (let i = 0; i < lines.length; i++) {
+ if (lines[i].includes(query)) {
+ // Make sure this looks like a tag opening, not a comment or string
+ const line = lines[i].trim();
+ if (line.startsWith('<!--') || line.startsWith('{/*') || line.startsWith('//')) continue;
+ // Skip lines inside data-impeccable-variant containers (already wrapped)
+ if (lines[i].includes('data-impeccable-variant')) continue;
+ startLine = i;
+ break;
+ }
+ }
+
+ if (startLine === -1) return null;
+
+ // Find the end of this element by counting open/close tags
+ const endLine = findClosingLine(lines, startLine);
+ return { startLine, endLine };
+}
+
+/**
+ * Starting from a line with an opening tag, find the line with the matching
+ * closing tag by counting tag nesting depth.
+ */
+function findClosingLine(lines, start) {
+ // Extract the tag name from the opening line
+ const openMatch = lines[start].match(/<(\w+)[\s>]/);
+ if (!openMatch) return start; // self-closing or text-only line
+
+ const tagName = openMatch[1];
+ let depth = 0;
+
+ for (let i = start; i < lines.length; i++) {
+ const line = lines[i];
+ // Count opening tags (not self-closing)
+ const opens = (line.match(new RegExp('<' + tagName + '[\\s>]', 'g')) || []).length;
+ const selfCloses = (line.match(new RegExp('<' + tagName + '[^>]*/>', 'g')) || []).length;
+ const closes = (line.match(new RegExp('</' + tagName + '\\s*>', 'g')) || []).length;
+
+ depth += opens - selfCloses - closes;
+
+ if (depth <= 0) return i;
+ }
+
+ // If we can't find the close, return a reasonable guess
+ return Math.min(start + 50, lines.length - 1);
+}
diff --git a/.gemini/skills/impeccable/reference/live.md b/.gemini/skills/impeccable/reference/live.md
index 53b64a21a..ba0e9b0c5 100644
--- a/.gemini/skills/impeccable/reference/live.md
+++ b/.gemini/skills/impeccable/reference/live.md
@@ -10,7 +10,7 @@ Launch interactive live variant mode: select elements in the browser, pick a des
1. Read `.impeccable.md` if it exists. Keep the design context in mind for variant generation.
2. Start the live variant server:
```bash
- npx impeccable live &
+ node {{scripts_path}}/live-server.mjs &
```
3. Note the **port** and **token** printed to stdout.
@@ -53,7 +53,7 @@ Run a blocking poll loop. On each iteration, wait for a browser event and respon
```
LOOP:
- Run: npx impeccable poll
+ Run: node {{scripts_path}}/live-poll.mjs
Read the JSON output. Dispatch based on the "type" field:
TYPE "generate":
@@ -85,7 +85,7 @@ The event contains: `{id, action, freeformPrompt, count, pageUrl, element}`.
Use the `wrap` helper to find the element and create the variant container:
```bash
-npx impeccable wrap --id EVENT_ID --count EVENT_COUNT --element-id "ELEMENT_ID" --classes "class1,class2" --tag "div"
+node {{scripts_path}}/live-wrap.mjs --id EVENT_ID --count EVENT_COUNT --element-id "ELEMENT_ID" --classes "class1,class2" --tag "div"
```
Pass the element's id (`event.element.id`), classes (`event.element.classes` joined with commas), and tag name. The command searches in priority order: ID match first, then class names, then tag+class combo. If `event.pageUrl` hints at the file (e.g., `/` is usually `index.html`), pass `--file PATH` to skip the search.
@@ -136,10 +136,14 @@ The first variant should NOT have `style="display: none"` (it should be visible
### Step 3: Signal completion
+Include `--file` so the browser can fetch variants directly if the dev server lacks HMR:
+
```bash
-npx impeccable poll --reply EVENT_ID done
+node {{scripts_path}}/live-poll.mjs --reply EVENT_ID done --file RELATIVE_PATH
```
+The file path should be relative to the project root (e.g., `public/index.html`, `src/App.tsx`).
+
## Handle Accept
The event contains: `{id, variantId}`.
@@ -151,7 +155,7 @@ The user accepted a specific variant. For v1 (inspection mode):
4. Remove any scoped CSS blocks (between `impeccable-variants-css-start` and `impeccable-variants-css-end` markers).
5. Reply:
```bash
- npx impeccable poll --reply SESSION_ID done
+ node {{scripts_path}}/live-poll.mjs --reply SESSION_ID done
```
## Handle Discard
@@ -163,7 +167,7 @@ The event contains: `{id}`.
3. Remove any scoped CSS blocks for this session.
4. Reply:
```bash
- npx impeccable poll --reply SESSION_ID done
+ node {{scripts_path}}/live-poll.mjs --reply SESSION_ID done
```
## Cleanup (on exit)
@@ -174,7 +178,7 @@ When the loop ends:
2. **Remove any leftover variant wrappers** (search for `impeccable-variants-start` markers and clean up).
3. **Stop the server**:
```bash
- npx impeccable live stop
+ node {{scripts_path}}/live-server.mjs stop
```
## Variant Generation Guidelines
diff --git a/.gemini/skills/impeccable/scripts/live-browser.js b/.gemini/skills/impeccable/scripts/live-browser.js
new file mode 100644
index 000000000..7a26c9829
--- /dev/null
+++ b/.gemini/skills/impeccable/scripts/live-browser.js
@@ -0,0 +1,1220 @@
+/**
+ * Impeccable Live Variant Mode — Browser Script
+ *
+ * Injected into the user's page via <script src="http://localhost:PORT/live.js">.
+ * The server prepends window.__IMPECCABLE_TOKEN__ and window.__IMPECCABLE_PORT__
+ * before this code.
+ *
+ * UI: a single floating bar that morphs between three states —
+ * configure (pick action + go), generating (progressive dots), and cycling
+ * (prev/next + accept/discard). Feels like Spotlight, not a modal.
+ */
+(function () {
+ 'use strict';
+ if (typeof window === 'undefined') return;
+
+ // Guard against double-init. Bun's HTML loader may process the <script> tag
+ // and create a bundled copy alongside the external load, or HMR may re-execute.
+ // Check BEFORE reading token/port to catch all cases.
+ if (window.__IMPECCABLE_LIVE_INIT__) return;
+ window.__IMPECCABLE_LIVE_INIT__ = true;
+
+ const TOKEN = window.__IMPECCABLE_TOKEN__;
+ const PORT = window.__IMPECCABLE_PORT__;
+ if (!TOKEN || !PORT) {
+ window.__IMPECCABLE_LIVE_INIT__ = false; // reset so the real load can init
+ return;
+ }
+
+ // ---------------------------------------------------------------------------
+ // Design tokens
+ // ---------------------------------------------------------------------------
+
+ const C = {
+ brand: 'oklch(55% 0.25 350)',
+ brandHov: 'oklch(48% 0.25 350)',
+ brandSoft: 'oklch(55% 0.25 350 / 0.12)',
+ ink: 'oklch(15% 0.01 350)',
+ ash: 'oklch(55% 0 0)',
+ paper: 'oklch(98% 0.005 350 / 0.92)',
+ paperSolid:'oklch(98% 0.005 350)',
+ mist: 'oklch(90% 0.01 350 / 0.6)',
+ white: 'oklch(99% 0 0)',
+ };
+ const FONT = 'system-ui, -apple-system, sans-serif';
+ const MONO = 'ui-monospace, SFMono-Regular, Menlo, monospace';
+ const Z = { highlight: 99990, bar: 99995, picker: 99997, toast: 99999 };
+ const EASE = 'cubic-bezier(0.22, 1, 0.36, 1)'; // ease-out-quint
+ const PREFIX = 'impeccable-live';
+
+ const SKIP_TAGS = new Set([
+ 'html', 'head', 'body', 'script', 'style', 'link', 'meta', 'noscript', 'br', 'wbr',
+ ]);
+
+ const ACTIONS = [
+ { value: 'impeccable', label: 'Freeform' },
+ { value: 'bolder', label: 'Bolder' },
+ { value: 'quieter', label: 'Quieter' },
+ { value: 'distill', label: 'Distill' },
+ { value: 'polish', label: 'Polish' },
+ { value: 'typeset', label: 'Typeset' },
+ { value: 'colorize', label: 'Colorize' },
+ { value: 'layout', label: 'Layout' },
+ { value: 'adapt', label: 'Adapt' },
+ { value: 'animate', label: 'Animate' },
+ { value: 'delight', label: 'Delight' },
+ { value: 'overdrive', label: 'Overdrive' },
+ ];
+
+ // ---------------------------------------------------------------------------
+ // State
+ // ---------------------------------------------------------------------------
+
+ let state = 'IDLE';
+ let hoveredElement = null;
+ let selectedElement = null;
+ let currentSessionId = null;
+ let expectedVariants = 0;
+ let arrivedVariants = 0;
+ let visibleVariant = 0;
+ let variantObserver = null;
+ let hasProjectContext = false;
+ let selectedAction = 'impeccable';
+ let selectedCount = 3;
+
+ // UI refs
+ let highlightEl = null;
+ let tooltipEl = null;
+ let barEl = null;
+ let pickerEl = null;
+ let toastEl = null;
+ let scrollRaf = null;
+
+ // ---------------------------------------------------------------------------
+ // Helpers
+ // ---------------------------------------------------------------------------
+
+ function own(el) {
+ return el && (el.id?.startsWith(PREFIX) || el.closest?.('[id^="' + PREFIX + '"]'));
+ }
+
+ function pickable(el) {
+ if (!el || el.nodeType !== 1) return false;
+ if (SKIP_TAGS.has(el.tagName.toLowerCase())) return false;
+ if (own(el)) return false;
+ const r = el.getBoundingClientRect();
+ return r.width >= 20 && r.height >= 20;
+ }
+
+ function desc(el) {
+ if (!el) return '';
+ let s = el.tagName.toLowerCase();
+ if (el.id) s += '#' + el.id;
+ else if (el.classList.length) s += '.' + [...el.classList].slice(0, 2).join('.');
+ return s;
+ }
+
+ function id8() { return crypto.randomUUID().replace(/-/g, '').slice(0, 8); }
+
+ // ---------------------------------------------------------------------------
+ // Highlight overlay
+ // ---------------------------------------------------------------------------
+
+ function initHighlight() {
+ highlightEl = document.createElement('div');
+ highlightEl.id = PREFIX + '-highlight';
+ Object.assign(highlightEl.style, {
+ position: 'fixed', top: '0', left: '0', width: '0', height: '0',
+ border: '2px solid ' + C.brand, borderRadius: '3px',
+ pointerEvents: 'none', zIndex: Z.highlight, boxSizing: 'border-box',
+ transition: 'top 0.08s ease, left 0.08s ease, width 0.08s ease, height 0.08s ease, opacity 0.15s ease',
+ display: 'none', opacity: '0',
+ });
+ document.body.appendChild(highlightEl);
+
+ tooltipEl = document.createElement('div');
+ tooltipEl.id = PREFIX + '-tooltip';
+ Object.assign(tooltipEl.style, {
+ position: 'fixed',
+ background: C.ink, color: C.white,
+ fontFamily: MONO, fontSize: '10px', fontWeight: '500',
+ padding: '2px 6px', borderRadius: '3px',
+ zIndex: Z.highlight + 1, pointerEvents: 'none',
+ whiteSpace: 'nowrap', display: 'none',
+ letterSpacing: '0.02em',
+ });
+ document.body.appendChild(tooltipEl);
+ }
+
+ function showHighlight(el) {
+ if (!el || !highlightEl) return;
+ const r = el.getBoundingClientRect();
+ Object.assign(highlightEl.style, {
+ top: (r.top - 2) + 'px', left: (r.left - 2) + 'px',
+ width: (r.width + 4) + 'px', height: (r.height + 4) + 'px',
+ display: 'block', opacity: '1',
+ });
+ tooltipEl.textContent = desc(el);
+ const tipTop = r.top - 20;
+ Object.assign(tooltipEl.style, {
+ top: (tipTop < 4 ? r.bottom + 4 : tipTop) + 'px',
+ left: Math.max(4, r.left) + 'px', display: 'block',
+ });
+ }
+
+ function hideHighlight() {
+ if (highlightEl) { highlightEl.style.opacity = '0'; highlightEl.style.display = 'none'; }
+ if (tooltipEl) tooltipEl.style.display = 'none';
+ }
+
+ // ---------------------------------------------------------------------------
+ // Element context extraction
+ // ---------------------------------------------------------------------------
+
+ function extractContext(el) {
+ const cs = getComputedStyle(el);
+ const r = el.getBoundingClientRect();
+ const props = {};
+ for (const sheet of document.styleSheets) {
+ try {
+ for (const rule of sheet.cssRules) {
+ if (rule.style) for (let i = 0; i < rule.style.length; i++) {
+ const p = rule.style[i];
+ if (p.startsWith('--') && !props[p]) {
+ const v = cs.getPropertyValue(p).trim();
+ if (v) props[p] = v;
+ }
+ }
+ }
+ } catch { /* cross-origin */ }
+ }
+ return {
+ tagName: el.tagName.toLowerCase(), id: el.id || null,
+ classes: [...el.classList],
+ textContent: (el.textContent || '').slice(0, 500),
+ outerHTML: el.outerHTML.slice(0, 10000),
+ computedStyles: {
+ 'font-family': cs.fontFamily, 'font-size': cs.fontSize,
+ 'font-weight': cs.fontWeight, 'line-height': cs.lineHeight,
+ 'color': cs.color, 'background': cs.background,
+ 'background-color': cs.backgroundColor,
+ 'padding': cs.padding, 'margin': cs.margin,
+ 'display': cs.display, 'position': cs.position,
+ 'gap': cs.gap, 'border-radius': cs.borderRadius,
+ 'box-shadow': cs.boxShadow,
+ },
+ cssCustomProperties: props,
+ parentContext: el.parentElement
+ ? '<' + el.parentElement.tagName.toLowerCase()
+ + (el.parentElement.id ? ' id="' + el.parentElement.id + '"' : '')
+ + (el.parentElement.className ? ' class="' + el.parentElement.className + '"' : '')
+ + '>'
+ : null,
+ boundingRect: { width: Math.round(r.width), height: Math.round(r.height) },
+ };
+ }
+
+ // ---------------------------------------------------------------------------
+ // The Bar — one floating element, three modes
+ // ---------------------------------------------------------------------------
+
+ function initBar() {
+ barEl = document.createElement('div');
+ barEl.id = PREFIX + '-bar';
+ Object.assign(barEl.style, {
+ position: 'fixed', zIndex: Z.bar,
+ display: 'none', opacity: '0',
+ transform: 'translateY(6px)',
+ transition: 'opacity 0.25s ' + EASE + ', transform 0.3s ' + EASE,
+ // Visual
+ background: C.paper,
+ backdropFilter: 'blur(16px)', WebkitBackdropFilter: 'blur(16px)',
+ border: '1px solid ' + C.mist,
+ borderRadius: '10px',
+ boxShadow: '0 4px 20px oklch(0% 0 0 / 0.08), 0 1px 3px oklch(0% 0 0 / 0.06)',
+ fontFamily: FONT, fontSize: '13px', color: C.ink,
+ padding: '6px',
+ maxWidth: '460px', minWidth: '320px',
+ });
+ document.body.appendChild(barEl);
+ }
+
+ function positionBar() {
+ if (!barEl || !selectedElement) return;
+ const r = selectedElement.getBoundingClientRect();
+ const barH = barEl.offsetHeight || 44;
+ const barW = barEl.offsetWidth || 380;
+ let top = r.bottom + 8;
+ let left = r.left + (r.width - barW) / 2;
+ // Keep in viewport
+ if (top + barH + 8 > window.innerHeight) top = r.top - barH - 8;
+ if (top < 8) top = 8;
+ if (left < 8) left = 8;
+ if (left + barW > window.innerWidth - 8) left = window.innerWidth - barW - 8;
+ Object.assign(barEl.style, { top: top + 'px', left: left + 'px' });
+ }
+
+ function showBar(mode) {
+ barEl.innerHTML = '';
+ if (mode === 'configure') barEl.appendChild(buildConfigureRow());
+ else if (mode === 'generating') barEl.appendChild(buildGeneratingRow());
+ else if (mode === 'cycling') barEl.appendChild(buildCyclingRow());
+ barEl.style.display = 'block';
+ positionBar();
+ requestAnimationFrame(() => {
+ barEl.style.opacity = '1';
+ barEl.style.transform = 'translateY(0)';
+ });
+ }
+
+ function hideBar() {
+ if (!barEl) return;
+ barEl.style.opacity = '0';
+ barEl.style.transform = 'translateY(6px)';
+ setTimeout(() => { if (barEl) barEl.style.display = 'none'; }, 250);
+ hideActionPicker();
+ }
+
+ function updateBarContent(mode) {
+ if (!barEl || barEl.style.display === 'none') return;
+ barEl.innerHTML = '';
+ // Reset bar styling
+ barEl.style.background = C.paper;
+ barEl.style.border = '1px solid ' + C.mist;
+ if (mode === 'configure') barEl.appendChild(buildConfigureRow());
+ else if (mode === 'generating') barEl.appendChild(buildGeneratingRow());
+ else if (mode === 'cycling') barEl.appendChild(buildCyclingRow());
+ else if (mode === 'saving') barEl.appendChild(buildSavingRow());
+ else if (mode === 'confirmed') {
+ barEl.appendChild(buildConfirmedRow());
+ barEl.style.background = 'oklch(95% 0.05 145)';
+ barEl.style.border = '1px solid oklch(75% 0.12 145 / 0.4)';
+ }
+ }
+
+ // --- Configure row ---
+
+ function buildConfigureRow() {
+ const row = el('div', {
+ display: 'flex', alignItems: 'center', gap: '4px',
+ });
+
+ // Action pill
+ const pill = el('button', {
+ display: 'inline-flex', alignItems: 'center', gap: '4px',
+ padding: '5px 10px', borderRadius: '6px',
+ background: C.ink, color: C.white,
+ fontFamily: FONT, fontSize: '12px', fontWeight: '500',
+ border: 'none', cursor: 'pointer',
+ transition: 'background 0.12s ease, transform 0.1s ease',
+ whiteSpace: 'nowrap', flexShrink: '0',
+ });
+ pill.textContent = actionLabel() + ' \u25BE';
+ pill.addEventListener('mouseenter', () => pill.style.background = C.brandHov);
+ pill.addEventListener('mouseleave', () => pill.style.background = C.ink);
+ pill.addEventListener('mousedown', () => pill.style.transform = 'scale(0.97)');
+ pill.addEventListener('mouseup', () => pill.style.transform = 'scale(1)');
+ pill.addEventListener('click', (e) => { e.stopPropagation(); toggleActionPicker(); });
+ row.appendChild(pill);
+
+ // Freeform input
+ const input = document.createElement('input');
+ input.id = PREFIX + '-input';
+ input.type = 'text';
+ input.placeholder = selectedAction === 'impeccable' ? 'describe what you want...' : 'refine further (optional)...';
+ Object.assign(input.style, {
+ flex: '1', minWidth: '0',
+ padding: '5px 8px', borderRadius: '6px',
+ border: '1px solid transparent', background: 'transparent',
+ fontFamily: FONT, fontSize: '12px', color: C.ink,
+ outline: 'none',
+ transition: 'border-color 0.15s ease, background 0.15s ease',
+ });
+ input.addEventListener('focus', () => {
+ input.style.borderColor = C.mist;
+ input.style.background = C.white;
+ });
+ input.addEventListener('blur', () => {
+ input.style.borderColor = 'transparent';
+ input.style.background = 'transparent';
+ });
+ input.addEventListener('keydown', (e) => {
+ e.stopPropagation(); // Don't trigger element picker keyboard nav
+ if (e.key === 'Enter') { e.preventDefault(); handleGo(); }
+ if (e.key === 'Escape') { e.preventDefault(); input.blur(); hideBar(); state = 'PICKING'; }
+ });
+ row.appendChild(input);
+
+ // Variant count toggle
+ const count = el('button', {
+ padding: '4px 6px', borderRadius: '5px',
+ border: '1px solid ' + C.mist, background: 'transparent',
+ fontFamily: MONO, fontSize: '11px', fontWeight: '600',
+ color: C.ash, cursor: 'pointer',
+ transition: 'color 0.12s ease, border-color 0.12s ease',
+ flexShrink: '0', whiteSpace: 'nowrap',
+ });
+ count.textContent = '\u00D7' + selectedCount;
+ count.title = 'Variants: click to change';
+ count.addEventListener('mouseenter', () => { count.style.color = C.ink; count.style.borderColor = C.ink; });
+ count.addEventListener('mouseleave', () => { count.style.color = C.ash; count.style.borderColor = C.mist; });
+ count.addEventListener('click', (e) => {
+ e.stopPropagation();
+ selectedCount = selectedCount >= 4 ? 2 : selectedCount + 1;
+ count.textContent = '\u00D7' + selectedCount;
+ });
+ row.appendChild(count);
+
+ // Go button
+ const go = el('button', {
+ padding: '5px 12px', borderRadius: '6px',
+ border: 'none', background: C.brand, color: C.white,
+ fontFamily: FONT, fontSize: '12px', fontWeight: '600',
+ cursor: 'pointer',
+ transition: 'background 0.12s ease, transform 0.1s ease',
+ flexShrink: '0', whiteSpace: 'nowrap',
+ });
+ go.textContent = 'Go \u2192';
+ go.addEventListener('mouseenter', () => go.style.background = C.brandHov);
+ go.addEventListener('mouseleave', () => go.style.background = C.brand);
+ go.addEventListener('mousedown', () => go.style.transform = 'scale(0.97)');
+ go.addEventListener('mouseup', () => go.style.transform = 'scale(1)');
+ go.addEventListener('click', (e) => { e.stopPropagation(); handleGo(); });
+ row.appendChild(go);
+
+ // Auto-focus input after a beat
+ setTimeout(() => input.focus(), 60);
+ return row;
+ }
+
+ // --- Generating row ---
+
+ function buildGeneratingRow() {
+ const row = el('div', {
+ display: 'flex', alignItems: 'center', gap: '8px',
+ padding: '2px 4px',
+ });
+
+ // Action label
+ const label = el('span', {
+ fontWeight: '600', fontSize: '12px', color: C.ink,
+ flexShrink: '0', whiteSpace: 'nowrap',
+ });
+ label.textContent = actionLabel();
+ row.appendChild(label);
+
+ // Dots
+ row.appendChild(buildDots(false));
+
+ // Status
+ const status = el('span', {
+ fontSize: '11px', color: C.ash, whiteSpace: 'nowrap',
+ marginLeft: 'auto',
+ });
+ status.textContent = arrivedVariants < expectedVariants
+ ? 'Generating ' + (arrivedVariants + 1) + ' of ' + expectedVariants + '...'
+ : 'Done';
+ row.appendChild(status);
+
+ return row;
+ }
+
+ // --- Cycling row ---
+
+ function buildCyclingRow() {
+ const row = el('div', {
+ display: 'flex', alignItems: 'center', gap: '6px',
+ padding: '1px 2px',
+ });
+
+ // Prev
+ const prev = navBtn('\u2190');
+ prev.addEventListener('click', (e) => { e.stopPropagation(); cycleVariant(-1); });
+ if (visibleVariant <= 1) prev.style.opacity = '0.3';
+ row.appendChild(prev);
+
+ // Dots (clickable)
+ row.appendChild(buildDots(true));
+
+ // Counter
+ const counter = el('span', {
+ fontFamily: MONO, fontSize: '11px', fontWeight: '500',
+ color: C.ash, minWidth: '24px', textAlign: 'center',
+ });
+ counter.textContent = visibleVariant + '/' + arrivedVariants;
+ row.appendChild(counter);
+
+ // Next
+ const next = navBtn('\u2192');
+ next.addEventListener('click', (e) => { e.stopPropagation(); cycleVariant(1); });
+ if (visibleVariant >= arrivedVariants) next.style.opacity = '0.3';
+ row.appendChild(next);
+
+ // Spacer
+ row.appendChild(el('div', { flex: '1' }));
+
+ // Accept
+ const accept = el('button', {
+ padding: '4px 10px', borderRadius: '5px',
+ border: 'none', background: C.ink, color: C.white,
+ fontFamily: FONT, fontSize: '11px', fontWeight: '600',
+ cursor: 'pointer', transition: 'background 0.12s ease',
+ whiteSpace: 'nowrap',
+ });
+ accept.textContent = '\u2713 Accept';
+ accept.addEventListener('mouseenter', () => accept.style.background = C.brand);
+ accept.addEventListener('mouseleave', () => accept.style.background = C.ink);
+ accept.addEventListener('click', (e) => { e.stopPropagation(); handleAccept(); });
+ if (arrivedVariants === 0) { accept.style.opacity = '0.3'; accept.style.pointerEvents = 'none'; }
+ row.appendChild(accept);
+
+ // Discard
+ const discard = el('button', {
+ padding: '4px 6px', borderRadius: '5px',
+ border: '1px solid ' + C.mist, background: 'transparent',
+ fontFamily: FONT, fontSize: '11px', color: C.ash,
+ cursor: 'pointer', transition: 'color 0.12s ease, border-color 0.12s ease',
+ });
+ discard.textContent = '\u2715';
+ discard.title = 'Discard all variants';
+ discard.addEventListener('mouseenter', () => { discard.style.color = C.ink; discard.style.borderColor = C.ink; });
+ discard.addEventListener('mouseleave', () => { discard.style.color = C.ash; discard.style.borderColor = C.mist; });
+ discard.addEventListener('click', (e) => { e.stopPropagation(); handleDiscard(); });
+ row.appendChild(discard);
+
+ return row;
+ }
+
+ // --- Shared UI builders ---
+
+ // --- Saving row (waiting for agent to process accept/discard) ---
+
+ function buildSavingRow() {
+ const row = el('div', {
+ display: 'flex', alignItems: 'center', gap: '8px',
+ padding: '2px 8px',
+ });
+ const spinner = el('div', {
+ width: '14px', height: '14px', borderRadius: '50%',
+ border: '2px solid ' + C.mist,
+ borderTopColor: C.brand,
+ animation: 'impeccable-spin 0.6s linear infinite',
+ flexShrink: '0',
+ });
+ row.appendChild(spinner);
+ const label = el('span', {
+ fontSize: '12px', color: C.ash, fontWeight: '500',
+ });
+ label.textContent = 'Applying variant...';
+ row.appendChild(label);
+
+ // Inject the keyframes if not already present
+ if (!document.getElementById(PREFIX + '-keyframes')) {
+ const style = document.createElement('style');
+ style.id = PREFIX + '-keyframes';
+ style.textContent = '@keyframes impeccable-spin { to { transform: rotate(360deg); } }';
+ document.head.appendChild(style);
+ }
+ return row;
+ }
+
+ // --- Confirmed row (green success, auto-dismisses) ---
+
+ function buildConfirmedRow() {
+ const row = el('div', {
+ display: 'flex', alignItems: 'center', gap: '8px',
+ padding: '2px 8px',
+ });
+ const check = el('span', {
+ fontSize: '15px', lineHeight: '1', flexShrink: '0',
+ color: 'oklch(45% 0.15 145)',
+ });
+ check.textContent = '\u2713';
+ row.appendChild(check);
+ const label = el('span', {
+ fontSize: '12px', color: 'oklch(35% 0.1 145)', fontWeight: '600',
+ });
+ label.textContent = 'Variant applied';
+ row.appendChild(label);
+ return row;
+ }
+
+ // --- Shared UI builders ---
+
+ function buildDots(clickable) {
+ const container = el('div', {
+ display: 'flex', alignItems: 'center', gap: '4px',
+ });
+ for (let i = 1; i <= expectedVariants; i++) {
+ const arrived = i <= arrivedVariants;
+ const active = i === visibleVariant;
+ const dot = el('div', {
+ width: '7px', height: '7px', borderRadius: '50%',
+ background: active ? C.brand : (arrived ? C.ash : 'transparent'),
+ border: '1.5px solid ' + (arrived ? C.brand : C.mist),
+ transition: 'all 0.2s ' + EASE,
+ cursor: (clickable && arrived) ? 'pointer' : 'default',
+ transform: arrived ? 'scale(1)' : 'scale(0.6)',
+ opacity: arrived ? '1' : '0.4',
+ });
+ if (clickable && arrived) {
+ const idx = i;
+ dot.addEventListener('click', (e) => {
+ e.stopPropagation();
+ visibleVariant = idx;
+ showVariantInDOM(currentSessionId, idx);
+ updateSelectedElement();
+ updateBarContent('cycling');
+ });
+ }
+ container.appendChild(dot);
+ }
+ return container;
+ }
+
+ function navBtn(text) {
+ const b = el('button', {
+ width: '26px', height: '26px', borderRadius: '5px',
+ border: '1px solid ' + C.mist, background: 'transparent',
+ color: C.ink, fontFamily: FONT, fontSize: '13px',
+ cursor: 'pointer', display: 'flex', alignItems: 'center', justifyContent: 'center',
+ transition: 'border-color 0.12s ease, background 0.12s ease',
+ padding: '0', lineHeight: '1',
+ });
+ b.textContent = text;
+ b.addEventListener('mouseenter', () => { b.style.borderColor = C.ink; });
+ b.addEventListener('mouseleave', () => { b.style.borderColor = C.mist; });
+ return b;
+ }
+
+ function actionLabel() {
+ const a = ACTIONS.find(a => a.value === selectedAction);
+ return a ? a.label : 'Freeform';
+ }
+
+ function el(tag, styles) {
+ const e = document.createElement(tag);
+ if (styles) Object.assign(e.style, styles);
+ return e;
+ }
+
+ // ---------------------------------------------------------------------------
+ // Action picker popover
+ // ---------------------------------------------------------------------------
+
+ function initActionPicker() {
+ pickerEl = document.createElement('div');
+ pickerEl.id = PREFIX + '-picker';
+ Object.assign(pickerEl.style, {
+ position: 'fixed', zIndex: Z.picker,
+ display: 'none', opacity: '0',
+ transform: 'scale(0.96) translateY(4px)',
+ transformOrigin: 'bottom left',
+ transition: 'opacity 0.18s ' + EASE + ', transform 0.2s ' + EASE,
+ background: C.paperSolid,
+ border: '1px solid ' + C.mist,
+ borderRadius: '10px',
+ boxShadow: '0 8px 30px oklch(0% 0 0 / 0.10), 0 2px 6px oklch(0% 0 0 / 0.06)',
+ padding: '6px',
+ fontFamily: FONT,
+ });
+
+ // Build the chip grid
+ const grid = el('div', {
+ display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', gap: '3px',
+ });
+
+ ACTIONS.forEach(action => {
+ const chip = el('button', {
+ padding: '6px 8px', borderRadius: '6px',
+ border: 'none',
+ background: action.value === selectedAction ? C.brandSoft : 'transparent',
+ color: action.value === selectedAction ? C.brand : C.ink,
+ fontFamily: FONT, fontSize: '11px', fontWeight: '500',
+ cursor: 'pointer',
+ transition: 'background 0.1s ease, color 0.1s ease',
+ textAlign: 'center', whiteSpace: 'nowrap',
+ });
+ chip.textContent = action.label;
+ chip.dataset.action = action.value;
+ chip.addEventListener('mouseenter', () => {
+ if (action.value !== selectedAction) chip.style.background = C.brandSoft;
+ });
+ chip.addEventListener('mouseleave', () => {
+ chip.style.background = action.value === selectedAction ? C.brandSoft : 'transparent';
+ });
+ chip.addEventListener('click', (e) => {
+ e.stopPropagation();
+ selectedAction = action.value;
+ hideActionPicker();
+ updateBarContent('configure');
+ });
+ grid.appendChild(chip);
+ });
+
+ pickerEl.appendChild(grid);
+ document.body.appendChild(pickerEl);
+ }
+
+ function toggleActionPicker() {
+ if (pickerEl.style.display !== 'none') { hideActionPicker(); return; }
+ // Rebuild chips to reflect current selection
+ pickerEl.querySelectorAll('button').forEach(chip => {
+ const isActive = chip.dataset.action === selectedAction;
+ chip.style.background = isActive ? C.brandSoft : 'transparent';
+ chip.style.color = isActive ? C.brand : C.ink;
+ });
+ // Position above the bar
+ const barRect = barEl.getBoundingClientRect();
+ const pickerH = 90; // approximate
+ let top = barRect.top - pickerH - 6;
+ if (top < 8) top = barRect.bottom + 6;
+ Object.assign(pickerEl.style, {
+ top: top + 'px', left: barRect.left + 'px',
+ display: 'block',
+ });
+ requestAnimationFrame(() => {
+ pickerEl.style.opacity = '1';
+ pickerEl.style.transform = 'scale(1) translateY(0)';
+ });
+ }
+
+ function hideActionPicker() {
+ if (!pickerEl) return;
+ pickerEl.style.opacity = '0';
+ pickerEl.style.transform = 'scale(0.96) translateY(4px)';
+ setTimeout(() => { if (pickerEl) pickerEl.style.display = 'none'; }, 180);
+ }
+
+ // ---------------------------------------------------------------------------
+ // Variant cycling in DOM
+ // ---------------------------------------------------------------------------
+
+ function showVariantInDOM(sessionId, num) {
+ const wrapper = document.querySelector('[data-impeccable-variants="' + sessionId + '"]');
+ if (!wrapper) return;
+ for (const child of wrapper.children) {
+ const v = child.dataset ? child.dataset.impeccableVariant : null;
+ if (!v) continue;
+ child.style.display = (v === String(num)) ? '' : 'none';
+ }
+ }
+
+ /**
+ * No-HMR fallback: fetch the raw source file from the live server,
+ * parse it, extract the variant wrapper, and inject it into the live DOM.
+ * This works even when the dev server caches HTML (Bun, static servers).
+ */
+ function injectVariantsFromSource(filePath, sessionId) {
+ const url = 'http://localhost:' + PORT + '/source?token=' + TOKEN + '&path=' + encodeURIComponent(filePath);
+ fetch(url)
+ .then(r => { if (!r.ok) throw new Error(r.status); return r.text(); })
+ .then(html => {
+ // Parse the raw source HTML
+ const parser = new DOMParser();
+ const doc = parser.parseFromString(html, 'text/html');
+ const srcWrapper = doc.querySelector('[data-impeccable-variants="' + sessionId + '"]');
+ if (!srcWrapper) {
+ console.error('[impeccable] Variant wrapper not found in source file.');
+ return;
+ }
+
+ // Find the original element in the live DOM.
+ // The original is inside the wrapper in the source. We find the
+ // corresponding element in the live DOM by matching the first child's
+ // tag + classes from the original snapshot.
+ const origContent = srcWrapper.querySelector('[data-impeccable-variant="original"] > :first-child');
+ if (!origContent) return;
+
+ const tag = origContent.tagName.toLowerCase();
+ const cls = origContent.className;
+ let liveEl = null;
+ if (origContent.id) {
+ liveEl = document.getElementById(origContent.id);
+ } else if (cls) {
+ // Find by tag + exact class match
+ const candidates = document.querySelectorAll(tag + '.' + cls.split(' ')[0]);
+ for (const c of candidates) {
+ if (c.className === cls && !own(c)) { liveEl = c; break; }
+ }
+ }
+
+ if (!liveEl) {
+ console.error('[impeccable] Could not find original element in live DOM.');
+ return;
+ }
+
+ // Replace the live element with the full wrapper from source
+ const wrapper = srcWrapper.cloneNode(true);
+ liveEl.parentElement.replaceChild(wrapper, liveEl);
+
+ // Update state: count variants, show the first one
+ 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);
+
+ // Update selectedElement to the visible variant's content
+ const visEl = wrapper.querySelector('[data-impeccable-variant="1"] > :first-child');
+ selectedElement = visEl || wrapper.parentElement;
+
+ state = 'CYCLING';
+ updateBarContent('cycling');
+ saveSession();
+ console.log('[impeccable] Injected ' + arrivedVariants + ' variants from source file.');
+ })
+ .catch(err => {
+ console.error('[impeccable] Failed to fetch source:', err);
+ showToast('Could not load variants. Try refreshing the page.', 5000);
+ });
+ }
+
+ function cycleVariant(dir) {
+ const next = visibleVariant + dir;
+ if (next < 1 || next > arrivedVariants) return;
+ visibleVariant = next;
+ showVariantInDOM(currentSessionId, next);
+ updateSelectedElement();
+ updateBarContent('cycling');
+ saveSession();
+ }
+
+ function updateSelectedElement() {
+ if (!currentSessionId) return;
+ const wrapper = document.querySelector('[data-impeccable-variants="' + currentSessionId + '"]');
+ if (!wrapper) return;
+ const visEl = wrapper.querySelector('[data-impeccable-variant="' + visibleVariant + '"] > :first-child');
+ if (visEl) selectedElement = visEl;
+ }
+
+ // ---------------------------------------------------------------------------
+ // MutationObserver for progressive variant reveal
+ // ---------------------------------------------------------------------------
+
+ function startVariantObserver(sessionId) {
+ let updating = false; // re-entrancy guard
+
+ const obs = new MutationObserver((mutations) => {
+ if (updating) return;
+
+ // Only react to mutations that add nodes with data-impeccable-variant,
+ // or mutations inside the variant wrapper. Ignore our own bar/UI changes.
+ let dominated = false;
+ for (const m of mutations) {
+ if (m.target.closest?.('[data-impeccable-variants]')) { dominated = true; break; }
+ for (const n of m.addedNodes) {
+ if (n.nodeType === 1 && (n.dataset?.impeccableVariants || n.dataset?.impeccableVariant)) {
+ dominated = true; break;
+ }
+ }
+ if (dominated) break;
+ }
+ if (!dominated) return;
+
+ const wrapper = document.querySelector('[data-impeccable-variants="' + sessionId + '"]');
+ if (!wrapper) return;
+
+ const variants = wrapper.querySelectorAll('[data-impeccable-variant]:not([data-impeccable-variant="original"])');
+ const count = variants.length;
+
+ // Nothing new
+ if (count <= arrivedVariants) return;
+
+ updating = true;
+ arrivedVariants = count;
+ if (visibleVariant === 0 && arrivedVariants > 0) {
+ visibleVariant = 1;
+ showVariantInDOM(sessionId, 1);
+ }
+
+ const expected = parseInt(wrapper.dataset.impeccableVariantCount || '0');
+ if (expected > 0) expectedVariants = expected;
+
+ if (arrivedVariants >= expectedVariants && expectedVariants > 0) {
+ state = 'CYCLING';
+ updateBarContent('cycling');
+ } else if (state === 'GENERATING') {
+ updateBarContent('generating');
+ }
+ saveSession();
+ updating = false;
+ });
+
+ obs.observe(document.body, { childList: true, subtree: true });
+ return obs;
+ }
+
+ // ---------------------------------------------------------------------------
+ // Bar scroll tracking
+ // ---------------------------------------------------------------------------
+
+ function startScrollTracking() {
+ function tick() {
+ if (state === 'CONFIGURING' || state === 'GENERATING' || state === 'CYCLING') {
+ positionBar();
+ showHighlight(selectedElement);
+ }
+ scrollRaf = requestAnimationFrame(tick);
+ }
+ scrollRaf = requestAnimationFrame(tick);
+ }
+
+ function stopScrollTracking() {
+ if (scrollRaf) { cancelAnimationFrame(scrollRaf); scrollRaf = null; }
+ }
+
+ // ---------------------------------------------------------------------------
+ // SSE (server→browser) + fetch POST (browser→server)
+ // Zero-dependency replacement for WebSocket.
+ // ---------------------------------------------------------------------------
+
+ let evtSource = null;
+
+ function connectSSE() {
+ evtSource = new EventSource('http://localhost:' + PORT + '/events?token=' + TOKEN);
+
+ evtSource.onmessage = (e) => {
+ let msg; try { msg = JSON.parse(e.data); } catch { return; }
+ switch (msg.type) {
+ case 'connected':
+ hasProjectContext = !!msg.hasProjectContext;
+ if (!hasProjectContext) showToast('No .impeccable.md found. Variants will be brand-agnostic.', 6000);
+ console.log('[impeccable] Live mode connected.');
+ if (state === 'IDLE') state = 'PICKING';
+ break;
+ case 'done':
+ if (state === 'SAVING') {
+ state = 'CONFIRMED';
+ updateBarContent('confirmed');
+ setTimeout(() => {
+ hideBar();
+ hideHighlight();
+ stopScrollTracking();
+ if (variantObserver) { variantObserver.disconnect(); variantObserver = null; }
+ clearSession();
+ selectedElement = null;
+ currentSessionId = null;
+ selectedAction = 'impeccable';
+ state = 'PICKING';
+ }, 1800);
+ return;
+ }
+ if (arrivedVariants === 0 && expectedVariants > 0 && msg.file) {
+ console.log('[impeccable] No HMR detected. Fetching variants from source file...');
+ injectVariantsFromSource(msg.file, currentSessionId);
+ return;
+ }
+ state = 'CYCLING';
+ updateBarContent('cycling');
+ break;
+ case 'error':
+ console.error('[impeccable] Error:', msg.message);
+ showToast('Error: ' + msg.message, 5000);
+ hideBar();
+ state = 'PICKING';
+ break;
+ }
+ };
+
+ evtSource.onerror = () => {
+ // EventSource auto-reconnects. Log once.
+ console.log('[impeccable] SSE connection lost. Reconnecting...');
+ };
+ }
+
+ function sendEvent(msg) {
+ msg.token = TOKEN;
+ 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));
+ }
+
+ // ---------------------------------------------------------------------------
+ // Event handlers
+ // ---------------------------------------------------------------------------
+
+ function handleMouseMove(e) {
+ if (state !== 'PICKING') return;
+ const target = document.elementFromPoint(e.clientX, e.clientY);
+ if (!target || !pickable(target) || target === hoveredElement) return;
+ hoveredElement = target;
+ showHighlight(target);
+ }
+
+ function handleClick(e) {
+ // Close action picker on any outside click
+ if (pickerEl?.style.display !== 'none' && !own(e.target)) {
+ hideActionPicker();
+ }
+ if (state !== 'PICKING') return;
+ if (own(e.target)) return;
+ if (!hoveredElement || !pickable(hoveredElement)) return;
+ e.preventDefault();
+ e.stopPropagation();
+ selectedElement = hoveredElement;
+ state = 'CONFIGURING';
+ showHighlight(selectedElement);
+ showBar('configure');
+ startScrollTracking();
+ }
+
+ function handleKeyDown(e) {
+ if (e.key === 'Escape') {
+ e.preventDefault();
+ if (pickerEl?.style.display !== 'none') { hideActionPicker(); return; }
+ if (state === 'CONFIGURING') { hideBar(); stopScrollTracking(); state = 'PICKING'; return; }
+ if (state === 'CYCLING') { handleDiscard(); return; }
+ if (state === 'SAVING' || state === 'CONFIRMED') return; // don't interrupt
+ if (state === 'PICKING') { hideHighlight(); state = 'IDLE'; return; }
+ }
+
+ if (state === 'PICKING' && hoveredElement) {
+ let next = null;
+ if (e.key === 'ArrowDown' && !e.shiftKey) {
+ next = hoveredElement.nextElementSibling;
+ while (next && !pickable(next)) next = next.nextElementSibling;
+ } else if (e.key === 'ArrowUp' && !e.shiftKey) {
+ next = hoveredElement.previousElementSibling;
+ while (next && !pickable(next)) next = next.previousElementSibling;
+ } else if (e.key === 'ArrowUp' && e.shiftKey) {
+ next = hoveredElement.parentElement;
+ if (next && !pickable(next)) next = null;
+ } else if (e.key === 'ArrowDown' && e.shiftKey) {
+ next = hoveredElement.firstElementChild;
+ while (next && !pickable(next)) next = next.nextElementSibling;
+ } else if (e.key === 'Enter') {
+ e.preventDefault();
+ selectedElement = hoveredElement;
+ state = 'CONFIGURING';
+ showHighlight(selectedElement);
+ showBar('configure');
+ startScrollTracking();
+ return;
+ }
+ if (next) {
+ e.preventDefault();
+ hoveredElement = next;
+ showHighlight(next);
+ next.scrollIntoView({ block: 'nearest', behavior: 'smooth' });
+ }
+ return;
+ }
+
+ if (state === 'CYCLING') {
+ if (e.key === 'ArrowLeft') { e.preventDefault(); cycleVariant(-1); }
+ if (e.key === 'ArrowRight') { e.preventDefault(); cycleVariant(1); }
+ if (e.key === 'Enter') { e.preventDefault(); handleAccept(); }
+ }
+ }
+
+ function handleGo() {
+ if (!selectedElement || state !== 'CONFIGURING') return;
+ const input = document.getElementById(PREFIX + '-input');
+ const prompt = input ? input.value.trim() : '';
+
+ currentSessionId = id8();
+ expectedVariants = selectedCount;
+ arrivedVariants = 0;
+ visibleVariant = 0;
+
+ sendEvent({
+ type: 'generate', id: currentSessionId,
+ action: selectedAction,
+ freeformPrompt: prompt || undefined,
+ count: selectedCount,
+ pageUrl: location.pathname,
+ element: extractContext(selectedElement),
+ });
+
+ state = 'GENERATING';
+ showBar('generating');
+ saveSession();
+ if (variantObserver) variantObserver.disconnect();
+ variantObserver = startVariantObserver(currentSessionId);
+ }
+
+ function handleAccept() {
+ if (!currentSessionId || arrivedVariants === 0) return;
+ sendEvent({ type: 'accept', id: currentSessionId, variantId: String(visibleVariant) });
+ markSessionHandled();
+ state = 'SAVING';
+ updateBarContent('saving');
+ // Don't cleanup yet — wait for the "done" WS message to show confirmation
+ }
+
+ function handleDiscard() {
+ if (!currentSessionId) return;
+ sendEvent({ type: 'discard', id: currentSessionId });
+ markSessionHandled();
+ state = 'SAVING';
+ updateBarContent('saving');
+ // Wait for "done" WS message to show confirmation and dismiss
+ }
+
+ // ---------------------------------------------------------------------------
+ // Session persistence via localStorage
+ // ---------------------------------------------------------------------------
+ // Survives page reloads, browser close/reopen, HMR, and accidental refreshes.
+
+ const LS_KEY = PREFIX + '-session';
+
+ function saveSession() {
+ if (!currentSessionId) return;
+ 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 */ }
+ }
+
+ function loadSession() {
+ try {
+ const raw = localStorage.getItem(LS_KEY);
+ return raw ? JSON.parse(raw) : null;
+ } catch { return null; }
+ }
+
+ function clearSession() {
+ try { localStorage.removeItem(LS_KEY); } catch {}
+ }
+
+ /** Mark session as handled (accepted/discarded). The agent will clean up
+ * the source, but until it does the wrapper is still in the HTML. This
+ * prevents resumeSession from picking it up again after reload. */
+ function markSessionHandled() {
+ if (!currentSessionId) return;
+ try {
+ localStorage.setItem(LS_KEY + '-handled', currentSessionId);
+ } catch {}
+ }
+
+ function isSessionHandled(id) {
+ try {
+ return localStorage.getItem(LS_KEY + '-handled') === id;
+ } catch { return false; }
+ }
+
+ function clearHandled() {
+ try { localStorage.removeItem(LS_KEY + '-handled'); } catch {}
+ }
+
+ function cleanup() {
+ hideBar();
+ hideHighlight();
+ stopScrollTracking();
+ if (variantObserver) { variantObserver.disconnect(); variantObserver = null; }
+ clearSession();
+ selectedElement = null;
+ currentSessionId = null;
+ selectedAction = 'impeccable';
+ state = 'PICKING';
+ }
+
+ // ---------------------------------------------------------------------------
+ // Toast
+ // ---------------------------------------------------------------------------
+
+ function showToast(message, duration) {
+ if (toastEl) toastEl.remove();
+ toastEl = el('div', {
+ position: 'fixed', bottom: '16px', left: '50%',
+ transform: 'translateX(-50%) translateY(8px)',
+ background: C.ink, color: C.white,
+ fontFamily: FONT, fontSize: '12px',
+ padding: '8px 16px', borderRadius: '8px',
+ zIndex: Z.toast, opacity: '0',
+ transition: 'opacity 0.25s ' + EASE + ', transform 0.25s ' + EASE,
+ pointerEvents: 'none', maxWidth: '420px', textAlign: 'center',
+ });
+ toastEl.id = PREFIX + '-toast';
+ toastEl.textContent = message;
+ document.body.appendChild(toastEl);
+ requestAnimationFrame(() => {
+ toastEl.style.opacity = '1';
+ toastEl.style.transform = 'translateX(-50%) translateY(0)';
+ });
+ setTimeout(() => {
+ if (toastEl) {
+ toastEl.style.opacity = '0';
+ toastEl.style.transform = 'translateX(-50%) translateY(8px)';
+ setTimeout(() => { if (toastEl) { toastEl.remove(); toastEl = null; } }, 250);
+ }
+ }, duration);
+ }
+
+ // ---------------------------------------------------------------------------
+ // Init
+ // ---------------------------------------------------------------------------
+
+ // Resume an active variant session after HMR/page reload.
+ // If a [data-impeccable-variants] wrapper exists in the DOM, the agent wrote
+ // variants before HMR fired. Pick up where we left off.
+ function resumeSession() {
+ const wrapper = document.querySelector('[data-impeccable-variants]');
+ if (!wrapper) { clearSession(); clearHandled(); return false; }
+
+ const sessionId = wrapper.dataset.impeccableVariants;
+
+ // Don't resume if this session was already accepted/discarded
+ if (isSessionHandled(sessionId)) return false;
+
+ currentSessionId = sessionId;
+ expectedVariants = parseInt(wrapper.dataset.impeccableVariantCount || '0');
+ const variants = wrapper.querySelectorAll('[data-impeccable-variant]:not([data-impeccable-variant="original"])');
+ arrivedVariants = variants.length;
+
+ // Restore visible variant from localStorage if available, else default to 1
+ const saved = loadSession();
+ visibleVariant = (saved && saved.id === sessionId && saved.visible > 0 && saved.visible <= arrivedVariants)
+ ? saved.visible : (arrivedVariants > 0 ? 1 : 0);
+
+ // Find the visible variant's content element for highlight positioning
+ const visEl = wrapper.querySelector('[data-impeccable-variant="' + visibleVariant + '"] > :first-child');
+ selectedElement = visEl || wrapper.parentElement;
+
+ // Set display state BEFORE starting observer (avoid triggering it)
+ if (visibleVariant > 0) showVariantInDOM(currentSessionId, visibleVariant);
+
+ state = arrivedVariants >= expectedVariants ? 'CYCLING' : 'GENERATING';
+ showBar(state === 'CYCLING' ? 'cycling' : 'generating');
+ startScrollTracking();
+ saveSession();
+
+ // Start observing for more variants AFTER initial setup
+ if (variantObserver) variantObserver.disconnect();
+ variantObserver = startVariantObserver(currentSessionId);
+ return true;
+ }
+
+ function init() {
+ initHighlight();
+ initBar();
+ initActionPicker();
+ document.addEventListener('mousemove', handleMouseMove, true);
+ document.addEventListener('click', handleClick, true);
+ document.addEventListener('keydown', handleKeyDown, true);
+ connectSSE();
+
+ // Check for an active session to resume (variant wrapper already in DOM after HMR)
+ if (!resumeSession()) {
+ console.log('[impeccable] Live variant mode ready. Hover over elements to pick one.');
+ } else {
+ console.log('[impeccable] Resumed active variant session ' + currentSessionId + ' (' + arrivedVariants + '/' + expectedVariants + ' variants).');
+ }
+ }
+
+ if (document.readyState === 'loading') {
+ document.addEventListener('DOMContentLoaded', init);
+ } else {
+ init();
+ }
+})();
diff --git a/.gemini/skills/impeccable/scripts/live-poll.mjs b/.gemini/skills/impeccable/scripts/live-poll.mjs
new file mode 100644
index 000000000..52859416c
--- /dev/null
+++ b/.gemini/skills/impeccable/scripts/live-poll.mjs
@@ -0,0 +1,123 @@
+/**
+ * CLI client for the live variant mode poll/reply protocol.
+ *
+ * Usage:
+ * npx impeccable poll # Block until browser event, print JSON
+ * npx impeccable poll --timeout=60000 # Custom timeout (ms)
+ * npx impeccable poll --reply <id> done # Reply "done" to event <id>
+ * npx impeccable poll --reply <id> error "msg" # Reply with error
+ */
+
+import fs from 'node:fs';
+import path from 'node:path';
+import os from 'node:os';
+
+const LIVE_PID_FILE = path.join(os.tmpdir(), 'impeccable-live.json');
+
+function readServerInfo() {
+ try {
+ return JSON.parse(fs.readFileSync(LIVE_PID_FILE, 'utf-8'));
+ } catch {
+ console.error('No running live server found. Start one with: npx impeccable live');
+ process.exit(1);
+ }
+}
+
+export async function pollCli() {
+ const args = process.argv.slice(2);
+
+ if (args.includes('--help') || args.includes('-h')) {
+ console.log(`Usage: impeccable poll [options]
+
+Wait for a browser event from the live variant server, or reply to one.
+
+Modes:
+ poll Block until a browser event arrives, print JSON
+ poll --reply <id> done Reply "done" to event <id>
+ poll --reply <id> error "msg" Reply with an error message
+
+Options:
+ --timeout=MS Poll timeout in milliseconds (default: 120000)
+ --help Show this help message`);
+ process.exit(0);
+ }
+
+ const info = readServerInfo();
+ const base = `http://localhost:${info.port}`;
+
+ // Reply mode: npx impeccable poll --reply <id> <status> [--file path] [message]
+ const replyIdx = args.indexOf('--reply');
+ if (replyIdx !== -1) {
+ const id = args[replyIdx + 1];
+ const status = args[replyIdx + 2] || 'done';
+ const fileIdx = args.indexOf('--file');
+ const filePath = fileIdx !== -1 && fileIdx + 1 < args.length ? args[fileIdx + 1] : undefined;
+ // Message is any remaining positional arg that isn't a flag
+ const message = args.find((a, i) => i > replyIdx + 2 && !a.startsWith('--') && i !== fileIdx + 1) || undefined;
+
+ if (!id) {
+ console.error('Usage: npx impeccable poll --reply <id> <status> [--file path] [message]');
+ process.exit(1);
+ }
+
+ 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);
+ }
+
+ // Success — silent exit (agent doesn't need output for replies)
+ } catch (err) {
+ if (err.cause?.code === 'ECONNREFUSED') {
+ console.error('Live server not running. Start one with: npx impeccable live');
+ } else {
+ console.error('Reply failed:', err.message);
+ }
+ process.exit(1);
+ }
+ return;
+ }
+
+ // Poll mode: block until browser event
+ const timeoutArg = args.find(a => a.startsWith('--timeout='));
+ const timeout = timeoutArg ? parseInt(timeoutArg.split('=')[1], 10) : 120000;
+
+ try {
+ const res = await fetch(`${base}/poll?token=${info.token}&timeout=${timeout}`);
+
+ if (res.status === 401) {
+ console.error('Authentication failed. The server token may have changed.');
+ console.error('Try restarting: npx impeccable live stop && npx impeccable live');
+ process.exit(1);
+ }
+
+ if (!res.ok) {
+ console.error(`Poll failed: ${res.status} ${res.statusText}`);
+ process.exit(1);
+ }
+
+ const event = await res.json();
+ // Print the event as JSON — the agent reads this from stdout
+ console.log(JSON.stringify(event));
+ } catch (err) {
+ if (err.cause?.code === 'ECONNREFUSED') {
+ console.error('Live server not running. Start one with: npx impeccable live');
+ } else {
+ console.error('Poll failed:', err.message);
+ }
+ process.exit(1);
+ }
+}
diff --git a/.gemini/skills/impeccable/scripts/live-server.mjs b/.gemini/skills/impeccable/scripts/live-server.mjs
new file mode 100644
index 000000000..d436bad58
--- /dev/null
+++ b/.gemini/skills/impeccable/scripts/live-server.mjs
@@ -0,0 +1,416 @@
+#!/usr/bin/env node
+/**
+ * Live variant mode server (self-contained, zero dependencies).
+ *
+ * Serves the browser script (/live.js), the detection overlay (/detect.js),
+ * uses Server-Sent Events (SSE) for server→browser push, and HTTP POST for
+ * browser→server events. Agent communicates via HTTP long-poll (/poll).
+ *
+ * Usage:
+ * node <scripts_path>/live-server.mjs # start
+ * node <scripts_path>/live-server.mjs stop # stop
+ * node <scripts_path>/live-server.mjs --help
+ */
+
+import http from 'node:http';
+import { randomUUID } from 'node:crypto';
+import fs from 'node:fs';
+import path from 'node:path';
+import os from 'node:os';
+import net from 'node:net';
+import { fileURLToPath } from 'node:url';
+
+const __dirname = path.dirname(fileURLToPath(import.meta.url));
+const LIVE_PID_FILE = path.join(os.tmpdir(), 'impeccable-live.json');
+const DEFAULT_POLL_TIMEOUT = 120_000;
+
+// ---------------------------------------------------------------------------
+// Port detection
+// ---------------------------------------------------------------------------
+
+async function findOpenPort(start = 8400) {
+ return new Promise((resolve) => {
+ const srv = net.createServer();
+ srv.listen(start, '127.0.0.1', () => {
+ const port = srv.address().port;
+ srv.close(() => resolve(port));
+ });
+ srv.on('error', () => resolve(findOpenPort(start + 1)));
+ });
+}
+
+// ---------------------------------------------------------------------------
+// Session state
+// ---------------------------------------------------------------------------
+
+const state = {
+ token: null,
+ port: null,
+ sseClients: new Set(), // SSE response objects (server→browser push)
+ pendingEvents: [], // browser events waiting for agent poll
+ pendingPolls: [], // agent poll callbacks waiting for browser events
+ exitTimer: null,
+};
+
+function enqueueEvent(event) {
+ if (state.pendingPolls.length > 0) {
+ state.pendingPolls.shift()(event);
+ } else {
+ state.pendingEvents.push(event);
+ }
+}
+
+/** Push a message to all connected SSE clients. */
+function broadcast(msg) {
+ const data = 'data: ' + JSON.stringify(msg) + '\n\n';
+ for (const res of state.sseClients) {
+ try { res.write(data); } catch { /* client gone */ }
+ }
+}
+
+// ---------------------------------------------------------------------------
+// Load scripts
+// ---------------------------------------------------------------------------
+
+function loadBrowserScripts() {
+ // Detection script: look relative to the skill scripts dir, then fall back
+ // to the npm package location (src/detect-antipatterns-browser.js)
+ const detectPaths = [
+ path.join(__dirname, '..', '..', '..', '..', 'src', 'detect-antipatterns-browser.js'),
+ path.join(process.cwd(), 'node_modules', 'impeccable', 'src', 'detect-antipatterns-browser.js'),
+ ];
+ let detectScript = '';
+ for (const p of detectPaths) {
+ try { detectScript = fs.readFileSync(p, 'utf-8'); break; } catch { /* try next */ }
+ }
+
+ const livePath = path.join(__dirname, 'live-browser.js');
+ let liveScript = '';
+ try {
+ liveScript = fs.readFileSync(livePath, 'utf-8');
+ } catch {
+ process.stderr.write('Error: live-browser.js not found at ' + livePath + '\n');
+ process.exit(1);
+ }
+
+ return { detectScript, liveScript };
+}
+
+function hasProjectContext() {
+ try {
+ fs.accessSync(path.join(process.cwd(), '.impeccable.md'), fs.constants.R_OK);
+ return true;
+ } catch { return false; }
+}
+
+// ---------------------------------------------------------------------------
+// Validation (inline — no external import needed for self-contained script)
+// ---------------------------------------------------------------------------
+
+const VISUAL_ACTIONS = [
+ 'impeccable', 'bolder', 'quieter', 'distill', 'polish', 'typeset',
+ 'colorize', 'layout', 'adapt', 'animate', 'delight', 'overdrive',
+];
+
+function validateEvent(msg) {
+ if (!msg || typeof msg !== 'object' || !msg.type) return 'Missing or invalid message';
+ switch (msg.type) {
+ case 'generate':
+ if (!msg.id || typeof msg.id !== 'string') return 'generate: missing id';
+ if (!msg.action || !VISUAL_ACTIONS.includes(msg.action)) return 'generate: invalid action';
+ if (!Number.isInteger(msg.count) || msg.count < 1 || msg.count > 8) return 'generate: count must be 1-8';
+ if (!msg.element || !msg.element.outerHTML) return 'generate: missing element context';
+ return null;
+ case 'accept':
+ if (!msg.id) return 'accept: missing id';
+ if (!msg.variantId) return 'accept: missing variantId';
+ return null;
+ case 'discard':
+ return msg.id ? null : 'discard: missing id';
+ case 'exit':
+ return null;
+ default:
+ return 'Unknown event type: ' + msg.type;
+ }
+}
+
+// ---------------------------------------------------------------------------
+// HTTP request handler
+// ---------------------------------------------------------------------------
+
+function createRequestHandler({ detectScript, liveScriptWithToken }) {
+ return (req, res) => {
+ const url = new URL(req.url, `http://localhost:${state.port}`);
+ res.setHeader('Access-Control-Allow-Origin', '*');
+ res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS');
+ res.setHeader('Access-Control-Allow-Headers', 'Content-Type');
+ if (req.method === 'OPTIONS') { res.writeHead(204); res.end(); return; }
+
+ const p = url.pathname;
+
+ // --- Scripts ---
+ if (p === '/live.js') {
+ res.writeHead(200, { 'Content-Type': 'application/javascript' });
+ res.end(liveScriptWithToken);
+ return;
+ }
+ if (p === '/detect.js' || p === '/') {
+ if (!detectScript) { res.writeHead(404); res.end('Not available'); return; }
+ res.writeHead(200, { 'Content-Type': 'application/javascript' });
+ res.end(detectScript);
+ return;
+ }
+
+ // --- Health ---
+ if (p === '/health') {
+ res.writeHead(200, { 'Content-Type': 'application/json' });
+ res.end(JSON.stringify({
+ status: 'ok', port: state.port, mode: 'variant',
+ hasProjectContext: hasProjectContext(),
+ connectedClients: state.sseClients.size,
+ }));
+ return;
+ }
+
+ // --- Source file (no-HMR fallback) ---
+ if (p === '/source') {
+ const token = url.searchParams.get('token');
+ if (token !== state.token) { res.writeHead(401); res.end('Unauthorized'); return; }
+ const filePath = url.searchParams.get('path');
+ if (!filePath || filePath.includes('..')) { res.writeHead(400); res.end('Bad path'); return; }
+ const absPath = path.resolve(process.cwd(), filePath);
+ if (!absPath.startsWith(process.cwd())) { res.writeHead(403); res.end('Forbidden'); return; }
+ try {
+ res.writeHead(200, { 'Content-Type': 'text/html; charset=utf-8' });
+ res.end(fs.readFileSync(absPath, 'utf-8'));
+ } catch { res.writeHead(404); res.end('File not found'); }
+ return;
+ }
+
+ // --- SSE: server→browser push (replaces WebSocket) ---
+ if (p === '/events' && req.method === 'GET') {
+ const token = url.searchParams.get('token');
+ if (token !== state.token) { res.writeHead(401); res.end('Unauthorized'); return; }
+ res.writeHead(200, {
+ 'Content-Type': 'text/event-stream',
+ 'Cache-Control': 'no-cache',
+ 'Connection': 'keep-alive',
+ });
+ res.write('data: ' + JSON.stringify({
+ type: 'connected',
+ hasProjectContext: hasProjectContext(),
+ }) + '\n\n');
+
+ state.sseClients.add(res);
+ clearTimeout(state.exitTimer);
+
+ req.on('close', () => {
+ state.sseClients.delete(res);
+ if (state.sseClients.size === 0) {
+ clearTimeout(state.exitTimer);
+ state.exitTimer = setTimeout(() => {
+ if (state.sseClients.size === 0) enqueueEvent({ type: 'exit' });
+ }, 8000);
+ }
+ });
+ return;
+ }
+
+ // --- Browser→server events (replaces WebSocket messages) ---
+ if (p === '/events' && req.method === 'POST') {
+ let body = '';
+ req.on('data', (c) => { body += c; });
+ req.on('end', () => {
+ let msg;
+ try { msg = JSON.parse(body); } catch {
+ res.writeHead(400, { 'Content-Type': 'application/json' });
+ res.end(JSON.stringify({ error: 'Invalid JSON' }));
+ return;
+ }
+ if (msg.token !== state.token) {
+ res.writeHead(401, { 'Content-Type': 'application/json' });
+ res.end(JSON.stringify({ error: 'Unauthorized' }));
+ return;
+ }
+ const error = validateEvent(msg);
+ if (error) {
+ res.writeHead(400, { 'Content-Type': 'application/json' });
+ res.end(JSON.stringify({ error }));
+ return;
+ }
+ enqueueEvent(msg);
+ res.writeHead(200, { 'Content-Type': 'application/json' });
+ res.end(JSON.stringify({ ok: true }));
+ });
+ return;
+ }
+
+ // --- Stop ---
+ if (p === '/stop') {
+ const token = url.searchParams.get('token');
+ if (token !== state.token) { res.writeHead(401); res.end('Unauthorized'); return; }
+ res.writeHead(200, { 'Content-Type': 'text/plain' });
+ res.end('stopping');
+ shutdown();
+ return;
+ }
+
+ // --- Agent poll ---
+ if (p === '/poll' && req.method === 'GET') {
+ handlePollGet(req, res, url);
+ return;
+ }
+ if (p === '/poll' && req.method === 'POST') {
+ handlePollPost(req, res);
+ return;
+ }
+
+ res.writeHead(404); res.end('Not found');
+ };
+}
+
+// ---------------------------------------------------------------------------
+// Agent poll endpoints (unchanged from WS version)
+// ---------------------------------------------------------------------------
+
+function handlePollGet(req, res, url) {
+ 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 timeout = parseInt(url.searchParams.get('timeout') || DEFAULT_POLL_TIMEOUT, 10);
+ if (state.pendingEvents.length > 0) {
+ res.writeHead(200, { 'Content-Type': 'application/json' });
+ res.end(JSON.stringify(state.pendingEvents.shift()));
+ return;
+ }
+ const timer = setTimeout(() => {
+ const idx = state.pendingPolls.indexOf(resolve);
+ if (idx !== -1) state.pendingPolls.splice(idx, 1);
+ res.writeHead(200, { 'Content-Type': 'application/json' });
+ res.end(JSON.stringify({ type: 'timeout' }));
+ }, timeout);
+ function resolve(event) {
+ clearTimeout(timer);
+ res.writeHead(200, { 'Content-Type': 'application/json' });
+ res.end(JSON.stringify(event));
+ }
+ state.pendingPolls.push(resolve);
+ req.on('close', () => {
+ clearTimeout(timer);
+ const idx = state.pendingPolls.indexOf(resolve);
+ if (idx !== -1) state.pendingPolls.splice(idx, 1);
+ });
+}
+
+function handlePollPost(req, res) {
+ let body = '';
+ req.on('data', (c) => { body += c; });
+ req.on('end', () => {
+ let msg;
+ try { msg = JSON.parse(body); } catch {
+ res.writeHead(400, { 'Content-Type': 'application/json' });
+ res.end(JSON.stringify({ error: 'Invalid JSON' }));
+ return;
+ }
+ if (msg.token !== state.token) {
+ res.writeHead(401, { 'Content-Type': 'application/json' });
+ res.end(JSON.stringify({ error: 'Unauthorized' }));
+ return;
+ }
+ // Forward the reply to the browser via SSE
+ broadcast({ type: msg.type || 'done', id: msg.id, message: msg.message, file: msg.file, data: msg.data });
+ res.writeHead(200, { 'Content-Type': 'application/json' });
+ res.end(JSON.stringify({ ok: true }));
+ });
+}
+
+// ---------------------------------------------------------------------------
+// Lifecycle
+// ---------------------------------------------------------------------------
+
+let httpServer = null;
+
+function shutdown() {
+ try { fs.unlinkSync(LIVE_PID_FILE); } catch {}
+ for (const res of state.sseClients) { try { res.end(); } catch {} }
+ state.sseClients.clear();
+ for (const resolve of state.pendingPolls) resolve({ type: 'exit' });
+ state.pendingPolls.length = 0;
+ if (httpServer) httpServer.close();
+ process.exit(0);
+}
+
+// ---------------------------------------------------------------------------
+// Main
+// ---------------------------------------------------------------------------
+
+const args = process.argv.slice(2);
+
+if (args.includes('--help') || args.includes('-h')) {
+ console.log(`Usage: node live-server.mjs [options]
+
+Start the live variant mode server (zero dependencies).
+
+Commands:
+ (default) Start the server
+ stop Stop a running server
+
+Options:
+ --port=PORT Use a specific port (default: auto-detect starting at 8400)
+ --help Show this help
+
+Endpoints:
+ /live.js Browser script (element picker + variant cycling)
+ /detect.js Detection overlay (backwards compatible)
+ /events SSE stream (server→browser) + POST (browser→server)
+ /poll Long-poll for agent CLI
+ /source Raw source file reader (no-HMR fallback)
+ /health Health check`);
+ process.exit(0);
+}
+
+if (args.includes('stop')) {
+ try {
+ const info = JSON.parse(fs.readFileSync(LIVE_PID_FILE, 'utf-8'));
+ 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 { console.log('No running live server found.'); }
+ process.exit(0);
+}
+
+// Check for existing session
+try {
+ const existing = JSON.parse(fs.readFileSync(LIVE_PID_FILE, 'utf-8'));
+ 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 {}
+
+state.token = randomUUID();
+const portArg = args.find(a => a.startsWith('--port='));
+state.port = portArg ? parseInt(portArg.split('=')[1], 10) : await findOpenPort();
+
+const { detectScript, liveScript } = loadBrowserScripts();
+const liveScriptWithToken =
+ `window.__IMPECCABLE_TOKEN__ = '${state.token}';\n` +
+ `window.__IMPECCABLE_PORT__ = ${state.port};\n` +
+ liveScript;
+
+httpServer = http.createServer(createRequestHandler({ detectScript, liveScriptWithToken }));
+
+httpServer.listen(state.port, '127.0.0.1', () => {
+ fs.writeFileSync(LIVE_PID_FILE, JSON.stringify({ 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`);
+ console.log(`Inject: <script src="${url}/live.js"><\/script>`);
+ console.log(`Stop: node ${path.basename(fileURLToPath(import.meta.url))} stop`);
+});
+
+process.on('SIGINT', shutdown);
+process.on('SIGTERM', shutdown);
diff --git a/.gemini/skills/impeccable/scripts/live-wrap.mjs b/.gemini/skills/impeccable/scripts/live-wrap.mjs
new file mode 100644
index 000000000..f1c838cdd
--- /dev/null
+++ b/.gemini/skills/impeccable/scripts/live-wrap.mjs
@@ -0,0 +1,298 @@
+/**
+ * CLI helper: find an element in source and wrap it in a variant container.
+ *
+ * Usage:
+ * npx impeccable wrap --id SESSION_ID --count N --query "hero-combined-left" [--file path]
+ *
+ * Searches project files for the element matching the query (class name, ID, or
+ * text snippet), wraps it with the variant scaffolding, and prints the file path
+ * + line range where the agent should insert variant HTML.
+ *
+ * This replaces 3-4 agent tool calls (grep + read + edit) with a single CLI call.
+ */
+
+import fs from 'node:fs';
+import path from 'node:path';
+
+const EXTENSIONS = ['.html', '.jsx', '.tsx', '.vue', '.svelte', '.astro'];
+
+export async function wrapCli() {
+ const args = process.argv.slice(2);
+
+ if (args.includes('--help') || args.includes('-h')) {
+ console.log(`Usage: impeccable wrap [options]
+
+Find an element in source and wrap it in a variant container.
+
+Required:
+ --id ID Session ID for the variant wrapper
+ --count N Number of expected variants (1-8)
+
+Element identification (at least one required):
+ --element-id ID HTML id attribute of the element
+ --classes A,B,C Comma-separated CSS class names
+ --tag TAG Tag name (div, section, etc.)
+ --query TEXT Fallback: raw text to search for
+
+Optional:
+ --file PATH Source file to search in (skips auto-detection)
+ --help Show this help message
+
+Output (JSON):
+ { file, startLine, endLine, insertLine, commentSyntax }
+
+The agent should insert variant HTML at insertLine.`);
+ process.exit(0);
+ }
+
+ const id = argVal(args, '--id');
+ const count = parseInt(argVal(args, '--count') || '3');
+ const elementId = argVal(args, '--element-id');
+ const classes = argVal(args, '--classes');
+ const tag = argVal(args, '--tag');
+ const query = argVal(args, '--query');
+ const filePath = argVal(args, '--file');
+
+ if (!id) { console.error('Missing --id'); process.exit(1); }
+ if (!elementId && !classes && !query) {
+ console.error('Need at least one of: --element-id, --classes, --query');
+ process.exit(1);
+ }
+
+ // Build search queries in priority order (most specific first)
+ const queries = buildSearchQueries(elementId, classes, tag, query);
+
+ // Find the source file
+ let targetFile = filePath;
+ let matchedQuery = null;
+ if (!targetFile) {
+ for (const q of queries) {
+ targetFile = findFileWithQuery(q, process.cwd());
+ if (targetFile) { matchedQuery = q; break; }
+ }
+ if (!targetFile) {
+ console.error(JSON.stringify({ error: 'Could not find element in project files. Searched for: ' + queries.join(', ') }));
+ process.exit(1);
+ }
+ } else {
+ matchedQuery = queries[0];
+ }
+
+ const content = fs.readFileSync(targetFile, 'utf-8');
+ const lines = content.split('\n');
+
+ // Find the element, trying each query in priority order
+ let match = null;
+ for (const q of queries) {
+ match = findElement(lines, q);
+ if (match) break;
+ }
+ if (!match) {
+ console.error(JSON.stringify({ error: 'Found file but could not locate element in ' + targetFile + '. Searched for: ' + queries.join(', ') }));
+ process.exit(1);
+ }
+
+ const { startLine, endLine } = match;
+ const commentSyntax = detectCommentSyntax(targetFile);
+ const indent = lines[startLine].match(/^(\s*)/)[1];
+
+ // Extract the original element
+ const originalLines = lines.slice(startLine, endLine + 1);
+ const originalIndented = originalLines.map(l => indent + ' ' + l.trimStart()).join('\n');
+
+ // Build the wrapper
+ const wrapperLines = [
+ indent + commentSyntax.open + ' impeccable-variants-start ' + id + ' ' + commentSyntax.close,
+ indent + '<div data-impeccable-variants="' + id + '" data-impeccable-variant-count="' + count + '" style="display: contents">',
+ indent + ' ' + commentSyntax.open + ' Original ' + commentSyntax.close,
+ indent + ' <div data-impeccable-variant="original">',
+ originalIndented,
+ indent + ' </div>',
+ indent + ' ' + commentSyntax.open + ' Variants: insert below this line ' + commentSyntax.close,
+ indent + '</div>',
+ indent + commentSyntax.open + ' impeccable-variants-end ' + id + ' ' + commentSyntax.close,
+ ];
+
+ // Replace the original element with the wrapper
+ const newLines = [
+ ...lines.slice(0, startLine),
+ ...wrapperLines,
+ ...lines.slice(endLine + 1),
+ ];
+ fs.writeFileSync(targetFile, newLines.join('\n'), 'utf-8');
+
+ // Calculate insert line (the "insert below this line" comment)
+ const insertLine = startLine + 6; // 0-indexed in the new file
+
+ console.log(JSON.stringify({
+ file: path.relative(process.cwd(), targetFile),
+ startLine: startLine + 1, // 1-indexed for the agent
+ endLine: startLine + wrapperLines.length, // 1-indexed
+ insertLine: insertLine + 1, // 1-indexed: where variants go
+ commentSyntax: commentSyntax,
+ originalLineCount: originalLines.length,
+ }));
+}
+
+// ---------------------------------------------------------------------------
+// Helpers
+// ---------------------------------------------------------------------------
+
+function argVal(args, flag) {
+ const idx = args.indexOf(flag);
+ return idx !== -1 && idx + 1 < args.length ? args[idx + 1] : null;
+}
+
+/**
+ * Build search query strings in priority order (most specific first).
+ * ID is most reliable, then specific class combos, then single classes, then raw query.
+ */
+function buildSearchQueries(elementId, classes, tag, query) {
+ const queries = [];
+
+ // 1. ID is the most specific
+ if (elementId) {
+ queries.push('id="' + elementId + '"');
+ }
+
+ // 2. Full class attribute match (for elements with distinctive multi-class combos)
+ if (classes) {
+ const classList = classes.split(',').map(c => c.trim()).filter(Boolean);
+ if (classList.length > 1) {
+ // Try the most distinctive class first (longest, most specific)
+ const sorted = [...classList].sort((a, b) => b.length - a.length);
+ queries.push('class="' + classList.join(' ') + '"'); // exact full match
+ queries.push(sorted[0]); // most distinctive single class
+ } else if (classList.length === 1) {
+ queries.push(classList[0]);
+ }
+ }
+
+ // 3. Tag + class combo (e.g., <section class="hero">)
+ if (tag && classes) {
+ const firstClass = classes.split(',')[0].trim();
+ queries.push('<' + tag + ' class="' + firstClass);
+ }
+
+ // 4. Raw fallback query
+ if (query) {
+ queries.push(query);
+ }
+
+ return queries;
+}
+
+function detectCommentSyntax(filePath) {
+ const ext = path.extname(filePath).toLowerCase();
+ if (ext === '.jsx' || ext === '.tsx') {
+ return { open: '{/*', close: '*/}' };
+ }
+ // HTML, Vue, Svelte, Astro all use HTML comments
+ return { open: '<!--', close: '-->' };
+}
+
+/**
+ * Search project files for the query string (class name, ID, etc.)
+ * Returns the first matching file path, or null.
+ */
+function findFileWithQuery(query, cwd) {
+ const searchDirs = ['src', 'app', 'pages', 'components', 'public', 'views', 'templates', '.'];
+ const seen = new Set();
+
+ for (const dir of searchDirs) {
+ const absDir = path.join(cwd, dir);
+ if (!fs.existsSync(absDir)) continue;
+ const result = searchDir(absDir, query, seen, 0);
+ if (result) return result;
+ }
+ return null;
+}
+
+function searchDir(dir, query, seen, depth) {
+ if (depth > 5) return null; // don't go too deep
+ const realDir = fs.realpathSync(dir);
+ if (seen.has(realDir)) return null;
+ seen.add(realDir);
+
+ let entries;
+ try { entries = fs.readdirSync(dir, { withFileTypes: true }); }
+ catch { return null; }
+
+ // Check files first
+ for (const entry of entries) {
+ if (!entry.isFile()) continue;
+ const ext = path.extname(entry.name).toLowerCase();
+ if (!EXTENSIONS.includes(ext)) continue;
+
+ const filePath = path.join(dir, entry.name);
+ try {
+ const content = fs.readFileSync(filePath, 'utf-8');
+ if (content.includes(query)) return filePath;
+ } catch { /* skip unreadable files */ }
+ }
+
+ // Then recurse into directories
+ for (const entry of entries) {
+ if (!entry.isDirectory()) continue;
+ if (entry.name === 'node_modules' || entry.name === '.git' || entry.name === 'dist' || entry.name === 'build') continue;
+ const result = searchDir(path.join(dir, entry.name), query, seen, depth + 1);
+ if (result) return result;
+ }
+
+ return null;
+}
+
+/**
+ * Find the element's start and end line in the file.
+ * The query is a class name, ID, or text snippet.
+ * We find the line containing the query, then find the matching closing tag.
+ */
+function findElement(lines, query) {
+ // Find the line containing the query
+ let startLine = -1;
+ for (let i = 0; i < lines.length; i++) {
+ if (lines[i].includes(query)) {
+ // Make sure this looks like a tag opening, not a comment or string
+ const line = lines[i].trim();
+ if (line.startsWith('<!--') || line.startsWith('{/*') || line.startsWith('//')) continue;
+ // Skip lines inside data-impeccable-variant containers (already wrapped)
+ if (lines[i].includes('data-impeccable-variant')) continue;
+ startLine = i;
+ break;
+ }
+ }
+
+ if (startLine === -1) return null;
+
+ // Find the end of this element by counting open/close tags
+ const endLine = findClosingLine(lines, startLine);
+ return { startLine, endLine };
+}
+
+/**
+ * Starting from a line with an opening tag, find the line with the matching
+ * closing tag by counting tag nesting depth.
+ */
+function findClosingLine(lines, start) {
+ // Extract the tag name from the opening line
+ const openMatch = lines[start].match(/<(\w+)[\s>]/);
+ if (!openMatch) return start; // self-closing or text-only line
+
+ const tagName = openMatch[1];
+ let depth = 0;
+
+ for (let i = start; i < lines.length; i++) {
+ const line = lines[i];
+ // Count opening tags (not self-closing)
+ const opens = (line.match(new RegExp('<' + tagName + '[\\s>]', 'g')) || []).length;
+ const selfCloses = (line.match(new RegExp('<' + tagName + '[^>]*/>', 'g')) || []).length;
+ const closes = (line.match(new RegExp('</' + tagName + '\\s*>', 'g')) || []).length;
+
+ depth += opens - selfCloses - closes;
+
+ if (depth <= 0) return i;
+ }
+
+ // If we can't find the close, return a reasonable guess
+ return Math.min(start + 50, lines.length - 1);
+}
diff --git a/.kiro/skills/impeccable/reference/live.md b/.kiro/skills/impeccable/reference/live.md
index 53b64a21a..ba0e9b0c5 100644
--- a/.kiro/skills/impeccable/reference/live.md
+++ b/.kiro/skills/impeccable/reference/live.md
@@ -10,7 +10,7 @@ Launch interactive live variant mode: select elements in the browser, pick a des
1. Read `.impeccable.md` if it exists. Keep the design context in mind for variant generation.
2. Start the live variant server:
```bash
- npx impeccable live &
+ node {{scripts_path}}/live-server.mjs &
```
3. Note the **port** and **token** printed to stdout.
@@ -53,7 +53,7 @@ Run a blocking poll loop. On each iteration, wait for a browser event and respon
```
LOOP:
- Run: npx impeccable poll
+ Run: node {{scripts_path}}/live-poll.mjs
Read the JSON output. Dispatch based on the "type" field:
TYPE "generate":
@@ -85,7 +85,7 @@ The event contains: `{id, action, freeformPrompt, count, pageUrl, element}`.
Use the `wrap` helper to find the element and create the variant container:
```bash
-npx impeccable wrap --id EVENT_ID --count EVENT_COUNT --element-id "ELEMENT_ID" --classes "class1,class2" --tag "div"
+node {{scripts_path}}/live-wrap.mjs --id EVENT_ID --count EVENT_COUNT --element-id "ELEMENT_ID" --classes "class1,class2" --tag "div"
```
Pass the element's id (`event.element.id`), classes (`event.element.classes` joined with commas), and tag name. The command searches in priority order: ID match first, then class names, then tag+class combo. If `event.pageUrl` hints at the file (e.g., `/` is usually `index.html`), pass `--file PATH` to skip the search.
@@ -136,10 +136,14 @@ The first variant should NOT have `style="display: none"` (it should be visible
### Step 3: Signal completion
+Include `--file` so the browser can fetch variants directly if the dev server lacks HMR:
+
```bash
-npx impeccable poll --reply EVENT_ID done
+node {{scripts_path}}/live-poll.mjs --reply EVENT_ID done --file RELATIVE_PATH
```
+The file path should be relative to the project root (e.g., `public/index.html`, `src/App.tsx`).
+
## Handle Accept
The event contains: `{id, variantId}`.
@@ -151,7 +155,7 @@ The user accepted a specific variant. For v1 (inspection mode):
4. Remove any scoped CSS blocks (between `impeccable-variants-css-start` and `impeccable-variants-css-end` markers).
5. Reply:
```bash
- npx impeccable poll --reply SESSION_ID done
+ node {{scripts_path}}/live-poll.mjs --reply SESSION_ID done
```
## Handle Discard
@@ -163,7 +167,7 @@ The event contains: `{id}`.
3. Remove any scoped CSS blocks for this session.
4. Reply:
```bash
- npx impeccable poll --reply SESSION_ID done
+ node {{scripts_path}}/live-poll.mjs --reply SESSION_ID done
```
## Cleanup (on exit)
@@ -174,7 +178,7 @@ When the loop ends:
2. **Remove any leftover variant wrappers** (search for `impeccable-variants-start` markers and clean up).
3. **Stop the server**:
```bash
- npx impeccable live stop
+ node {{scripts_path}}/live-server.mjs stop
```
## Variant Generation Guidelines
diff --git a/.kiro/skills/impeccable/scripts/live-browser.js b/.kiro/skills/impeccable/scripts/live-browser.js
new file mode 100644
index 000000000..7a26c9829
--- /dev/null
+++ b/.kiro/skills/impeccable/scripts/live-browser.js
@@ -0,0 +1,1220 @@
+/**
+ * Impeccable Live Variant Mode — Browser Script
+ *
+ * Injected into the user's page via <script src="http://localhost:PORT/live.js">.
+ * The server prepends window.__IMPECCABLE_TOKEN__ and window.__IMPECCABLE_PORT__
+ * before this code.
+ *
+ * UI: a single floating bar that morphs between three states —
+ * configure (pick action + go), generating (progressive dots), and cycling
+ * (prev/next + accept/discard). Feels like Spotlight, not a modal.
+ */
+(function () {
+ 'use strict';
+ if (typeof window === 'undefined') return;
+
+ // Guard against double-init. Bun's HTML loader may process the <script> tag
+ // and create a bundled copy alongside the external load, or HMR may re-execute.
+ // Check BEFORE reading token/port to catch all cases.
+ if (window.__IMPECCABLE_LIVE_INIT__) return;
+ window.__IMPECCABLE_LIVE_INIT__ = true;
+
+ const TOKEN = window.__IMPECCABLE_TOKEN__;
+ const PORT = window.__IMPECCABLE_PORT__;
+ if (!TOKEN || !PORT) {
+ window.__IMPECCABLE_LIVE_INIT__ = false; // reset so the real load can init
+ return;
+ }
+
+ // ---------------------------------------------------------------------------
+ // Design tokens
+ // ---------------------------------------------------------------------------
+
+ const C = {
+ brand: 'oklch(55% 0.25 350)',
+ brandHov: 'oklch(48% 0.25 350)',
+ brandSoft: 'oklch(55% 0.25 350 / 0.12)',
+ ink: 'oklch(15% 0.01 350)',
+ ash: 'oklch(55% 0 0)',
+ paper: 'oklch(98% 0.005 350 / 0.92)',
+ paperSolid:'oklch(98% 0.005 350)',
+ mist: 'oklch(90% 0.01 350 / 0.6)',
+ white: 'oklch(99% 0 0)',
+ };
+ const FONT = 'system-ui, -apple-system, sans-serif';
+ const MONO = 'ui-monospace, SFMono-Regular, Menlo, monospace';
+ const Z = { highlight: 99990, bar: 99995, picker: 99997, toast: 99999 };
+ const EASE = 'cubic-bezier(0.22, 1, 0.36, 1)'; // ease-out-quint
+ const PREFIX = 'impeccable-live';
+
+ const SKIP_TAGS = new Set([
+ 'html', 'head', 'body', 'script', 'style', 'link', 'meta', 'noscript', 'br', 'wbr',
+ ]);
+
+ const ACTIONS = [
+ { value: 'impeccable', label: 'Freeform' },
+ { value: 'bolder', label: 'Bolder' },
+ { value: 'quieter', label: 'Quieter' },
+ { value: 'distill', label: 'Distill' },
+ { value: 'polish', label: 'Polish' },
+ { value: 'typeset', label: 'Typeset' },
+ { value: 'colorize', label: 'Colorize' },
+ { value: 'layout', label: 'Layout' },
+ { value: 'adapt', label: 'Adapt' },
+ { value: 'animate', label: 'Animate' },
+ { value: 'delight', label: 'Delight' },
+ { value: 'overdrive', label: 'Overdrive' },
+ ];
+
+ // ---------------------------------------------------------------------------
+ // State
+ // ---------------------------------------------------------------------------
+
+ let state = 'IDLE';
+ let hoveredElement = null;
+ let selectedElement = null;
+ let currentSessionId = null;
+ let expectedVariants = 0;
+ let arrivedVariants = 0;
+ let visibleVariant = 0;
+ let variantObserver = null;
+ let hasProjectContext = false;
+ let selectedAction = 'impeccable';
+ let selectedCount = 3;
+
+ // UI refs
+ let highlightEl = null;
+ let tooltipEl = null;
+ let barEl = null;
+ let pickerEl = null;
+ let toastEl = null;
+ let scrollRaf = null;
+
+ // ---------------------------------------------------------------------------
+ // Helpers
+ // ---------------------------------------------------------------------------
+
+ function own(el) {
+ return el && (el.id?.startsWith(PREFIX) || el.closest?.('[id^="' + PREFIX + '"]'));
+ }
+
+ function pickable(el) {
+ if (!el || el.nodeType !== 1) return false;
+ if (SKIP_TAGS.has(el.tagName.toLowerCase())) return false;
+ if (own(el)) return false;
+ const r = el.getBoundingClientRect();
+ return r.width >= 20 && r.height >= 20;
+ }
+
+ function desc(el) {
+ if (!el) return '';
+ let s = el.tagName.toLowerCase();
+ if (el.id) s += '#' + el.id;
+ else if (el.classList.length) s += '.' + [...el.classList].slice(0, 2).join('.');
+ return s;
+ }
+
+ function id8() { return crypto.randomUUID().replace(/-/g, '').slice(0, 8); }
+
+ // ---------------------------------------------------------------------------
+ // Highlight overlay
+ // ---------------------------------------------------------------------------
+
+ function initHighlight() {
+ highlightEl = document.createElement('div');
+ highlightEl.id = PREFIX + '-highlight';
+ Object.assign(highlightEl.style, {
+ position: 'fixed', top: '0', left: '0', width: '0', height: '0',
+ border: '2px solid ' + C.brand, borderRadius: '3px',
+ pointerEvents: 'none', zIndex: Z.highlight, boxSizing: 'border-box',
+ transition: 'top 0.08s ease, left 0.08s ease, width 0.08s ease, height 0.08s ease, opacity 0.15s ease',
+ display: 'none', opacity: '0',
+ });
+ document.body.appendChild(highlightEl);
+
+ tooltipEl = document.createElement('div');
+ tooltipEl.id = PREFIX + '-tooltip';
+ Object.assign(tooltipEl.style, {
+ position: 'fixed',
+ background: C.ink, color: C.white,
+ fontFamily: MONO, fontSize: '10px', fontWeight: '500',
+ padding: '2px 6px', borderRadius: '3px',
+ zIndex: Z.highlight + 1, pointerEvents: 'none',
+ whiteSpace: 'nowrap', display: 'none',
+ letterSpacing: '0.02em',
+ });
+ document.body.appendChild(tooltipEl);
+ }
+
+ function showHighlight(el) {
+ if (!el || !highlightEl) return;
+ const r = el.getBoundingClientRect();
+ Object.assign(highlightEl.style, {
+ top: (r.top - 2) + 'px', left: (r.left - 2) + 'px',
+ width: (r.width + 4) + 'px', height: (r.height + 4) + 'px',
+ display: 'block', opacity: '1',
+ });
+ tooltipEl.textContent = desc(el);
+ const tipTop = r.top - 20;
+ Object.assign(tooltipEl.style, {
+ top: (tipTop < 4 ? r.bottom + 4 : tipTop) + 'px',
+ left: Math.max(4, r.left) + 'px', display: 'block',
+ });
+ }
+
+ function hideHighlight() {
+ if (highlightEl) { highlightEl.style.opacity = '0'; highlightEl.style.display = 'none'; }
+ if (tooltipEl) tooltipEl.style.display = 'none';
+ }
+
+ // ---------------------------------------------------------------------------
+ // Element context extraction
+ // ---------------------------------------------------------------------------
+
+ function extractContext(el) {
+ const cs = getComputedStyle(el);
+ const r = el.getBoundingClientRect();
+ const props = {};
+ for (const sheet of document.styleSheets) {
+ try {
+ for (const rule of sheet.cssRules) {
+ if (rule.style) for (let i = 0; i < rule.style.length; i++) {
+ const p = rule.style[i];
+ if (p.startsWith('--') && !props[p]) {
+ const v = cs.getPropertyValue(p).trim();
+ if (v) props[p] = v;
+ }
+ }
+ }
+ } catch { /* cross-origin */ }
+ }
+ return {
+ tagName: el.tagName.toLowerCase(), id: el.id || null,
+ classes: [...el.classList],
+ textContent: (el.textContent || '').slice(0, 500),
+ outerHTML: el.outerHTML.slice(0, 10000),
+ computedStyles: {
+ 'font-family': cs.fontFamily, 'font-size': cs.fontSize,
+ 'font-weight': cs.fontWeight, 'line-height': cs.lineHeight,
+ 'color': cs.color, 'background': cs.background,
+ 'background-color': cs.backgroundColor,
+ 'padding': cs.padding, 'margin': cs.margin,
+ 'display': cs.display, 'position': cs.position,
+ 'gap': cs.gap, 'border-radius': cs.borderRadius,
+ 'box-shadow': cs.boxShadow,
+ },
+ cssCustomProperties: props,
+ parentContext: el.parentElement
+ ? '<' + el.parentElement.tagName.toLowerCase()
+ + (el.parentElement.id ? ' id="' + el.parentElement.id + '"' : '')
+ + (el.parentElement.className ? ' class="' + el.parentElement.className + '"' : '')
+ + '>'
+ : null,
+ boundingRect: { width: Math.round(r.width), height: Math.round(r.height) },
+ };
+ }
+
+ // ---------------------------------------------------------------------------
+ // The Bar — one floating element, three modes
+ // ---------------------------------------------------------------------------
+
+ function initBar() {
+ barEl = document.createElement('div');
+ barEl.id = PREFIX + '-bar';
+ Object.assign(barEl.style, {
+ position: 'fixed', zIndex: Z.bar,
+ display: 'none', opacity: '0',
+ transform: 'translateY(6px)',
+ transition: 'opacity 0.25s ' + EASE + ', transform 0.3s ' + EASE,
+ // Visual
+ background: C.paper,
+ backdropFilter: 'blur(16px)', WebkitBackdropFilter: 'blur(16px)',
+ border: '1px solid ' + C.mist,
+ borderRadius: '10px',
+ boxShadow: '0 4px 20px oklch(0% 0 0 / 0.08), 0 1px 3px oklch(0% 0 0 / 0.06)',
+ fontFamily: FONT, fontSize: '13px', color: C.ink,
+ padding: '6px',
+ maxWidth: '460px', minWidth: '320px',
+ });
+ document.body.appendChild(barEl);
+ }
+
+ function positionBar() {
+ if (!barEl || !selectedElement) return;
+ const r = selectedElement.getBoundingClientRect();
+ const barH = barEl.offsetHeight || 44;
+ const barW = barEl.offsetWidth || 380;
+ let top = r.bottom + 8;
+ let left = r.left + (r.width - barW) / 2;
+ // Keep in viewport
+ if (top + barH + 8 > window.innerHeight) top = r.top - barH - 8;
+ if (top < 8) top = 8;
+ if (left < 8) left = 8;
+ if (left + barW > window.innerWidth - 8) left = window.innerWidth - barW - 8;
+ Object.assign(barEl.style, { top: top + 'px', left: left + 'px' });
+ }
+
+ function showBar(mode) {
+ barEl.innerHTML = '';
+ if (mode === 'configure') barEl.appendChild(buildConfigureRow());
+ else if (mode === 'generating') barEl.appendChild(buildGeneratingRow());
+ else if (mode === 'cycling') barEl.appendChild(buildCyclingRow());
+ barEl.style.display = 'block';
+ positionBar();
+ requestAnimationFrame(() => {
+ barEl.style.opacity = '1';
+ barEl.style.transform = 'translateY(0)';
+ });
+ }
+
+ function hideBar() {
+ if (!barEl) return;
+ barEl.style.opacity = '0';
+ barEl.style.transform = 'translateY(6px)';
+ setTimeout(() => { if (barEl) barEl.style.display = 'none'; }, 250);
+ hideActionPicker();
+ }
+
+ function updateBarContent(mode) {
+ if (!barEl || barEl.style.display === 'none') return;
+ barEl.innerHTML = '';
+ // Reset bar styling
+ barEl.style.background = C.paper;
+ barEl.style.border = '1px solid ' + C.mist;
+ if (mode === 'configure') barEl.appendChild(buildConfigureRow());
+ else if (mode === 'generating') barEl.appendChild(buildGeneratingRow());
+ else if (mode === 'cycling') barEl.appendChild(buildCyclingRow());
+ else if (mode === 'saving') barEl.appendChild(buildSavingRow());
+ else if (mode === 'confirmed') {
+ barEl.appendChild(buildConfirmedRow());
+ barEl.style.background = 'oklch(95% 0.05 145)';
+ barEl.style.border = '1px solid oklch(75% 0.12 145 / 0.4)';
+ }
+ }
+
+ // --- Configure row ---
+
+ function buildConfigureRow() {
+ const row = el('div', {
+ display: 'flex', alignItems: 'center', gap: '4px',
+ });
+
+ // Action pill
+ const pill = el('button', {
+ display: 'inline-flex', alignItems: 'center', gap: '4px',
+ padding: '5px 10px', borderRadius: '6px',
+ background: C.ink, color: C.white,
+ fontFamily: FONT, fontSize: '12px', fontWeight: '500',
+ border: 'none', cursor: 'pointer',
+ transition: 'background 0.12s ease, transform 0.1s ease',
+ whiteSpace: 'nowrap', flexShrink: '0',
+ });
+ pill.textContent = actionLabel() + ' \u25BE';
+ pill.addEventListener('mouseenter', () => pill.style.background = C.brandHov);
+ pill.addEventListener('mouseleave', () => pill.style.background = C.ink);
+ pill.addEventListener('mousedown', () => pill.style.transform = 'scale(0.97)');
+ pill.addEventListener('mouseup', () => pill.style.transform = 'scale(1)');
+ pill.addEventListener('click', (e) => { e.stopPropagation(); toggleActionPicker(); });
+ row.appendChild(pill);
+
+ // Freeform input
+ const input = document.createElement('input');
+ input.id = PREFIX + '-input';
+ input.type = 'text';
+ input.placeholder = selectedAction === 'impeccable' ? 'describe what you want...' : 'refine further (optional)...';
+ Object.assign(input.style, {
+ flex: '1', minWidth: '0',
+ padding: '5px 8px', borderRadius: '6px',
+ border: '1px solid transparent', background: 'transparent',
+ fontFamily: FONT, fontSize: '12px', color: C.ink,
+ outline: 'none',
+ transition: 'border-color 0.15s ease, background 0.15s ease',
+ });
+ input.addEventListener('focus', () => {
+ input.style.borderColor = C.mist;
+ input.style.background = C.white;
+ });
+ input.addEventListener('blur', () => {
+ input.style.borderColor = 'transparent';
+ input.style.background = 'transparent';
+ });
+ input.addEventListener('keydown', (e) => {
+ e.stopPropagation(); // Don't trigger element picker keyboard nav
+ if (e.key === 'Enter') { e.preventDefault(); handleGo(); }
+ if (e.key === 'Escape') { e.preventDefault(); input.blur(); hideBar(); state = 'PICKING'; }
+ });
+ row.appendChild(input);
+
+ // Variant count toggle
+ const count = el('button', {
+ padding: '4px 6px', borderRadius: '5px',
+ border: '1px solid ' + C.mist, background: 'transparent',
+ fontFamily: MONO, fontSize: '11px', fontWeight: '600',
+ color: C.ash, cursor: 'pointer',
+ transition: 'color 0.12s ease, border-color 0.12s ease',
+ flexShrink: '0', whiteSpace: 'nowrap',
+ });
+ count.textContent = '\u00D7' + selectedCount;
+ count.title = 'Variants: click to change';
+ count.addEventListener('mouseenter', () => { count.style.color = C.ink; count.style.borderColor = C.ink; });
+ count.addEventListener('mouseleave', () => { count.style.color = C.ash; count.style.borderColor = C.mist; });
+ count.addEventListener('click', (e) => {
+ e.stopPropagation();
+ selectedCount = selectedCount >= 4 ? 2 : selectedCount + 1;
+ count.textContent = '\u00D7' + selectedCount;
+ });
+ row.appendChild(count);
+
+ // Go button
+ const go = el('button', {
+ padding: '5px 12px', borderRadius: '6px',
+ border: 'none', background: C.brand, color: C.white,
+ fontFamily: FONT, fontSize: '12px', fontWeight: '600',
+ cursor: 'pointer',
+ transition: 'background 0.12s ease, transform 0.1s ease',
+ flexShrink: '0', whiteSpace: 'nowrap',
+ });
+ go.textContent = 'Go \u2192';
+ go.addEventListener('mouseenter', () => go.style.background = C.brandHov);
+ go.addEventListener('mouseleave', () => go.style.background = C.brand);
+ go.addEventListener('mousedown', () => go.style.transform = 'scale(0.97)');
+ go.addEventListener('mouseup', () => go.style.transform = 'scale(1)');
+ go.addEventListener('click', (e) => { e.stopPropagation(); handleGo(); });
+ row.appendChild(go);
+
+ // Auto-focus input after a beat
+ setTimeout(() => input.focus(), 60);
+ return row;
+ }
+
+ // --- Generating row ---
+
+ function buildGeneratingRow() {
+ const row = el('div', {
+ display: 'flex', alignItems: 'center', gap: '8px',
+ padding: '2px 4px',
+ });
+
+ // Action label
+ const label = el('span', {
+ fontWeight: '600', fontSize: '12px', color: C.ink,
+ flexShrink: '0', whiteSpace: 'nowrap',
+ });
+ label.textContent = actionLabel();
+ row.appendChild(label);
+
+ // Dots
+ row.appendChild(buildDots(false));
+
+ // Status
+ const status = el('span', {
+ fontSize: '11px', color: C.ash, whiteSpace: 'nowrap',
+ marginLeft: 'auto',
+ });
+ status.textContent = arrivedVariants < expectedVariants
+ ? 'Generating ' + (arrivedVariants + 1) + ' of ' + expectedVariants + '...'
+ : 'Done';
+ row.appendChild(status);
+
+ return row;
+ }
+
+ // --- Cycling row ---
+
+ function buildCyclingRow() {
+ const row = el('div', {
+ display: 'flex', alignItems: 'center', gap: '6px',
+ padding: '1px 2px',
+ });
+
+ // Prev
+ const prev = navBtn('\u2190');
+ prev.addEventListener('click', (e) => { e.stopPropagation(); cycleVariant(-1); });
+ if (visibleVariant <= 1) prev.style.opacity = '0.3';
+ row.appendChild(prev);
+
+ // Dots (clickable)
+ row.appendChild(buildDots(true));
+
+ // Counter
+ const counter = el('span', {
+ fontFamily: MONO, fontSize: '11px', fontWeight: '500',
+ color: C.ash, minWidth: '24px', textAlign: 'center',
+ });
+ counter.textContent = visibleVariant + '/' + arrivedVariants;
+ row.appendChild(counter);
+
+ // Next
+ const next = navBtn('\u2192');
+ next.addEventListener('click', (e) => { e.stopPropagation(); cycleVariant(1); });
+ if (visibleVariant >= arrivedVariants) next.style.opacity = '0.3';
+ row.appendChild(next);
+
+ // Spacer
+ row.appendChild(el('div', { flex: '1' }));
+
+ // Accept
+ const accept = el('button', {
+ padding: '4px 10px', borderRadius: '5px',
+ border: 'none', background: C.ink, color: C.white,
+ fontFamily: FONT, fontSize: '11px', fontWeight: '600',
+ cursor: 'pointer', transition: 'background 0.12s ease',
+ whiteSpace: 'nowrap',
+ });
+ accept.textContent = '\u2713 Accept';
+ accept.addEventListener('mouseenter', () => accept.style.background = C.brand);
+ accept.addEventListener('mouseleave', () => accept.style.background = C.ink);
+ accept.addEventListener('click', (e) => { e.stopPropagation(); handleAccept(); });
+ if (arrivedVariants === 0) { accept.style.opacity = '0.3'; accept.style.pointerEvents = 'none'; }
+ row.appendChild(accept);
+
+ // Discard
+ const discard = el('button', {
+ padding: '4px 6px', borderRadius: '5px',
+ border: '1px solid ' + C.mist, background: 'transparent',
+ fontFamily: FONT, fontSize: '11px', color: C.ash,
+ cursor: 'pointer', transition: 'color 0.12s ease, border-color 0.12s ease',
+ });
+ discard.textContent = '\u2715';
+ discard.title = 'Discard all variants';
+ discard.addEventListener('mouseenter', () => { discard.style.color = C.ink; discard.style.borderColor = C.ink; });
+ discard.addEventListener('mouseleave', () => { discard.style.color = C.ash; discard.style.borderColor = C.mist; });
+ discard.addEventListener('click', (e) => { e.stopPropagation(); handleDiscard(); });
+ row.appendChild(discard);
+
+ return row;
+ }
+
+ // --- Shared UI builders ---
+
+ // --- Saving row (waiting for agent to process accept/discard) ---
+
+ function buildSavingRow() {
+ const row = el('div', {
+ display: 'flex', alignItems: 'center', gap: '8px',
+ padding: '2px 8px',
+ });
+ const spinner = el('div', {
+ width: '14px', height: '14px', borderRadius: '50%',
+ border: '2px solid ' + C.mist,
+ borderTopColor: C.brand,
+ animation: 'impeccable-spin 0.6s linear infinite',
+ flexShrink: '0',
+ });
+ row.appendChild(spinner);
+ const label = el('span', {
+ fontSize: '12px', color: C.ash, fontWeight: '500',
+ });
+ label.textContent = 'Applying variant...';
+ row.appendChild(label);
+
+ // Inject the keyframes if not already present
+ if (!document.getElementById(PREFIX + '-keyframes')) {
+ const style = document.createElement('style');
+ style.id = PREFIX + '-keyframes';
+ style.textContent = '@keyframes impeccable-spin { to { transform: rotate(360deg); } }';
+ document.head.appendChild(style);
+ }
+ return row;
+ }
+
+ // --- Confirmed row (green success, auto-dismisses) ---
+
+ function buildConfirmedRow() {
+ const row = el('div', {
+ display: 'flex', alignItems: 'center', gap: '8px',
+ padding: '2px 8px',
+ });
+ const check = el('span', {
+ fontSize: '15px', lineHeight: '1', flexShrink: '0',
+ color: 'oklch(45% 0.15 145)',
+ });
+ check.textContent = '\u2713';
+ row.appendChild(check);
+ const label = el('span', {
+ fontSize: '12px', color: 'oklch(35% 0.1 145)', fontWeight: '600',
+ });
+ label.textContent = 'Variant applied';
+ row.appendChild(label);
+ return row;
+ }
+
+ // --- Shared UI builders ---
+
+ function buildDots(clickable) {
+ const container = el('div', {
+ display: 'flex', alignItems: 'center', gap: '4px',
+ });
+ for (let i = 1; i <= expectedVariants; i++) {
+ const arrived = i <= arrivedVariants;
+ const active = i === visibleVariant;
+ const dot = el('div', {
+ width: '7px', height: '7px', borderRadius: '50%',
+ background: active ? C.brand : (arrived ? C.ash : 'transparent'),
+ border: '1.5px solid ' + (arrived ? C.brand : C.mist),
+ transition: 'all 0.2s ' + EASE,
+ cursor: (clickable && arrived) ? 'pointer' : 'default',
+ transform: arrived ? 'scale(1)' : 'scale(0.6)',
+ opacity: arrived ? '1' : '0.4',
+ });
+ if (clickable && arrived) {
+ const idx = i;
+ dot.addEventListener('click', (e) => {
+ e.stopPropagation();
+ visibleVariant = idx;
+ showVariantInDOM(currentSessionId, idx);
+ updateSelectedElement();
+ updateBarContent('cycling');
+ });
+ }
+ container.appendChild(dot);
+ }
+ return container;
+ }
+
+ function navBtn(text) {
+ const b = el('button', {
+ width: '26px', height: '26px', borderRadius: '5px',
+ border: '1px solid ' + C.mist, background: 'transparent',
+ color: C.ink, fontFamily: FONT, fontSize: '13px',
+ cursor: 'pointer', display: 'flex', alignItems: 'center', justifyContent: 'center',
+ transition: 'border-color 0.12s ease, background 0.12s ease',
+ padding: '0', lineHeight: '1',
+ });
+ b.textContent = text;
+ b.addEventListener('mouseenter', () => { b.style.borderColor = C.ink; });
+ b.addEventListener('mouseleave', () => { b.style.borderColor = C.mist; });
+ return b;
+ }
+
+ function actionLabel() {
+ const a = ACTIONS.find(a => a.value === selectedAction);
+ return a ? a.label : 'Freeform';
+ }
+
+ function el(tag, styles) {
+ const e = document.createElement(tag);
+ if (styles) Object.assign(e.style, styles);
+ return e;
+ }
+
+ // ---------------------------------------------------------------------------
+ // Action picker popover
+ // ---------------------------------------------------------------------------
+
+ function initActionPicker() {
+ pickerEl = document.createElement('div');
+ pickerEl.id = PREFIX + '-picker';
+ Object.assign(pickerEl.style, {
+ position: 'fixed', zIndex: Z.picker,
+ display: 'none', opacity: '0',
+ transform: 'scale(0.96) translateY(4px)',
+ transformOrigin: 'bottom left',
+ transition: 'opacity 0.18s ' + EASE + ', transform 0.2s ' + EASE,
+ background: C.paperSolid,
+ border: '1px solid ' + C.mist,
+ borderRadius: '10px',
+ boxShadow: '0 8px 30px oklch(0% 0 0 / 0.10), 0 2px 6px oklch(0% 0 0 / 0.06)',
+ padding: '6px',
+ fontFamily: FONT,
+ });
+
+ // Build the chip grid
+ const grid = el('div', {
+ display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', gap: '3px',
+ });
+
+ ACTIONS.forEach(action => {
+ const chip = el('button', {
+ padding: '6px 8px', borderRadius: '6px',
+ border: 'none',
+ background: action.value === selectedAction ? C.brandSoft : 'transparent',
+ color: action.value === selectedAction ? C.brand : C.ink,
+ fontFamily: FONT, fontSize: '11px', fontWeight: '500',
+ cursor: 'pointer',
+ transition: 'background 0.1s ease, color 0.1s ease',
+ textAlign: 'center', whiteSpace: 'nowrap',
+ });
+ chip.textContent = action.label;
+ chip.dataset.action = action.value;
+ chip.addEventListener('mouseenter', () => {
+ if (action.value !== selectedAction) chip.style.background = C.brandSoft;
+ });
+ chip.addEventListener('mouseleave', () => {
+ chip.style.background = action.value === selectedAction ? C.brandSoft : 'transparent';
+ });
+ chip.addEventListener('click', (e) => {
+ e.stopPropagation();
+ selectedAction = action.value;
+ hideActionPicker();
+ updateBarContent('configure');
+ });
+ grid.appendChild(chip);
+ });
+
+ pickerEl.appendChild(grid);
+ document.body.appendChild(pickerEl);
+ }
+
+ function toggleActionPicker() {
+ if (pickerEl.style.display !== 'none') { hideActionPicker(); return; }
+ // Rebuild chips to reflect current selection
+ pickerEl.querySelectorAll('button').forEach(chip => {
+ const isActive = chip.dataset.action === selectedAction;
+ chip.style.background = isActive ? C.brandSoft : 'transparent';
+ chip.style.color = isActive ? C.brand : C.ink;
+ });
+ // Position above the bar
+ const barRect = barEl.getBoundingClientRect();
+ const pickerH = 90; // approximate
+ let top = barRect.top - pickerH - 6;
+ if (top < 8) top = barRect.bottom + 6;
+ Object.assign(pickerEl.style, {
+ top: top + 'px', left: barRect.left + 'px',
+ display: 'block',
+ });
+ requestAnimationFrame(() => {
+ pickerEl.style.opacity = '1';
+ pickerEl.style.transform = 'scale(1) translateY(0)';
+ });
+ }
+
+ function hideActionPicker() {
+ if (!pickerEl) return;
+ pickerEl.style.opacity = '0';
+ pickerEl.style.transform = 'scale(0.96) translateY(4px)';
+ setTimeout(() => { if (pickerEl) pickerEl.style.display = 'none'; }, 180);
+ }
+
+ // ---------------------------------------------------------------------------
+ // Variant cycling in DOM
+ // ---------------------------------------------------------------------------
+
+ function showVariantInDOM(sessionId, num) {
+ const wrapper = document.querySelector('[data-impeccable-variants="' + sessionId + '"]');
+ if (!wrapper) return;
+ for (const child of wrapper.children) {
+ const v = child.dataset ? child.dataset.impeccableVariant : null;
+ if (!v) continue;
+ child.style.display = (v === String(num)) ? '' : 'none';
+ }
+ }
+
+ /**
+ * No-HMR fallback: fetch the raw source file from the live server,
+ * parse it, extract the variant wrapper, and inject it into the live DOM.
+ * This works even when the dev server caches HTML (Bun, static servers).
+ */
+ function injectVariantsFromSource(filePath, sessionId) {
+ const url = 'http://localhost:' + PORT + '/source?token=' + TOKEN + '&path=' + encodeURIComponent(filePath);
+ fetch(url)
+ .then(r => { if (!r.ok) throw new Error(r.status); return r.text(); })
+ .then(html => {
+ // Parse the raw source HTML
+ const parser = new DOMParser();
+ const doc = parser.parseFromString(html, 'text/html');
+ const srcWrapper = doc.querySelector('[data-impeccable-variants="' + sessionId + '"]');
+ if (!srcWrapper) {
+ console.error('[impeccable] Variant wrapper not found in source file.');
+ return;
+ }
+
+ // Find the original element in the live DOM.
+ // The original is inside the wrapper in the source. We find the
+ // corresponding element in the live DOM by matching the first child's
+ // tag + classes from the original snapshot.
+ const origContent = srcWrapper.querySelector('[data-impeccable-variant="original"] > :first-child');
+ if (!origContent) return;
+
+ const tag = origContent.tagName.toLowerCase();
+ const cls = origContent.className;
+ let liveEl = null;
+ if (origContent.id) {
+ liveEl = document.getElementById(origContent.id);
+ } else if (cls) {
+ // Find by tag + exact class match
+ const candidates = document.querySelectorAll(tag + '.' + cls.split(' ')[0]);
+ for (const c of candidates) {
+ if (c.className === cls && !own(c)) { liveEl = c; break; }
+ }
+ }
+
+ if (!liveEl) {
+ console.error('[impeccable] Could not find original element in live DOM.');
+ return;
+ }
+
+ // Replace the live element with the full wrapper from source
+ const wrapper = srcWrapper.cloneNode(true);
+ liveEl.parentElement.replaceChild(wrapper, liveEl);
+
+ // Update state: count variants, show the first one
+ 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);
+
+ // Update selectedElement to the visible variant's content
+ const visEl = wrapper.querySelector('[data-impeccable-variant="1"] > :first-child');
+ selectedElement = visEl || wrapper.parentElement;
+
+ state = 'CYCLING';
+ updateBarContent('cycling');
+ saveSession();
+ console.log('[impeccable] Injected ' + arrivedVariants + ' variants from source file.');
+ })
+ .catch(err => {
+ console.error('[impeccable] Failed to fetch source:', err);
+ showToast('Could not load variants. Try refreshing the page.', 5000);
+ });
+ }
+
+ function cycleVariant(dir) {
+ const next = visibleVariant + dir;
+ if (next < 1 || next > arrivedVariants) return;
+ visibleVariant = next;
+ showVariantInDOM(currentSessionId, next);
+ updateSelectedElement();
+ updateBarContent('cycling');
+ saveSession();
+ }
+
+ function updateSelectedElement() {
+ if (!currentSessionId) return;
+ const wrapper = document.querySelector('[data-impeccable-variants="' + currentSessionId + '"]');
+ if (!wrapper) return;
+ const visEl = wrapper.querySelector('[data-impeccable-variant="' + visibleVariant + '"] > :first-child');
+ if (visEl) selectedElement = visEl;
+ }
+
+ // ---------------------------------------------------------------------------
+ // MutationObserver for progressive variant reveal
+ // ---------------------------------------------------------------------------
+
+ function startVariantObserver(sessionId) {
+ let updating = false; // re-entrancy guard
+
+ const obs = new MutationObserver((mutations) => {
+ if (updating) return;
+
+ // Only react to mutations that add nodes with data-impeccable-variant,
+ // or mutations inside the variant wrapper. Ignore our own bar/UI changes.
+ let dominated = false;
+ for (const m of mutations) {
+ if (m.target.closest?.('[data-impeccable-variants]')) { dominated = true; break; }
+ for (const n of m.addedNodes) {
+ if (n.nodeType === 1 && (n.dataset?.impeccableVariants || n.dataset?.impeccableVariant)) {
+ dominated = true; break;
+ }
+ }
+ if (dominated) break;
+ }
+ if (!dominated) return;
+
+ const wrapper = document.querySelector('[data-impeccable-variants="' + sessionId + '"]');
+ if (!wrapper) return;
+
+ const variants = wrapper.querySelectorAll('[data-impeccable-variant]:not([data-impeccable-variant="original"])');
+ const count = variants.length;
+
+ // Nothing new
+ if (count <= arrivedVariants) return;
+
+ updating = true;
+ arrivedVariants = count;
+ if (visibleVariant === 0 && arrivedVariants > 0) {
+ visibleVariant = 1;
+ showVariantInDOM(sessionId, 1);
+ }
+
+ const expected = parseInt(wrapper.dataset.impeccableVariantCount || '0');
+ if (expected > 0) expectedVariants = expected;
+
+ if (arrivedVariants >= expectedVariants && expectedVariants > 0) {
+ state = 'CYCLING';
+ updateBarContent('cycling');
+ } else if (state === 'GENERATING') {
+ updateBarContent('generating');
+ }
+ saveSession();
+ updating = false;
+ });
+
+ obs.observe(document.body, { childList: true, subtree: true });
+ return obs;
+ }
+
+ // ---------------------------------------------------------------------------
+ // Bar scroll tracking
+ // ---------------------------------------------------------------------------
+
+ function startScrollTracking() {
+ function tick() {
+ if (state === 'CONFIGURING' || state === 'GENERATING' || state === 'CYCLING') {
+ positionBar();
+ showHighlight(selectedElement);
+ }
+ scrollRaf = requestAnimationFrame(tick);
+ }
+ scrollRaf = requestAnimationFrame(tick);
+ }
+
+ function stopScrollTracking() {
+ if (scrollRaf) { cancelAnimationFrame(scrollRaf); scrollRaf = null; }
+ }
+
+ // ---------------------------------------------------------------------------
+ // SSE (server→browser) + fetch POST (browser→server)
+ // Zero-dependency replacement for WebSocket.
+ // ---------------------------------------------------------------------------
+
+ let evtSource = null;
+
+ function connectSSE() {
+ evtSource = new EventSource('http://localhost:' + PORT + '/events?token=' + TOKEN);
+
+ evtSource.onmessage = (e) => {
+ let msg; try { msg = JSON.parse(e.data); } catch { return; }
+ switch (msg.type) {
+ case 'connected':
+ hasProjectContext = !!msg.hasProjectContext;
+ if (!hasProjectContext) showToast('No .impeccable.md found. Variants will be brand-agnostic.', 6000);
+ console.log('[impeccable] Live mode connected.');
+ if (state === 'IDLE') state = 'PICKING';
+ break;
+ case 'done':
+ if (state === 'SAVING') {
+ state = 'CONFIRMED';
+ updateBarContent('confirmed');
+ setTimeout(() => {
+ hideBar();
+ hideHighlight();
+ stopScrollTracking();
+ if (variantObserver) { variantObserver.disconnect(); variantObserver = null; }
+ clearSession();
+ selectedElement = null;
+ currentSessionId = null;
+ selectedAction = 'impeccable';
+ state = 'PICKING';
+ }, 1800);
+ return;
+ }
+ if (arrivedVariants === 0 && expectedVariants > 0 && msg.file) {
+ console.log('[impeccable] No HMR detected. Fetching variants from source file...');
+ injectVariantsFromSource(msg.file, currentSessionId);
+ return;
+ }
+ state = 'CYCLING';
+ updateBarContent('cycling');
+ break;
+ case 'error':
+ console.error('[impeccable] Error:', msg.message);
+ showToast('Error: ' + msg.message, 5000);
+ hideBar();
+ state = 'PICKING';
+ break;
+ }
+ };
+
+ evtSource.onerror = () => {
+ // EventSource auto-reconnects. Log once.
+ console.log('[impeccable] SSE connection lost. Reconnecting...');
+ };
+ }
+
+ function sendEvent(msg) {
+ msg.token = TOKEN;
+ 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));
+ }
+
+ // ---------------------------------------------------------------------------
+ // Event handlers
+ // ---------------------------------------------------------------------------
+
+ function handleMouseMove(e) {
+ if (state !== 'PICKING') return;
+ const target = document.elementFromPoint(e.clientX, e.clientY);
+ if (!target || !pickable(target) || target === hoveredElement) return;
+ hoveredElement = target;
+ showHighlight(target);
+ }
+
+ function handleClick(e) {
+ // Close action picker on any outside click
+ if (pickerEl?.style.display !== 'none' && !own(e.target)) {
+ hideActionPicker();
+ }
+ if (state !== 'PICKING') return;
+ if (own(e.target)) return;
+ if (!hoveredElement || !pickable(hoveredElement)) return;
+ e.preventDefault();
+ e.stopPropagation();
+ selectedElement = hoveredElement;
+ state = 'CONFIGURING';
+ showHighlight(selectedElement);
+ showBar('configure');
+ startScrollTracking();
+ }
+
+ function handleKeyDown(e) {
+ if (e.key === 'Escape') {
+ e.preventDefault();
+ if (pickerEl?.style.display !== 'none') { hideActionPicker(); return; }
+ if (state === 'CONFIGURING') { hideBar(); stopScrollTracking(); state = 'PICKING'; return; }
+ if (state === 'CYCLING') { handleDiscard(); return; }
+ if (state === 'SAVING' || state === 'CONFIRMED') return; // don't interrupt
+ if (state === 'PICKING') { hideHighlight(); state = 'IDLE'; return; }
+ }
+
+ if (state === 'PICKING' && hoveredElement) {
+ let next = null;
+ if (e.key === 'ArrowDown' && !e.shiftKey) {
+ next = hoveredElement.nextElementSibling;
+ while (next && !pickable(next)) next = next.nextElementSibling;
+ } else if (e.key === 'ArrowUp' && !e.shiftKey) {
+ next = hoveredElement.previousElementSibling;
+ while (next && !pickable(next)) next = next.previousElementSibling;
+ } else if (e.key === 'ArrowUp' && e.shiftKey) {
+ next = hoveredElement.parentElement;
+ if (next && !pickable(next)) next = null;
+ } else if (e.key === 'ArrowDown' && e.shiftKey) {
+ next = hoveredElement.firstElementChild;
+ while (next && !pickable(next)) next = next.nextElementSibling;
+ } else if (e.key === 'Enter') {
+ e.preventDefault();
+ selectedElement = hoveredElement;
+ state = 'CONFIGURING';
+ showHighlight(selectedElement);
+ showBar('configure');
+ startScrollTracking();
+ return;
+ }
+ if (next) {
+ e.preventDefault();
+ hoveredElement = next;
+ showHighlight(next);
+ next.scrollIntoView({ block: 'nearest', behavior: 'smooth' });
+ }
+ return;
+ }
+
+ if (state === 'CYCLING') {
+ if (e.key === 'ArrowLeft') { e.preventDefault(); cycleVariant(-1); }
+ if (e.key === 'ArrowRight') { e.preventDefault(); cycleVariant(1); }
+ if (e.key === 'Enter') { e.preventDefault(); handleAccept(); }
+ }
+ }
+
+ function handleGo() {
+ if (!selectedElement || state !== 'CONFIGURING') return;
+ const input = document.getElementById(PREFIX + '-input');
+ const prompt = input ? input.value.trim() : '';
+
+ currentSessionId = id8();
+ expectedVariants = selectedCount;
+ arrivedVariants = 0;
+ visibleVariant = 0;
+
+ sendEvent({
+ type: 'generate', id: currentSessionId,
+ action: selectedAction,
+ freeformPrompt: prompt || undefined,
+ count: selectedCount,
+ pageUrl: location.pathname,
+ element: extractContext(selectedElement),
+ });
+
+ state = 'GENERATING';
+ showBar('generating');
+ saveSession();
+ if (variantObserver) variantObserver.disconnect();
+ variantObserver = startVariantObserver(currentSessionId);
+ }
+
+ function handleAccept() {
+ if (!currentSessionId || arrivedVariants === 0) return;
+ sendEvent({ type: 'accept', id: currentSessionId, variantId: String(visibleVariant) });
+ markSessionHandled();
+ state = 'SAVING';
+ updateBarContent('saving');
+ // Don't cleanup yet — wait for the "done" WS message to show confirmation
+ }
+
+ function handleDiscard() {
+ if (!currentSessionId) return;
+ sendEvent({ type: 'discard', id: currentSessionId });
+ markSessionHandled();
+ state = 'SAVING';
+ updateBarContent('saving');
+ // Wait for "done" WS message to show confirmation and dismiss
+ }
+
+ // ---------------------------------------------------------------------------
+ // Session persistence via localStorage
+ // ---------------------------------------------------------------------------
+ // Survives page reloads, browser close/reopen, HMR, and accidental refreshes.
+
+ const LS_KEY = PREFIX + '-session';
+
+ function saveSession() {
+ if (!currentSessionId) return;
+ 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 */ }
+ }
+
+ function loadSession() {
+ try {
+ const raw = localStorage.getItem(LS_KEY);
+ return raw ? JSON.parse(raw) : null;
+ } catch { return null; }
+ }
+
+ function clearSession() {
+ try { localStorage.removeItem(LS_KEY); } catch {}
+ }
+
+ /** Mark session as handled (accepted/discarded). The agent will clean up
+ * the source, but until it does the wrapper is still in the HTML. This
+ * prevents resumeSession from picking it up again after reload. */
+ function markSessionHandled() {
+ if (!currentSessionId) return;
+ try {
+ localStorage.setItem(LS_KEY + '-handled', currentSessionId);
+ } catch {}
+ }
+
+ function isSessionHandled(id) {
+ try {
+ return localStorage.getItem(LS_KEY + '-handled') === id;
+ } catch { return false; }
+ }
+
+ function clearHandled() {
+ try { localStorage.removeItem(LS_KEY + '-handled'); } catch {}
+ }
+
+ function cleanup() {
+ hideBar();
+ hideHighlight();
+ stopScrollTracking();
+ if (variantObserver) { variantObserver.disconnect(); variantObserver = null; }
+ clearSession();
+ selectedElement = null;
+ currentSessionId = null;
+ selectedAction = 'impeccable';
+ state = 'PICKING';
+ }
+
+ // ---------------------------------------------------------------------------
+ // Toast
+ // ---------------------------------------------------------------------------
+
+ function showToast(message, duration) {
+ if (toastEl) toastEl.remove();
+ toastEl = el('div', {
+ position: 'fixed', bottom: '16px', left: '50%',
+ transform: 'translateX(-50%) translateY(8px)',
+ background: C.ink, color: C.white,
+ fontFamily: FONT, fontSize: '12px',
+ padding: '8px 16px', borderRadius: '8px',
+ zIndex: Z.toast, opacity: '0',
+ transition: 'opacity 0.25s ' + EASE + ', transform 0.25s ' + EASE,
+ pointerEvents: 'none', maxWidth: '420px', textAlign: 'center',
+ });
+ toastEl.id = PREFIX + '-toast';
+ toastEl.textContent = message;
+ document.body.appendChild(toastEl);
+ requestAnimationFrame(() => {
+ toastEl.style.opacity = '1';
+ toastEl.style.transform = 'translateX(-50%) translateY(0)';
+ });
+ setTimeout(() => {
+ if (toastEl) {
+ toastEl.style.opacity = '0';
+ toastEl.style.transform = 'translateX(-50%) translateY(8px)';
+ setTimeout(() => { if (toastEl) { toastEl.remove(); toastEl = null; } }, 250);
+ }
+ }, duration);
+ }
+
+ // ---------------------------------------------------------------------------
+ // Init
+ // ---------------------------------------------------------------------------
+
+ // Resume an active variant session after HMR/page reload.
+ // If a [data-impeccable-variants] wrapper exists in the DOM, the agent wrote
+ // variants before HMR fired. Pick up where we left off.
+ function resumeSession() {
+ const wrapper = document.querySelector('[data-impeccable-variants]');
+ if (!wrapper) { clearSession(); clearHandled(); return false; }
+
+ const sessionId = wrapper.dataset.impeccableVariants;
+
+ // Don't resume if this session was already accepted/discarded
+ if (isSessionHandled(sessionId)) return false;
+
+ currentSessionId = sessionId;
+ expectedVariants = parseInt(wrapper.dataset.impeccableVariantCount || '0');
+ const variants = wrapper.querySelectorAll('[data-impeccable-variant]:not([data-impeccable-variant="original"])');
+ arrivedVariants = variants.length;
+
+ // Restore visible variant from localStorage if available, else default to 1
+ const saved = loadSession();
+ visibleVariant = (saved && saved.id === sessionId && saved.visible > 0 && saved.visible <= arrivedVariants)
+ ? saved.visible : (arrivedVariants > 0 ? 1 : 0);
+
+ // Find the visible variant's content element for highlight positioning
+ const visEl = wrapper.querySelector('[data-impeccable-variant="' + visibleVariant + '"] > :first-child');
+ selectedElement = visEl || wrapper.parentElement;
+
+ // Set display state BEFORE starting observer (avoid triggering it)
+ if (visibleVariant > 0) showVariantInDOM(currentSessionId, visibleVariant);
+
+ state = arrivedVariants >= expectedVariants ? 'CYCLING' : 'GENERATING';
+ showBar(state === 'CYCLING' ? 'cycling' : 'generating');
+ startScrollTracking();
+ saveSession();
+
+ // Start observing for more variants AFTER initial setup
+ if (variantObserver) variantObserver.disconnect();
+ variantObserver = startVariantObserver(currentSessionId);
+ return true;
+ }
+
+ function init() {
+ initHighlight();
+ initBar();
+ initActionPicker();
+ document.addEventListener('mousemove', handleMouseMove, true);
+ document.addEventListener('click', handleClick, true);
+ document.addEventListener('keydown', handleKeyDown, true);
+ connectSSE();
+
+ // Check for an active session to resume (variant wrapper already in DOM after HMR)
+ if (!resumeSession()) {
+ console.log('[impeccable] Live variant mode ready. Hover over elements to pick one.');
+ } else {
+ console.log('[impeccable] Resumed active variant session ' + currentSessionId + ' (' + arrivedVariants + '/' + expectedVariants + ' variants).');
+ }
+ }
+
+ if (document.readyState === 'loading') {
+ document.addEventListener('DOMContentLoaded', init);
+ } else {
+ init();
+ }
+})();
diff --git a/.kiro/skills/impeccable/scripts/live-poll.mjs b/.kiro/skills/impeccable/scripts/live-poll.mjs
new file mode 100644
index 000000000..52859416c
--- /dev/null
+++ b/.kiro/skills/impeccable/scripts/live-poll.mjs
@@ -0,0 +1,123 @@
+/**
+ * CLI client for the live variant mode poll/reply protocol.
+ *
+ * Usage:
+ * npx impeccable poll # Block until browser event, print JSON
+ * npx impeccable poll --timeout=60000 # Custom timeout (ms)
+ * npx impeccable poll --reply <id> done # Reply "done" to event <id>
+ * npx impeccable poll --reply <id> error "msg" # Reply with error
+ */
+
+import fs from 'node:fs';
+import path from 'node:path';
+import os from 'node:os';
+
+const LIVE_PID_FILE = path.join(os.tmpdir(), 'impeccable-live.json');
+
+function readServerInfo() {
+ try {
+ return JSON.parse(fs.readFileSync(LIVE_PID_FILE, 'utf-8'));
+ } catch {
+ console.error('No running live server found. Start one with: npx impeccable live');
+ process.exit(1);
+ }
+}
+
+export async function pollCli() {
+ const args = process.argv.slice(2);
+
+ if (args.includes('--help') || args.includes('-h')) {
+ console.log(`Usage: impeccable poll [options]
+
+Wait for a browser event from the live variant server, or reply to one.
+
+Modes:
+ poll Block until a browser event arrives, print JSON
+ poll --reply <id> done Reply "done" to event <id>
+ poll --reply <id> error "msg" Reply with an error message
+
+Options:
+ --timeout=MS Poll timeout in milliseconds (default: 120000)
+ --help Show this help message`);
+ process.exit(0);
+ }
+
+ const info = readServerInfo();
+ const base = `http://localhost:${info.port}`;
+
+ // Reply mode: npx impeccable poll --reply <id> <status> [--file path] [message]
+ const replyIdx = args.indexOf('--reply');
+ if (replyIdx !== -1) {
+ const id = args[replyIdx + 1];
+ const status = args[replyIdx + 2] || 'done';
+ const fileIdx = args.indexOf('--file');
+ const filePath = fileIdx !== -1 && fileIdx + 1 < args.length ? args[fileIdx + 1] : undefined;
+ // Message is any remaining positional arg that isn't a flag
+ const message = args.find((a, i) => i > replyIdx + 2 && !a.startsWith('--') && i !== fileIdx + 1) || undefined;
+
+ if (!id) {
+ console.error('Usage: npx impeccable poll --reply <id> <status> [--file path] [message]');
+ process.exit(1);
+ }
+
+ 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);
+ }
+
+ // Success — silent exit (agent doesn't need output for replies)
+ } catch (err) {
+ if (err.cause?.code === 'ECONNREFUSED') {
+ console.error('Live server not running. Start one with: npx impeccable live');
+ } else {
+ console.error('Reply failed:', err.message);
+ }
+ process.exit(1);
+ }
+ return;
+ }
+
+ // Poll mode: block until browser event
+ const timeoutArg = args.find(a => a.startsWith('--timeout='));
+ const timeout = timeoutArg ? parseInt(timeoutArg.split('=')[1], 10) : 120000;
+
+ try {
+ const res = await fetch(`${base}/poll?token=${info.token}&timeout=${timeout}`);
+
+ if (res.status === 401) {
+ console.error('Authentication failed. The server token may have changed.');
+ console.error('Try restarting: npx impeccable live stop && npx impeccable live');
+ process.exit(1);
+ }
+
+ if (!res.ok) {
+ console.error(`Poll failed: ${res.status} ${res.statusText}`);
+ process.exit(1);
+ }
+
+ const event = await res.json();
+ // Print the event as JSON — the agent reads this from stdout
+ console.log(JSON.stringify(event));
+ } catch (err) {
+ if (err.cause?.code === 'ECONNREFUSED') {
+ console.error('Live server not running. Start one with: npx impeccable live');
+ } else {
+ console.error('Poll failed:', err.message);
+ }
+ process.exit(1);
+ }
+}
diff --git a/.kiro/skills/impeccable/scripts/live-server.mjs b/.kiro/skills/impeccable/scripts/live-server.mjs
new file mode 100644
index 000000000..d436bad58
--- /dev/null
+++ b/.kiro/skills/impeccable/scripts/live-server.mjs
@@ -0,0 +1,416 @@
+#!/usr/bin/env node
+/**
+ * Live variant mode server (self-contained, zero dependencies).
+ *
+ * Serves the browser script (/live.js), the detection overlay (/detect.js),
+ * uses Server-Sent Events (SSE) for server→browser push, and HTTP POST for
+ * browser→server events. Agent communicates via HTTP long-poll (/poll).
+ *
+ * Usage:
+ * node <scripts_path>/live-server.mjs # start
+ * node <scripts_path>/live-server.mjs stop # stop
+ * node <scripts_path>/live-server.mjs --help
+ */
+
+import http from 'node:http';
+import { randomUUID } from 'node:crypto';
+import fs from 'node:fs';
+import path from 'node:path';
+import os from 'node:os';
+import net from 'node:net';
+import { fileURLToPath } from 'node:url';
+
+const __dirname = path.dirname(fileURLToPath(import.meta.url));
+const LIVE_PID_FILE = path.join(os.tmpdir(), 'impeccable-live.json');
+const DEFAULT_POLL_TIMEOUT = 120_000;
+
+// ---------------------------------------------------------------------------
+// Port detection
+// ---------------------------------------------------------------------------
+
+async function findOpenPort(start = 8400) {
+ return new Promise((resolve) => {
+ const srv = net.createServer();
+ srv.listen(start, '127.0.0.1', () => {
+ const port = srv.address().port;
+ srv.close(() => resolve(port));
+ });
+ srv.on('error', () => resolve(findOpenPort(start + 1)));
+ });
+}
+
+// ---------------------------------------------------------------------------
+// Session state
+// ---------------------------------------------------------------------------
+
+const state = {
+ token: null,
+ port: null,
+ sseClients: new Set(), // SSE response objects (server→browser push)
+ pendingEvents: [], // browser events waiting for agent poll
+ pendingPolls: [], // agent poll callbacks waiting for browser events
+ exitTimer: null,
+};
+
+function enqueueEvent(event) {
+ if (state.pendingPolls.length > 0) {
+ state.pendingPolls.shift()(event);
+ } else {
+ state.pendingEvents.push(event);
+ }
+}
+
+/** Push a message to all connected SSE clients. */
+function broadcast(msg) {
+ const data = 'data: ' + JSON.stringify(msg) + '\n\n';
+ for (const res of state.sseClients) {
+ try { res.write(data); } catch { /* client gone */ }
+ }
+}
+
+// ---------------------------------------------------------------------------
+// Load scripts
+// ---------------------------------------------------------------------------
+
+function loadBrowserScripts() {
+ // Detection script: look relative to the skill scripts dir, then fall back
+ // to the npm package location (src/detect-antipatterns-browser.js)
+ const detectPaths = [
+ path.join(__dirname, '..', '..', '..', '..', 'src', 'detect-antipatterns-browser.js'),
+ path.join(process.cwd(), 'node_modules', 'impeccable', 'src', 'detect-antipatterns-browser.js'),
+ ];
+ let detectScript = '';
+ for (const p of detectPaths) {
+ try { detectScript = fs.readFileSync(p, 'utf-8'); break; } catch { /* try next */ }
+ }
+
+ const livePath = path.join(__dirname, 'live-browser.js');
+ let liveScript = '';
+ try {
+ liveScript = fs.readFileSync(livePath, 'utf-8');
+ } catch {
+ process.stderr.write('Error: live-browser.js not found at ' + livePath + '\n');
+ process.exit(1);
+ }
+
+ return { detectScript, liveScript };
+}
+
+function hasProjectContext() {
+ try {
+ fs.accessSync(path.join(process.cwd(), '.impeccable.md'), fs.constants.R_OK);
+ return true;
+ } catch { return false; }
+}
+
+// ---------------------------------------------------------------------------
+// Validation (inline — no external import needed for self-contained script)
+// ---------------------------------------------------------------------------
+
+const VISUAL_ACTIONS = [
+ 'impeccable', 'bolder', 'quieter', 'distill', 'polish', 'typeset',
+ 'colorize', 'layout', 'adapt', 'animate', 'delight', 'overdrive',
+];
+
+function validateEvent(msg) {
+ if (!msg || typeof msg !== 'object' || !msg.type) return 'Missing or invalid message';
+ switch (msg.type) {
+ case 'generate':
+ if (!msg.id || typeof msg.id !== 'string') return 'generate: missing id';
+ if (!msg.action || !VISUAL_ACTIONS.includes(msg.action)) return 'generate: invalid action';
+ if (!Number.isInteger(msg.count) || msg.count < 1 || msg.count > 8) return 'generate: count must be 1-8';
+ if (!msg.element || !msg.element.outerHTML) return 'generate: missing element context';
+ return null;
+ case 'accept':
+ if (!msg.id) return 'accept: missing id';
+ if (!msg.variantId) return 'accept: missing variantId';
+ return null;
+ case 'discard':
+ return msg.id ? null : 'discard: missing id';
+ case 'exit':
+ return null;
+ default:
+ return 'Unknown event type: ' + msg.type;
+ }
+}
+
+// ---------------------------------------------------------------------------
+// HTTP request handler
+// ---------------------------------------------------------------------------
+
+function createRequestHandler({ detectScript, liveScriptWithToken }) {
+ return (req, res) => {
+ const url = new URL(req.url, `http://localhost:${state.port}`);
+ res.setHeader('Access-Control-Allow-Origin', '*');
+ res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS');
+ res.setHeader('Access-Control-Allow-Headers', 'Content-Type');
+ if (req.method === 'OPTIONS') { res.writeHead(204); res.end(); return; }
+
+ const p = url.pathname;
+
+ // --- Scripts ---
+ if (p === '/live.js') {
+ res.writeHead(200, { 'Content-Type': 'application/javascript' });
+ res.end(liveScriptWithToken);
+ return;
+ }
+ if (p === '/detect.js' || p === '/') {
+ if (!detectScript) { res.writeHead(404); res.end('Not available'); return; }
+ res.writeHead(200, { 'Content-Type': 'application/javascript' });
+ res.end(detectScript);
+ return;
+ }
+
+ // --- Health ---
+ if (p === '/health') {
+ res.writeHead(200, { 'Content-Type': 'application/json' });
+ res.end(JSON.stringify({
+ status: 'ok', port: state.port, mode: 'variant',
+ hasProjectContext: hasProjectContext(),
+ connectedClients: state.sseClients.size,
+ }));
+ return;
+ }
+
+ // --- Source file (no-HMR fallback) ---
+ if (p === '/source') {
+ const token = url.searchParams.get('token');
+ if (token !== state.token) { res.writeHead(401); res.end('Unauthorized'); return; }
+ const filePath = url.searchParams.get('path');
+ if (!filePath || filePath.includes('..')) { res.writeHead(400); res.end('Bad path'); return; }
+ const absPath = path.resolve(process.cwd(), filePath);
+ if (!absPath.startsWith(process.cwd())) { res.writeHead(403); res.end('Forbidden'); return; }
+ try {
+ res.writeHead(200, { 'Content-Type': 'text/html; charset=utf-8' });
+ res.end(fs.readFileSync(absPath, 'utf-8'));
+ } catch { res.writeHead(404); res.end('File not found'); }
+ return;
+ }
+
+ // --- SSE: server→browser push (replaces WebSocket) ---
+ if (p === '/events' && req.method === 'GET') {
+ const token = url.searchParams.get('token');
+ if (token !== state.token) { res.writeHead(401); res.end('Unauthorized'); return; }
+ res.writeHead(200, {
+ 'Content-Type': 'text/event-stream',
+ 'Cache-Control': 'no-cache',
+ 'Connection': 'keep-alive',
+ });
+ res.write('data: ' + JSON.stringify({
+ type: 'connected',
+ hasProjectContext: hasProjectContext(),
+ }) + '\n\n');
+
+ state.sseClients.add(res);
+ clearTimeout(state.exitTimer);
+
+ req.on('close', () => {
+ state.sseClients.delete(res);
+ if (state.sseClients.size === 0) {
+ clearTimeout(state.exitTimer);
+ state.exitTimer = setTimeout(() => {
+ if (state.sseClients.size === 0) enqueueEvent({ type: 'exit' });
+ }, 8000);
+ }
+ });
+ return;
+ }
+
+ // --- Browser→server events (replaces WebSocket messages) ---
+ if (p === '/events' && req.method === 'POST') {
+ let body = '';
+ req.on('data', (c) => { body += c; });
+ req.on('end', () => {
+ let msg;
+ try { msg = JSON.parse(body); } catch {
+ res.writeHead(400, { 'Content-Type': 'application/json' });
+ res.end(JSON.stringify({ error: 'Invalid JSON' }));
+ return;
+ }
+ if (msg.token !== state.token) {
+ res.writeHead(401, { 'Content-Type': 'application/json' });
+ res.end(JSON.stringify({ error: 'Unauthorized' }));
+ return;
+ }
+ const error = validateEvent(msg);
+ if (error) {
+ res.writeHead(400, { 'Content-Type': 'application/json' });
+ res.end(JSON.stringify({ error }));
+ return;
+ }
+ enqueueEvent(msg);
+ res.writeHead(200, { 'Content-Type': 'application/json' });
+ res.end(JSON.stringify({ ok: true }));
+ });
+ return;
+ }
+
+ // --- Stop ---
+ if (p === '/stop') {
+ const token = url.searchParams.get('token');
+ if (token !== state.token) { res.writeHead(401); res.end('Unauthorized'); return; }
+ res.writeHead(200, { 'Content-Type': 'text/plain' });
+ res.end('stopping');
+ shutdown();
+ return;
+ }
+
+ // --- Agent poll ---
+ if (p === '/poll' && req.method === 'GET') {
+ handlePollGet(req, res, url);
+ return;
+ }
+ if (p === '/poll' && req.method === 'POST') {
+ handlePollPost(req, res);
+ return;
+ }
+
+ res.writeHead(404); res.end('Not found');
+ };
+}
+
+// ---------------------------------------------------------------------------
+// Agent poll endpoints (unchanged from WS version)
+// ---------------------------------------------------------------------------
+
+function handlePollGet(req, res, url) {
+ 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 timeout = parseInt(url.searchParams.get('timeout') || DEFAULT_POLL_TIMEOUT, 10);
+ if (state.pendingEvents.length > 0) {
+ res.writeHead(200, { 'Content-Type': 'application/json' });
+ res.end(JSON.stringify(state.pendingEvents.shift()));
+ return;
+ }
+ const timer = setTimeout(() => {
+ const idx = state.pendingPolls.indexOf(resolve);
+ if (idx !== -1) state.pendingPolls.splice(idx, 1);
+ res.writeHead(200, { 'Content-Type': 'application/json' });
+ res.end(JSON.stringify({ type: 'timeout' }));
+ }, timeout);
+ function resolve(event) {
+ clearTimeout(timer);
+ res.writeHead(200, { 'Content-Type': 'application/json' });
+ res.end(JSON.stringify(event));
+ }
+ state.pendingPolls.push(resolve);
+ req.on('close', () => {
+ clearTimeout(timer);
+ const idx = state.pendingPolls.indexOf(resolve);
+ if (idx !== -1) state.pendingPolls.splice(idx, 1);
+ });
+}
+
+function handlePollPost(req, res) {
+ let body = '';
+ req.on('data', (c) => { body += c; });
+ req.on('end', () => {
+ let msg;
+ try { msg = JSON.parse(body); } catch {
+ res.writeHead(400, { 'Content-Type': 'application/json' });
+ res.end(JSON.stringify({ error: 'Invalid JSON' }));
+ return;
+ }
+ if (msg.token !== state.token) {
+ res.writeHead(401, { 'Content-Type': 'application/json' });
+ res.end(JSON.stringify({ error: 'Unauthorized' }));
+ return;
+ }
+ // Forward the reply to the browser via SSE
+ broadcast({ type: msg.type || 'done', id: msg.id, message: msg.message, file: msg.file, data: msg.data });
+ res.writeHead(200, { 'Content-Type': 'application/json' });
+ res.end(JSON.stringify({ ok: true }));
+ });
+}
+
+// ---------------------------------------------------------------------------
+// Lifecycle
+// ---------------------------------------------------------------------------
+
+let httpServer = null;
+
+function shutdown() {
+ try { fs.unlinkSync(LIVE_PID_FILE); } catch {}
+ for (const res of state.sseClients) { try { res.end(); } catch {} }
+ state.sseClients.clear();
+ for (const resolve of state.pendingPolls) resolve({ type: 'exit' });
+ state.pendingPolls.length = 0;
+ if (httpServer) httpServer.close();
+ process.exit(0);
+}
+
+// ---------------------------------------------------------------------------
+// Main
+// ---------------------------------------------------------------------------
+
+const args = process.argv.slice(2);
+
+if (args.includes('--help') || args.includes('-h')) {
+ console.log(`Usage: node live-server.mjs [options]
+
+Start the live variant mode server (zero dependencies).
+
+Commands:
+ (default) Start the server
+ stop Stop a running server
+
+Options:
+ --port=PORT Use a specific port (default: auto-detect starting at 8400)
+ --help Show this help
+
+Endpoints:
+ /live.js Browser script (element picker + variant cycling)
+ /detect.js Detection overlay (backwards compatible)
+ /events SSE stream (server→browser) + POST (browser→server)
+ /poll Long-poll for agent CLI
+ /source Raw source file reader (no-HMR fallback)
+ /health Health check`);
+ process.exit(0);
+}
+
+if (args.includes('stop')) {
+ try {
+ const info = JSON.parse(fs.readFileSync(LIVE_PID_FILE, 'utf-8'));
+ 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 { console.log('No running live server found.'); }
+ process.exit(0);
+}
+
+// Check for existing session
+try {
+ const existing = JSON.parse(fs.readFileSync(LIVE_PID_FILE, 'utf-8'));
+ 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 {}
+
+state.token = randomUUID();
+const portArg = args.find(a => a.startsWith('--port='));
+state.port = portArg ? parseInt(portArg.split('=')[1], 10) : await findOpenPort();
+
+const { detectScript, liveScript } = loadBrowserScripts();
+const liveScriptWithToken =
+ `window.__IMPECCABLE_TOKEN__ = '${state.token}';\n` +
+ `window.__IMPECCABLE_PORT__ = ${state.port};\n` +
+ liveScript;
+
+httpServer = http.createServer(createRequestHandler({ detectScript, liveScriptWithToken }));
+
+httpServer.listen(state.port, '127.0.0.1', () => {
+ fs.writeFileSync(LIVE_PID_FILE, JSON.stringify({ 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`);
+ console.log(`Inject: <script src="${url}/live.js"><\/script>`);
+ console.log(`Stop: node ${path.basename(fileURLToPath(import.meta.url))} stop`);
+});
+
+process.on('SIGINT', shutdown);
+process.on('SIGTERM', shutdown);
diff --git a/.kiro/skills/impeccable/scripts/live-wrap.mjs b/.kiro/skills/impeccable/scripts/live-wrap.mjs
new file mode 100644
index 000000000..f1c838cdd
--- /dev/null
+++ b/.kiro/skills/impeccable/scripts/live-wrap.mjs
@@ -0,0 +1,298 @@
+/**
+ * CLI helper: find an element in source and wrap it in a variant container.
+ *
+ * Usage:
+ * npx impeccable wrap --id SESSION_ID --count N --query "hero-combined-left" [--file path]
+ *
+ * Searches project files for the element matching the query (class name, ID, or
+ * text snippet), wraps it with the variant scaffolding, and prints the file path
+ * + line range where the agent should insert variant HTML.
+ *
+ * This replaces 3-4 agent tool calls (grep + read + edit) with a single CLI call.
+ */
+
+import fs from 'node:fs';
+import path from 'node:path';
+
+const EXTENSIONS = ['.html', '.jsx', '.tsx', '.vue', '.svelte', '.astro'];
+
+export async function wrapCli() {
+ const args = process.argv.slice(2);
+
+ if (args.includes('--help') || args.includes('-h')) {
+ console.log(`Usage: impeccable wrap [options]
+
+Find an element in source and wrap it in a variant container.
+
+Required:
+ --id ID Session ID for the variant wrapper
+ --count N Number of expected variants (1-8)
+
+Element identification (at least one required):
+ --element-id ID HTML id attribute of the element
+ --classes A,B,C Comma-separated CSS class names
+ --tag TAG Tag name (div, section, etc.)
+ --query TEXT Fallback: raw text to search for
+
+Optional:
+ --file PATH Source file to search in (skips auto-detection)
+ --help Show this help message
+
+Output (JSON):
+ { file, startLine, endLine, insertLine, commentSyntax }
+
+The agent should insert variant HTML at insertLine.`);
+ process.exit(0);
+ }
+
+ const id = argVal(args, '--id');
+ const count = parseInt(argVal(args, '--count') || '3');
+ const elementId = argVal(args, '--element-id');
+ const classes = argVal(args, '--classes');
+ const tag = argVal(args, '--tag');
+ const query = argVal(args, '--query');
+ const filePath = argVal(args, '--file');
+
+ if (!id) { console.error('Missing --id'); process.exit(1); }
+ if (!elementId && !classes && !query) {
+ console.error('Need at least one of: --element-id, --classes, --query');
+ process.exit(1);
+ }
+
+ // Build search queries in priority order (most specific first)
+ const queries = buildSearchQueries(elementId, classes, tag, query);
+
+ // Find the source file
+ let targetFile = filePath;
+ let matchedQuery = null;
+ if (!targetFile) {
+ for (const q of queries) {
+ targetFile = findFileWithQuery(q, process.cwd());
+ if (targetFile) { matchedQuery = q; break; }
+ }
+ if (!targetFile) {
+ console.error(JSON.stringify({ error: 'Could not find element in project files. Searched for: ' + queries.join(', ') }));
+ process.exit(1);
+ }
+ } else {
+ matchedQuery = queries[0];
+ }
+
+ const content = fs.readFileSync(targetFile, 'utf-8');
+ const lines = content.split('\n');
+
+ // Find the element, trying each query in priority order
+ let match = null;
+ for (const q of queries) {
+ match = findElement(lines, q);
+ if (match) break;
+ }
+ if (!match) {
+ console.error(JSON.stringify({ error: 'Found file but could not locate element in ' + targetFile + '. Searched for: ' + queries.join(', ') }));
+ process.exit(1);
+ }
+
+ const { startLine, endLine } = match;
+ const commentSyntax = detectCommentSyntax(targetFile);
+ const indent = lines[startLine].match(/^(\s*)/)[1];
+
+ // Extract the original element
+ const originalLines = lines.slice(startLine, endLine + 1);
+ const originalIndented = originalLines.map(l => indent + ' ' + l.trimStart()).join('\n');
+
+ // Build the wrapper
+ const wrapperLines = [
+ indent + commentSyntax.open + ' impeccable-variants-start ' + id + ' ' + commentSyntax.close,
+ indent + '<div data-impeccable-variants="' + id + '" data-impeccable-variant-count="' + count + '" style="display: contents">',
+ indent + ' ' + commentSyntax.open + ' Original ' + commentSyntax.close,
+ indent + ' <div data-impeccable-variant="original">',
+ originalIndented,
+ indent + ' </div>',
+ indent + ' ' + commentSyntax.open + ' Variants: insert below this line ' + commentSyntax.close,
+ indent + '</div>',
+ indent + commentSyntax.open + ' impeccable-variants-end ' + id + ' ' + commentSyntax.close,
+ ];
+
+ // Replace the original element with the wrapper
+ const newLines = [
+ ...lines.slice(0, startLine),
+ ...wrapperLines,
+ ...lines.slice(endLine + 1),
+ ];
+ fs.writeFileSync(targetFile, newLines.join('\n'), 'utf-8');
+
+ // Calculate insert line (the "insert below this line" comment)
+ const insertLine = startLine + 6; // 0-indexed in the new file
+
+ console.log(JSON.stringify({
+ file: path.relative(process.cwd(), targetFile),
+ startLine: startLine + 1, // 1-indexed for the agent
+ endLine: startLine + wrapperLines.length, // 1-indexed
+ insertLine: insertLine + 1, // 1-indexed: where variants go
+ commentSyntax: commentSyntax,
+ originalLineCount: originalLines.length,
+ }));
+}
+
+// ---------------------------------------------------------------------------
+// Helpers
+// ---------------------------------------------------------------------------
+
+function argVal(args, flag) {
+ const idx = args.indexOf(flag);
+ return idx !== -1 && idx + 1 < args.length ? args[idx + 1] : null;
+}
+
+/**
+ * Build search query strings in priority order (most specific first).
+ * ID is most reliable, then specific class combos, then single classes, then raw query.
+ */
+function buildSearchQueries(elementId, classes, tag, query) {
+ const queries = [];
+
+ // 1. ID is the most specific
+ if (elementId) {
+ queries.push('id="' + elementId + '"');
+ }
+
+ // 2. Full class attribute match (for elements with distinctive multi-class combos)
+ if (classes) {
+ const classList = classes.split(',').map(c => c.trim()).filter(Boolean);
+ if (classList.length > 1) {
+ // Try the most distinctive class first (longest, most specific)
+ const sorted = [...classList].sort((a, b) => b.length - a.length);
+ queries.push('class="' + classList.join(' ') + '"'); // exact full match
+ queries.push(sorted[0]); // most distinctive single class
+ } else if (classList.length === 1) {
+ queries.push(classList[0]);
+ }
+ }
+
+ // 3. Tag + class combo (e.g., <section class="hero">)
+ if (tag && classes) {
+ const firstClass = classes.split(',')[0].trim();
+ queries.push('<' + tag + ' class="' + firstClass);
+ }
+
+ // 4. Raw fallback query
+ if (query) {
+ queries.push(query);
+ }
+
+ return queries;
+}
+
+function detectCommentSyntax(filePath) {
+ const ext = path.extname(filePath).toLowerCase();
+ if (ext === '.jsx' || ext === '.tsx') {
+ return { open: '{/*', close: '*/}' };
+ }
+ // HTML, Vue, Svelte, Astro all use HTML comments
+ return { open: '<!--', close: '-->' };
+}
+
+/**
+ * Search project files for the query string (class name, ID, etc.)
+ * Returns the first matching file path, or null.
+ */
+function findFileWithQuery(query, cwd) {
+ const searchDirs = ['src', 'app', 'pages', 'components', 'public', 'views', 'templates', '.'];
+ const seen = new Set();
+
+ for (const dir of searchDirs) {
+ const absDir = path.join(cwd, dir);
+ if (!fs.existsSync(absDir)) continue;
+ const result = searchDir(absDir, query, seen, 0);
+ if (result) return result;
+ }
+ return null;
+}
+
+function searchDir(dir, query, seen, depth) {
+ if (depth > 5) return null; // don't go too deep
+ const realDir = fs.realpathSync(dir);
+ if (seen.has(realDir)) return null;
+ seen.add(realDir);
+
+ let entries;
+ try { entries = fs.readdirSync(dir, { withFileTypes: true }); }
+ catch { return null; }
+
+ // Check files first
+ for (const entry of entries) {
+ if (!entry.isFile()) continue;
+ const ext = path.extname(entry.name).toLowerCase();
+ if (!EXTENSIONS.includes(ext)) continue;
+
+ const filePath = path.join(dir, entry.name);
+ try {
+ const content = fs.readFileSync(filePath, 'utf-8');
+ if (content.includes(query)) return filePath;
+ } catch { /* skip unreadable files */ }
+ }
+
+ // Then recurse into directories
+ for (const entry of entries) {
+ if (!entry.isDirectory()) continue;
+ if (entry.name === 'node_modules' || entry.name === '.git' || entry.name === 'dist' || entry.name === 'build') continue;
+ const result = searchDir(path.join(dir, entry.name), query, seen, depth + 1);
+ if (result) return result;
+ }
+
+ return null;
+}
+
+/**
+ * Find the element's start and end line in the file.
+ * The query is a class name, ID, or text snippet.
+ * We find the line containing the query, then find the matching closing tag.
+ */
+function findElement(lines, query) {
+ // Find the line containing the query
+ let startLine = -1;
+ for (let i = 0; i < lines.length; i++) {
+ if (lines[i].includes(query)) {
+ // Make sure this looks like a tag opening, not a comment or string
+ const line = lines[i].trim();
+ if (line.startsWith('<!--') || line.startsWith('{/*') || line.startsWith('//')) continue;
+ // Skip lines inside data-impeccable-variant containers (already wrapped)
+ if (lines[i].includes('data-impeccable-variant')) continue;
+ startLine = i;
+ break;
+ }
+ }
+
+ if (startLine === -1) return null;
+
+ // Find the end of this element by counting open/close tags
+ const endLine = findClosingLine(lines, startLine);
+ return { startLine, endLine };
+}
+
+/**
+ * Starting from a line with an opening tag, find the line with the matching
+ * closing tag by counting tag nesting depth.
+ */
+function findClosingLine(lines, start) {
+ // Extract the tag name from the opening line
+ const openMatch = lines[start].match(/<(\w+)[\s>]/);
+ if (!openMatch) return start; // self-closing or text-only line
+
+ const tagName = openMatch[1];
+ let depth = 0;
+
+ for (let i = start; i < lines.length; i++) {
+ const line = lines[i];
+ // Count opening tags (not self-closing)
+ const opens = (line.match(new RegExp('<' + tagName + '[\\s>]', 'g')) || []).length;
+ const selfCloses = (line.match(new RegExp('<' + tagName + '[^>]*/>', 'g')) || []).length;
+ const closes = (line.match(new RegExp('</' + tagName + '\\s*>', 'g')) || []).length;
+
+ depth += opens - selfCloses - closes;
+
+ if (depth <= 0) return i;
+ }
+
+ // If we can't find the close, return a reasonable guess
+ return Math.min(start + 50, lines.length - 1);
+}
diff --git a/.opencode/skills/impeccable/reference/live.md b/.opencode/skills/impeccable/reference/live.md
index 53b64a21a..ba0e9b0c5 100644
--- a/.opencode/skills/impeccable/reference/live.md
+++ b/.opencode/skills/impeccable/reference/live.md
@@ -10,7 +10,7 @@ Launch interactive live variant mode: select elements in the browser, pick a des
1. Read `.impeccable.md` if it exists. Keep the design context in mind for variant generation.
2. Start the live variant server:
```bash
- npx impeccable live &
+ node {{scripts_path}}/live-server.mjs &
```
3. Note the **port** and **token** printed to stdout.
@@ -53,7 +53,7 @@ Run a blocking poll loop. On each iteration, wait for a browser event and respon
```
LOOP:
- Run: npx impeccable poll
+ Run: node {{scripts_path}}/live-poll.mjs
Read the JSON output. Dispatch based on the "type" field:
TYPE "generate":
@@ -85,7 +85,7 @@ The event contains: `{id, action, freeformPrompt, count, pageUrl, element}`.
Use the `wrap` helper to find the element and create the variant container:
```bash
-npx impeccable wrap --id EVENT_ID --count EVENT_COUNT --element-id "ELEMENT_ID" --classes "class1,class2" --tag "div"
+node {{scripts_path}}/live-wrap.mjs --id EVENT_ID --count EVENT_COUNT --element-id "ELEMENT_ID" --classes "class1,class2" --tag "div"
```
Pass the element's id (`event.element.id`), classes (`event.element.classes` joined with commas), and tag name. The command searches in priority order: ID match first, then class names, then tag+class combo. If `event.pageUrl` hints at the file (e.g., `/` is usually `index.html`), pass `--file PATH` to skip the search.
@@ -136,10 +136,14 @@ The first variant should NOT have `style="display: none"` (it should be visible
### Step 3: Signal completion
+Include `--file` so the browser can fetch variants directly if the dev server lacks HMR:
+
```bash
-npx impeccable poll --reply EVENT_ID done
+node {{scripts_path}}/live-poll.mjs --reply EVENT_ID done --file RELATIVE_PATH
```
+The file path should be relative to the project root (e.g., `public/index.html`, `src/App.tsx`).
+
## Handle Accept
The event contains: `{id, variantId}`.
@@ -151,7 +155,7 @@ The user accepted a specific variant. For v1 (inspection mode):
4. Remove any scoped CSS blocks (between `impeccable-variants-css-start` and `impeccable-variants-css-end` markers).
5. Reply:
```bash
- npx impeccable poll --reply SESSION_ID done
+ node {{scripts_path}}/live-poll.mjs --reply SESSION_ID done
```
## Handle Discard
@@ -163,7 +167,7 @@ The event contains: `{id}`.
3. Remove any scoped CSS blocks for this session.
4. Reply:
```bash
- npx impeccable poll --reply SESSION_ID done
+ node {{scripts_path}}/live-poll.mjs --reply SESSION_ID done
```
## Cleanup (on exit)
@@ -174,7 +178,7 @@ When the loop ends:
2. **Remove any leftover variant wrappers** (search for `impeccable-variants-start` markers and clean up).
3. **Stop the server**:
```bash
- npx impeccable live stop
+ node {{scripts_path}}/live-server.mjs stop
```
## Variant Generation Guidelines
diff --git a/.opencode/skills/impeccable/scripts/live-browser.js b/.opencode/skills/impeccable/scripts/live-browser.js
new file mode 100644
index 000000000..7a26c9829
--- /dev/null
+++ b/.opencode/skills/impeccable/scripts/live-browser.js
@@ -0,0 +1,1220 @@
+/**
+ * Impeccable Live Variant Mode — Browser Script
+ *
+ * Injected into the user's page via <script src="http://localhost:PORT/live.js">.
+ * The server prepends window.__IMPECCABLE_TOKEN__ and window.__IMPECCABLE_PORT__
+ * before this code.
+ *
+ * UI: a single floating bar that morphs between three states —
+ * configure (pick action + go), generating (progressive dots), and cycling
+ * (prev/next + accept/discard). Feels like Spotlight, not a modal.
+ */
+(function () {
+ 'use strict';
+ if (typeof window === 'undefined') return;
+
+ // Guard against double-init. Bun's HTML loader may process the <script> tag
+ // and create a bundled copy alongside the external load, or HMR may re-execute.
+ // Check BEFORE reading token/port to catch all cases.
+ if (window.__IMPECCABLE_LIVE_INIT__) return;
+ window.__IMPECCABLE_LIVE_INIT__ = true;
+
+ const TOKEN = window.__IMPECCABLE_TOKEN__;
+ const PORT = window.__IMPECCABLE_PORT__;
+ if (!TOKEN || !PORT) {
+ window.__IMPECCABLE_LIVE_INIT__ = false; // reset so the real load can init
+ return;
+ }
+
+ // ---------------------------------------------------------------------------
+ // Design tokens
+ // ---------------------------------------------------------------------------
+
+ const C = {
+ brand: 'oklch(55% 0.25 350)',
+ brandHov: 'oklch(48% 0.25 350)',
+ brandSoft: 'oklch(55% 0.25 350 / 0.12)',
+ ink: 'oklch(15% 0.01 350)',
+ ash: 'oklch(55% 0 0)',
+ paper: 'oklch(98% 0.005 350 / 0.92)',
+ paperSolid:'oklch(98% 0.005 350)',
+ mist: 'oklch(90% 0.01 350 / 0.6)',
+ white: 'oklch(99% 0 0)',
+ };
+ const FONT = 'system-ui, -apple-system, sans-serif';
+ const MONO = 'ui-monospace, SFMono-Regular, Menlo, monospace';
+ const Z = { highlight: 99990, bar: 99995, picker: 99997, toast: 99999 };
+ const EASE = 'cubic-bezier(0.22, 1, 0.36, 1)'; // ease-out-quint
+ const PREFIX = 'impeccable-live';
+
+ const SKIP_TAGS = new Set([
+ 'html', 'head', 'body', 'script', 'style', 'link', 'meta', 'noscript', 'br', 'wbr',
+ ]);
+
+ const ACTIONS = [
+ { value: 'impeccable', label: 'Freeform' },
+ { value: 'bolder', label: 'Bolder' },
+ { value: 'quieter', label: 'Quieter' },
+ { value: 'distill', label: 'Distill' },
+ { value: 'polish', label: 'Polish' },
+ { value: 'typeset', label: 'Typeset' },
+ { value: 'colorize', label: 'Colorize' },
+ { value: 'layout', label: 'Layout' },
+ { value: 'adapt', label: 'Adapt' },
+ { value: 'animate', label: 'Animate' },
+ { value: 'delight', label: 'Delight' },
+ { value: 'overdrive', label: 'Overdrive' },
+ ];
+
+ // ---------------------------------------------------------------------------
+ // State
+ // ---------------------------------------------------------------------------
+
+ let state = 'IDLE';
+ let hoveredElement = null;
+ let selectedElement = null;
+ let currentSessionId = null;
+ let expectedVariants = 0;
+ let arrivedVariants = 0;
+ let visibleVariant = 0;
+ let variantObserver = null;
+ let hasProjectContext = false;
+ let selectedAction = 'impeccable';
+ let selectedCount = 3;
+
+ // UI refs
+ let highlightEl = null;
+ let tooltipEl = null;
+ let barEl = null;
+ let pickerEl = null;
+ let toastEl = null;
+ let scrollRaf = null;
+
+ // ---------------------------------------------------------------------------
+ // Helpers
+ // ---------------------------------------------------------------------------
+
+ function own(el) {
+ return el && (el.id?.startsWith(PREFIX) || el.closest?.('[id^="' + PREFIX + '"]'));
+ }
+
+ function pickable(el) {
+ if (!el || el.nodeType !== 1) return false;
+ if (SKIP_TAGS.has(el.tagName.toLowerCase())) return false;
+ if (own(el)) return false;
+ const r = el.getBoundingClientRect();
+ return r.width >= 20 && r.height >= 20;
+ }
+
+ function desc(el) {
+ if (!el) return '';
+ let s = el.tagName.toLowerCase();
+ if (el.id) s += '#' + el.id;
+ else if (el.classList.length) s += '.' + [...el.classList].slice(0, 2).join('.');
+ return s;
+ }
+
+ function id8() { return crypto.randomUUID().replace(/-/g, '').slice(0, 8); }
+
+ // ---------------------------------------------------------------------------
+ // Highlight overlay
+ // ---------------------------------------------------------------------------
+
+ function initHighlight() {
+ highlightEl = document.createElement('div');
+ highlightEl.id = PREFIX + '-highlight';
+ Object.assign(highlightEl.style, {
+ position: 'fixed', top: '0', left: '0', width: '0', height: '0',
+ border: '2px solid ' + C.brand, borderRadius: '3px',
+ pointerEvents: 'none', zIndex: Z.highlight, boxSizing: 'border-box',
+ transition: 'top 0.08s ease, left 0.08s ease, width 0.08s ease, height 0.08s ease, opacity 0.15s ease',
+ display: 'none', opacity: '0',
+ });
+ document.body.appendChild(highlightEl);
+
+ tooltipEl = document.createElement('div');
+ tooltipEl.id = PREFIX + '-tooltip';
+ Object.assign(tooltipEl.style, {
+ position: 'fixed',
+ background: C.ink, color: C.white,
+ fontFamily: MONO, fontSize: '10px', fontWeight: '500',
+ padding: '2px 6px', borderRadius: '3px',
+ zIndex: Z.highlight + 1, pointerEvents: 'none',
+ whiteSpace: 'nowrap', display: 'none',
+ letterSpacing: '0.02em',
+ });
+ document.body.appendChild(tooltipEl);
+ }
+
+ function showHighlight(el) {
+ if (!el || !highlightEl) return;
+ const r = el.getBoundingClientRect();
+ Object.assign(highlightEl.style, {
+ top: (r.top - 2) + 'px', left: (r.left - 2) + 'px',
+ width: (r.width + 4) + 'px', height: (r.height + 4) + 'px',
+ display: 'block', opacity: '1',
+ });
+ tooltipEl.textContent = desc(el);
+ const tipTop = r.top - 20;
+ Object.assign(tooltipEl.style, {
+ top: (tipTop < 4 ? r.bottom + 4 : tipTop) + 'px',
+ left: Math.max(4, r.left) + 'px', display: 'block',
+ });
+ }
+
+ function hideHighlight() {
+ if (highlightEl) { highlightEl.style.opacity = '0'; highlightEl.style.display = 'none'; }
+ if (tooltipEl) tooltipEl.style.display = 'none';
+ }
+
+ // ---------------------------------------------------------------------------
+ // Element context extraction
+ // ---------------------------------------------------------------------------
+
+ function extractContext(el) {
+ const cs = getComputedStyle(el);
+ const r = el.getBoundingClientRect();
+ const props = {};
+ for (const sheet of document.styleSheets) {
+ try {
+ for (const rule of sheet.cssRules) {
+ if (rule.style) for (let i = 0; i < rule.style.length; i++) {
+ const p = rule.style[i];
+ if (p.startsWith('--') && !props[p]) {
+ const v = cs.getPropertyValue(p).trim();
+ if (v) props[p] = v;
+ }
+ }
+ }
+ } catch { /* cross-origin */ }
+ }
+ return {
+ tagName: el.tagName.toLowerCase(), id: el.id || null,
+ classes: [...el.classList],
+ textContent: (el.textContent || '').slice(0, 500),
+ outerHTML: el.outerHTML.slice(0, 10000),
+ computedStyles: {
+ 'font-family': cs.fontFamily, 'font-size': cs.fontSize,
+ 'font-weight': cs.fontWeight, 'line-height': cs.lineHeight,
+ 'color': cs.color, 'background': cs.background,
+ 'background-color': cs.backgroundColor,
+ 'padding': cs.padding, 'margin': cs.margin,
+ 'display': cs.display, 'position': cs.position,
+ 'gap': cs.gap, 'border-radius': cs.borderRadius,
+ 'box-shadow': cs.boxShadow,
+ },
+ cssCustomProperties: props,
+ parentContext: el.parentElement
+ ? '<' + el.parentElement.tagName.toLowerCase()
+ + (el.parentElement.id ? ' id="' + el.parentElement.id + '"' : '')
+ + (el.parentElement.className ? ' class="' + el.parentElement.className + '"' : '')
+ + '>'
+ : null,
+ boundingRect: { width: Math.round(r.width), height: Math.round(r.height) },
+ };
+ }
+
+ // ---------------------------------------------------------------------------
+ // The Bar — one floating element, three modes
+ // ---------------------------------------------------------------------------
+
+ function initBar() {
+ barEl = document.createElement('div');
+ barEl.id = PREFIX + '-bar';
+ Object.assign(barEl.style, {
+ position: 'fixed', zIndex: Z.bar,
+ display: 'none', opacity: '0',
+ transform: 'translateY(6px)',
+ transition: 'opacity 0.25s ' + EASE + ', transform 0.3s ' + EASE,
+ // Visual
+ background: C.paper,
+ backdropFilter: 'blur(16px)', WebkitBackdropFilter: 'blur(16px)',
+ border: '1px solid ' + C.mist,
+ borderRadius: '10px',
+ boxShadow: '0 4px 20px oklch(0% 0 0 / 0.08), 0 1px 3px oklch(0% 0 0 / 0.06)',
+ fontFamily: FONT, fontSize: '13px', color: C.ink,
+ padding: '6px',
+ maxWidth: '460px', minWidth: '320px',
+ });
+ document.body.appendChild(barEl);
+ }
+
+ function positionBar() {
+ if (!barEl || !selectedElement) return;
+ const r = selectedElement.getBoundingClientRect();
+ const barH = barEl.offsetHeight || 44;
+ const barW = barEl.offsetWidth || 380;
+ let top = r.bottom + 8;
+ let left = r.left + (r.width - barW) / 2;
+ // Keep in viewport
+ if (top + barH + 8 > window.innerHeight) top = r.top - barH - 8;
+ if (top < 8) top = 8;
+ if (left < 8) left = 8;
+ if (left + barW > window.innerWidth - 8) left = window.innerWidth - barW - 8;
+ Object.assign(barEl.style, { top: top + 'px', left: left + 'px' });
+ }
+
+ function showBar(mode) {
+ barEl.innerHTML = '';
+ if (mode === 'configure') barEl.appendChild(buildConfigureRow());
+ else if (mode === 'generating') barEl.appendChild(buildGeneratingRow());
+ else if (mode === 'cycling') barEl.appendChild(buildCyclingRow());
+ barEl.style.display = 'block';
+ positionBar();
+ requestAnimationFrame(() => {
+ barEl.style.opacity = '1';
+ barEl.style.transform = 'translateY(0)';
+ });
+ }
+
+ function hideBar() {
+ if (!barEl) return;
+ barEl.style.opacity = '0';
+ barEl.style.transform = 'translateY(6px)';
+ setTimeout(() => { if (barEl) barEl.style.display = 'none'; }, 250);
+ hideActionPicker();
+ }
+
+ function updateBarContent(mode) {
+ if (!barEl || barEl.style.display === 'none') return;
+ barEl.innerHTML = '';
+ // Reset bar styling
+ barEl.style.background = C.paper;
+ barEl.style.border = '1px solid ' + C.mist;
+ if (mode === 'configure') barEl.appendChild(buildConfigureRow());
+ else if (mode === 'generating') barEl.appendChild(buildGeneratingRow());
+ else if (mode === 'cycling') barEl.appendChild(buildCyclingRow());
+ else if (mode === 'saving') barEl.appendChild(buildSavingRow());
+ else if (mode === 'confirmed') {
+ barEl.appendChild(buildConfirmedRow());
+ barEl.style.background = 'oklch(95% 0.05 145)';
+ barEl.style.border = '1px solid oklch(75% 0.12 145 / 0.4)';
+ }
+ }
+
+ // --- Configure row ---
+
+ function buildConfigureRow() {
+ const row = el('div', {
+ display: 'flex', alignItems: 'center', gap: '4px',
+ });
+
+ // Action pill
+ const pill = el('button', {
+ display: 'inline-flex', alignItems: 'center', gap: '4px',
+ padding: '5px 10px', borderRadius: '6px',
+ background: C.ink, color: C.white,
+ fontFamily: FONT, fontSize: '12px', fontWeight: '500',
+ border: 'none', cursor: 'pointer',
+ transition: 'background 0.12s ease, transform 0.1s ease',
+ whiteSpace: 'nowrap', flexShrink: '0',
+ });
+ pill.textContent = actionLabel() + ' \u25BE';
+ pill.addEventListener('mouseenter', () => pill.style.background = C.brandHov);
+ pill.addEventListener('mouseleave', () => pill.style.background = C.ink);
+ pill.addEventListener('mousedown', () => pill.style.transform = 'scale(0.97)');
+ pill.addEventListener('mouseup', () => pill.style.transform = 'scale(1)');
+ pill.addEventListener('click', (e) => { e.stopPropagation(); toggleActionPicker(); });
+ row.appendChild(pill);
+
+ // Freeform input
+ const input = document.createElement('input');
+ input.id = PREFIX + '-input';
+ input.type = 'text';
+ input.placeholder = selectedAction === 'impeccable' ? 'describe what you want...' : 'refine further (optional)...';
+ Object.assign(input.style, {
+ flex: '1', minWidth: '0',
+ padding: '5px 8px', borderRadius: '6px',
+ border: '1px solid transparent', background: 'transparent',
+ fontFamily: FONT, fontSize: '12px', color: C.ink,
+ outline: 'none',
+ transition: 'border-color 0.15s ease, background 0.15s ease',
+ });
+ input.addEventListener('focus', () => {
+ input.style.borderColor = C.mist;
+ input.style.background = C.white;
+ });
+ input.addEventListener('blur', () => {
+ input.style.borderColor = 'transparent';
+ input.style.background = 'transparent';
+ });
+ input.addEventListener('keydown', (e) => {
+ e.stopPropagation(); // Don't trigger element picker keyboard nav
+ if (e.key === 'Enter') { e.preventDefault(); handleGo(); }
+ if (e.key === 'Escape') { e.preventDefault(); input.blur(); hideBar(); state = 'PICKING'; }
+ });
+ row.appendChild(input);
+
+ // Variant count toggle
+ const count = el('button', {
+ padding: '4px 6px', borderRadius: '5px',
+ border: '1px solid ' + C.mist, background: 'transparent',
+ fontFamily: MONO, fontSize: '11px', fontWeight: '600',
+ color: C.ash, cursor: 'pointer',
+ transition: 'color 0.12s ease, border-color 0.12s ease',
+ flexShrink: '0', whiteSpace: 'nowrap',
+ });
+ count.textContent = '\u00D7' + selectedCount;
+ count.title = 'Variants: click to change';
+ count.addEventListener('mouseenter', () => { count.style.color = C.ink; count.style.borderColor = C.ink; });
+ count.addEventListener('mouseleave', () => { count.style.color = C.ash; count.style.borderColor = C.mist; });
+ count.addEventListener('click', (e) => {
+ e.stopPropagation();
+ selectedCount = selectedCount >= 4 ? 2 : selectedCount + 1;
+ count.textContent = '\u00D7' + selectedCount;
+ });
+ row.appendChild(count);
+
+ // Go button
+ const go = el('button', {
+ padding: '5px 12px', borderRadius: '6px',
+ border: 'none', background: C.brand, color: C.white,
+ fontFamily: FONT, fontSize: '12px', fontWeight: '600',
+ cursor: 'pointer',
+ transition: 'background 0.12s ease, transform 0.1s ease',
+ flexShrink: '0', whiteSpace: 'nowrap',
+ });
+ go.textContent = 'Go \u2192';
+ go.addEventListener('mouseenter', () => go.style.background = C.brandHov);
+ go.addEventListener('mouseleave', () => go.style.background = C.brand);
+ go.addEventListener('mousedown', () => go.style.transform = 'scale(0.97)');
+ go.addEventListener('mouseup', () => go.style.transform = 'scale(1)');
+ go.addEventListener('click', (e) => { e.stopPropagation(); handleGo(); });
+ row.appendChild(go);
+
+ // Auto-focus input after a beat
+ setTimeout(() => input.focus(), 60);
+ return row;
+ }
+
+ // --- Generating row ---
+
+ function buildGeneratingRow() {
+ const row = el('div', {
+ display: 'flex', alignItems: 'center', gap: '8px',
+ padding: '2px 4px',
+ });
+
+ // Action label
+ const label = el('span', {
+ fontWeight: '600', fontSize: '12px', color: C.ink,
+ flexShrink: '0', whiteSpace: 'nowrap',
+ });
+ label.textContent = actionLabel();
+ row.appendChild(label);
+
+ // Dots
+ row.appendChild(buildDots(false));
+
+ // Status
+ const status = el('span', {
+ fontSize: '11px', color: C.ash, whiteSpace: 'nowrap',
+ marginLeft: 'auto',
+ });
+ status.textContent = arrivedVariants < expectedVariants
+ ? 'Generating ' + (arrivedVariants + 1) + ' of ' + expectedVariants + '...'
+ : 'Done';
+ row.appendChild(status);
+
+ return row;
+ }
+
+ // --- Cycling row ---
+
+ function buildCyclingRow() {
+ const row = el('div', {
+ display: 'flex', alignItems: 'center', gap: '6px',
+ padding: '1px 2px',
+ });
+
+ // Prev
+ const prev = navBtn('\u2190');
+ prev.addEventListener('click', (e) => { e.stopPropagation(); cycleVariant(-1); });
+ if (visibleVariant <= 1) prev.style.opacity = '0.3';
+ row.appendChild(prev);
+
+ // Dots (clickable)
+ row.appendChild(buildDots(true));
+
+ // Counter
+ const counter = el('span', {
+ fontFamily: MONO, fontSize: '11px', fontWeight: '500',
+ color: C.ash, minWidth: '24px', textAlign: 'center',
+ });
+ counter.textContent = visibleVariant + '/' + arrivedVariants;
+ row.appendChild(counter);
+
+ // Next
+ const next = navBtn('\u2192');
+ next.addEventListener('click', (e) => { e.stopPropagation(); cycleVariant(1); });
+ if (visibleVariant >= arrivedVariants) next.style.opacity = '0.3';
+ row.appendChild(next);
+
+ // Spacer
+ row.appendChild(el('div', { flex: '1' }));
+
+ // Accept
+ const accept = el('button', {
+ padding: '4px 10px', borderRadius: '5px',
+ border: 'none', background: C.ink, color: C.white,
+ fontFamily: FONT, fontSize: '11px', fontWeight: '600',
+ cursor: 'pointer', transition: 'background 0.12s ease',
+ whiteSpace: 'nowrap',
+ });
+ accept.textContent = '\u2713 Accept';
+ accept.addEventListener('mouseenter', () => accept.style.background = C.brand);
+ accept.addEventListener('mouseleave', () => accept.style.background = C.ink);
+ accept.addEventListener('click', (e) => { e.stopPropagation(); handleAccept(); });
+ if (arrivedVariants === 0) { accept.style.opacity = '0.3'; accept.style.pointerEvents = 'none'; }
+ row.appendChild(accept);
+
+ // Discard
+ const discard = el('button', {
+ padding: '4px 6px', borderRadius: '5px',
+ border: '1px solid ' + C.mist, background: 'transparent',
+ fontFamily: FONT, fontSize: '11px', color: C.ash,
+ cursor: 'pointer', transition: 'color 0.12s ease, border-color 0.12s ease',
+ });
+ discard.textContent = '\u2715';
+ discard.title = 'Discard all variants';
+ discard.addEventListener('mouseenter', () => { discard.style.color = C.ink; discard.style.borderColor = C.ink; });
+ discard.addEventListener('mouseleave', () => { discard.style.color = C.ash; discard.style.borderColor = C.mist; });
+ discard.addEventListener('click', (e) => { e.stopPropagation(); handleDiscard(); });
+ row.appendChild(discard);
+
+ return row;
+ }
+
+ // --- Shared UI builders ---
+
+ // --- Saving row (waiting for agent to process accept/discard) ---
+
+ function buildSavingRow() {
+ const row = el('div', {
+ display: 'flex', alignItems: 'center', gap: '8px',
+ padding: '2px 8px',
+ });
+ const spinner = el('div', {
+ width: '14px', height: '14px', borderRadius: '50%',
+ border: '2px solid ' + C.mist,
+ borderTopColor: C.brand,
+ animation: 'impeccable-spin 0.6s linear infinite',
+ flexShrink: '0',
+ });
+ row.appendChild(spinner);
+ const label = el('span', {
+ fontSize: '12px', color: C.ash, fontWeight: '500',
+ });
+ label.textContent = 'Applying variant...';
+ row.appendChild(label);
+
+ // Inject the keyframes if not already present
+ if (!document.getElementById(PREFIX + '-keyframes')) {
+ const style = document.createElement('style');
+ style.id = PREFIX + '-keyframes';
+ style.textContent = '@keyframes impeccable-spin { to { transform: rotate(360deg); } }';
+ document.head.appendChild(style);
+ }
+ return row;
+ }
+
+ // --- Confirmed row (green success, auto-dismisses) ---
+
+ function buildConfirmedRow() {
+ const row = el('div', {
+ display: 'flex', alignItems: 'center', gap: '8px',
+ padding: '2px 8px',
+ });
+ const check = el('span', {
+ fontSize: '15px', lineHeight: '1', flexShrink: '0',
+ color: 'oklch(45% 0.15 145)',
+ });
+ check.textContent = '\u2713';
+ row.appendChild(check);
+ const label = el('span', {
+ fontSize: '12px', color: 'oklch(35% 0.1 145)', fontWeight: '600',
+ });
+ label.textContent = 'Variant applied';
+ row.appendChild(label);
+ return row;
+ }
+
+ // --- Shared UI builders ---
+
+ function buildDots(clickable) {
+ const container = el('div', {
+ display: 'flex', alignItems: 'center', gap: '4px',
+ });
+ for (let i = 1; i <= expectedVariants; i++) {
+ const arrived = i <= arrivedVariants;
+ const active = i === visibleVariant;
+ const dot = el('div', {
+ width: '7px', height: '7px', borderRadius: '50%',
+ background: active ? C.brand : (arrived ? C.ash : 'transparent'),
+ border: '1.5px solid ' + (arrived ? C.brand : C.mist),
+ transition: 'all 0.2s ' + EASE,
+ cursor: (clickable && arrived) ? 'pointer' : 'default',
+ transform: arrived ? 'scale(1)' : 'scale(0.6)',
+ opacity: arrived ? '1' : '0.4',
+ });
+ if (clickable && arrived) {
+ const idx = i;
+ dot.addEventListener('click', (e) => {
+ e.stopPropagation();
+ visibleVariant = idx;
+ showVariantInDOM(currentSessionId, idx);
+ updateSelectedElement();
+ updateBarContent('cycling');
+ });
+ }
+ container.appendChild(dot);
+ }
+ return container;
+ }
+
+ function navBtn(text) {
+ const b = el('button', {
+ width: '26px', height: '26px', borderRadius: '5px',
+ border: '1px solid ' + C.mist, background: 'transparent',
+ color: C.ink, fontFamily: FONT, fontSize: '13px',
+ cursor: 'pointer', display: 'flex', alignItems: 'center', justifyContent: 'center',
+ transition: 'border-color 0.12s ease, background 0.12s ease',
+ padding: '0', lineHeight: '1',
+ });
+ b.textContent = text;
+ b.addEventListener('mouseenter', () => { b.style.borderColor = C.ink; });
+ b.addEventListener('mouseleave', () => { b.style.borderColor = C.mist; });
+ return b;
+ }
+
+ function actionLabel() {
+ const a = ACTIONS.find(a => a.value === selectedAction);
+ return a ? a.label : 'Freeform';
+ }
+
+ function el(tag, styles) {
+ const e = document.createElement(tag);
+ if (styles) Object.assign(e.style, styles);
+ return e;
+ }
+
+ // ---------------------------------------------------------------------------
+ // Action picker popover
+ // ---------------------------------------------------------------------------
+
+ function initActionPicker() {
+ pickerEl = document.createElement('div');
+ pickerEl.id = PREFIX + '-picker';
+ Object.assign(pickerEl.style, {
+ position: 'fixed', zIndex: Z.picker,
+ display: 'none', opacity: '0',
+ transform: 'scale(0.96) translateY(4px)',
+ transformOrigin: 'bottom left',
+ transition: 'opacity 0.18s ' + EASE + ', transform 0.2s ' + EASE,
+ background: C.paperSolid,
+ border: '1px solid ' + C.mist,
+ borderRadius: '10px',
+ boxShadow: '0 8px 30px oklch(0% 0 0 / 0.10), 0 2px 6px oklch(0% 0 0 / 0.06)',
+ padding: '6px',
+ fontFamily: FONT,
+ });
+
+ // Build the chip grid
+ const grid = el('div', {
+ display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', gap: '3px',
+ });
+
+ ACTIONS.forEach(action => {
+ const chip = el('button', {
+ padding: '6px 8px', borderRadius: '6px',
+ border: 'none',
+ background: action.value === selectedAction ? C.brandSoft : 'transparent',
+ color: action.value === selectedAction ? C.brand : C.ink,
+ fontFamily: FONT, fontSize: '11px', fontWeight: '500',
+ cursor: 'pointer',
+ transition: 'background 0.1s ease, color 0.1s ease',
+ textAlign: 'center', whiteSpace: 'nowrap',
+ });
+ chip.textContent = action.label;
+ chip.dataset.action = action.value;
+ chip.addEventListener('mouseenter', () => {
+ if (action.value !== selectedAction) chip.style.background = C.brandSoft;
+ });
+ chip.addEventListener('mouseleave', () => {
+ chip.style.background = action.value === selectedAction ? C.brandSoft : 'transparent';
+ });
+ chip.addEventListener('click', (e) => {
+ e.stopPropagation();
+ selectedAction = action.value;
+ hideActionPicker();
+ updateBarContent('configure');
+ });
+ grid.appendChild(chip);
+ });
+
+ pickerEl.appendChild(grid);
+ document.body.appendChild(pickerEl);
+ }
+
+ function toggleActionPicker() {
+ if (pickerEl.style.display !== 'none') { hideActionPicker(); return; }
+ // Rebuild chips to reflect current selection
+ pickerEl.querySelectorAll('button').forEach(chip => {
+ const isActive = chip.dataset.action === selectedAction;
+ chip.style.background = isActive ? C.brandSoft : 'transparent';
+ chip.style.color = isActive ? C.brand : C.ink;
+ });
+ // Position above the bar
+ const barRect = barEl.getBoundingClientRect();
+ const pickerH = 90; // approximate
+ let top = barRect.top - pickerH - 6;
+ if (top < 8) top = barRect.bottom + 6;
+ Object.assign(pickerEl.style, {
+ top: top + 'px', left: barRect.left + 'px',
+ display: 'block',
+ });
+ requestAnimationFrame(() => {
+ pickerEl.style.opacity = '1';
+ pickerEl.style.transform = 'scale(1) translateY(0)';
+ });
+ }
+
+ function hideActionPicker() {
+ if (!pickerEl) return;
+ pickerEl.style.opacity = '0';
+ pickerEl.style.transform = 'scale(0.96) translateY(4px)';
+ setTimeout(() => { if (pickerEl) pickerEl.style.display = 'none'; }, 180);
+ }
+
+ // ---------------------------------------------------------------------------
+ // Variant cycling in DOM
+ // ---------------------------------------------------------------------------
+
+ function showVariantInDOM(sessionId, num) {
+ const wrapper = document.querySelector('[data-impeccable-variants="' + sessionId + '"]');
+ if (!wrapper) return;
+ for (const child of wrapper.children) {
+ const v = child.dataset ? child.dataset.impeccableVariant : null;
+ if (!v) continue;
+ child.style.display = (v === String(num)) ? '' : 'none';
+ }
+ }
+
+ /**
+ * No-HMR fallback: fetch the raw source file from the live server,
+ * parse it, extract the variant wrapper, and inject it into the live DOM.
+ * This works even when the dev server caches HTML (Bun, static servers).
+ */
+ function injectVariantsFromSource(filePath, sessionId) {
+ const url = 'http://localhost:' + PORT + '/source?token=' + TOKEN + '&path=' + encodeURIComponent(filePath);
+ fetch(url)
+ .then(r => { if (!r.ok) throw new Error(r.status); return r.text(); })
+ .then(html => {
+ // Parse the raw source HTML
+ const parser = new DOMParser();
+ const doc = parser.parseFromString(html, 'text/html');
+ const srcWrapper = doc.querySelector('[data-impeccable-variants="' + sessionId + '"]');
+ if (!srcWrapper) {
+ console.error('[impeccable] Variant wrapper not found in source file.');
+ return;
+ }
+
+ // Find the original element in the live DOM.
+ // The original is inside the wrapper in the source. We find the
+ // corresponding element in the live DOM by matching the first child's
+ // tag + classes from the original snapshot.
+ const origContent = srcWrapper.querySelector('[data-impeccable-variant="original"] > :first-child');
+ if (!origContent) return;
+
+ const tag = origContent.tagName.toLowerCase();
+ const cls = origContent.className;
+ let liveEl = null;
+ if (origContent.id) {
+ liveEl = document.getElementById(origContent.id);
+ } else if (cls) {
+ // Find by tag + exact class match
+ const candidates = document.querySelectorAll(tag + '.' + cls.split(' ')[0]);
+ for (const c of candidates) {
+ if (c.className === cls && !own(c)) { liveEl = c; break; }
+ }
+ }
+
+ if (!liveEl) {
+ console.error('[impeccable] Could not find original element in live DOM.');
+ return;
+ }
+
+ // Replace the live element with the full wrapper from source
+ const wrapper = srcWrapper.cloneNode(true);
+ liveEl.parentElement.replaceChild(wrapper, liveEl);
+
+ // Update state: count variants, show the first one
+ 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);
+
+ // Update selectedElement to the visible variant's content
+ const visEl = wrapper.querySelector('[data-impeccable-variant="1"] > :first-child');
+ selectedElement = visEl || wrapper.parentElement;
+
+ state = 'CYCLING';
+ updateBarContent('cycling');
+ saveSession();
+ console.log('[impeccable] Injected ' + arrivedVariants + ' variants from source file.');
+ })
+ .catch(err => {
+ console.error('[impeccable] Failed to fetch source:', err);
+ showToast('Could not load variants. Try refreshing the page.', 5000);
+ });
+ }
+
+ function cycleVariant(dir) {
+ const next = visibleVariant + dir;
+ if (next < 1 || next > arrivedVariants) return;
+ visibleVariant = next;
+ showVariantInDOM(currentSessionId, next);
+ updateSelectedElement();
+ updateBarContent('cycling');
+ saveSession();
+ }
+
+ function updateSelectedElement() {
+ if (!currentSessionId) return;
+ const wrapper = document.querySelector('[data-impeccable-variants="' + currentSessionId + '"]');
+ if (!wrapper) return;
+ const visEl = wrapper.querySelector('[data-impeccable-variant="' + visibleVariant + '"] > :first-child');
+ if (visEl) selectedElement = visEl;
+ }
+
+ // ---------------------------------------------------------------------------
+ // MutationObserver for progressive variant reveal
+ // ---------------------------------------------------------------------------
+
+ function startVariantObserver(sessionId) {
+ let updating = false; // re-entrancy guard
+
+ const obs = new MutationObserver((mutations) => {
+ if (updating) return;
+
+ // Only react to mutations that add nodes with data-impeccable-variant,
+ // or mutations inside the variant wrapper. Ignore our own bar/UI changes.
+ let dominated = false;
+ for (const m of mutations) {
+ if (m.target.closest?.('[data-impeccable-variants]')) { dominated = true; break; }
+ for (const n of m.addedNodes) {
+ if (n.nodeType === 1 && (n.dataset?.impeccableVariants || n.dataset?.impeccableVariant)) {
+ dominated = true; break;
+ }
+ }
+ if (dominated) break;
+ }
+ if (!dominated) return;
+
+ const wrapper = document.querySelector('[data-impeccable-variants="' + sessionId + '"]');
+ if (!wrapper) return;
+
+ const variants = wrapper.querySelectorAll('[data-impeccable-variant]:not([data-impeccable-variant="original"])');
+ const count = variants.length;
+
+ // Nothing new
+ if (count <= arrivedVariants) return;
+
+ updating = true;
+ arrivedVariants = count;
+ if (visibleVariant === 0 && arrivedVariants > 0) {
+ visibleVariant = 1;
+ showVariantInDOM(sessionId, 1);
+ }
+
+ const expected = parseInt(wrapper.dataset.impeccableVariantCount || '0');
+ if (expected > 0) expectedVariants = expected;
+
+ if (arrivedVariants >= expectedVariants && expectedVariants > 0) {
+ state = 'CYCLING';
+ updateBarContent('cycling');
+ } else if (state === 'GENERATING') {
+ updateBarContent('generating');
+ }
+ saveSession();
+ updating = false;
+ });
+
+ obs.observe(document.body, { childList: true, subtree: true });
+ return obs;
+ }
+
+ // ---------------------------------------------------------------------------
+ // Bar scroll tracking
+ // ---------------------------------------------------------------------------
+
+ function startScrollTracking() {
+ function tick() {
+ if (state === 'CONFIGURING' || state === 'GENERATING' || state === 'CYCLING') {
+ positionBar();
+ showHighlight(selectedElement);
+ }
+ scrollRaf = requestAnimationFrame(tick);
+ }
+ scrollRaf = requestAnimationFrame(tick);
+ }
+
+ function stopScrollTracking() {
+ if (scrollRaf) { cancelAnimationFrame(scrollRaf); scrollRaf = null; }
+ }
+
+ // ---------------------------------------------------------------------------
+ // SSE (server→browser) + fetch POST (browser→server)
+ // Zero-dependency replacement for WebSocket.
+ // ---------------------------------------------------------------------------
+
+ let evtSource = null;
+
+ function connectSSE() {
+ evtSource = new EventSource('http://localhost:' + PORT + '/events?token=' + TOKEN);
+
+ evtSource.onmessage = (e) => {
+ let msg; try { msg = JSON.parse(e.data); } catch { return; }
+ switch (msg.type) {
+ case 'connected':
+ hasProjectContext = !!msg.hasProjectContext;
+ if (!hasProjectContext) showToast('No .impeccable.md found. Variants will be brand-agnostic.', 6000);
+ console.log('[impeccable] Live mode connected.');
+ if (state === 'IDLE') state = 'PICKING';
+ break;
+ case 'done':
+ if (state === 'SAVING') {
+ state = 'CONFIRMED';
+ updateBarContent('confirmed');
+ setTimeout(() => {
+ hideBar();
+ hideHighlight();
+ stopScrollTracking();
+ if (variantObserver) { variantObserver.disconnect(); variantObserver = null; }
+ clearSession();
+ selectedElement = null;
+ currentSessionId = null;
+ selectedAction = 'impeccable';
+ state = 'PICKING';
+ }, 1800);
+ return;
+ }
+ if (arrivedVariants === 0 && expectedVariants > 0 && msg.file) {
+ console.log('[impeccable] No HMR detected. Fetching variants from source file...');
+ injectVariantsFromSource(msg.file, currentSessionId);
+ return;
+ }
+ state = 'CYCLING';
+ updateBarContent('cycling');
+ break;
+ case 'error':
+ console.error('[impeccable] Error:', msg.message);
+ showToast('Error: ' + msg.message, 5000);
+ hideBar();
+ state = 'PICKING';
+ break;
+ }
+ };
+
+ evtSource.onerror = () => {
+ // EventSource auto-reconnects. Log once.
+ console.log('[impeccable] SSE connection lost. Reconnecting...');
+ };
+ }
+
+ function sendEvent(msg) {
+ msg.token = TOKEN;
+ 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));
+ }
+
+ // ---------------------------------------------------------------------------
+ // Event handlers
+ // ---------------------------------------------------------------------------
+
+ function handleMouseMove(e) {
+ if (state !== 'PICKING') return;
+ const target = document.elementFromPoint(e.clientX, e.clientY);
+ if (!target || !pickable(target) || target === hoveredElement) return;
+ hoveredElement = target;
+ showHighlight(target);
+ }
+
+ function handleClick(e) {
+ // Close action picker on any outside click
+ if (pickerEl?.style.display !== 'none' && !own(e.target)) {
+ hideActionPicker();
+ }
+ if (state !== 'PICKING') return;
+ if (own(e.target)) return;
+ if (!hoveredElement || !pickable(hoveredElement)) return;
+ e.preventDefault();
+ e.stopPropagation();
+ selectedElement = hoveredElement;
+ state = 'CONFIGURING';
+ showHighlight(selectedElement);
+ showBar('configure');
+ startScrollTracking();
+ }
+
+ function handleKeyDown(e) {
+ if (e.key === 'Escape') {
+ e.preventDefault();
+ if (pickerEl?.style.display !== 'none') { hideActionPicker(); return; }
+ if (state === 'CONFIGURING') { hideBar(); stopScrollTracking(); state = 'PICKING'; return; }
+ if (state === 'CYCLING') { handleDiscard(); return; }
+ if (state === 'SAVING' || state === 'CONFIRMED') return; // don't interrupt
+ if (state === 'PICKING') { hideHighlight(); state = 'IDLE'; return; }
+ }
+
+ if (state === 'PICKING' && hoveredElement) {
+ let next = null;
+ if (e.key === 'ArrowDown' && !e.shiftKey) {
+ next = hoveredElement.nextElementSibling;
+ while (next && !pickable(next)) next = next.nextElementSibling;
+ } else if (e.key === 'ArrowUp' && !e.shiftKey) {
+ next = hoveredElement.previousElementSibling;
+ while (next && !pickable(next)) next = next.previousElementSibling;
+ } else if (e.key === 'ArrowUp' && e.shiftKey) {
+ next = hoveredElement.parentElement;
+ if (next && !pickable(next)) next = null;
+ } else if (e.key === 'ArrowDown' && e.shiftKey) {
+ next = hoveredElement.firstElementChild;
+ while (next && !pickable(next)) next = next.nextElementSibling;
+ } else if (e.key === 'Enter') {
+ e.preventDefault();
+ selectedElement = hoveredElement;
+ state = 'CONFIGURING';
+ showHighlight(selectedElement);
+ showBar('configure');
+ startScrollTracking();
+ return;
+ }
+ if (next) {
+ e.preventDefault();
+ hoveredElement = next;
+ showHighlight(next);
+ next.scrollIntoView({ block: 'nearest', behavior: 'smooth' });
+ }
+ return;
+ }
+
+ if (state === 'CYCLING') {
+ if (e.key === 'ArrowLeft') { e.preventDefault(); cycleVariant(-1); }
+ if (e.key === 'ArrowRight') { e.preventDefault(); cycleVariant(1); }
+ if (e.key === 'Enter') { e.preventDefault(); handleAccept(); }
+ }
+ }
+
+ function handleGo() {
+ if (!selectedElement || state !== 'CONFIGURING') return;
+ const input = document.getElementById(PREFIX + '-input');
+ const prompt = input ? input.value.trim() : '';
+
+ currentSessionId = id8();
+ expectedVariants = selectedCount;
+ arrivedVariants = 0;
+ visibleVariant = 0;
+
+ sendEvent({
+ type: 'generate', id: currentSessionId,
+ action: selectedAction,
+ freeformPrompt: prompt || undefined,
+ count: selectedCount,
+ pageUrl: location.pathname,
+ element: extractContext(selectedElement),
+ });
+
+ state = 'GENERATING';
+ showBar('generating');
+ saveSession();
+ if (variantObserver) variantObserver.disconnect();
+ variantObserver = startVariantObserver(currentSessionId);
+ }
+
+ function handleAccept() {
+ if (!currentSessionId || arrivedVariants === 0) return;
+ sendEvent({ type: 'accept', id: currentSessionId, variantId: String(visibleVariant) });
+ markSessionHandled();
+ state = 'SAVING';
+ updateBarContent('saving');
+ // Don't cleanup yet — wait for the "done" WS message to show confirmation
+ }
+
+ function handleDiscard() {
+ if (!currentSessionId) return;
+ sendEvent({ type: 'discard', id: currentSessionId });
+ markSessionHandled();
+ state = 'SAVING';
+ updateBarContent('saving');
+ // Wait for "done" WS message to show confirmation and dismiss
+ }
+
+ // ---------------------------------------------------------------------------
+ // Session persistence via localStorage
+ // ---------------------------------------------------------------------------
+ // Survives page reloads, browser close/reopen, HMR, and accidental refreshes.
+
+ const LS_KEY = PREFIX + '-session';
+
+ function saveSession() {
+ if (!currentSessionId) return;
+ 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 */ }
+ }
+
+ function loadSession() {
+ try {
+ const raw = localStorage.getItem(LS_KEY);
+ return raw ? JSON.parse(raw) : null;
+ } catch { return null; }
+ }
+
+ function clearSession() {
+ try { localStorage.removeItem(LS_KEY); } catch {}
+ }
+
+ /** Mark session as handled (accepted/discarded). The agent will clean up
+ * the source, but until it does the wrapper is still in the HTML. This
+ * prevents resumeSession from picking it up again after reload. */
+ function markSessionHandled() {
+ if (!currentSessionId) return;
+ try {
+ localStorage.setItem(LS_KEY + '-handled', currentSessionId);
+ } catch {}
+ }
+
+ function isSessionHandled(id) {
+ try {
+ return localStorage.getItem(LS_KEY + '-handled') === id;
+ } catch { return false; }
+ }
+
+ function clearHandled() {
+ try { localStorage.removeItem(LS_KEY + '-handled'); } catch {}
+ }
+
+ function cleanup() {
+ hideBar();
+ hideHighlight();
+ stopScrollTracking();
+ if (variantObserver) { variantObserver.disconnect(); variantObserver = null; }
+ clearSession();
+ selectedElement = null;
+ currentSessionId = null;
+ selectedAction = 'impeccable';
+ state = 'PICKING';
+ }
+
+ // ---------------------------------------------------------------------------
+ // Toast
+ // ---------------------------------------------------------------------------
+
+ function showToast(message, duration) {
+ if (toastEl) toastEl.remove();
+ toastEl = el('div', {
+ position: 'fixed', bottom: '16px', left: '50%',
+ transform: 'translateX(-50%) translateY(8px)',
+ background: C.ink, color: C.white,
+ fontFamily: FONT, fontSize: '12px',
+ padding: '8px 16px', borderRadius: '8px',
+ zIndex: Z.toast, opacity: '0',
+ transition: 'opacity 0.25s ' + EASE + ', transform 0.25s ' + EASE,
+ pointerEvents: 'none', maxWidth: '420px', textAlign: 'center',
+ });
+ toastEl.id = PREFIX + '-toast';
+ toastEl.textContent = message;
+ document.body.appendChild(toastEl);
+ requestAnimationFrame(() => {
+ toastEl.style.opacity = '1';
+ toastEl.style.transform = 'translateX(-50%) translateY(0)';
+ });
+ setTimeout(() => {
+ if (toastEl) {
+ toastEl.style.opacity = '0';
+ toastEl.style.transform = 'translateX(-50%) translateY(8px)';
+ setTimeout(() => { if (toastEl) { toastEl.remove(); toastEl = null; } }, 250);
+ }
+ }, duration);
+ }
+
+ // ---------------------------------------------------------------------------
+ // Init
+ // ---------------------------------------------------------------------------
+
+ // Resume an active variant session after HMR/page reload.
+ // If a [data-impeccable-variants] wrapper exists in the DOM, the agent wrote
+ // variants before HMR fired. Pick up where we left off.
+ function resumeSession() {
+ const wrapper = document.querySelector('[data-impeccable-variants]');
+ if (!wrapper) { clearSession(); clearHandled(); return false; }
+
+ const sessionId = wrapper.dataset.impeccableVariants;
+
+ // Don't resume if this session was already accepted/discarded
+ if (isSessionHandled(sessionId)) return false;
+
+ currentSessionId = sessionId;
+ expectedVariants = parseInt(wrapper.dataset.impeccableVariantCount || '0');
+ const variants = wrapper.querySelectorAll('[data-impeccable-variant]:not([data-impeccable-variant="original"])');
+ arrivedVariants = variants.length;
+
+ // Restore visible variant from localStorage if available, else default to 1
+ const saved = loadSession();
+ visibleVariant = (saved && saved.id === sessionId && saved.visible > 0 && saved.visible <= arrivedVariants)
+ ? saved.visible : (arrivedVariants > 0 ? 1 : 0);
+
+ // Find the visible variant's content element for highlight positioning
+ const visEl = wrapper.querySelector('[data-impeccable-variant="' + visibleVariant + '"] > :first-child');
+ selectedElement = visEl || wrapper.parentElement;
+
+ // Set display state BEFORE starting observer (avoid triggering it)
+ if (visibleVariant > 0) showVariantInDOM(currentSessionId, visibleVariant);
+
+ state = arrivedVariants >= expectedVariants ? 'CYCLING' : 'GENERATING';
+ showBar(state === 'CYCLING' ? 'cycling' : 'generating');
+ startScrollTracking();
+ saveSession();
+
+ // Start observing for more variants AFTER initial setup
+ if (variantObserver) variantObserver.disconnect();
+ variantObserver = startVariantObserver(currentSessionId);
+ return true;
+ }
+
+ function init() {
+ initHighlight();
+ initBar();
+ initActionPicker();
+ document.addEventListener('mousemove', handleMouseMove, true);
+ document.addEventListener('click', handleClick, true);
+ document.addEventListener('keydown', handleKeyDown, true);
+ connectSSE();
+
+ // Check for an active session to resume (variant wrapper already in DOM after HMR)
+ if (!resumeSession()) {
+ console.log('[impeccable] Live variant mode ready. Hover over elements to pick one.');
+ } else {
+ console.log('[impeccable] Resumed active variant session ' + currentSessionId + ' (' + arrivedVariants + '/' + expectedVariants + ' variants).');
+ }
+ }
+
+ if (document.readyState === 'loading') {
+ document.addEventListener('DOMContentLoaded', init);
+ } else {
+ init();
+ }
+})();
diff --git a/.opencode/skills/impeccable/scripts/live-poll.mjs b/.opencode/skills/impeccable/scripts/live-poll.mjs
new file mode 100644
index 000000000..52859416c
--- /dev/null
+++ b/.opencode/skills/impeccable/scripts/live-poll.mjs
@@ -0,0 +1,123 @@
+/**
+ * CLI client for the live variant mode poll/reply protocol.
+ *
+ * Usage:
+ * npx impeccable poll # Block until browser event, print JSON
+ * npx impeccable poll --timeout=60000 # Custom timeout (ms)
+ * npx impeccable poll --reply <id> done # Reply "done" to event <id>
+ * npx impeccable poll --reply <id> error "msg" # Reply with error
+ */
+
+import fs from 'node:fs';
+import path from 'node:path';
+import os from 'node:os';
+
+const LIVE_PID_FILE = path.join(os.tmpdir(), 'impeccable-live.json');
+
+function readServerInfo() {
+ try {
+ return JSON.parse(fs.readFileSync(LIVE_PID_FILE, 'utf-8'));
+ } catch {
+ console.error('No running live server found. Start one with: npx impeccable live');
+ process.exit(1);
+ }
+}
+
+export async function pollCli() {
+ const args = process.argv.slice(2);
+
+ if (args.includes('--help') || args.includes('-h')) {
+ console.log(`Usage: impeccable poll [options]
+
+Wait for a browser event from the live variant server, or reply to one.
+
+Modes:
+ poll Block until a browser event arrives, print JSON
+ poll --reply <id> done Reply "done" to event <id>
+ poll --reply <id> error "msg" Reply with an error message
+
+Options:
+ --timeout=MS Poll timeout in milliseconds (default: 120000)
+ --help Show this help message`);
+ process.exit(0);
+ }
+
+ const info = readServerInfo();
+ const base = `http://localhost:${info.port}`;
+
+ // Reply mode: npx impeccable poll --reply <id> <status> [--file path] [message]
+ const replyIdx = args.indexOf('--reply');
+ if (replyIdx !== -1) {
+ const id = args[replyIdx + 1];
+ const status = args[replyIdx + 2] || 'done';
+ const fileIdx = args.indexOf('--file');
+ const filePath = fileIdx !== -1 && fileIdx + 1 < args.length ? args[fileIdx + 1] : undefined;
+ // Message is any remaining positional arg that isn't a flag
+ const message = args.find((a, i) => i > replyIdx + 2 && !a.startsWith('--') && i !== fileIdx + 1) || undefined;
+
+ if (!id) {
+ console.error('Usage: npx impeccable poll --reply <id> <status> [--file path] [message]');
+ process.exit(1);
+ }
+
+ 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);
+ }
+
+ // Success — silent exit (agent doesn't need output for replies)
+ } catch (err) {
+ if (err.cause?.code === 'ECONNREFUSED') {
+ console.error('Live server not running. Start one with: npx impeccable live');
+ } else {
+ console.error('Reply failed:', err.message);
+ }
+ process.exit(1);
+ }
+ return;
+ }
+
+ // Poll mode: block until browser event
+ const timeoutArg = args.find(a => a.startsWith('--timeout='));
+ const timeout = timeoutArg ? parseInt(timeoutArg.split('=')[1], 10) : 120000;
+
+ try {
+ const res = await fetch(`${base}/poll?token=${info.token}&timeout=${timeout}`);
+
+ if (res.status === 401) {
+ console.error('Authentication failed. The server token may have changed.');
+ console.error('Try restarting: npx impeccable live stop && npx impeccable live');
+ process.exit(1);
+ }
+
+ if (!res.ok) {
+ console.error(`Poll failed: ${res.status} ${res.statusText}`);
+ process.exit(1);
+ }
+
+ const event = await res.json();
+ // Print the event as JSON — the agent reads this from stdout
+ console.log(JSON.stringify(event));
+ } catch (err) {
+ if (err.cause?.code === 'ECONNREFUSED') {
+ console.error('Live server not running. Start one with: npx impeccable live');
+ } else {
+ console.error('Poll failed:', err.message);
+ }
+ process.exit(1);
+ }
+}
diff --git a/.opencode/skills/impeccable/scripts/live-server.mjs b/.opencode/skills/impeccable/scripts/live-server.mjs
new file mode 100644
index 000000000..d436bad58
--- /dev/null
+++ b/.opencode/skills/impeccable/scripts/live-server.mjs
@@ -0,0 +1,416 @@
+#!/usr/bin/env node
+/**
+ * Live variant mode server (self-contained, zero dependencies).
+ *
+ * Serves the browser script (/live.js), the detection overlay (/detect.js),
+ * uses Server-Sent Events (SSE) for server→browser push, and HTTP POST for
+ * browser→server events. Agent communicates via HTTP long-poll (/poll).
+ *
+ * Usage:
+ * node <scripts_path>/live-server.mjs # start
+ * node <scripts_path>/live-server.mjs stop # stop
+ * node <scripts_path>/live-server.mjs --help
+ */
+
+import http from 'node:http';
+import { randomUUID } from 'node:crypto';
+import fs from 'node:fs';
+import path from 'node:path';
+import os from 'node:os';
+import net from 'node:net';
+import { fileURLToPath } from 'node:url';
+
+const __dirname = path.dirname(fileURLToPath(import.meta.url));
+const LIVE_PID_FILE = path.join(os.tmpdir(), 'impeccable-live.json');
+const DEFAULT_POLL_TIMEOUT = 120_000;
+
+// ---------------------------------------------------------------------------
+// Port detection
+// ---------------------------------------------------------------------------
+
+async function findOpenPort(start = 8400) {
+ return new Promise((resolve) => {
+ const srv = net.createServer();
+ srv.listen(start, '127.0.0.1', () => {
+ const port = srv.address().port;
+ srv.close(() => resolve(port));
+ });
+ srv.on('error', () => resolve(findOpenPort(start + 1)));
+ });
+}
+
+// ---------------------------------------------------------------------------
+// Session state
+// ---------------------------------------------------------------------------
+
+const state = {
+ token: null,
+ port: null,
+ sseClients: new Set(), // SSE response objects (server→browser push)
+ pendingEvents: [], // browser events waiting for agent poll
+ pendingPolls: [], // agent poll callbacks waiting for browser events
+ exitTimer: null,
+};
+
+function enqueueEvent(event) {
+ if (state.pendingPolls.length > 0) {
+ state.pendingPolls.shift()(event);
+ } else {
+ state.pendingEvents.push(event);
+ }
+}
+
+/** Push a message to all connected SSE clients. */
+function broadcast(msg) {
+ const data = 'data: ' + JSON.stringify(msg) + '\n\n';
+ for (const res of state.sseClients) {
+ try { res.write(data); } catch { /* client gone */ }
+ }
+}
+
+// ---------------------------------------------------------------------------
+// Load scripts
+// ---------------------------------------------------------------------------
+
+function loadBrowserScripts() {
+ // Detection script: look relative to the skill scripts dir, then fall back
+ // to the npm package location (src/detect-antipatterns-browser.js)
+ const detectPaths = [
+ path.join(__dirname, '..', '..', '..', '..', 'src', 'detect-antipatterns-browser.js'),
+ path.join(process.cwd(), 'node_modules', 'impeccable', 'src', 'detect-antipatterns-browser.js'),
+ ];
+ let detectScript = '';
+ for (const p of detectPaths) {
+ try { detectScript = fs.readFileSync(p, 'utf-8'); break; } catch { /* try next */ }
+ }
+
+ const livePath = path.join(__dirname, 'live-browser.js');
+ let liveScript = '';
+ try {
+ liveScript = fs.readFileSync(livePath, 'utf-8');
+ } catch {
+ process.stderr.write('Error: live-browser.js not found at ' + livePath + '\n');
+ process.exit(1);
+ }
+
+ return { detectScript, liveScript };
+}
+
+function hasProjectContext() {
+ try {
+ fs.accessSync(path.join(process.cwd(), '.impeccable.md'), fs.constants.R_OK);
+ return true;
+ } catch { return false; }
+}
+
+// ---------------------------------------------------------------------------
+// Validation (inline — no external import needed for self-contained script)
+// ---------------------------------------------------------------------------
+
+const VISUAL_ACTIONS = [
+ 'impeccable', 'bolder', 'quieter', 'distill', 'polish', 'typeset',
+ 'colorize', 'layout', 'adapt', 'animate', 'delight', 'overdrive',
+];
+
+function validateEvent(msg) {
+ if (!msg || typeof msg !== 'object' || !msg.type) return 'Missing or invalid message';
+ switch (msg.type) {
+ case 'generate':
+ if (!msg.id || typeof msg.id !== 'string') return 'generate: missing id';
+ if (!msg.action || !VISUAL_ACTIONS.includes(msg.action)) return 'generate: invalid action';
+ if (!Number.isInteger(msg.count) || msg.count < 1 || msg.count > 8) return 'generate: count must be 1-8';
+ if (!msg.element || !msg.element.outerHTML) return 'generate: missing element context';
+ return null;
+ case 'accept':
+ if (!msg.id) return 'accept: missing id';
+ if (!msg.variantId) return 'accept: missing variantId';
+ return null;
+ case 'discard':
+ return msg.id ? null : 'discard: missing id';
+ case 'exit':
+ return null;
+ default:
+ return 'Unknown event type: ' + msg.type;
+ }
+}
+
+// ---------------------------------------------------------------------------
+// HTTP request handler
+// ---------------------------------------------------------------------------
+
+function createRequestHandler({ detectScript, liveScriptWithToken }) {
+ return (req, res) => {
+ const url = new URL(req.url, `http://localhost:${state.port}`);
+ res.setHeader('Access-Control-Allow-Origin', '*');
+ res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS');
+ res.setHeader('Access-Control-Allow-Headers', 'Content-Type');
+ if (req.method === 'OPTIONS') { res.writeHead(204); res.end(); return; }
+
+ const p = url.pathname;
+
+ // --- Scripts ---
+ if (p === '/live.js') {
+ res.writeHead(200, { 'Content-Type': 'application/javascript' });
+ res.end(liveScriptWithToken);
+ return;
+ }
+ if (p === '/detect.js' || p === '/') {
+ if (!detectScript) { res.writeHead(404); res.end('Not available'); return; }
+ res.writeHead(200, { 'Content-Type': 'application/javascript' });
+ res.end(detectScript);
+ return;
+ }
+
+ // --- Health ---
+ if (p === '/health') {
+ res.writeHead(200, { 'Content-Type': 'application/json' });
+ res.end(JSON.stringify({
+ status: 'ok', port: state.port, mode: 'variant',
+ hasProjectContext: hasProjectContext(),
+ connectedClients: state.sseClients.size,
+ }));
+ return;
+ }
+
+ // --- Source file (no-HMR fallback) ---
+ if (p === '/source') {
+ const token = url.searchParams.get('token');
+ if (token !== state.token) { res.writeHead(401); res.end('Unauthorized'); return; }
+ const filePath = url.searchParams.get('path');
+ if (!filePath || filePath.includes('..')) { res.writeHead(400); res.end('Bad path'); return; }
+ const absPath = path.resolve(process.cwd(), filePath);
+ if (!absPath.startsWith(process.cwd())) { res.writeHead(403); res.end('Forbidden'); return; }
+ try {
+ res.writeHead(200, { 'Content-Type': 'text/html; charset=utf-8' });
+ res.end(fs.readFileSync(absPath, 'utf-8'));
+ } catch { res.writeHead(404); res.end('File not found'); }
+ return;
+ }
+
+ // --- SSE: server→browser push (replaces WebSocket) ---
+ if (p === '/events' && req.method === 'GET') {
+ const token = url.searchParams.get('token');
+ if (token !== state.token) { res.writeHead(401); res.end('Unauthorized'); return; }
+ res.writeHead(200, {
+ 'Content-Type': 'text/event-stream',
+ 'Cache-Control': 'no-cache',
+ 'Connection': 'keep-alive',
+ });
+ res.write('data: ' + JSON.stringify({
+ type: 'connected',
+ hasProjectContext: hasProjectContext(),
+ }) + '\n\n');
+
+ state.sseClients.add(res);
+ clearTimeout(state.exitTimer);
+
+ req.on('close', () => {
+ state.sseClients.delete(res);
+ if (state.sseClients.size === 0) {
+ clearTimeout(state.exitTimer);
+ state.exitTimer = setTimeout(() => {
+ if (state.sseClients.size === 0) enqueueEvent({ type: 'exit' });
+ }, 8000);
+ }
+ });
+ return;
+ }
+
+ // --- Browser→server events (replaces WebSocket messages) ---
+ if (p === '/events' && req.method === 'POST') {
+ let body = '';
+ req.on('data', (c) => { body += c; });
+ req.on('end', () => {
+ let msg;
+ try { msg = JSON.parse(body); } catch {
+ res.writeHead(400, { 'Content-Type': 'application/json' });
+ res.end(JSON.stringify({ error: 'Invalid JSON' }));
+ return;
+ }
+ if (msg.token !== state.token) {
+ res.writeHead(401, { 'Content-Type': 'application/json' });
+ res.end(JSON.stringify({ error: 'Unauthorized' }));
+ return;
+ }
+ const error = validateEvent(msg);
+ if (error) {
+ res.writeHead(400, { 'Content-Type': 'application/json' });
+ res.end(JSON.stringify({ error }));
+ return;
+ }
+ enqueueEvent(msg);
+ res.writeHead(200, { 'Content-Type': 'application/json' });
+ res.end(JSON.stringify({ ok: true }));
+ });
+ return;
+ }
+
+ // --- Stop ---
+ if (p === '/stop') {
+ const token = url.searchParams.get('token');
+ if (token !== state.token) { res.writeHead(401); res.end('Unauthorized'); return; }
+ res.writeHead(200, { 'Content-Type': 'text/plain' });
+ res.end('stopping');
+ shutdown();
+ return;
+ }
+
+ // --- Agent poll ---
+ if (p === '/poll' && req.method === 'GET') {
+ handlePollGet(req, res, url);
+ return;
+ }
+ if (p === '/poll' && req.method === 'POST') {
+ handlePollPost(req, res);
+ return;
+ }
+
+ res.writeHead(404); res.end('Not found');
+ };
+}
+
+// ---------------------------------------------------------------------------
+// Agent poll endpoints (unchanged from WS version)
+// ---------------------------------------------------------------------------
+
+function handlePollGet(req, res, url) {
+ 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 timeout = parseInt(url.searchParams.get('timeout') || DEFAULT_POLL_TIMEOUT, 10);
+ if (state.pendingEvents.length > 0) {
+ res.writeHead(200, { 'Content-Type': 'application/json' });
+ res.end(JSON.stringify(state.pendingEvents.shift()));
+ return;
+ }
+ const timer = setTimeout(() => {
+ const idx = state.pendingPolls.indexOf(resolve);
+ if (idx !== -1) state.pendingPolls.splice(idx, 1);
+ res.writeHead(200, { 'Content-Type': 'application/json' });
+ res.end(JSON.stringify({ type: 'timeout' }));
+ }, timeout);
+ function resolve(event) {
+ clearTimeout(timer);
+ res.writeHead(200, { 'Content-Type': 'application/json' });
+ res.end(JSON.stringify(event));
+ }
+ state.pendingPolls.push(resolve);
+ req.on('close', () => {
+ clearTimeout(timer);
+ const idx = state.pendingPolls.indexOf(resolve);
+ if (idx !== -1) state.pendingPolls.splice(idx, 1);
+ });
+}
+
+function handlePollPost(req, res) {
+ let body = '';
+ req.on('data', (c) => { body += c; });
+ req.on('end', () => {
+ let msg;
+ try { msg = JSON.parse(body); } catch {
+ res.writeHead(400, { 'Content-Type': 'application/json' });
+ res.end(JSON.stringify({ error: 'Invalid JSON' }));
+ return;
+ }
+ if (msg.token !== state.token) {
+ res.writeHead(401, { 'Content-Type': 'application/json' });
+ res.end(JSON.stringify({ error: 'Unauthorized' }));
+ return;
+ }
+ // Forward the reply to the browser via SSE
+ broadcast({ type: msg.type || 'done', id: msg.id, message: msg.message, file: msg.file, data: msg.data });
+ res.writeHead(200, { 'Content-Type': 'application/json' });
+ res.end(JSON.stringify({ ok: true }));
+ });
+}
+
+// ---------------------------------------------------------------------------
+// Lifecycle
+// ---------------------------------------------------------------------------
+
+let httpServer = null;
+
+function shutdown() {
+ try { fs.unlinkSync(LIVE_PID_FILE); } catch {}
+ for (const res of state.sseClients) { try { res.end(); } catch {} }
+ state.sseClients.clear();
+ for (const resolve of state.pendingPolls) resolve({ type: 'exit' });
+ state.pendingPolls.length = 0;
+ if (httpServer) httpServer.close();
+ process.exit(0);
+}
+
+// ---------------------------------------------------------------------------
+// Main
+// ---------------------------------------------------------------------------
+
+const args = process.argv.slice(2);
+
+if (args.includes('--help') || args.includes('-h')) {
+ console.log(`Usage: node live-server.mjs [options]
+
+Start the live variant mode server (zero dependencies).
+
+Commands:
+ (default) Start the server
+ stop Stop a running server
+
+Options:
+ --port=PORT Use a specific port (default: auto-detect starting at 8400)
+ --help Show this help
+
+Endpoints:
+ /live.js Browser script (element picker + variant cycling)
+ /detect.js Detection overlay (backwards compatible)
+ /events SSE stream (server→browser) + POST (browser→server)
+ /poll Long-poll for agent CLI
+ /source Raw source file reader (no-HMR fallback)
+ /health Health check`);
+ process.exit(0);
+}
+
+if (args.includes('stop')) {
+ try {
+ const info = JSON.parse(fs.readFileSync(LIVE_PID_FILE, 'utf-8'));
+ 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 { console.log('No running live server found.'); }
+ process.exit(0);
+}
+
+// Check for existing session
+try {
+ const existing = JSON.parse(fs.readFileSync(LIVE_PID_FILE, 'utf-8'));
+ 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 {}
+
+state.token = randomUUID();
+const portArg = args.find(a => a.startsWith('--port='));
+state.port = portArg ? parseInt(portArg.split('=')[1], 10) : await findOpenPort();
+
+const { detectScript, liveScript } = loadBrowserScripts();
+const liveScriptWithToken =
+ `window.__IMPECCABLE_TOKEN__ = '${state.token}';\n` +
+ `window.__IMPECCABLE_PORT__ = ${state.port};\n` +
+ liveScript;
+
+httpServer = http.createServer(createRequestHandler({ detectScript, liveScriptWithToken }));
+
+httpServer.listen(state.port, '127.0.0.1', () => {
+ fs.writeFileSync(LIVE_PID_FILE, JSON.stringify({ 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`);
+ console.log(`Inject: <script src="${url}/live.js"><\/script>`);
+ console.log(`Stop: node ${path.basename(fileURLToPath(import.meta.url))} stop`);
+});
+
+process.on('SIGINT', shutdown);
+process.on('SIGTERM', shutdown);
diff --git a/.opencode/skills/impeccable/scripts/live-wrap.mjs b/.opencode/skills/impeccable/scripts/live-wrap.mjs
new file mode 100644
index 000000000..f1c838cdd
--- /dev/null
+++ b/.opencode/skills/impeccable/scripts/live-wrap.mjs
@@ -0,0 +1,298 @@
+/**
+ * CLI helper: find an element in source and wrap it in a variant container.
+ *
+ * Usage:
+ * npx impeccable wrap --id SESSION_ID --count N --query "hero-combined-left" [--file path]
+ *
+ * Searches project files for the element matching the query (class name, ID, or
+ * text snippet), wraps it with the variant scaffolding, and prints the file path
+ * + line range where the agent should insert variant HTML.
+ *
+ * This replaces 3-4 agent tool calls (grep + read + edit) with a single CLI call.
+ */
+
+import fs from 'node:fs';
+import path from 'node:path';
+
+const EXTENSIONS = ['.html', '.jsx', '.tsx', '.vue', '.svelte', '.astro'];
+
+export async function wrapCli() {
+ const args = process.argv.slice(2);
+
+ if (args.includes('--help') || args.includes('-h')) {
+ console.log(`Usage: impeccable wrap [options]
+
+Find an element in source and wrap it in a variant container.
+
+Required:
+ --id ID Session ID for the variant wrapper
+ --count N Number of expected variants (1-8)
+
+Element identification (at least one required):
+ --element-id ID HTML id attribute of the element
+ --classes A,B,C Comma-separated CSS class names
+ --tag TAG Tag name (div, section, etc.)
+ --query TEXT Fallback: raw text to search for
+
+Optional:
+ --file PATH Source file to search in (skips auto-detection)
+ --help Show this help message
+
+Output (JSON):
+ { file, startLine, endLine, insertLine, commentSyntax }
+
+The agent should insert variant HTML at insertLine.`);
+ process.exit(0);
+ }
+
+ const id = argVal(args, '--id');
+ const count = parseInt(argVal(args, '--count') || '3');
+ const elementId = argVal(args, '--element-id');
+ const classes = argVal(args, '--classes');
+ const tag = argVal(args, '--tag');
+ const query = argVal(args, '--query');
+ const filePath = argVal(args, '--file');
+
+ if (!id) { console.error('Missing --id'); process.exit(1); }
+ if (!elementId && !classes && !query) {
+ console.error('Need at least one of: --element-id, --classes, --query');
+ process.exit(1);
+ }
+
+ // Build search queries in priority order (most specific first)
+ const queries = buildSearchQueries(elementId, classes, tag, query);
+
+ // Find the source file
+ let targetFile = filePath;
+ let matchedQuery = null;
+ if (!targetFile) {
+ for (const q of queries) {
+ targetFile = findFileWithQuery(q, process.cwd());
+ if (targetFile) { matchedQuery = q; break; }
+ }
+ if (!targetFile) {
+ console.error(JSON.stringify({ error: 'Could not find element in project files. Searched for: ' + queries.join(', ') }));
+ process.exit(1);
+ }
+ } else {
+ matchedQuery = queries[0];
+ }
+
+ const content = fs.readFileSync(targetFile, 'utf-8');
+ const lines = content.split('\n');
+
+ // Find the element, trying each query in priority order
+ let match = null;
+ for (const q of queries) {
+ match = findElement(lines, q);
+ if (match) break;
+ }
+ if (!match) {
+ console.error(JSON.stringify({ error: 'Found file but could not locate element in ' + targetFile + '. Searched for: ' + queries.join(', ') }));
+ process.exit(1);
+ }
+
+ const { startLine, endLine } = match;
+ const commentSyntax = detectCommentSyntax(targetFile);
+ const indent = lines[startLine].match(/^(\s*)/)[1];
+
+ // Extract the original element
+ const originalLines = lines.slice(startLine, endLine + 1);
+ const originalIndented = originalLines.map(l => indent + ' ' + l.trimStart()).join('\n');
+
+ // Build the wrapper
+ const wrapperLines = [
+ indent + commentSyntax.open + ' impeccable-variants-start ' + id + ' ' + commentSyntax.close,
+ indent + '<div data-impeccable-variants="' + id + '" data-impeccable-variant-count="' + count + '" style="display: contents">',
+ indent + ' ' + commentSyntax.open + ' Original ' + commentSyntax.close,
+ indent + ' <div data-impeccable-variant="original">',
+ originalIndented,
+ indent + ' </div>',
+ indent + ' ' + commentSyntax.open + ' Variants: insert below this line ' + commentSyntax.close,
+ indent + '</div>',
+ indent + commentSyntax.open + ' impeccable-variants-end ' + id + ' ' + commentSyntax.close,
+ ];
+
+ // Replace the original element with the wrapper
+ const newLines = [
+ ...lines.slice(0, startLine),
+ ...wrapperLines,
+ ...lines.slice(endLine + 1),
+ ];
+ fs.writeFileSync(targetFile, newLines.join('\n'), 'utf-8');
+
+ // Calculate insert line (the "insert below this line" comment)
+ const insertLine = startLine + 6; // 0-indexed in the new file
+
+ console.log(JSON.stringify({
+ file: path.relative(process.cwd(), targetFile),
+ startLine: startLine + 1, // 1-indexed for the agent
+ endLine: startLine + wrapperLines.length, // 1-indexed
+ insertLine: insertLine + 1, // 1-indexed: where variants go
+ commentSyntax: commentSyntax,
+ originalLineCount: originalLines.length,
+ }));
+}
+
+// ---------------------------------------------------------------------------
+// Helpers
+// ---------------------------------------------------------------------------
+
+function argVal(args, flag) {
+ const idx = args.indexOf(flag);
+ return idx !== -1 && idx + 1 < args.length ? args[idx + 1] : null;
+}
+
+/**
+ * Build search query strings in priority order (most specific first).
+ * ID is most reliable, then specific class combos, then single classes, then raw query.
+ */
+function buildSearchQueries(elementId, classes, tag, query) {
+ const queries = [];
+
+ // 1. ID is the most specific
+ if (elementId) {
+ queries.push('id="' + elementId + '"');
+ }
+
+ // 2. Full class attribute match (for elements with distinctive multi-class combos)
+ if (classes) {
+ const classList = classes.split(',').map(c => c.trim()).filter(Boolean);
+ if (classList.length > 1) {
+ // Try the most distinctive class first (longest, most specific)
+ const sorted = [...classList].sort((a, b) => b.length - a.length);
+ queries.push('class="' + classList.join(' ') + '"'); // exact full match
+ queries.push(sorted[0]); // most distinctive single class
+ } else if (classList.length === 1) {
+ queries.push(classList[0]);
+ }
+ }
+
+ // 3. Tag + class combo (e.g., <section class="hero">)
+ if (tag && classes) {
+ const firstClass = classes.split(',')[0].trim();
+ queries.push('<' + tag + ' class="' + firstClass);
+ }
+
+ // 4. Raw fallback query
+ if (query) {
+ queries.push(query);
+ }
+
+ return queries;
+}
+
+function detectCommentSyntax(filePath) {
+ const ext = path.extname(filePath).toLowerCase();
+ if (ext === '.jsx' || ext === '.tsx') {
+ return { open: '{/*', close: '*/}' };
+ }
+ // HTML, Vue, Svelte, Astro all use HTML comments
+ return { open: '<!--', close: '-->' };
+}
+
+/**
+ * Search project files for the query string (class name, ID, etc.)
+ * Returns the first matching file path, or null.
+ */
+function findFileWithQuery(query, cwd) {
+ const searchDirs = ['src', 'app', 'pages', 'components', 'public', 'views', 'templates', '.'];
+ const seen = new Set();
+
+ for (const dir of searchDirs) {
+ const absDir = path.join(cwd, dir);
+ if (!fs.existsSync(absDir)) continue;
+ const result = searchDir(absDir, query, seen, 0);
+ if (result) return result;
+ }
+ return null;
+}
+
+function searchDir(dir, query, seen, depth) {
+ if (depth > 5) return null; // don't go too deep
+ const realDir = fs.realpathSync(dir);
+ if (seen.has(realDir)) return null;
+ seen.add(realDir);
+
+ let entries;
+ try { entries = fs.readdirSync(dir, { withFileTypes: true }); }
+ catch { return null; }
+
+ // Check files first
+ for (const entry of entries) {
+ if (!entry.isFile()) continue;
+ const ext = path.extname(entry.name).toLowerCase();
+ if (!EXTENSIONS.includes(ext)) continue;
+
+ const filePath = path.join(dir, entry.name);
+ try {
+ const content = fs.readFileSync(filePath, 'utf-8');
+ if (content.includes(query)) return filePath;
+ } catch { /* skip unreadable files */ }
+ }
+
+ // Then recurse into directories
+ for (const entry of entries) {
+ if (!entry.isDirectory()) continue;
+ if (entry.name === 'node_modules' || entry.name === '.git' || entry.name === 'dist' || entry.name === 'build') continue;
+ const result = searchDir(path.join(dir, entry.name), query, seen, depth + 1);
+ if (result) return result;
+ }
+
+ return null;
+}
+
+/**
+ * Find the element's start and end line in the file.
+ * The query is a class name, ID, or text snippet.
+ * We find the line containing the query, then find the matching closing tag.
+ */
+function findElement(lines, query) {
+ // Find the line containing the query
+ let startLine = -1;
+ for (let i = 0; i < lines.length; i++) {
+ if (lines[i].includes(query)) {
+ // Make sure this looks like a tag opening, not a comment or string
+ const line = lines[i].trim();
+ if (line.startsWith('<!--') || line.startsWith('{/*') || line.startsWith('//')) continue;
+ // Skip lines inside data-impeccable-variant containers (already wrapped)
+ if (lines[i].includes('data-impeccable-variant')) continue;
+ startLine = i;
+ break;
+ }
+ }
+
+ if (startLine === -1) return null;
+
+ // Find the end of this element by counting open/close tags
+ const endLine = findClosingLine(lines, startLine);
+ return { startLine, endLine };
+}
+
+/**
+ * Starting from a line with an opening tag, find the line with the matching
+ * closing tag by counting tag nesting depth.
+ */
+function findClosingLine(lines, start) {
+ // Extract the tag name from the opening line
+ const openMatch = lines[start].match(/<(\w+)[\s>]/);
+ if (!openMatch) return start; // self-closing or text-only line
+
+ const tagName = openMatch[1];
+ let depth = 0;
+
+ for (let i = start; i < lines.length; i++) {
+ const line = lines[i];
+ // Count opening tags (not self-closing)
+ const opens = (line.match(new RegExp('<' + tagName + '[\\s>]', 'g')) || []).length;
+ const selfCloses = (line.match(new RegExp('<' + tagName + '[^>]*/>', 'g')) || []).length;
+ const closes = (line.match(new RegExp('</' + tagName + '\\s*>', 'g')) || []).length;
+
+ depth += opens - selfCloses - closes;
+
+ if (depth <= 0) return i;
+ }
+
+ // If we can't find the close, return a reasonable guess
+ return Math.min(start + 50, lines.length - 1);
+}
diff --git a/.pi/skills/impeccable/reference/live.md b/.pi/skills/impeccable/reference/live.md
index 53b64a21a..ba0e9b0c5 100644
--- a/.pi/skills/impeccable/reference/live.md
+++ b/.pi/skills/impeccable/reference/live.md
@@ -10,7 +10,7 @@ Launch interactive live variant mode: select elements in the browser, pick a des
1. Read `.impeccable.md` if it exists. Keep the design context in mind for variant generation.
2. Start the live variant server:
```bash
- npx impeccable live &
+ node {{scripts_path}}/live-server.mjs &
```
3. Note the **port** and **token** printed to stdout.
@@ -53,7 +53,7 @@ Run a blocking poll loop. On each iteration, wait for a browser event and respon
```
LOOP:
- Run: npx impeccable poll
+ Run: node {{scripts_path}}/live-poll.mjs
Read the JSON output. Dispatch based on the "type" field:
TYPE "generate":
@@ -85,7 +85,7 @@ The event contains: `{id, action, freeformPrompt, count, pageUrl, element}`.
Use the `wrap` helper to find the element and create the variant container:
```bash
-npx impeccable wrap --id EVENT_ID --count EVENT_COUNT --element-id "ELEMENT_ID" --classes "class1,class2" --tag "div"
+node {{scripts_path}}/live-wrap.mjs --id EVENT_ID --count EVENT_COUNT --element-id "ELEMENT_ID" --classes "class1,class2" --tag "div"
```
Pass the element's id (`event.element.id`), classes (`event.element.classes` joined with commas), and tag name. The command searches in priority order: ID match first, then class names, then tag+class combo. If `event.pageUrl` hints at the file (e.g., `/` is usually `index.html`), pass `--file PATH` to skip the search.
@@ -136,10 +136,14 @@ The first variant should NOT have `style="display: none"` (it should be visible
### Step 3: Signal completion
+Include `--file` so the browser can fetch variants directly if the dev server lacks HMR:
+
```bash
-npx impeccable poll --reply EVENT_ID done
+node {{scripts_path}}/live-poll.mjs --reply EVENT_ID done --file RELATIVE_PATH
```
+The file path should be relative to the project root (e.g., `public/index.html`, `src/App.tsx`).
+
## Handle Accept
The event contains: `{id, variantId}`.
@@ -151,7 +155,7 @@ The user accepted a specific variant. For v1 (inspection mode):
4. Remove any scoped CSS blocks (between `impeccable-variants-css-start` and `impeccable-variants-css-end` markers).
5. Reply:
```bash
- npx impeccable poll --reply SESSION_ID done
+ node {{scripts_path}}/live-poll.mjs --reply SESSION_ID done
```
## Handle Discard
@@ -163,7 +167,7 @@ The event contains: `{id}`.
3. Remove any scoped CSS blocks for this session.
4. Reply:
```bash
- npx impeccable poll --reply SESSION_ID done
+ node {{scripts_path}}/live-poll.mjs --reply SESSION_ID done
```
## Cleanup (on exit)
@@ -174,7 +178,7 @@ When the loop ends:
2. **Remove any leftover variant wrappers** (search for `impeccable-variants-start` markers and clean up).
3. **Stop the server**:
```bash
- npx impeccable live stop
+ node {{scripts_path}}/live-server.mjs stop
```
## Variant Generation Guidelines
diff --git a/.pi/skills/impeccable/scripts/live-browser.js b/.pi/skills/impeccable/scripts/live-browser.js
new file mode 100644
index 000000000..7a26c9829
--- /dev/null
+++ b/.pi/skills/impeccable/scripts/live-browser.js
@@ -0,0 +1,1220 @@
+/**
+ * Impeccable Live Variant Mode — Browser Script
+ *
+ * Injected into the user's page via <script src="http://localhost:PORT/live.js">.
+ * The server prepends window.__IMPECCABLE_TOKEN__ and window.__IMPECCABLE_PORT__
+ * before this code.
+ *
+ * UI: a single floating bar that morphs between three states —
+ * configure (pick action + go), generating (progressive dots), and cycling
+ * (prev/next + accept/discard). Feels like Spotlight, not a modal.
+ */
+(function () {
+ 'use strict';
+ if (typeof window === 'undefined') return;
+
+ // Guard against double-init. Bun's HTML loader may process the <script> tag
+ // and create a bundled copy alongside the external load, or HMR may re-execute.
+ // Check BEFORE reading token/port to catch all cases.
+ if (window.__IMPECCABLE_LIVE_INIT__) return;
+ window.__IMPECCABLE_LIVE_INIT__ = true;
+
+ const TOKEN = window.__IMPECCABLE_TOKEN__;
+ const PORT = window.__IMPECCABLE_PORT__;
+ if (!TOKEN || !PORT) {
+ window.__IMPECCABLE_LIVE_INIT__ = false; // reset so the real load can init
+ return;
+ }
+
+ // ---------------------------------------------------------------------------
+ // Design tokens
+ // ---------------------------------------------------------------------------
+
+ const C = {
+ brand: 'oklch(55% 0.25 350)',
+ brandHov: 'oklch(48% 0.25 350)',
+ brandSoft: 'oklch(55% 0.25 350 / 0.12)',
+ ink: 'oklch(15% 0.01 350)',
+ ash: 'oklch(55% 0 0)',
+ paper: 'oklch(98% 0.005 350 / 0.92)',
+ paperSolid:'oklch(98% 0.005 350)',
+ mist: 'oklch(90% 0.01 350 / 0.6)',
+ white: 'oklch(99% 0 0)',
+ };
+ const FONT = 'system-ui, -apple-system, sans-serif';
+ const MONO = 'ui-monospace, SFMono-Regular, Menlo, monospace';
+ const Z = { highlight: 99990, bar: 99995, picker: 99997, toast: 99999 };
+ const EASE = 'cubic-bezier(0.22, 1, 0.36, 1)'; // ease-out-quint
+ const PREFIX = 'impeccable-live';
+
+ const SKIP_TAGS = new Set([
+ 'html', 'head', 'body', 'script', 'style', 'link', 'meta', 'noscript', 'br', 'wbr',
+ ]);
+
+ const ACTIONS = [
+ { value: 'impeccable', label: 'Freeform' },
+ { value: 'bolder', label: 'Bolder' },
+ { value: 'quieter', label: 'Quieter' },
+ { value: 'distill', label: 'Distill' },
+ { value: 'polish', label: 'Polish' },
+ { value: 'typeset', label: 'Typeset' },
+ { value: 'colorize', label: 'Colorize' },
+ { value: 'layout', label: 'Layout' },
+ { value: 'adapt', label: 'Adapt' },
+ { value: 'animate', label: 'Animate' },
+ { value: 'delight', label: 'Delight' },
+ { value: 'overdrive', label: 'Overdrive' },
+ ];
+
+ // ---------------------------------------------------------------------------
+ // State
+ // ---------------------------------------------------------------------------
+
+ let state = 'IDLE';
+ let hoveredElement = null;
+ let selectedElement = null;
+ let currentSessionId = null;
+ let expectedVariants = 0;
+ let arrivedVariants = 0;
+ let visibleVariant = 0;
+ let variantObserver = null;
+ let hasProjectContext = false;
+ let selectedAction = 'impeccable';
+ let selectedCount = 3;
+
+ // UI refs
+ let highlightEl = null;
+ let tooltipEl = null;
+ let barEl = null;
+ let pickerEl = null;
+ let toastEl = null;
+ let scrollRaf = null;
+
+ // ---------------------------------------------------------------------------
+ // Helpers
+ // ---------------------------------------------------------------------------
+
+ function own(el) {
+ return el && (el.id?.startsWith(PREFIX) || el.closest?.('[id^="' + PREFIX + '"]'));
+ }
+
+ function pickable(el) {
+ if (!el || el.nodeType !== 1) return false;
+ if (SKIP_TAGS.has(el.tagName.toLowerCase())) return false;
+ if (own(el)) return false;
+ const r = el.getBoundingClientRect();
+ return r.width >= 20 && r.height >= 20;
+ }
+
+ function desc(el) {
+ if (!el) return '';
+ let s = el.tagName.toLowerCase();
+ if (el.id) s += '#' + el.id;
+ else if (el.classList.length) s += '.' + [...el.classList].slice(0, 2).join('.');
+ return s;
+ }
+
+ function id8() { return crypto.randomUUID().replace(/-/g, '').slice(0, 8); }
+
+ // ---------------------------------------------------------------------------
+ // Highlight overlay
+ // ---------------------------------------------------------------------------
+
+ function initHighlight() {
+ highlightEl = document.createElement('div');
+ highlightEl.id = PREFIX + '-highlight';
+ Object.assign(highlightEl.style, {
+ position: 'fixed', top: '0', left: '0', width: '0', height: '0',
+ border: '2px solid ' + C.brand, borderRadius: '3px',
+ pointerEvents: 'none', zIndex: Z.highlight, boxSizing: 'border-box',
+ transition: 'top 0.08s ease, left 0.08s ease, width 0.08s ease, height 0.08s ease, opacity 0.15s ease',
+ display: 'none', opacity: '0',
+ });
+ document.body.appendChild(highlightEl);
+
+ tooltipEl = document.createElement('div');
+ tooltipEl.id = PREFIX + '-tooltip';
+ Object.assign(tooltipEl.style, {
+ position: 'fixed',
+ background: C.ink, color: C.white,
+ fontFamily: MONO, fontSize: '10px', fontWeight: '500',
+ padding: '2px 6px', borderRadius: '3px',
+ zIndex: Z.highlight + 1, pointerEvents: 'none',
+ whiteSpace: 'nowrap', display: 'none',
+ letterSpacing: '0.02em',
+ });
+ document.body.appendChild(tooltipEl);
+ }
+
+ function showHighlight(el) {
+ if (!el || !highlightEl) return;
+ const r = el.getBoundingClientRect();
+ Object.assign(highlightEl.style, {
+ top: (r.top - 2) + 'px', left: (r.left - 2) + 'px',
+ width: (r.width + 4) + 'px', height: (r.height + 4) + 'px',
+ display: 'block', opacity: '1',
+ });
+ tooltipEl.textContent = desc(el);
+ const tipTop = r.top - 20;
+ Object.assign(tooltipEl.style, {
+ top: (tipTop < 4 ? r.bottom + 4 : tipTop) + 'px',
+ left: Math.max(4, r.left) + 'px', display: 'block',
+ });
+ }
+
+ function hideHighlight() {
+ if (highlightEl) { highlightEl.style.opacity = '0'; highlightEl.style.display = 'none'; }
+ if (tooltipEl) tooltipEl.style.display = 'none';
+ }
+
+ // ---------------------------------------------------------------------------
+ // Element context extraction
+ // ---------------------------------------------------------------------------
+
+ function extractContext(el) {
+ const cs = getComputedStyle(el);
+ const r = el.getBoundingClientRect();
+ const props = {};
+ for (const sheet of document.styleSheets) {
+ try {
+ for (const rule of sheet.cssRules) {
+ if (rule.style) for (let i = 0; i < rule.style.length; i++) {
+ const p = rule.style[i];
+ if (p.startsWith('--') && !props[p]) {
+ const v = cs.getPropertyValue(p).trim();
+ if (v) props[p] = v;
+ }
+ }
+ }
+ } catch { /* cross-origin */ }
+ }
+ return {
+ tagName: el.tagName.toLowerCase(), id: el.id || null,
+ classes: [...el.classList],
+ textContent: (el.textContent || '').slice(0, 500),
+ outerHTML: el.outerHTML.slice(0, 10000),
+ computedStyles: {
+ 'font-family': cs.fontFamily, 'font-size': cs.fontSize,
+ 'font-weight': cs.fontWeight, 'line-height': cs.lineHeight,
+ 'color': cs.color, 'background': cs.background,
+ 'background-color': cs.backgroundColor,
+ 'padding': cs.padding, 'margin': cs.margin,
+ 'display': cs.display, 'position': cs.position,
+ 'gap': cs.gap, 'border-radius': cs.borderRadius,
+ 'box-shadow': cs.boxShadow,
+ },
+ cssCustomProperties: props,
+ parentContext: el.parentElement
+ ? '<' + el.parentElement.tagName.toLowerCase()
+ + (el.parentElement.id ? ' id="' + el.parentElement.id + '"' : '')
+ + (el.parentElement.className ? ' class="' + el.parentElement.className + '"' : '')
+ + '>'
+ : null,
+ boundingRect: { width: Math.round(r.width), height: Math.round(r.height) },
+ };
+ }
+
+ // ---------------------------------------------------------------------------
+ // The Bar — one floating element, three modes
+ // ---------------------------------------------------------------------------
+
+ function initBar() {
+ barEl = document.createElement('div');
+ barEl.id = PREFIX + '-bar';
+ Object.assign(barEl.style, {
+ position: 'fixed', zIndex: Z.bar,
+ display: 'none', opacity: '0',
+ transform: 'translateY(6px)',
+ transition: 'opacity 0.25s ' + EASE + ', transform 0.3s ' + EASE,
+ // Visual
+ background: C.paper,
+ backdropFilter: 'blur(16px)', WebkitBackdropFilter: 'blur(16px)',
+ border: '1px solid ' + C.mist,
+ borderRadius: '10px',
+ boxShadow: '0 4px 20px oklch(0% 0 0 / 0.08), 0 1px 3px oklch(0% 0 0 / 0.06)',
+ fontFamily: FONT, fontSize: '13px', color: C.ink,
+ padding: '6px',
+ maxWidth: '460px', minWidth: '320px',
+ });
+ document.body.appendChild(barEl);
+ }
+
+ function positionBar() {
+ if (!barEl || !selectedElement) return;
+ const r = selectedElement.getBoundingClientRect();
+ const barH = barEl.offsetHeight || 44;
+ const barW = barEl.offsetWidth || 380;
+ let top = r.bottom + 8;
+ let left = r.left + (r.width - barW) / 2;
+ // Keep in viewport
+ if (top + barH + 8 > window.innerHeight) top = r.top - barH - 8;
+ if (top < 8) top = 8;
+ if (left < 8) left = 8;
+ if (left + barW > window.innerWidth - 8) left = window.innerWidth - barW - 8;
+ Object.assign(barEl.style, { top: top + 'px', left: left + 'px' });
+ }
+
+ function showBar(mode) {
+ barEl.innerHTML = '';
+ if (mode === 'configure') barEl.appendChild(buildConfigureRow());
+ else if (mode === 'generating') barEl.appendChild(buildGeneratingRow());
+ else if (mode === 'cycling') barEl.appendChild(buildCyclingRow());
+ barEl.style.display = 'block';
+ positionBar();
+ requestAnimationFrame(() => {
+ barEl.style.opacity = '1';
+ barEl.style.transform = 'translateY(0)';
+ });
+ }
+
+ function hideBar() {
+ if (!barEl) return;
+ barEl.style.opacity = '0';
+ barEl.style.transform = 'translateY(6px)';
+ setTimeout(() => { if (barEl) barEl.style.display = 'none'; }, 250);
+ hideActionPicker();
+ }
+
+ function updateBarContent(mode) {
+ if (!barEl || barEl.style.display === 'none') return;
+ barEl.innerHTML = '';
+ // Reset bar styling
+ barEl.style.background = C.paper;
+ barEl.style.border = '1px solid ' + C.mist;
+ if (mode === 'configure') barEl.appendChild(buildConfigureRow());
+ else if (mode === 'generating') barEl.appendChild(buildGeneratingRow());
+ else if (mode === 'cycling') barEl.appendChild(buildCyclingRow());
+ else if (mode === 'saving') barEl.appendChild(buildSavingRow());
+ else if (mode === 'confirmed') {
+ barEl.appendChild(buildConfirmedRow());
+ barEl.style.background = 'oklch(95% 0.05 145)';
+ barEl.style.border = '1px solid oklch(75% 0.12 145 / 0.4)';
+ }
+ }
+
+ // --- Configure row ---
+
+ function buildConfigureRow() {
+ const row = el('div', {
+ display: 'flex', alignItems: 'center', gap: '4px',
+ });
+
+ // Action pill
+ const pill = el('button', {
+ display: 'inline-flex', alignItems: 'center', gap: '4px',
+ padding: '5px 10px', borderRadius: '6px',
+ background: C.ink, color: C.white,
+ fontFamily: FONT, fontSize: '12px', fontWeight: '500',
+ border: 'none', cursor: 'pointer',
+ transition: 'background 0.12s ease, transform 0.1s ease',
+ whiteSpace: 'nowrap', flexShrink: '0',
+ });
+ pill.textContent = actionLabel() + ' \u25BE';
+ pill.addEventListener('mouseenter', () => pill.style.background = C.brandHov);
+ pill.addEventListener('mouseleave', () => pill.style.background = C.ink);
+ pill.addEventListener('mousedown', () => pill.style.transform = 'scale(0.97)');
+ pill.addEventListener('mouseup', () => pill.style.transform = 'scale(1)');
+ pill.addEventListener('click', (e) => { e.stopPropagation(); toggleActionPicker(); });
+ row.appendChild(pill);
+
+ // Freeform input
+ const input = document.createElement('input');
+ input.id = PREFIX + '-input';
+ input.type = 'text';
+ input.placeholder = selectedAction === 'impeccable' ? 'describe what you want...' : 'refine further (optional)...';
+ Object.assign(input.style, {
+ flex: '1', minWidth: '0',
+ padding: '5px 8px', borderRadius: '6px',
+ border: '1px solid transparent', background: 'transparent',
+ fontFamily: FONT, fontSize: '12px', color: C.ink,
+ outline: 'none',
+ transition: 'border-color 0.15s ease, background 0.15s ease',
+ });
+ input.addEventListener('focus', () => {
+ input.style.borderColor = C.mist;
+ input.style.background = C.white;
+ });
+ input.addEventListener('blur', () => {
+ input.style.borderColor = 'transparent';
+ input.style.background = 'transparent';
+ });
+ input.addEventListener('keydown', (e) => {
+ e.stopPropagation(); // Don't trigger element picker keyboard nav
+ if (e.key === 'Enter') { e.preventDefault(); handleGo(); }
+ if (e.key === 'Escape') { e.preventDefault(); input.blur(); hideBar(); state = 'PICKING'; }
+ });
+ row.appendChild(input);
+
+ // Variant count toggle
+ const count = el('button', {
+ padding: '4px 6px', borderRadius: '5px',
+ border: '1px solid ' + C.mist, background: 'transparent',
+ fontFamily: MONO, fontSize: '11px', fontWeight: '600',
+ color: C.ash, cursor: 'pointer',
+ transition: 'color 0.12s ease, border-color 0.12s ease',
+ flexShrink: '0', whiteSpace: 'nowrap',
+ });
+ count.textContent = '\u00D7' + selectedCount;
+ count.title = 'Variants: click to change';
+ count.addEventListener('mouseenter', () => { count.style.color = C.ink; count.style.borderColor = C.ink; });
+ count.addEventListener('mouseleave', () => { count.style.color = C.ash; count.style.borderColor = C.mist; });
+ count.addEventListener('click', (e) => {
+ e.stopPropagation();
+ selectedCount = selectedCount >= 4 ? 2 : selectedCount + 1;
+ count.textContent = '\u00D7' + selectedCount;
+ });
+ row.appendChild(count);
+
+ // Go button
+ const go = el('button', {
+ padding: '5px 12px', borderRadius: '6px',
+ border: 'none', background: C.brand, color: C.white,
+ fontFamily: FONT, fontSize: '12px', fontWeight: '600',
+ cursor: 'pointer',
+ transition: 'background 0.12s ease, transform 0.1s ease',
+ flexShrink: '0', whiteSpace: 'nowrap',
+ });
+ go.textContent = 'Go \u2192';
+ go.addEventListener('mouseenter', () => go.style.background = C.brandHov);
+ go.addEventListener('mouseleave', () => go.style.background = C.brand);
+ go.addEventListener('mousedown', () => go.style.transform = 'scale(0.97)');
+ go.addEventListener('mouseup', () => go.style.transform = 'scale(1)');
+ go.addEventListener('click', (e) => { e.stopPropagation(); handleGo(); });
+ row.appendChild(go);
+
+ // Auto-focus input after a beat
+ setTimeout(() => input.focus(), 60);
+ return row;
+ }
+
+ // --- Generating row ---
+
+ function buildGeneratingRow() {
+ const row = el('div', {
+ display: 'flex', alignItems: 'center', gap: '8px',
+ padding: '2px 4px',
+ });
+
+ // Action label
+ const label = el('span', {
+ fontWeight: '600', fontSize: '12px', color: C.ink,
+ flexShrink: '0', whiteSpace: 'nowrap',
+ });
+ label.textContent = actionLabel();
+ row.appendChild(label);
+
+ // Dots
+ row.appendChild(buildDots(false));
+
+ // Status
+ const status = el('span', {
+ fontSize: '11px', color: C.ash, whiteSpace: 'nowrap',
+ marginLeft: 'auto',
+ });
+ status.textContent = arrivedVariants < expectedVariants
+ ? 'Generating ' + (arrivedVariants + 1) + ' of ' + expectedVariants + '...'
+ : 'Done';
+ row.appendChild(status);
+
+ return row;
+ }
+
+ // --- Cycling row ---
+
+ function buildCyclingRow() {
+ const row = el('div', {
+ display: 'flex', alignItems: 'center', gap: '6px',
+ padding: '1px 2px',
+ });
+
+ // Prev
+ const prev = navBtn('\u2190');
+ prev.addEventListener('click', (e) => { e.stopPropagation(); cycleVariant(-1); });
+ if (visibleVariant <= 1) prev.style.opacity = '0.3';
+ row.appendChild(prev);
+
+ // Dots (clickable)
+ row.appendChild(buildDots(true));
+
+ // Counter
+ const counter = el('span', {
+ fontFamily: MONO, fontSize: '11px', fontWeight: '500',
+ color: C.ash, minWidth: '24px', textAlign: 'center',
+ });
+ counter.textContent = visibleVariant + '/' + arrivedVariants;
+ row.appendChild(counter);
+
+ // Next
+ const next = navBtn('\u2192');
+ next.addEventListener('click', (e) => { e.stopPropagation(); cycleVariant(1); });
+ if (visibleVariant >= arrivedVariants) next.style.opacity = '0.3';
+ row.appendChild(next);
+
+ // Spacer
+ row.appendChild(el('div', { flex: '1' }));
+
+ // Accept
+ const accept = el('button', {
+ padding: '4px 10px', borderRadius: '5px',
+ border: 'none', background: C.ink, color: C.white,
+ fontFamily: FONT, fontSize: '11px', fontWeight: '600',
+ cursor: 'pointer', transition: 'background 0.12s ease',
+ whiteSpace: 'nowrap',
+ });
+ accept.textContent = '\u2713 Accept';
+ accept.addEventListener('mouseenter', () => accept.style.background = C.brand);
+ accept.addEventListener('mouseleave', () => accept.style.background = C.ink);
+ accept.addEventListener('click', (e) => { e.stopPropagation(); handleAccept(); });
+ if (arrivedVariants === 0) { accept.style.opacity = '0.3'; accept.style.pointerEvents = 'none'; }
+ row.appendChild(accept);
+
+ // Discard
+ const discard = el('button', {
+ padding: '4px 6px', borderRadius: '5px',
+ border: '1px solid ' + C.mist, background: 'transparent',
+ fontFamily: FONT, fontSize: '11px', color: C.ash,
+ cursor: 'pointer', transition: 'color 0.12s ease, border-color 0.12s ease',
+ });
+ discard.textContent = '\u2715';
+ discard.title = 'Discard all variants';
+ discard.addEventListener('mouseenter', () => { discard.style.color = C.ink; discard.style.borderColor = C.ink; });
+ discard.addEventListener('mouseleave', () => { discard.style.color = C.ash; discard.style.borderColor = C.mist; });
+ discard.addEventListener('click', (e) => { e.stopPropagation(); handleDiscard(); });
+ row.appendChild(discard);
+
+ return row;
+ }
+
+ // --- Shared UI builders ---
+
+ // --- Saving row (waiting for agent to process accept/discard) ---
+
+ function buildSavingRow() {
+ const row = el('div', {
+ display: 'flex', alignItems: 'center', gap: '8px',
+ padding: '2px 8px',
+ });
+ const spinner = el('div', {
+ width: '14px', height: '14px', borderRadius: '50%',
+ border: '2px solid ' + C.mist,
+ borderTopColor: C.brand,
+ animation: 'impeccable-spin 0.6s linear infinite',
+ flexShrink: '0',
+ });
+ row.appendChild(spinner);
+ const label = el('span', {
+ fontSize: '12px', color: C.ash, fontWeight: '500',
+ });
+ label.textContent = 'Applying variant...';
+ row.appendChild(label);
+
+ // Inject the keyframes if not already present
+ if (!document.getElementById(PREFIX + '-keyframes')) {
+ const style = document.createElement('style');
+ style.id = PREFIX + '-keyframes';
+ style.textContent = '@keyframes impeccable-spin { to { transform: rotate(360deg); } }';
+ document.head.appendChild(style);
+ }
+ return row;
+ }
+
+ // --- Confirmed row (green success, auto-dismisses) ---
+
+ function buildConfirmedRow() {
+ const row = el('div', {
+ display: 'flex', alignItems: 'center', gap: '8px',
+ padding: '2px 8px',
+ });
+ const check = el('span', {
+ fontSize: '15px', lineHeight: '1', flexShrink: '0',
+ color: 'oklch(45% 0.15 145)',
+ });
+ check.textContent = '\u2713';
+ row.appendChild(check);
+ const label = el('span', {
+ fontSize: '12px', color: 'oklch(35% 0.1 145)', fontWeight: '600',
+ });
+ label.textContent = 'Variant applied';
+ row.appendChild(label);
+ return row;
+ }
+
+ // --- Shared UI builders ---
+
+ function buildDots(clickable) {
+ const container = el('div', {
+ display: 'flex', alignItems: 'center', gap: '4px',
+ });
+ for (let i = 1; i <= expectedVariants; i++) {
+ const arrived = i <= arrivedVariants;
+ const active = i === visibleVariant;
+ const dot = el('div', {
+ width: '7px', height: '7px', borderRadius: '50%',
+ background: active ? C.brand : (arrived ? C.ash : 'transparent'),
+ border: '1.5px solid ' + (arrived ? C.brand : C.mist),
+ transition: 'all 0.2s ' + EASE,
+ cursor: (clickable && arrived) ? 'pointer' : 'default',
+ transform: arrived ? 'scale(1)' : 'scale(0.6)',
+ opacity: arrived ? '1' : '0.4',
+ });
+ if (clickable && arrived) {
+ const idx = i;
+ dot.addEventListener('click', (e) => {
+ e.stopPropagation();
+ visibleVariant = idx;
+ showVariantInDOM(currentSessionId, idx);
+ updateSelectedElement();
+ updateBarContent('cycling');
+ });
+ }
+ container.appendChild(dot);
+ }
+ return container;
+ }
+
+ function navBtn(text) {
+ const b = el('button', {
+ width: '26px', height: '26px', borderRadius: '5px',
+ border: '1px solid ' + C.mist, background: 'transparent',
+ color: C.ink, fontFamily: FONT, fontSize: '13px',
+ cursor: 'pointer', display: 'flex', alignItems: 'center', justifyContent: 'center',
+ transition: 'border-color 0.12s ease, background 0.12s ease',
+ padding: '0', lineHeight: '1',
+ });
+ b.textContent = text;
+ b.addEventListener('mouseenter', () => { b.style.borderColor = C.ink; });
+ b.addEventListener('mouseleave', () => { b.style.borderColor = C.mist; });
+ return b;
+ }
+
+ function actionLabel() {
+ const a = ACTIONS.find(a => a.value === selectedAction);
+ return a ? a.label : 'Freeform';
+ }
+
+ function el(tag, styles) {
+ const e = document.createElement(tag);
+ if (styles) Object.assign(e.style, styles);
+ return e;
+ }
+
+ // ---------------------------------------------------------------------------
+ // Action picker popover
+ // ---------------------------------------------------------------------------
+
+ function initActionPicker() {
+ pickerEl = document.createElement('div');
+ pickerEl.id = PREFIX + '-picker';
+ Object.assign(pickerEl.style, {
+ position: 'fixed', zIndex: Z.picker,
+ display: 'none', opacity: '0',
+ transform: 'scale(0.96) translateY(4px)',
+ transformOrigin: 'bottom left',
+ transition: 'opacity 0.18s ' + EASE + ', transform 0.2s ' + EASE,
+ background: C.paperSolid,
+ border: '1px solid ' + C.mist,
+ borderRadius: '10px',
+ boxShadow: '0 8px 30px oklch(0% 0 0 / 0.10), 0 2px 6px oklch(0% 0 0 / 0.06)',
+ padding: '6px',
+ fontFamily: FONT,
+ });
+
+ // Build the chip grid
+ const grid = el('div', {
+ display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', gap: '3px',
+ });
+
+ ACTIONS.forEach(action => {
+ const chip = el('button', {
+ padding: '6px 8px', borderRadius: '6px',
+ border: 'none',
+ background: action.value === selectedAction ? C.brandSoft : 'transparent',
+ color: action.value === selectedAction ? C.brand : C.ink,
+ fontFamily: FONT, fontSize: '11px', fontWeight: '500',
+ cursor: 'pointer',
+ transition: 'background 0.1s ease, color 0.1s ease',
+ textAlign: 'center', whiteSpace: 'nowrap',
+ });
+ chip.textContent = action.label;
+ chip.dataset.action = action.value;
+ chip.addEventListener('mouseenter', () => {
+ if (action.value !== selectedAction) chip.style.background = C.brandSoft;
+ });
+ chip.addEventListener('mouseleave', () => {
+ chip.style.background = action.value === selectedAction ? C.brandSoft : 'transparent';
+ });
+ chip.addEventListener('click', (e) => {
+ e.stopPropagation();
+ selectedAction = action.value;
+ hideActionPicker();
+ updateBarContent('configure');
+ });
+ grid.appendChild(chip);
+ });
+
+ pickerEl.appendChild(grid);
+ document.body.appendChild(pickerEl);
+ }
+
+ function toggleActionPicker() {
+ if (pickerEl.style.display !== 'none') { hideActionPicker(); return; }
+ // Rebuild chips to reflect current selection
+ pickerEl.querySelectorAll('button').forEach(chip => {
+ const isActive = chip.dataset.action === selectedAction;
+ chip.style.background = isActive ? C.brandSoft : 'transparent';
+ chip.style.color = isActive ? C.brand : C.ink;
+ });
+ // Position above the bar
+ const barRect = barEl.getBoundingClientRect();
+ const pickerH = 90; // approximate
+ let top = barRect.top - pickerH - 6;
+ if (top < 8) top = barRect.bottom + 6;
+ Object.assign(pickerEl.style, {
+ top: top + 'px', left: barRect.left + 'px',
+ display: 'block',
+ });
+ requestAnimationFrame(() => {
+ pickerEl.style.opacity = '1';
+ pickerEl.style.transform = 'scale(1) translateY(0)';
+ });
+ }
+
+ function hideActionPicker() {
+ if (!pickerEl) return;
+ pickerEl.style.opacity = '0';
+ pickerEl.style.transform = 'scale(0.96) translateY(4px)';
+ setTimeout(() => { if (pickerEl) pickerEl.style.display = 'none'; }, 180);
+ }
+
+ // ---------------------------------------------------------------------------
+ // Variant cycling in DOM
+ // ---------------------------------------------------------------------------
+
+ function showVariantInDOM(sessionId, num) {
+ const wrapper = document.querySelector('[data-impeccable-variants="' + sessionId + '"]');
+ if (!wrapper) return;
+ for (const child of wrapper.children) {
+ const v = child.dataset ? child.dataset.impeccableVariant : null;
+ if (!v) continue;
+ child.style.display = (v === String(num)) ? '' : 'none';
+ }
+ }
+
+ /**
+ * No-HMR fallback: fetch the raw source file from the live server,
+ * parse it, extract the variant wrapper, and inject it into the live DOM.
+ * This works even when the dev server caches HTML (Bun, static servers).
+ */
+ function injectVariantsFromSource(filePath, sessionId) {
+ const url = 'http://localhost:' + PORT + '/source?token=' + TOKEN + '&path=' + encodeURIComponent(filePath);
+ fetch(url)
+ .then(r => { if (!r.ok) throw new Error(r.status); return r.text(); })
+ .then(html => {
+ // Parse the raw source HTML
+ const parser = new DOMParser();
+ const doc = parser.parseFromString(html, 'text/html');
+ const srcWrapper = doc.querySelector('[data-impeccable-variants="' + sessionId + '"]');
+ if (!srcWrapper) {
+ console.error('[impeccable] Variant wrapper not found in source file.');
+ return;
+ }
+
+ // Find the original element in the live DOM.
+ // The original is inside the wrapper in the source. We find the
+ // corresponding element in the live DOM by matching the first child's
+ // tag + classes from the original snapshot.
+ const origContent = srcWrapper.querySelector('[data-impeccable-variant="original"] > :first-child');
+ if (!origContent) return;
+
+ const tag = origContent.tagName.toLowerCase();
+ const cls = origContent.className;
+ let liveEl = null;
+ if (origContent.id) {
+ liveEl = document.getElementById(origContent.id);
+ } else if (cls) {
+ // Find by tag + exact class match
+ const candidates = document.querySelectorAll(tag + '.' + cls.split(' ')[0]);
+ for (const c of candidates) {
+ if (c.className === cls && !own(c)) { liveEl = c; break; }
+ }
+ }
+
+ if (!liveEl) {
+ console.error('[impeccable] Could not find original element in live DOM.');
+ return;
+ }
+
+ // Replace the live element with the full wrapper from source
+ const wrapper = srcWrapper.cloneNode(true);
+ liveEl.parentElement.replaceChild(wrapper, liveEl);
+
+ // Update state: count variants, show the first one
+ 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);
+
+ // Update selectedElement to the visible variant's content
+ const visEl = wrapper.querySelector('[data-impeccable-variant="1"] > :first-child');
+ selectedElement = visEl || wrapper.parentElement;
+
+ state = 'CYCLING';
+ updateBarContent('cycling');
+ saveSession();
+ console.log('[impeccable] Injected ' + arrivedVariants + ' variants from source file.');
+ })
+ .catch(err => {
+ console.error('[impeccable] Failed to fetch source:', err);
+ showToast('Could not load variants. Try refreshing the page.', 5000);
+ });
+ }
+
+ function cycleVariant(dir) {
+ const next = visibleVariant + dir;
+ if (next < 1 || next > arrivedVariants) return;
+ visibleVariant = next;
+ showVariantInDOM(currentSessionId, next);
+ updateSelectedElement();
+ updateBarContent('cycling');
+ saveSession();
+ }
+
+ function updateSelectedElement() {
+ if (!currentSessionId) return;
+ const wrapper = document.querySelector('[data-impeccable-variants="' + currentSessionId + '"]');
+ if (!wrapper) return;
+ const visEl = wrapper.querySelector('[data-impeccable-variant="' + visibleVariant + '"] > :first-child');
+ if (visEl) selectedElement = visEl;
+ }
+
+ // ---------------------------------------------------------------------------
+ // MutationObserver for progressive variant reveal
+ // ---------------------------------------------------------------------------
+
+ function startVariantObserver(sessionId) {
+ let updating = false; // re-entrancy guard
+
+ const obs = new MutationObserver((mutations) => {
+ if (updating) return;
+
+ // Only react to mutations that add nodes with data-impeccable-variant,
+ // or mutations inside the variant wrapper. Ignore our own bar/UI changes.
+ let dominated = false;
+ for (const m of mutations) {
+ if (m.target.closest?.('[data-impeccable-variants]')) { dominated = true; break; }
+ for (const n of m.addedNodes) {
+ if (n.nodeType === 1 && (n.dataset?.impeccableVariants || n.dataset?.impeccableVariant)) {
+ dominated = true; break;
+ }
+ }
+ if (dominated) break;
+ }
+ if (!dominated) return;
+
+ const wrapper = document.querySelector('[data-impeccable-variants="' + sessionId + '"]');
+ if (!wrapper) return;
+
+ const variants = wrapper.querySelectorAll('[data-impeccable-variant]:not([data-impeccable-variant="original"])');
+ const count = variants.length;
+
+ // Nothing new
+ if (count <= arrivedVariants) return;
+
+ updating = true;
+ arrivedVariants = count;
+ if (visibleVariant === 0 && arrivedVariants > 0) {
+ visibleVariant = 1;
+ showVariantInDOM(sessionId, 1);
+ }
+
+ const expected = parseInt(wrapper.dataset.impeccableVariantCount || '0');
+ if (expected > 0) expectedVariants = expected;
+
+ if (arrivedVariants >= expectedVariants && expectedVariants > 0) {
+ state = 'CYCLING';
+ updateBarContent('cycling');
+ } else if (state === 'GENERATING') {
+ updateBarContent('generating');
+ }
+ saveSession();
+ updating = false;
+ });
+
+ obs.observe(document.body, { childList: true, subtree: true });
+ return obs;
+ }
+
+ // ---------------------------------------------------------------------------
+ // Bar scroll tracking
+ // ---------------------------------------------------------------------------
+
+ function startScrollTracking() {
+ function tick() {
+ if (state === 'CONFIGURING' || state === 'GENERATING' || state === 'CYCLING') {
+ positionBar();
+ showHighlight(selectedElement);
+ }
+ scrollRaf = requestAnimationFrame(tick);
+ }
+ scrollRaf = requestAnimationFrame(tick);
+ }
+
+ function stopScrollTracking() {
+ if (scrollRaf) { cancelAnimationFrame(scrollRaf); scrollRaf = null; }
+ }
+
+ // ---------------------------------------------------------------------------
+ // SSE (server→browser) + fetch POST (browser→server)
+ // Zero-dependency replacement for WebSocket.
+ // ---------------------------------------------------------------------------
+
+ let evtSource = null;
+
+ function connectSSE() {
+ evtSource = new EventSource('http://localhost:' + PORT + '/events?token=' + TOKEN);
+
+ evtSource.onmessage = (e) => {
+ let msg; try { msg = JSON.parse(e.data); } catch { return; }
+ switch (msg.type) {
+ case 'connected':
+ hasProjectContext = !!msg.hasProjectContext;
+ if (!hasProjectContext) showToast('No .impeccable.md found. Variants will be brand-agnostic.', 6000);
+ console.log('[impeccable] Live mode connected.');
+ if (state === 'IDLE') state = 'PICKING';
+ break;
+ case 'done':
+ if (state === 'SAVING') {
+ state = 'CONFIRMED';
+ updateBarContent('confirmed');
+ setTimeout(() => {
+ hideBar();
+ hideHighlight();
+ stopScrollTracking();
+ if (variantObserver) { variantObserver.disconnect(); variantObserver = null; }
+ clearSession();
+ selectedElement = null;
+ currentSessionId = null;
+ selectedAction = 'impeccable';
+ state = 'PICKING';
+ }, 1800);
+ return;
+ }
+ if (arrivedVariants === 0 && expectedVariants > 0 && msg.file) {
+ console.log('[impeccable] No HMR detected. Fetching variants from source file...');
+ injectVariantsFromSource(msg.file, currentSessionId);
+ return;
+ }
+ state = 'CYCLING';
+ updateBarContent('cycling');
+ break;
+ case 'error':
+ console.error('[impeccable] Error:', msg.message);
+ showToast('Error: ' + msg.message, 5000);
+ hideBar();
+ state = 'PICKING';
+ break;
+ }
+ };
+
+ evtSource.onerror = () => {
+ // EventSource auto-reconnects. Log once.
+ console.log('[impeccable] SSE connection lost. Reconnecting...');
+ };
+ }
+
+ function sendEvent(msg) {
+ msg.token = TOKEN;
+ 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));
+ }
+
+ // ---------------------------------------------------------------------------
+ // Event handlers
+ // ---------------------------------------------------------------------------
+
+ function handleMouseMove(e) {
+ if (state !== 'PICKING') return;
+ const target = document.elementFromPoint(e.clientX, e.clientY);
+ if (!target || !pickable(target) || target === hoveredElement) return;
+ hoveredElement = target;
+ showHighlight(target);
+ }
+
+ function handleClick(e) {
+ // Close action picker on any outside click
+ if (pickerEl?.style.display !== 'none' && !own(e.target)) {
+ hideActionPicker();
+ }
+ if (state !== 'PICKING') return;
+ if (own(e.target)) return;
+ if (!hoveredElement || !pickable(hoveredElement)) return;
+ e.preventDefault();
+ e.stopPropagation();
+ selectedElement = hoveredElement;
+ state = 'CONFIGURING';
+ showHighlight(selectedElement);
+ showBar('configure');
+ startScrollTracking();
+ }
+
+ function handleKeyDown(e) {
+ if (e.key === 'Escape') {
+ e.preventDefault();
+ if (pickerEl?.style.display !== 'none') { hideActionPicker(); return; }
+ if (state === 'CONFIGURING') { hideBar(); stopScrollTracking(); state = 'PICKING'; return; }
+ if (state === 'CYCLING') { handleDiscard(); return; }
+ if (state === 'SAVING' || state === 'CONFIRMED') return; // don't interrupt
+ if (state === 'PICKING') { hideHighlight(); state = 'IDLE'; return; }
+ }
+
+ if (state === 'PICKING' && hoveredElement) {
+ let next = null;
+ if (e.key === 'ArrowDown' && !e.shiftKey) {
+ next = hoveredElement.nextElementSibling;
+ while (next && !pickable(next)) next = next.nextElementSibling;
+ } else if (e.key === 'ArrowUp' && !e.shiftKey) {
+ next = hoveredElement.previousElementSibling;
+ while (next && !pickable(next)) next = next.previousElementSibling;
+ } else if (e.key === 'ArrowUp' && e.shiftKey) {
+ next = hoveredElement.parentElement;
+ if (next && !pickable(next)) next = null;
+ } else if (e.key === 'ArrowDown' && e.shiftKey) {
+ next = hoveredElement.firstElementChild;
+ while (next && !pickable(next)) next = next.nextElementSibling;
+ } else if (e.key === 'Enter') {
+ e.preventDefault();
+ selectedElement = hoveredElement;
+ state = 'CONFIGURING';
+ showHighlight(selectedElement);
+ showBar('configure');
+ startScrollTracking();
+ return;
+ }
+ if (next) {
+ e.preventDefault();
+ hoveredElement = next;
+ showHighlight(next);
+ next.scrollIntoView({ block: 'nearest', behavior: 'smooth' });
+ }
+ return;
+ }
+
+ if (state === 'CYCLING') {
+ if (e.key === 'ArrowLeft') { e.preventDefault(); cycleVariant(-1); }
+ if (e.key === 'ArrowRight') { e.preventDefault(); cycleVariant(1); }
+ if (e.key === 'Enter') { e.preventDefault(); handleAccept(); }
+ }
+ }
+
+ function handleGo() {
+ if (!selectedElement || state !== 'CONFIGURING') return;
+ const input = document.getElementById(PREFIX + '-input');
+ const prompt = input ? input.value.trim() : '';
+
+ currentSessionId = id8();
+ expectedVariants = selectedCount;
+ arrivedVariants = 0;
+ visibleVariant = 0;
+
+ sendEvent({
+ type: 'generate', id: currentSessionId,
+ action: selectedAction,
+ freeformPrompt: prompt || undefined,
+ count: selectedCount,
+ pageUrl: location.pathname,
+ element: extractContext(selectedElement),
+ });
+
+ state = 'GENERATING';
+ showBar('generating');
+ saveSession();
+ if (variantObserver) variantObserver.disconnect();
+ variantObserver = startVariantObserver(currentSessionId);
+ }
+
+ function handleAccept() {
+ if (!currentSessionId || arrivedVariants === 0) return;
+ sendEvent({ type: 'accept', id: currentSessionId, variantId: String(visibleVariant) });
+ markSessionHandled();
+ state = 'SAVING';
+ updateBarContent('saving');
+ // Don't cleanup yet — wait for the "done" WS message to show confirmation
+ }
+
+ function handleDiscard() {
+ if (!currentSessionId) return;
+ sendEvent({ type: 'discard', id: currentSessionId });
+ markSessionHandled();
+ state = 'SAVING';
+ updateBarContent('saving');
+ // Wait for "done" WS message to show confirmation and dismiss
+ }
+
+ // ---------------------------------------------------------------------------
+ // Session persistence via localStorage
+ // ---------------------------------------------------------------------------
+ // Survives page reloads, browser close/reopen, HMR, and accidental refreshes.
+
+ const LS_KEY = PREFIX + '-session';
+
+ function saveSession() {
+ if (!currentSessionId) return;
+ 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 */ }
+ }
+
+ function loadSession() {
+ try {
+ const raw = localStorage.getItem(LS_KEY);
+ return raw ? JSON.parse(raw) : null;
+ } catch { return null; }
+ }
+
+ function clearSession() {
+ try { localStorage.removeItem(LS_KEY); } catch {}
+ }
+
+ /** Mark session as handled (accepted/discarded). The agent will clean up
+ * the source, but until it does the wrapper is still in the HTML. This
+ * prevents resumeSession from picking it up again after reload. */
+ function markSessionHandled() {
+ if (!currentSessionId) return;
+ try {
+ localStorage.setItem(LS_KEY + '-handled', currentSessionId);
+ } catch {}
+ }
+
+ function isSessionHandled(id) {
+ try {
+ return localStorage.getItem(LS_KEY + '-handled') === id;
+ } catch { return false; }
+ }
+
+ function clearHandled() {
+ try { localStorage.removeItem(LS_KEY + '-handled'); } catch {}
+ }
+
+ function cleanup() {
+ hideBar();
+ hideHighlight();
+ stopScrollTracking();
+ if (variantObserver) { variantObserver.disconnect(); variantObserver = null; }
+ clearSession();
+ selectedElement = null;
+ currentSessionId = null;
+ selectedAction = 'impeccable';
+ state = 'PICKING';
+ }
+
+ // ---------------------------------------------------------------------------
+ // Toast
+ // ---------------------------------------------------------------------------
+
+ function showToast(message, duration) {
+ if (toastEl) toastEl.remove();
+ toastEl = el('div', {
+ position: 'fixed', bottom: '16px', left: '50%',
+ transform: 'translateX(-50%) translateY(8px)',
+ background: C.ink, color: C.white,
+ fontFamily: FONT, fontSize: '12px',
+ padding: '8px 16px', borderRadius: '8px',
+ zIndex: Z.toast, opacity: '0',
+ transition: 'opacity 0.25s ' + EASE + ', transform 0.25s ' + EASE,
+ pointerEvents: 'none', maxWidth: '420px', textAlign: 'center',
+ });
+ toastEl.id = PREFIX + '-toast';
+ toastEl.textContent = message;
+ document.body.appendChild(toastEl);
+ requestAnimationFrame(() => {
+ toastEl.style.opacity = '1';
+ toastEl.style.transform = 'translateX(-50%) translateY(0)';
+ });
+ setTimeout(() => {
+ if (toastEl) {
+ toastEl.style.opacity = '0';
+ toastEl.style.transform = 'translateX(-50%) translateY(8px)';
+ setTimeout(() => { if (toastEl) { toastEl.remove(); toastEl = null; } }, 250);
+ }
+ }, duration);
+ }
+
+ // ---------------------------------------------------------------------------
+ // Init
+ // ---------------------------------------------------------------------------
+
+ // Resume an active variant session after HMR/page reload.
+ // If a [data-impeccable-variants] wrapper exists in the DOM, the agent wrote
+ // variants before HMR fired. Pick up where we left off.
+ function resumeSession() {
+ const wrapper = document.querySelector('[data-impeccable-variants]');
+ if (!wrapper) { clearSession(); clearHandled(); return false; }
+
+ const sessionId = wrapper.dataset.impeccableVariants;
+
+ // Don't resume if this session was already accepted/discarded
+ if (isSessionHandled(sessionId)) return false;
+
+ currentSessionId = sessionId;
+ expectedVariants = parseInt(wrapper.dataset.impeccableVariantCount || '0');
+ const variants = wrapper.querySelectorAll('[data-impeccable-variant]:not([data-impeccable-variant="original"])');
+ arrivedVariants = variants.length;
+
+ // Restore visible variant from localStorage if available, else default to 1
+ const saved = loadSession();
+ visibleVariant = (saved && saved.id === sessionId && saved.visible > 0 && saved.visible <= arrivedVariants)
+ ? saved.visible : (arrivedVariants > 0 ? 1 : 0);
+
+ // Find the visible variant's content element for highlight positioning
+ const visEl = wrapper.querySelector('[data-impeccable-variant="' + visibleVariant + '"] > :first-child');
+ selectedElement = visEl || wrapper.parentElement;
+
+ // Set display state BEFORE starting observer (avoid triggering it)
+ if (visibleVariant > 0) showVariantInDOM(currentSessionId, visibleVariant);
+
+ state = arrivedVariants >= expectedVariants ? 'CYCLING' : 'GENERATING';
+ showBar(state === 'CYCLING' ? 'cycling' : 'generating');
+ startScrollTracking();
+ saveSession();
+
+ // Start observing for more variants AFTER initial setup
+ if (variantObserver) variantObserver.disconnect();
+ variantObserver = startVariantObserver(currentSessionId);
+ return true;
+ }
+
+ function init() {
+ initHighlight();
+ initBar();
+ initActionPicker();
+ document.addEventListener('mousemove', handleMouseMove, true);
+ document.addEventListener('click', handleClick, true);
+ document.addEventListener('keydown', handleKeyDown, true);
+ connectSSE();
+
+ // Check for an active session to resume (variant wrapper already in DOM after HMR)
+ if (!resumeSession()) {
+ console.log('[impeccable] Live variant mode ready. Hover over elements to pick one.');
+ } else {
+ console.log('[impeccable] Resumed active variant session ' + currentSessionId + ' (' + arrivedVariants + '/' + expectedVariants + ' variants).');
+ }
+ }
+
+ if (document.readyState === 'loading') {
+ document.addEventListener('DOMContentLoaded', init);
+ } else {
+ init();
+ }
+})();
diff --git a/.pi/skills/impeccable/scripts/live-poll.mjs b/.pi/skills/impeccable/scripts/live-poll.mjs
new file mode 100644
index 000000000..52859416c
--- /dev/null
+++ b/.pi/skills/impeccable/scripts/live-poll.mjs
@@ -0,0 +1,123 @@
+/**
+ * CLI client for the live variant mode poll/reply protocol.
+ *
+ * Usage:
+ * npx impeccable poll # Block until browser event, print JSON
+ * npx impeccable poll --timeout=60000 # Custom timeout (ms)
+ * npx impeccable poll --reply <id> done # Reply "done" to event <id>
+ * npx impeccable poll --reply <id> error "msg" # Reply with error
+ */
+
+import fs from 'node:fs';
+import path from 'node:path';
+import os from 'node:os';
+
+const LIVE_PID_FILE = path.join(os.tmpdir(), 'impeccable-live.json');
+
+function readServerInfo() {
+ try {
+ return JSON.parse(fs.readFileSync(LIVE_PID_FILE, 'utf-8'));
+ } catch {
+ console.error('No running live server found. Start one with: npx impeccable live');
+ process.exit(1);
+ }
+}
+
+export async function pollCli() {
+ const args = process.argv.slice(2);
+
+ if (args.includes('--help') || args.includes('-h')) {
+ console.log(`Usage: impeccable poll [options]
+
+Wait for a browser event from the live variant server, or reply to one.
+
+Modes:
+ poll Block until a browser event arrives, print JSON
+ poll --reply <id> done Reply "done" to event <id>
+ poll --reply <id> error "msg" Reply with an error message
+
+Options:
+ --timeout=MS Poll timeout in milliseconds (default: 120000)
+ --help Show this help message`);
+ process.exit(0);
+ }
+
+ const info = readServerInfo();
+ const base = `http://localhost:${info.port}`;
+
+ // Reply mode: npx impeccable poll --reply <id> <status> [--file path] [message]
+ const replyIdx = args.indexOf('--reply');
+ if (replyIdx !== -1) {
+ const id = args[replyIdx + 1];
+ const status = args[replyIdx + 2] || 'done';
+ const fileIdx = args.indexOf('--file');
+ const filePath = fileIdx !== -1 && fileIdx + 1 < args.length ? args[fileIdx + 1] : undefined;
+ // Message is any remaining positional arg that isn't a flag
+ const message = args.find((a, i) => i > replyIdx + 2 && !a.startsWith('--') && i !== fileIdx + 1) || undefined;
+
+ if (!id) {
+ console.error('Usage: npx impeccable poll --reply <id> <status> [--file path] [message]');
+ process.exit(1);
+ }
+
+ 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);
+ }
+
+ // Success — silent exit (agent doesn't need output for replies)
+ } catch (err) {
+ if (err.cause?.code === 'ECONNREFUSED') {
+ console.error('Live server not running. Start one with: npx impeccable live');
+ } else {
+ console.error('Reply failed:', err.message);
+ }
+ process.exit(1);
+ }
+ return;
+ }
+
+ // Poll mode: block until browser event
+ const timeoutArg = args.find(a => a.startsWith('--timeout='));
+ const timeout = timeoutArg ? parseInt(timeoutArg.split('=')[1], 10) : 120000;
+
+ try {
+ const res = await fetch(`${base}/poll?token=${info.token}&timeout=${timeout}`);
+
+ if (res.status === 401) {
+ console.error('Authentication failed. The server token may have changed.');
+ console.error('Try restarting: npx impeccable live stop && npx impeccable live');
+ process.exit(1);
+ }
+
+ if (!res.ok) {
+ console.error(`Poll failed: ${res.status} ${res.statusText}`);
+ process.exit(1);
+ }
+
+ const event = await res.json();
+ // Print the event as JSON — the agent reads this from stdout
+ console.log(JSON.stringify(event));
+ } catch (err) {
+ if (err.cause?.code === 'ECONNREFUSED') {
+ console.error('Live server not running. Start one with: npx impeccable live');
+ } else {
+ console.error('Poll failed:', err.message);
+ }
+ process.exit(1);
+ }
+}
diff --git a/.pi/skills/impeccable/scripts/live-server.mjs b/.pi/skills/impeccable/scripts/live-server.mjs
new file mode 100644
index 000000000..d436bad58
--- /dev/null
+++ b/.pi/skills/impeccable/scripts/live-server.mjs
@@ -0,0 +1,416 @@
+#!/usr/bin/env node
+/**
+ * Live variant mode server (self-contained, zero dependencies).
+ *
+ * Serves the browser script (/live.js), the detection overlay (/detect.js),
+ * uses Server-Sent Events (SSE) for server→browser push, and HTTP POST for
+ * browser→server events. Agent communicates via HTTP long-poll (/poll).
+ *
+ * Usage:
+ * node <scripts_path>/live-server.mjs # start
+ * node <scripts_path>/live-server.mjs stop # stop
+ * node <scripts_path>/live-server.mjs --help
+ */
+
+import http from 'node:http';
+import { randomUUID } from 'node:crypto';
+import fs from 'node:fs';
+import path from 'node:path';
+import os from 'node:os';
+import net from 'node:net';
+import { fileURLToPath } from 'node:url';
+
+const __dirname = path.dirname(fileURLToPath(import.meta.url));
+const LIVE_PID_FILE = path.join(os.tmpdir(), 'impeccable-live.json');
+const DEFAULT_POLL_TIMEOUT = 120_000;
+
+// ---------------------------------------------------------------------------
+// Port detection
+// ---------------------------------------------------------------------------
+
+async function findOpenPort(start = 8400) {
+ return new Promise((resolve) => {
+ const srv = net.createServer();
+ srv.listen(start, '127.0.0.1', () => {
+ const port = srv.address().port;
+ srv.close(() => resolve(port));
+ });
+ srv.on('error', () => resolve(findOpenPort(start + 1)));
+ });
+}
+
+// ---------------------------------------------------------------------------
+// Session state
+// ---------------------------------------------------------------------------
+
+const state = {
+ token: null,
+ port: null,
+ sseClients: new Set(), // SSE response objects (server→browser push)
+ pendingEvents: [], // browser events waiting for agent poll
+ pendingPolls: [], // agent poll callbacks waiting for browser events
+ exitTimer: null,
+};
+
+function enqueueEvent(event) {
+ if (state.pendingPolls.length > 0) {
+ state.pendingPolls.shift()(event);
+ } else {
+ state.pendingEvents.push(event);
+ }
+}
+
+/** Push a message to all connected SSE clients. */
+function broadcast(msg) {
+ const data = 'data: ' + JSON.stringify(msg) + '\n\n';
+ for (const res of state.sseClients) {
+ try { res.write(data); } catch { /* client gone */ }
+ }
+}
+
+// ---------------------------------------------------------------------------
+// Load scripts
+// ---------------------------------------------------------------------------
+
+function loadBrowserScripts() {
+ // Detection script: look relative to the skill scripts dir, then fall back
+ // to the npm package location (src/detect-antipatterns-browser.js)
+ const detectPaths = [
+ path.join(__dirname, '..', '..', '..', '..', 'src', 'detect-antipatterns-browser.js'),
+ path.join(process.cwd(), 'node_modules', 'impeccable', 'src', 'detect-antipatterns-browser.js'),
+ ];
+ let detectScript = '';
+ for (const p of detectPaths) {
+ try { detectScript = fs.readFileSync(p, 'utf-8'); break; } catch { /* try next */ }
+ }
+
+ const livePath = path.join(__dirname, 'live-browser.js');
+ let liveScript = '';
+ try {
+ liveScript = fs.readFileSync(livePath, 'utf-8');
+ } catch {
+ process.stderr.write('Error: live-browser.js not found at ' + livePath + '\n');
+ process.exit(1);
+ }
+
+ return { detectScript, liveScript };
+}
+
+function hasProjectContext() {
+ try {
+ fs.accessSync(path.join(process.cwd(), '.impeccable.md'), fs.constants.R_OK);
+ return true;
+ } catch { return false; }
+}
+
+// ---------------------------------------------------------------------------
+// Validation (inline — no external import needed for self-contained script)
+// ---------------------------------------------------------------------------
+
+const VISUAL_ACTIONS = [
+ 'impeccable', 'bolder', 'quieter', 'distill', 'polish', 'typeset',
+ 'colorize', 'layout', 'adapt', 'animate', 'delight', 'overdrive',
+];
+
+function validateEvent(msg) {
+ if (!msg || typeof msg !== 'object' || !msg.type) return 'Missing or invalid message';
+ switch (msg.type) {
+ case 'generate':
+ if (!msg.id || typeof msg.id !== 'string') return 'generate: missing id';
+ if (!msg.action || !VISUAL_ACTIONS.includes(msg.action)) return 'generate: invalid action';
+ if (!Number.isInteger(msg.count) || msg.count < 1 || msg.count > 8) return 'generate: count must be 1-8';
+ if (!msg.element || !msg.element.outerHTML) return 'generate: missing element context';
+ return null;
+ case 'accept':
+ if (!msg.id) return 'accept: missing id';
+ if (!msg.variantId) return 'accept: missing variantId';
+ return null;
+ case 'discard':
+ return msg.id ? null : 'discard: missing id';
+ case 'exit':
+ return null;
+ default:
+ return 'Unknown event type: ' + msg.type;
+ }
+}
+
+// ---------------------------------------------------------------------------
+// HTTP request handler
+// ---------------------------------------------------------------------------
+
+function createRequestHandler({ detectScript, liveScriptWithToken }) {
+ return (req, res) => {
+ const url = new URL(req.url, `http://localhost:${state.port}`);
+ res.setHeader('Access-Control-Allow-Origin', '*');
+ res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS');
+ res.setHeader('Access-Control-Allow-Headers', 'Content-Type');
+ if (req.method === 'OPTIONS') { res.writeHead(204); res.end(); return; }
+
+ const p = url.pathname;
+
+ // --- Scripts ---
+ if (p === '/live.js') {
+ res.writeHead(200, { 'Content-Type': 'application/javascript' });
+ res.end(liveScriptWithToken);
+ return;
+ }
+ if (p === '/detect.js' || p === '/') {
+ if (!detectScript) { res.writeHead(404); res.end('Not available'); return; }
+ res.writeHead(200, { 'Content-Type': 'application/javascript' });
+ res.end(detectScript);
+ return;
+ }
+
+ // --- Health ---
+ if (p === '/health') {
+ res.writeHead(200, { 'Content-Type': 'application/json' });
+ res.end(JSON.stringify({
+ status: 'ok', port: state.port, mode: 'variant',
+ hasProjectContext: hasProjectContext(),
+ connectedClients: state.sseClients.size,
+ }));
+ return;
+ }
+
+ // --- Source file (no-HMR fallback) ---
+ if (p === '/source') {
+ const token = url.searchParams.get('token');
+ if (token !== state.token) { res.writeHead(401); res.end('Unauthorized'); return; }
+ const filePath = url.searchParams.get('path');
+ if (!filePath || filePath.includes('..')) { res.writeHead(400); res.end('Bad path'); return; }
+ const absPath = path.resolve(process.cwd(), filePath);
+ if (!absPath.startsWith(process.cwd())) { res.writeHead(403); res.end('Forbidden'); return; }
+ try {
+ res.writeHead(200, { 'Content-Type': 'text/html; charset=utf-8' });
+ res.end(fs.readFileSync(absPath, 'utf-8'));
+ } catch { res.writeHead(404); res.end('File not found'); }
+ return;
+ }
+
+ // --- SSE: server→browser push (replaces WebSocket) ---
+ if (p === '/events' && req.method === 'GET') {
+ const token = url.searchParams.get('token');
+ if (token !== state.token) { res.writeHead(401); res.end('Unauthorized'); return; }
+ res.writeHead(200, {
+ 'Content-Type': 'text/event-stream',
+ 'Cache-Control': 'no-cache',
+ 'Connection': 'keep-alive',
+ });
+ res.write('data: ' + JSON.stringify({
+ type: 'connected',
+ hasProjectContext: hasProjectContext(),
+ }) + '\n\n');
+
+ state.sseClients.add(res);
+ clearTimeout(state.exitTimer);
+
+ req.on('close', () => {
+ state.sseClients.delete(res);
+ if (state.sseClients.size === 0) {
+ clearTimeout(state.exitTimer);
+ state.exitTimer = setTimeout(() => {
+ if (state.sseClients.size === 0) enqueueEvent({ type: 'exit' });
+ }, 8000);
+ }
+ });
+ return;
+ }
+
+ // --- Browser→server events (replaces WebSocket messages) ---
+ if (p === '/events' && req.method === 'POST') {
+ let body = '';
+ req.on('data', (c) => { body += c; });
+ req.on('end', () => {
+ let msg;
+ try { msg = JSON.parse(body); } catch {
+ res.writeHead(400, { 'Content-Type': 'application/json' });
+ res.end(JSON.stringify({ error: 'Invalid JSON' }));
+ return;
+ }
+ if (msg.token !== state.token) {
+ res.writeHead(401, { 'Content-Type': 'application/json' });
+ res.end(JSON.stringify({ error: 'Unauthorized' }));
+ return;
+ }
+ const error = validateEvent(msg);
+ if (error) {
+ res.writeHead(400, { 'Content-Type': 'application/json' });
+ res.end(JSON.stringify({ error }));
+ return;
+ }
+ enqueueEvent(msg);
+ res.writeHead(200, { 'Content-Type': 'application/json' });
+ res.end(JSON.stringify({ ok: true }));
+ });
+ return;
+ }
+
+ // --- Stop ---
+ if (p === '/stop') {
+ const token = url.searchParams.get('token');
+ if (token !== state.token) { res.writeHead(401); res.end('Unauthorized'); return; }
+ res.writeHead(200, { 'Content-Type': 'text/plain' });
+ res.end('stopping');
+ shutdown();
+ return;
+ }
+
+ // --- Agent poll ---
+ if (p === '/poll' && req.method === 'GET') {
+ handlePollGet(req, res, url);
+ return;
+ }
+ if (p === '/poll' && req.method === 'POST') {
+ handlePollPost(req, res);
+ return;
+ }
+
+ res.writeHead(404); res.end('Not found');
+ };
+}
+
+// ---------------------------------------------------------------------------
+// Agent poll endpoints (unchanged from WS version)
+// ---------------------------------------------------------------------------
+
+function handlePollGet(req, res, url) {
+ 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 timeout = parseInt(url.searchParams.get('timeout') || DEFAULT_POLL_TIMEOUT, 10);
+ if (state.pendingEvents.length > 0) {
+ res.writeHead(200, { 'Content-Type': 'application/json' });
+ res.end(JSON.stringify(state.pendingEvents.shift()));
+ return;
+ }
+ const timer = setTimeout(() => {
+ const idx = state.pendingPolls.indexOf(resolve);
+ if (idx !== -1) state.pendingPolls.splice(idx, 1);
+ res.writeHead(200, { 'Content-Type': 'application/json' });
+ res.end(JSON.stringify({ type: 'timeout' }));
+ }, timeout);
+ function resolve(event) {
+ clearTimeout(timer);
+ res.writeHead(200, { 'Content-Type': 'application/json' });
+ res.end(JSON.stringify(event));
+ }
+ state.pendingPolls.push(resolve);
+ req.on('close', () => {
+ clearTimeout(timer);
+ const idx = state.pendingPolls.indexOf(resolve);
+ if (idx !== -1) state.pendingPolls.splice(idx, 1);
+ });
+}
+
+function handlePollPost(req, res) {
+ let body = '';
+ req.on('data', (c) => { body += c; });
+ req.on('end', () => {
+ let msg;
+ try { msg = JSON.parse(body); } catch {
+ res.writeHead(400, { 'Content-Type': 'application/json' });
+ res.end(JSON.stringify({ error: 'Invalid JSON' }));
+ return;
+ }
+ if (msg.token !== state.token) {
+ res.writeHead(401, { 'Content-Type': 'application/json' });
+ res.end(JSON.stringify({ error: 'Unauthorized' }));
+ return;
+ }
+ // Forward the reply to the browser via SSE
+ broadcast({ type: msg.type || 'done', id: msg.id, message: msg.message, file: msg.file, data: msg.data });
+ res.writeHead(200, { 'Content-Type': 'application/json' });
+ res.end(JSON.stringify({ ok: true }));
+ });
+}
+
+// ---------------------------------------------------------------------------
+// Lifecycle
+// ---------------------------------------------------------------------------
+
+let httpServer = null;
+
+function shutdown() {
+ try { fs.unlinkSync(LIVE_PID_FILE); } catch {}
+ for (const res of state.sseClients) { try { res.end(); } catch {} }
+ state.sseClients.clear();
+ for (const resolve of state.pendingPolls) resolve({ type: 'exit' });
+ state.pendingPolls.length = 0;
+ if (httpServer) httpServer.close();
+ process.exit(0);
+}
+
+// ---------------------------------------------------------------------------
+// Main
+// ---------------------------------------------------------------------------
+
+const args = process.argv.slice(2);
+
+if (args.includes('--help') || args.includes('-h')) {
+ console.log(`Usage: node live-server.mjs [options]
+
+Start the live variant mode server (zero dependencies).
+
+Commands:
+ (default) Start the server
+ stop Stop a running server
+
+Options:
+ --port=PORT Use a specific port (default: auto-detect starting at 8400)
+ --help Show this help
+
+Endpoints:
+ /live.js Browser script (element picker + variant cycling)
+ /detect.js Detection overlay (backwards compatible)
+ /events SSE stream (server→browser) + POST (browser→server)
+ /poll Long-poll for agent CLI
+ /source Raw source file reader (no-HMR fallback)
+ /health Health check`);
+ process.exit(0);
+}
+
+if (args.includes('stop')) {
+ try {
+ const info = JSON.parse(fs.readFileSync(LIVE_PID_FILE, 'utf-8'));
+ 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 { console.log('No running live server found.'); }
+ process.exit(0);
+}
+
+// Check for existing session
+try {
+ const existing = JSON.parse(fs.readFileSync(LIVE_PID_FILE, 'utf-8'));
+ 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 {}
+
+state.token = randomUUID();
+const portArg = args.find(a => a.startsWith('--port='));
+state.port = portArg ? parseInt(portArg.split('=')[1], 10) : await findOpenPort();
+
+const { detectScript, liveScript } = loadBrowserScripts();
+const liveScriptWithToken =
+ `window.__IMPECCABLE_TOKEN__ = '${state.token}';\n` +
+ `window.__IMPECCABLE_PORT__ = ${state.port};\n` +
+ liveScript;
+
+httpServer = http.createServer(createRequestHandler({ detectScript, liveScriptWithToken }));
+
+httpServer.listen(state.port, '127.0.0.1', () => {
+ fs.writeFileSync(LIVE_PID_FILE, JSON.stringify({ 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`);
+ console.log(`Inject: <script src="${url}/live.js"><\/script>`);
+ console.log(`Stop: node ${path.basename(fileURLToPath(import.meta.url))} stop`);
+});
+
+process.on('SIGINT', shutdown);
+process.on('SIGTERM', shutdown);
diff --git a/.pi/skills/impeccable/scripts/live-wrap.mjs b/.pi/skills/impeccable/scripts/live-wrap.mjs
new file mode 100644
index 000000000..f1c838cdd
--- /dev/null
+++ b/.pi/skills/impeccable/scripts/live-wrap.mjs
@@ -0,0 +1,298 @@
+/**
+ * CLI helper: find an element in source and wrap it in a variant container.
+ *
+ * Usage:
+ * npx impeccable wrap --id SESSION_ID --count N --query "hero-combined-left" [--file path]
+ *
+ * Searches project files for the element matching the query (class name, ID, or
+ * text snippet), wraps it with the variant scaffolding, and prints the file path
+ * + line range where the agent should insert variant HTML.
+ *
+ * This replaces 3-4 agent tool calls (grep + read + edit) with a single CLI call.
+ */
+
+import fs from 'node:fs';
+import path from 'node:path';
+
+const EXTENSIONS = ['.html', '.jsx', '.tsx', '.vue', '.svelte', '.astro'];
+
+export async function wrapCli() {
+ const args = process.argv.slice(2);
+
+ if (args.includes('--help') || args.includes('-h')) {
+ console.log(`Usage: impeccable wrap [options]
+
+Find an element in source and wrap it in a variant container.
+
+Required:
+ --id ID Session ID for the variant wrapper
+ --count N Number of expected variants (1-8)
+
+Element identification (at least one required):
+ --element-id ID HTML id attribute of the element
+ --classes A,B,C Comma-separated CSS class names
+ --tag TAG Tag name (div, section, etc.)
+ --query TEXT Fallback: raw text to search for
+
+Optional:
+ --file PATH Source file to search in (skips auto-detection)
+ --help Show this help message
+
+Output (JSON):
+ { file, startLine, endLine, insertLine, commentSyntax }
+
+The agent should insert variant HTML at insertLine.`);
+ process.exit(0);
+ }
+
+ const id = argVal(args, '--id');
+ const count = parseInt(argVal(args, '--count') || '3');
+ const elementId = argVal(args, '--element-id');
+ const classes = argVal(args, '--classes');
+ const tag = argVal(args, '--tag');
+ const query = argVal(args, '--query');
+ const filePath = argVal(args, '--file');
+
+ if (!id) { console.error('Missing --id'); process.exit(1); }
+ if (!elementId && !classes && !query) {
+ console.error('Need at least one of: --element-id, --classes, --query');
+ process.exit(1);
+ }
+
+ // Build search queries in priority order (most specific first)
+ const queries = buildSearchQueries(elementId, classes, tag, query);
+
+ // Find the source file
+ let targetFile = filePath;
+ let matchedQuery = null;
+ if (!targetFile) {
+ for (const q of queries) {
+ targetFile = findFileWithQuery(q, process.cwd());
+ if (targetFile) { matchedQuery = q; break; }
+ }
+ if (!targetFile) {
+ console.error(JSON.stringify({ error: 'Could not find element in project files. Searched for: ' + queries.join(', ') }));
+ process.exit(1);
+ }
+ } else {
+ matchedQuery = queries[0];
+ }
+
+ const content = fs.readFileSync(targetFile, 'utf-8');
+ const lines = content.split('\n');
+
+ // Find the element, trying each query in priority order
+ let match = null;
+ for (const q of queries) {
+ match = findElement(lines, q);
+ if (match) break;
+ }
+ if (!match) {
+ console.error(JSON.stringify({ error: 'Found file but could not locate element in ' + targetFile + '. Searched for: ' + queries.join(', ') }));
+ process.exit(1);
+ }
+
+ const { startLine, endLine } = match;
+ const commentSyntax = detectCommentSyntax(targetFile);
+ const indent = lines[startLine].match(/^(\s*)/)[1];
+
+ // Extract the original element
+ const originalLines = lines.slice(startLine, endLine + 1);
+ const originalIndented = originalLines.map(l => indent + ' ' + l.trimStart()).join('\n');
+
+ // Build the wrapper
+ const wrapperLines = [
+ indent + commentSyntax.open + ' impeccable-variants-start ' + id + ' ' + commentSyntax.close,
+ indent + '<div data-impeccable-variants="' + id + '" data-impeccable-variant-count="' + count + '" style="display: contents">',
+ indent + ' ' + commentSyntax.open + ' Original ' + commentSyntax.close,
+ indent + ' <div data-impeccable-variant="original">',
+ originalIndented,
+ indent + ' </div>',
+ indent + ' ' + commentSyntax.open + ' Variants: insert below this line ' + commentSyntax.close,
+ indent + '</div>',
+ indent + commentSyntax.open + ' impeccable-variants-end ' + id + ' ' + commentSyntax.close,
+ ];
+
+ // Replace the original element with the wrapper
+ const newLines = [
+ ...lines.slice(0, startLine),
+ ...wrapperLines,
+ ...lines.slice(endLine + 1),
+ ];
+ fs.writeFileSync(targetFile, newLines.join('\n'), 'utf-8');
+
+ // Calculate insert line (the "insert below this line" comment)
+ const insertLine = startLine + 6; // 0-indexed in the new file
+
+ console.log(JSON.stringify({
+ file: path.relative(process.cwd(), targetFile),
+ startLine: startLine + 1, // 1-indexed for the agent
+ endLine: startLine + wrapperLines.length, // 1-indexed
+ insertLine: insertLine + 1, // 1-indexed: where variants go
+ commentSyntax: commentSyntax,
+ originalLineCount: originalLines.length,
+ }));
+}
+
+// ---------------------------------------------------------------------------
+// Helpers
+// ---------------------------------------------------------------------------
+
+function argVal(args, flag) {
+ const idx = args.indexOf(flag);
+ return idx !== -1 && idx + 1 < args.length ? args[idx + 1] : null;
+}
+
+/**
+ * Build search query strings in priority order (most specific first).
+ * ID is most reliable, then specific class combos, then single classes, then raw query.
+ */
+function buildSearchQueries(elementId, classes, tag, query) {
+ const queries = [];
+
+ // 1. ID is the most specific
+ if (elementId) {
+ queries.push('id="' + elementId + '"');
+ }
+
+ // 2. Full class attribute match (for elements with distinctive multi-class combos)
+ if (classes) {
+ const classList = classes.split(',').map(c => c.trim()).filter(Boolean);
+ if (classList.length > 1) {
+ // Try the most distinctive class first (longest, most specific)
+ const sorted = [...classList].sort((a, b) => b.length - a.length);
+ queries.push('class="' + classList.join(' ') + '"'); // exact full match
+ queries.push(sorted[0]); // most distinctive single class
+ } else if (classList.length === 1) {
+ queries.push(classList[0]);
+ }
+ }
+
+ // 3. Tag + class combo (e.g., <section class="hero">)
+ if (tag && classes) {
+ const firstClass = classes.split(',')[0].trim();
+ queries.push('<' + tag + ' class="' + firstClass);
+ }
+
+ // 4. Raw fallback query
+ if (query) {
+ queries.push(query);
+ }
+
+ return queries;
+}
+
+function detectCommentSyntax(filePath) {
+ const ext = path.extname(filePath).toLowerCase();
+ if (ext === '.jsx' || ext === '.tsx') {
+ return { open: '{/*', close: '*/}' };
+ }
+ // HTML, Vue, Svelte, Astro all use HTML comments
+ return { open: '<!--', close: '-->' };
+}
+
+/**
+ * Search project files for the query string (class name, ID, etc.)
+ * Returns the first matching file path, or null.
+ */
+function findFileWithQuery(query, cwd) {
+ const searchDirs = ['src', 'app', 'pages', 'components', 'public', 'views', 'templates', '.'];
+ const seen = new Set();
+
+ for (const dir of searchDirs) {
+ const absDir = path.join(cwd, dir);
+ if (!fs.existsSync(absDir)) continue;
+ const result = searchDir(absDir, query, seen, 0);
+ if (result) return result;
+ }
+ return null;
+}
+
+function searchDir(dir, query, seen, depth) {
+ if (depth > 5) return null; // don't go too deep
+ const realDir = fs.realpathSync(dir);
+ if (seen.has(realDir)) return null;
+ seen.add(realDir);
+
+ let entries;
+ try { entries = fs.readdirSync(dir, { withFileTypes: true }); }
+ catch { return null; }
+
+ // Check files first
+ for (const entry of entries) {
+ if (!entry.isFile()) continue;
+ const ext = path.extname(entry.name).toLowerCase();
+ if (!EXTENSIONS.includes(ext)) continue;
+
+ const filePath = path.join(dir, entry.name);
+ try {
+ const content = fs.readFileSync(filePath, 'utf-8');
+ if (content.includes(query)) return filePath;
+ } catch { /* skip unreadable files */ }
+ }
+
+ // Then recurse into directories
+ for (const entry of entries) {
+ if (!entry.isDirectory()) continue;
+ if (entry.name === 'node_modules' || entry.name === '.git' || entry.name === 'dist' || entry.name === 'build') continue;
+ const result = searchDir(path.join(dir, entry.name), query, seen, depth + 1);
+ if (result) return result;
+ }
+
+ return null;
+}
+
+/**
+ * Find the element's start and end line in the file.
+ * The query is a class name, ID, or text snippet.
+ * We find the line containing the query, then find the matching closing tag.
+ */
+function findElement(lines, query) {
+ // Find the line containing the query
+ let startLine = -1;
+ for (let i = 0; i < lines.length; i++) {
+ if (lines[i].includes(query)) {
+ // Make sure this looks like a tag opening, not a comment or string
+ const line = lines[i].trim();
+ if (line.startsWith('<!--') || line.startsWith('{/*') || line.startsWith('//')) continue;
+ // Skip lines inside data-impeccable-variant containers (already wrapped)
+ if (lines[i].includes('data-impeccable-variant')) continue;
+ startLine = i;
+ break;
+ }
+ }
+
+ if (startLine === -1) return null;
+
+ // Find the end of this element by counting open/close tags
+ const endLine = findClosingLine(lines, startLine);
+ return { startLine, endLine };
+}
+
+/**
+ * Starting from a line with an opening tag, find the line with the matching
+ * closing tag by counting tag nesting depth.
+ */
+function findClosingLine(lines, start) {
+ // Extract the tag name from the opening line
+ const openMatch = lines[start].match(/<(\w+)[\s>]/);
+ if (!openMatch) return start; // self-closing or text-only line
+
+ const tagName = openMatch[1];
+ let depth = 0;
+
+ for (let i = start; i < lines.length; i++) {
+ const line = lines[i];
+ // Count opening tags (not self-closing)
+ const opens = (line.match(new RegExp('<' + tagName + '[\\s>]', 'g')) || []).length;
+ const selfCloses = (line.match(new RegExp('<' + tagName + '[^>]*/>', 'g')) || []).length;
+ const closes = (line.match(new RegExp('</' + tagName + '\\s*>', 'g')) || []).length;
+
+ depth += opens - selfCloses - closes;
+
+ if (depth <= 0) return i;
+ }
+
+ // If we can't find the close, return a reasonable guess
+ return Math.min(start + 50, lines.length - 1);
+}
diff --git a/.rovodev/skills/impeccable/reference/live.md b/.rovodev/skills/impeccable/reference/live.md
index 53b64a21a..ba0e9b0c5 100644
--- a/.rovodev/skills/impeccable/reference/live.md
+++ b/.rovodev/skills/impeccable/reference/live.md
@@ -10,7 +10,7 @@ Launch interactive live variant mode: select elements in the browser, pick a des
1. Read `.impeccable.md` if it exists. Keep the design context in mind for variant generation.
2. Start the live variant server:
```bash
- npx impeccable live &
+ node {{scripts_path}}/live-server.mjs &
```
3. Note the **port** and **token** printed to stdout.
@@ -53,7 +53,7 @@ Run a blocking poll loop. On each iteration, wait for a browser event and respon
```
LOOP:
- Run: npx impeccable poll
+ Run: node {{scripts_path}}/live-poll.mjs
Read the JSON output. Dispatch based on the "type" field:
TYPE "generate":
@@ -85,7 +85,7 @@ The event contains: `{id, action, freeformPrompt, count, pageUrl, element}`.
Use the `wrap` helper to find the element and create the variant container:
```bash
-npx impeccable wrap --id EVENT_ID --count EVENT_COUNT --element-id "ELEMENT_ID" --classes "class1,class2" --tag "div"
+node {{scripts_path}}/live-wrap.mjs --id EVENT_ID --count EVENT_COUNT --element-id "ELEMENT_ID" --classes "class1,class2" --tag "div"
```
Pass the element's id (`event.element.id`), classes (`event.element.classes` joined with commas), and tag name. The command searches in priority order: ID match first, then class names, then tag+class combo. If `event.pageUrl` hints at the file (e.g., `/` is usually `index.html`), pass `--file PATH` to skip the search.
@@ -136,10 +136,14 @@ The first variant should NOT have `style="display: none"` (it should be visible
### Step 3: Signal completion
+Include `--file` so the browser can fetch variants directly if the dev server lacks HMR:
+
```bash
-npx impeccable poll --reply EVENT_ID done
+node {{scripts_path}}/live-poll.mjs --reply EVENT_ID done --file RELATIVE_PATH
```
+The file path should be relative to the project root (e.g., `public/index.html`, `src/App.tsx`).
+
## Handle Accept
The event contains: `{id, variantId}`.
@@ -151,7 +155,7 @@ The user accepted a specific variant. For v1 (inspection mode):
4. Remove any scoped CSS blocks (between `impeccable-variants-css-start` and `impeccable-variants-css-end` markers).
5. Reply:
```bash
- npx impeccable poll --reply SESSION_ID done
+ node {{scripts_path}}/live-poll.mjs --reply SESSION_ID done
```
## Handle Discard
@@ -163,7 +167,7 @@ The event contains: `{id}`.
3. Remove any scoped CSS blocks for this session.
4. Reply:
```bash
- npx impeccable poll --reply SESSION_ID done
+ node {{scripts_path}}/live-poll.mjs --reply SESSION_ID done
```
## Cleanup (on exit)
@@ -174,7 +178,7 @@ When the loop ends:
2. **Remove any leftover variant wrappers** (search for `impeccable-variants-start` markers and clean up).
3. **Stop the server**:
```bash
- npx impeccable live stop
+ node {{scripts_path}}/live-server.mjs stop
```
## Variant Generation Guidelines
diff --git a/.rovodev/skills/impeccable/scripts/live-browser.js b/.rovodev/skills/impeccable/scripts/live-browser.js
new file mode 100644
index 000000000..7a26c9829
--- /dev/null
+++ b/.rovodev/skills/impeccable/scripts/live-browser.js
@@ -0,0 +1,1220 @@
+/**
+ * Impeccable Live Variant Mode — Browser Script
+ *
+ * Injected into the user's page via <script src="http://localhost:PORT/live.js">.
+ * The server prepends window.__IMPECCABLE_TOKEN__ and window.__IMPECCABLE_PORT__
+ * before this code.
+ *
+ * UI: a single floating bar that morphs between three states —
+ * configure (pick action + go), generating (progressive dots), and cycling
+ * (prev/next + accept/discard). Feels like Spotlight, not a modal.
+ */
+(function () {
+ 'use strict';
+ if (typeof window === 'undefined') return;
+
+ // Guard against double-init. Bun's HTML loader may process the <script> tag
+ // and create a bundled copy alongside the external load, or HMR may re-execute.
+ // Check BEFORE reading token/port to catch all cases.
+ if (window.__IMPECCABLE_LIVE_INIT__) return;
+ window.__IMPECCABLE_LIVE_INIT__ = true;
+
+ const TOKEN = window.__IMPECCABLE_TOKEN__;
+ const PORT = window.__IMPECCABLE_PORT__;
+ if (!TOKEN || !PORT) {
+ window.__IMPECCABLE_LIVE_INIT__ = false; // reset so the real load can init
+ return;
+ }
+
+ // ---------------------------------------------------------------------------
+ // Design tokens
+ // ---------------------------------------------------------------------------
+
+ const C = {
+ brand: 'oklch(55% 0.25 350)',
+ brandHov: 'oklch(48% 0.25 350)',
+ brandSoft: 'oklch(55% 0.25 350 / 0.12)',
+ ink: 'oklch(15% 0.01 350)',
+ ash: 'oklch(55% 0 0)',
+ paper: 'oklch(98% 0.005 350 / 0.92)',
+ paperSolid:'oklch(98% 0.005 350)',
+ mist: 'oklch(90% 0.01 350 / 0.6)',
+ white: 'oklch(99% 0 0)',
+ };
+ const FONT = 'system-ui, -apple-system, sans-serif';
+ const MONO = 'ui-monospace, SFMono-Regular, Menlo, monospace';
+ const Z = { highlight: 99990, bar: 99995, picker: 99997, toast: 99999 };
+ const EASE = 'cubic-bezier(0.22, 1, 0.36, 1)'; // ease-out-quint
+ const PREFIX = 'impeccable-live';
+
+ const SKIP_TAGS = new Set([
+ 'html', 'head', 'body', 'script', 'style', 'link', 'meta', 'noscript', 'br', 'wbr',
+ ]);
+
+ const ACTIONS = [
+ { value: 'impeccable', label: 'Freeform' },
+ { value: 'bolder', label: 'Bolder' },
+ { value: 'quieter', label: 'Quieter' },
+ { value: 'distill', label: 'Distill' },
+ { value: 'polish', label: 'Polish' },
+ { value: 'typeset', label: 'Typeset' },
+ { value: 'colorize', label: 'Colorize' },
+ { value: 'layout', label: 'Layout' },
+ { value: 'adapt', label: 'Adapt' },
+ { value: 'animate', label: 'Animate' },
+ { value: 'delight', label: 'Delight' },
+ { value: 'overdrive', label: 'Overdrive' },
+ ];
+
+ // ---------------------------------------------------------------------------
+ // State
+ // ---------------------------------------------------------------------------
+
+ let state = 'IDLE';
+ let hoveredElement = null;
+ let selectedElement = null;
+ let currentSessionId = null;
+ let expectedVariants = 0;
+ let arrivedVariants = 0;
+ let visibleVariant = 0;
+ let variantObserver = null;
+ let hasProjectContext = false;
+ let selectedAction = 'impeccable';
+ let selectedCount = 3;
+
+ // UI refs
+ let highlightEl = null;
+ let tooltipEl = null;
+ let barEl = null;
+ let pickerEl = null;
+ let toastEl = null;
+ let scrollRaf = null;
+
+ // ---------------------------------------------------------------------------
+ // Helpers
+ // ---------------------------------------------------------------------------
+
+ function own(el) {
+ return el && (el.id?.startsWith(PREFIX) || el.closest?.('[id^="' + PREFIX + '"]'));
+ }
+
+ function pickable(el) {
+ if (!el || el.nodeType !== 1) return false;
+ if (SKIP_TAGS.has(el.tagName.toLowerCase())) return false;
+ if (own(el)) return false;
+ const r = el.getBoundingClientRect();
+ return r.width >= 20 && r.height >= 20;
+ }
+
+ function desc(el) {
+ if (!el) return '';
+ let s = el.tagName.toLowerCase();
+ if (el.id) s += '#' + el.id;
+ else if (el.classList.length) s += '.' + [...el.classList].slice(0, 2).join('.');
+ return s;
+ }
+
+ function id8() { return crypto.randomUUID().replace(/-/g, '').slice(0, 8); }
+
+ // ---------------------------------------------------------------------------
+ // Highlight overlay
+ // ---------------------------------------------------------------------------
+
+ function initHighlight() {
+ highlightEl = document.createElement('div');
+ highlightEl.id = PREFIX + '-highlight';
+ Object.assign(highlightEl.style, {
+ position: 'fixed', top: '0', left: '0', width: '0', height: '0',
+ border: '2px solid ' + C.brand, borderRadius: '3px',
+ pointerEvents: 'none', zIndex: Z.highlight, boxSizing: 'border-box',
+ transition: 'top 0.08s ease, left 0.08s ease, width 0.08s ease, height 0.08s ease, opacity 0.15s ease',
+ display: 'none', opacity: '0',
+ });
+ document.body.appendChild(highlightEl);
+
+ tooltipEl = document.createElement('div');
+ tooltipEl.id = PREFIX + '-tooltip';
+ Object.assign(tooltipEl.style, {
+ position: 'fixed',
+ background: C.ink, color: C.white,
+ fontFamily: MONO, fontSize: '10px', fontWeight: '500',
+ padding: '2px 6px', borderRadius: '3px',
+ zIndex: Z.highlight + 1, pointerEvents: 'none',
+ whiteSpace: 'nowrap', display: 'none',
+ letterSpacing: '0.02em',
+ });
+ document.body.appendChild(tooltipEl);
+ }
+
+ function showHighlight(el) {
+ if (!el || !highlightEl) return;
+ const r = el.getBoundingClientRect();
+ Object.assign(highlightEl.style, {
+ top: (r.top - 2) + 'px', left: (r.left - 2) + 'px',
+ width: (r.width + 4) + 'px', height: (r.height + 4) + 'px',
+ display: 'block', opacity: '1',
+ });
+ tooltipEl.textContent = desc(el);
+ const tipTop = r.top - 20;
+ Object.assign(tooltipEl.style, {
+ top: (tipTop < 4 ? r.bottom + 4 : tipTop) + 'px',
+ left: Math.max(4, r.left) + 'px', display: 'block',
+ });
+ }
+
+ function hideHighlight() {
+ if (highlightEl) { highlightEl.style.opacity = '0'; highlightEl.style.display = 'none'; }
+ if (tooltipEl) tooltipEl.style.display = 'none';
+ }
+
+ // ---------------------------------------------------------------------------
+ // Element context extraction
+ // ---------------------------------------------------------------------------
+
+ function extractContext(el) {
+ const cs = getComputedStyle(el);
+ const r = el.getBoundingClientRect();
+ const props = {};
+ for (const sheet of document.styleSheets) {
+ try {
+ for (const rule of sheet.cssRules) {
+ if (rule.style) for (let i = 0; i < rule.style.length; i++) {
+ const p = rule.style[i];
+ if (p.startsWith('--') && !props[p]) {
+ const v = cs.getPropertyValue(p).trim();
+ if (v) props[p] = v;
+ }
+ }
+ }
+ } catch { /* cross-origin */ }
+ }
+ return {
+ tagName: el.tagName.toLowerCase(), id: el.id || null,
+ classes: [...el.classList],
+ textContent: (el.textContent || '').slice(0, 500),
+ outerHTML: el.outerHTML.slice(0, 10000),
+ computedStyles: {
+ 'font-family': cs.fontFamily, 'font-size': cs.fontSize,
+ 'font-weight': cs.fontWeight, 'line-height': cs.lineHeight,
+ 'color': cs.color, 'background': cs.background,
+ 'background-color': cs.backgroundColor,
+ 'padding': cs.padding, 'margin': cs.margin,
+ 'display': cs.display, 'position': cs.position,
+ 'gap': cs.gap, 'border-radius': cs.borderRadius,
+ 'box-shadow': cs.boxShadow,
+ },
+ cssCustomProperties: props,
+ parentContext: el.parentElement
+ ? '<' + el.parentElement.tagName.toLowerCase()
+ + (el.parentElement.id ? ' id="' + el.parentElement.id + '"' : '')
+ + (el.parentElement.className ? ' class="' + el.parentElement.className + '"' : '')
+ + '>'
+ : null,
+ boundingRect: { width: Math.round(r.width), height: Math.round(r.height) },
+ };
+ }
+
+ // ---------------------------------------------------------------------------
+ // The Bar — one floating element, three modes
+ // ---------------------------------------------------------------------------
+
+ function initBar() {
+ barEl = document.createElement('div');
+ barEl.id = PREFIX + '-bar';
+ Object.assign(barEl.style, {
+ position: 'fixed', zIndex: Z.bar,
+ display: 'none', opacity: '0',
+ transform: 'translateY(6px)',
+ transition: 'opacity 0.25s ' + EASE + ', transform 0.3s ' + EASE,
+ // Visual
+ background: C.paper,
+ backdropFilter: 'blur(16px)', WebkitBackdropFilter: 'blur(16px)',
+ border: '1px solid ' + C.mist,
+ borderRadius: '10px',
+ boxShadow: '0 4px 20px oklch(0% 0 0 / 0.08), 0 1px 3px oklch(0% 0 0 / 0.06)',
+ fontFamily: FONT, fontSize: '13px', color: C.ink,
+ padding: '6px',
+ maxWidth: '460px', minWidth: '320px',
+ });
+ document.body.appendChild(barEl);
+ }
+
+ function positionBar() {
+ if (!barEl || !selectedElement) return;
+ const r = selectedElement.getBoundingClientRect();
+ const barH = barEl.offsetHeight || 44;
+ const barW = barEl.offsetWidth || 380;
+ let top = r.bottom + 8;
+ let left = r.left + (r.width - barW) / 2;
+ // Keep in viewport
+ if (top + barH + 8 > window.innerHeight) top = r.top - barH - 8;
+ if (top < 8) top = 8;
+ if (left < 8) left = 8;
+ if (left + barW > window.innerWidth - 8) left = window.innerWidth - barW - 8;
+ Object.assign(barEl.style, { top: top + 'px', left: left + 'px' });
+ }
+
+ function showBar(mode) {
+ barEl.innerHTML = '';
+ if (mode === 'configure') barEl.appendChild(buildConfigureRow());
+ else if (mode === 'generating') barEl.appendChild(buildGeneratingRow());
+ else if (mode === 'cycling') barEl.appendChild(buildCyclingRow());
+ barEl.style.display = 'block';
+ positionBar();
+ requestAnimationFrame(() => {
+ barEl.style.opacity = '1';
+ barEl.style.transform = 'translateY(0)';
+ });
+ }
+
+ function hideBar() {
+ if (!barEl) return;
+ barEl.style.opacity = '0';
+ barEl.style.transform = 'translateY(6px)';
+ setTimeout(() => { if (barEl) barEl.style.display = 'none'; }, 250);
+ hideActionPicker();
+ }
+
+ function updateBarContent(mode) {
+ if (!barEl || barEl.style.display === 'none') return;
+ barEl.innerHTML = '';
+ // Reset bar styling
+ barEl.style.background = C.paper;
+ barEl.style.border = '1px solid ' + C.mist;
+ if (mode === 'configure') barEl.appendChild(buildConfigureRow());
+ else if (mode === 'generating') barEl.appendChild(buildGeneratingRow());
+ else if (mode === 'cycling') barEl.appendChild(buildCyclingRow());
+ else if (mode === 'saving') barEl.appendChild(buildSavingRow());
+ else if (mode === 'confirmed') {
+ barEl.appendChild(buildConfirmedRow());
+ barEl.style.background = 'oklch(95% 0.05 145)';
+ barEl.style.border = '1px solid oklch(75% 0.12 145 / 0.4)';
+ }
+ }
+
+ // --- Configure row ---
+
+ function buildConfigureRow() {
+ const row = el('div', {
+ display: 'flex', alignItems: 'center', gap: '4px',
+ });
+
+ // Action pill
+ const pill = el('button', {
+ display: 'inline-flex', alignItems: 'center', gap: '4px',
+ padding: '5px 10px', borderRadius: '6px',
+ background: C.ink, color: C.white,
+ fontFamily: FONT, fontSize: '12px', fontWeight: '500',
+ border: 'none', cursor: 'pointer',
+ transition: 'background 0.12s ease, transform 0.1s ease',
+ whiteSpace: 'nowrap', flexShrink: '0',
+ });
+ pill.textContent = actionLabel() + ' \u25BE';
+ pill.addEventListener('mouseenter', () => pill.style.background = C.brandHov);
+ pill.addEventListener('mouseleave', () => pill.style.background = C.ink);
+ pill.addEventListener('mousedown', () => pill.style.transform = 'scale(0.97)');
+ pill.addEventListener('mouseup', () => pill.style.transform = 'scale(1)');
+ pill.addEventListener('click', (e) => { e.stopPropagation(); toggleActionPicker(); });
+ row.appendChild(pill);
+
+ // Freeform input
+ const input = document.createElement('input');
+ input.id = PREFIX + '-input';
+ input.type = 'text';
+ input.placeholder = selectedAction === 'impeccable' ? 'describe what you want...' : 'refine further (optional)...';
+ Object.assign(input.style, {
+ flex: '1', minWidth: '0',
+ padding: '5px 8px', borderRadius: '6px',
+ border: '1px solid transparent', background: 'transparent',
+ fontFamily: FONT, fontSize: '12px', color: C.ink,
+ outline: 'none',
+ transition: 'border-color 0.15s ease, background 0.15s ease',
+ });
+ input.addEventListener('focus', () => {
+ input.style.borderColor = C.mist;
+ input.style.background = C.white;
+ });
+ input.addEventListener('blur', () => {
+ input.style.borderColor = 'transparent';
+ input.style.background = 'transparent';
+ });
+ input.addEventListener('keydown', (e) => {
+ e.stopPropagation(); // Don't trigger element picker keyboard nav
+ if (e.key === 'Enter') { e.preventDefault(); handleGo(); }
+ if (e.key === 'Escape') { e.preventDefault(); input.blur(); hideBar(); state = 'PICKING'; }
+ });
+ row.appendChild(input);
+
+ // Variant count toggle
+ const count = el('button', {
+ padding: '4px 6px', borderRadius: '5px',
+ border: '1px solid ' + C.mist, background: 'transparent',
+ fontFamily: MONO, fontSize: '11px', fontWeight: '600',
+ color: C.ash, cursor: 'pointer',
+ transition: 'color 0.12s ease, border-color 0.12s ease',
+ flexShrink: '0', whiteSpace: 'nowrap',
+ });
+ count.textContent = '\u00D7' + selectedCount;
+ count.title = 'Variants: click to change';
+ count.addEventListener('mouseenter', () => { count.style.color = C.ink; count.style.borderColor = C.ink; });
+ count.addEventListener('mouseleave', () => { count.style.color = C.ash; count.style.borderColor = C.mist; });
+ count.addEventListener('click', (e) => {
+ e.stopPropagation();
+ selectedCount = selectedCount >= 4 ? 2 : selectedCount + 1;
+ count.textContent = '\u00D7' + selectedCount;
+ });
+ row.appendChild(count);
+
+ // Go button
+ const go = el('button', {
+ padding: '5px 12px', borderRadius: '6px',
+ border: 'none', background: C.brand, color: C.white,
+ fontFamily: FONT, fontSize: '12px', fontWeight: '600',
+ cursor: 'pointer',
+ transition: 'background 0.12s ease, transform 0.1s ease',
+ flexShrink: '0', whiteSpace: 'nowrap',
+ });
+ go.textContent = 'Go \u2192';
+ go.addEventListener('mouseenter', () => go.style.background = C.brandHov);
+ go.addEventListener('mouseleave', () => go.style.background = C.brand);
+ go.addEventListener('mousedown', () => go.style.transform = 'scale(0.97)');
+ go.addEventListener('mouseup', () => go.style.transform = 'scale(1)');
+ go.addEventListener('click', (e) => { e.stopPropagation(); handleGo(); });
+ row.appendChild(go);
+
+ // Auto-focus input after a beat
+ setTimeout(() => input.focus(), 60);
+ return row;
+ }
+
+ // --- Generating row ---
+
+ function buildGeneratingRow() {
+ const row = el('div', {
+ display: 'flex', alignItems: 'center', gap: '8px',
+ padding: '2px 4px',
+ });
+
+ // Action label
+ const label = el('span', {
+ fontWeight: '600', fontSize: '12px', color: C.ink,
+ flexShrink: '0', whiteSpace: 'nowrap',
+ });
+ label.textContent = actionLabel();
+ row.appendChild(label);
+
+ // Dots
+ row.appendChild(buildDots(false));
+
+ // Status
+ const status = el('span', {
+ fontSize: '11px', color: C.ash, whiteSpace: 'nowrap',
+ marginLeft: 'auto',
+ });
+ status.textContent = arrivedVariants < expectedVariants
+ ? 'Generating ' + (arrivedVariants + 1) + ' of ' + expectedVariants + '...'
+ : 'Done';
+ row.appendChild(status);
+
+ return row;
+ }
+
+ // --- Cycling row ---
+
+ function buildCyclingRow() {
+ const row = el('div', {
+ display: 'flex', alignItems: 'center', gap: '6px',
+ padding: '1px 2px',
+ });
+
+ // Prev
+ const prev = navBtn('\u2190');
+ prev.addEventListener('click', (e) => { e.stopPropagation(); cycleVariant(-1); });
+ if (visibleVariant <= 1) prev.style.opacity = '0.3';
+ row.appendChild(prev);
+
+ // Dots (clickable)
+ row.appendChild(buildDots(true));
+
+ // Counter
+ const counter = el('span', {
+ fontFamily: MONO, fontSize: '11px', fontWeight: '500',
+ color: C.ash, minWidth: '24px', textAlign: 'center',
+ });
+ counter.textContent = visibleVariant + '/' + arrivedVariants;
+ row.appendChild(counter);
+
+ // Next
+ const next = navBtn('\u2192');
+ next.addEventListener('click', (e) => { e.stopPropagation(); cycleVariant(1); });
+ if (visibleVariant >= arrivedVariants) next.style.opacity = '0.3';
+ row.appendChild(next);
+
+ // Spacer
+ row.appendChild(el('div', { flex: '1' }));
+
+ // Accept
+ const accept = el('button', {
+ padding: '4px 10px', borderRadius: '5px',
+ border: 'none', background: C.ink, color: C.white,
+ fontFamily: FONT, fontSize: '11px', fontWeight: '600',
+ cursor: 'pointer', transition: 'background 0.12s ease',
+ whiteSpace: 'nowrap',
+ });
+ accept.textContent = '\u2713 Accept';
+ accept.addEventListener('mouseenter', () => accept.style.background = C.brand);
+ accept.addEventListener('mouseleave', () => accept.style.background = C.ink);
+ accept.addEventListener('click', (e) => { e.stopPropagation(); handleAccept(); });
+ if (arrivedVariants === 0) { accept.style.opacity = '0.3'; accept.style.pointerEvents = 'none'; }
+ row.appendChild(accept);
+
+ // Discard
+ const discard = el('button', {
+ padding: '4px 6px', borderRadius: '5px',
+ border: '1px solid ' + C.mist, background: 'transparent',
+ fontFamily: FONT, fontSize: '11px', color: C.ash,
+ cursor: 'pointer', transition: 'color 0.12s ease, border-color 0.12s ease',
+ });
+ discard.textContent = '\u2715';
+ discard.title = 'Discard all variants';
+ discard.addEventListener('mouseenter', () => { discard.style.color = C.ink; discard.style.borderColor = C.ink; });
+ discard.addEventListener('mouseleave', () => { discard.style.color = C.ash; discard.style.borderColor = C.mist; });
+ discard.addEventListener('click', (e) => { e.stopPropagation(); handleDiscard(); });
+ row.appendChild(discard);
+
+ return row;
+ }
+
+ // --- Shared UI builders ---
+
+ // --- Saving row (waiting for agent to process accept/discard) ---
+
+ function buildSavingRow() {
+ const row = el('div', {
+ display: 'flex', alignItems: 'center', gap: '8px',
+ padding: '2px 8px',
+ });
+ const spinner = el('div', {
+ width: '14px', height: '14px', borderRadius: '50%',
+ border: '2px solid ' + C.mist,
+ borderTopColor: C.brand,
+ animation: 'impeccable-spin 0.6s linear infinite',
+ flexShrink: '0',
+ });
+ row.appendChild(spinner);
+ const label = el('span', {
+ fontSize: '12px', color: C.ash, fontWeight: '500',
+ });
+ label.textContent = 'Applying variant...';
+ row.appendChild(label);
+
+ // Inject the keyframes if not already present
+ if (!document.getElementById(PREFIX + '-keyframes')) {
+ const style = document.createElement('style');
+ style.id = PREFIX + '-keyframes';
+ style.textContent = '@keyframes impeccable-spin { to { transform: rotate(360deg); } }';
+ document.head.appendChild(style);
+ }
+ return row;
+ }
+
+ // --- Confirmed row (green success, auto-dismisses) ---
+
+ function buildConfirmedRow() {
+ const row = el('div', {
+ display: 'flex', alignItems: 'center', gap: '8px',
+ padding: '2px 8px',
+ });
+ const check = el('span', {
+ fontSize: '15px', lineHeight: '1', flexShrink: '0',
+ color: 'oklch(45% 0.15 145)',
+ });
+ check.textContent = '\u2713';
+ row.appendChild(check);
+ const label = el('span', {
+ fontSize: '12px', color: 'oklch(35% 0.1 145)', fontWeight: '600',
+ });
+ label.textContent = 'Variant applied';
+ row.appendChild(label);
+ return row;
+ }
+
+ // --- Shared UI builders ---
+
+ function buildDots(clickable) {
+ const container = el('div', {
+ display: 'flex', alignItems: 'center', gap: '4px',
+ });
+ for (let i = 1; i <= expectedVariants; i++) {
+ const arrived = i <= arrivedVariants;
+ const active = i === visibleVariant;
+ const dot = el('div', {
+ width: '7px', height: '7px', borderRadius: '50%',
+ background: active ? C.brand : (arrived ? C.ash : 'transparent'),
+ border: '1.5px solid ' + (arrived ? C.brand : C.mist),
+ transition: 'all 0.2s ' + EASE,
+ cursor: (clickable && arrived) ? 'pointer' : 'default',
+ transform: arrived ? 'scale(1)' : 'scale(0.6)',
+ opacity: arrived ? '1' : '0.4',
+ });
+ if (clickable && arrived) {
+ const idx = i;
+ dot.addEventListener('click', (e) => {
+ e.stopPropagation();
+ visibleVariant = idx;
+ showVariantInDOM(currentSessionId, idx);
+ updateSelectedElement();
+ updateBarContent('cycling');
+ });
+ }
+ container.appendChild(dot);
+ }
+ return container;
+ }
+
+ function navBtn(text) {
+ const b = el('button', {
+ width: '26px', height: '26px', borderRadius: '5px',
+ border: '1px solid ' + C.mist, background: 'transparent',
+ color: C.ink, fontFamily: FONT, fontSize: '13px',
+ cursor: 'pointer', display: 'flex', alignItems: 'center', justifyContent: 'center',
+ transition: 'border-color 0.12s ease, background 0.12s ease',
+ padding: '0', lineHeight: '1',
+ });
+ b.textContent = text;
+ b.addEventListener('mouseenter', () => { b.style.borderColor = C.ink; });
+ b.addEventListener('mouseleave', () => { b.style.borderColor = C.mist; });
+ return b;
+ }
+
+ function actionLabel() {
+ const a = ACTIONS.find(a => a.value === selectedAction);
+ return a ? a.label : 'Freeform';
+ }
+
+ function el(tag, styles) {
+ const e = document.createElement(tag);
+ if (styles) Object.assign(e.style, styles);
+ return e;
+ }
+
+ // ---------------------------------------------------------------------------
+ // Action picker popover
+ // ---------------------------------------------------------------------------
+
+ function initActionPicker() {
+ pickerEl = document.createElement('div');
+ pickerEl.id = PREFIX + '-picker';
+ Object.assign(pickerEl.style, {
+ position: 'fixed', zIndex: Z.picker,
+ display: 'none', opacity: '0',
+ transform: 'scale(0.96) translateY(4px)',
+ transformOrigin: 'bottom left',
+ transition: 'opacity 0.18s ' + EASE + ', transform 0.2s ' + EASE,
+ background: C.paperSolid,
+ border: '1px solid ' + C.mist,
+ borderRadius: '10px',
+ boxShadow: '0 8px 30px oklch(0% 0 0 / 0.10), 0 2px 6px oklch(0% 0 0 / 0.06)',
+ padding: '6px',
+ fontFamily: FONT,
+ });
+
+ // Build the chip grid
+ const grid = el('div', {
+ display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', gap: '3px',
+ });
+
+ ACTIONS.forEach(action => {
+ const chip = el('button', {
+ padding: '6px 8px', borderRadius: '6px',
+ border: 'none',
+ background: action.value === selectedAction ? C.brandSoft : 'transparent',
+ color: action.value === selectedAction ? C.brand : C.ink,
+ fontFamily: FONT, fontSize: '11px', fontWeight: '500',
+ cursor: 'pointer',
+ transition: 'background 0.1s ease, color 0.1s ease',
+ textAlign: 'center', whiteSpace: 'nowrap',
+ });
+ chip.textContent = action.label;
+ chip.dataset.action = action.value;
+ chip.addEventListener('mouseenter', () => {
+ if (action.value !== selectedAction) chip.style.background = C.brandSoft;
+ });
+ chip.addEventListener('mouseleave', () => {
+ chip.style.background = action.value === selectedAction ? C.brandSoft : 'transparent';
+ });
+ chip.addEventListener('click', (e) => {
+ e.stopPropagation();
+ selectedAction = action.value;
+ hideActionPicker();
+ updateBarContent('configure');
+ });
+ grid.appendChild(chip);
+ });
+
+ pickerEl.appendChild(grid);
+ document.body.appendChild(pickerEl);
+ }
+
+ function toggleActionPicker() {
+ if (pickerEl.style.display !== 'none') { hideActionPicker(); return; }
+ // Rebuild chips to reflect current selection
+ pickerEl.querySelectorAll('button').forEach(chip => {
+ const isActive = chip.dataset.action === selectedAction;
+ chip.style.background = isActive ? C.brandSoft : 'transparent';
+ chip.style.color = isActive ? C.brand : C.ink;
+ });
+ // Position above the bar
+ const barRect = barEl.getBoundingClientRect();
+ const pickerH = 90; // approximate
+ let top = barRect.top - pickerH - 6;
+ if (top < 8) top = barRect.bottom + 6;
+ Object.assign(pickerEl.style, {
+ top: top + 'px', left: barRect.left + 'px',
+ display: 'block',
+ });
+ requestAnimationFrame(() => {
+ pickerEl.style.opacity = '1';
+ pickerEl.style.transform = 'scale(1) translateY(0)';
+ });
+ }
+
+ function hideActionPicker() {
+ if (!pickerEl) return;
+ pickerEl.style.opacity = '0';
+ pickerEl.style.transform = 'scale(0.96) translateY(4px)';
+ setTimeout(() => { if (pickerEl) pickerEl.style.display = 'none'; }, 180);
+ }
+
+ // ---------------------------------------------------------------------------
+ // Variant cycling in DOM
+ // ---------------------------------------------------------------------------
+
+ function showVariantInDOM(sessionId, num) {
+ const wrapper = document.querySelector('[data-impeccable-variants="' + sessionId + '"]');
+ if (!wrapper) return;
+ for (const child of wrapper.children) {
+ const v = child.dataset ? child.dataset.impeccableVariant : null;
+ if (!v) continue;
+ child.style.display = (v === String(num)) ? '' : 'none';
+ }
+ }
+
+ /**
+ * No-HMR fallback: fetch the raw source file from the live server,
+ * parse it, extract the variant wrapper, and inject it into the live DOM.
+ * This works even when the dev server caches HTML (Bun, static servers).
+ */
+ function injectVariantsFromSource(filePath, sessionId) {
+ const url = 'http://localhost:' + PORT + '/source?token=' + TOKEN + '&path=' + encodeURIComponent(filePath);
+ fetch(url)
+ .then(r => { if (!r.ok) throw new Error(r.status); return r.text(); })
+ .then(html => {
+ // Parse the raw source HTML
+ const parser = new DOMParser();
+ const doc = parser.parseFromString(html, 'text/html');
+ const srcWrapper = doc.querySelector('[data-impeccable-variants="' + sessionId + '"]');
+ if (!srcWrapper) {
+ console.error('[impeccable] Variant wrapper not found in source file.');
+ return;
+ }
+
+ // Find the original element in the live DOM.
+ // The original is inside the wrapper in the source. We find the
+ // corresponding element in the live DOM by matching the first child's
+ // tag + classes from the original snapshot.
+ const origContent = srcWrapper.querySelector('[data-impeccable-variant="original"] > :first-child');
+ if (!origContent) return;
+
+ const tag = origContent.tagName.toLowerCase();
+ const cls = origContent.className;
+ let liveEl = null;
+ if (origContent.id) {
+ liveEl = document.getElementById(origContent.id);
+ } else if (cls) {
+ // Find by tag + exact class match
+ const candidates = document.querySelectorAll(tag + '.' + cls.split(' ')[0]);
+ for (const c of candidates) {
+ if (c.className === cls && !own(c)) { liveEl = c; break; }
+ }
+ }
+
+ if (!liveEl) {
+ console.error('[impeccable] Could not find original element in live DOM.');
+ return;
+ }
+
+ // Replace the live element with the full wrapper from source
+ const wrapper = srcWrapper.cloneNode(true);
+ liveEl.parentElement.replaceChild(wrapper, liveEl);
+
+ // Update state: count variants, show the first one
+ 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);
+
+ // Update selectedElement to the visible variant's content
+ const visEl = wrapper.querySelector('[data-impeccable-variant="1"] > :first-child');
+ selectedElement = visEl || wrapper.parentElement;
+
+ state = 'CYCLING';
+ updateBarContent('cycling');
+ saveSession();
+ console.log('[impeccable] Injected ' + arrivedVariants + ' variants from source file.');
+ })
+ .catch(err => {
+ console.error('[impeccable] Failed to fetch source:', err);
+ showToast('Could not load variants. Try refreshing the page.', 5000);
+ });
+ }
+
+ function cycleVariant(dir) {
+ const next = visibleVariant + dir;
+ if (next < 1 || next > arrivedVariants) return;
+ visibleVariant = next;
+ showVariantInDOM(currentSessionId, next);
+ updateSelectedElement();
+ updateBarContent('cycling');
+ saveSession();
+ }
+
+ function updateSelectedElement() {
+ if (!currentSessionId) return;
+ const wrapper = document.querySelector('[data-impeccable-variants="' + currentSessionId + '"]');
+ if (!wrapper) return;
+ const visEl = wrapper.querySelector('[data-impeccable-variant="' + visibleVariant + '"] > :first-child');
+ if (visEl) selectedElement = visEl;
+ }
+
+ // ---------------------------------------------------------------------------
+ // MutationObserver for progressive variant reveal
+ // ---------------------------------------------------------------------------
+
+ function startVariantObserver(sessionId) {
+ let updating = false; // re-entrancy guard
+
+ const obs = new MutationObserver((mutations) => {
+ if (updating) return;
+
+ // Only react to mutations that add nodes with data-impeccable-variant,
+ // or mutations inside the variant wrapper. Ignore our own bar/UI changes.
+ let dominated = false;
+ for (const m of mutations) {
+ if (m.target.closest?.('[data-impeccable-variants]')) { dominated = true; break; }
+ for (const n of m.addedNodes) {
+ if (n.nodeType === 1 && (n.dataset?.impeccableVariants || n.dataset?.impeccableVariant)) {
+ dominated = true; break;
+ }
+ }
+ if (dominated) break;
+ }
+ if (!dominated) return;
+
+ const wrapper = document.querySelector('[data-impeccable-variants="' + sessionId + '"]');
+ if (!wrapper) return;
+
+ const variants = wrapper.querySelectorAll('[data-impeccable-variant]:not([data-impeccable-variant="original"])');
+ const count = variants.length;
+
+ // Nothing new
+ if (count <= arrivedVariants) return;
+
+ updating = true;
+ arrivedVariants = count;
+ if (visibleVariant === 0 && arrivedVariants > 0) {
+ visibleVariant = 1;
+ showVariantInDOM(sessionId, 1);
+ }
+
+ const expected = parseInt(wrapper.dataset.impeccableVariantCount || '0');
+ if (expected > 0) expectedVariants = expected;
+
+ if (arrivedVariants >= expectedVariants && expectedVariants > 0) {
+ state = 'CYCLING';
+ updateBarContent('cycling');
+ } else if (state === 'GENERATING') {
+ updateBarContent('generating');
+ }
+ saveSession();
+ updating = false;
+ });
+
+ obs.observe(document.body, { childList: true, subtree: true });
+ return obs;
+ }
+
+ // ---------------------------------------------------------------------------
+ // Bar scroll tracking
+ // ---------------------------------------------------------------------------
+
+ function startScrollTracking() {
+ function tick() {
+ if (state === 'CONFIGURING' || state === 'GENERATING' || state === 'CYCLING') {
+ positionBar();
+ showHighlight(selectedElement);
+ }
+ scrollRaf = requestAnimationFrame(tick);
+ }
+ scrollRaf = requestAnimationFrame(tick);
+ }
+
+ function stopScrollTracking() {
+ if (scrollRaf) { cancelAnimationFrame(scrollRaf); scrollRaf = null; }
+ }
+
+ // ---------------------------------------------------------------------------
+ // SSE (server→browser) + fetch POST (browser→server)
+ // Zero-dependency replacement for WebSocket.
+ // ---------------------------------------------------------------------------
+
+ let evtSource = null;
+
+ function connectSSE() {
+ evtSource = new EventSource('http://localhost:' + PORT + '/events?token=' + TOKEN);
+
+ evtSource.onmessage = (e) => {
+ let msg; try { msg = JSON.parse(e.data); } catch { return; }
+ switch (msg.type) {
+ case 'connected':
+ hasProjectContext = !!msg.hasProjectContext;
+ if (!hasProjectContext) showToast('No .impeccable.md found. Variants will be brand-agnostic.', 6000);
+ console.log('[impeccable] Live mode connected.');
+ if (state === 'IDLE') state = 'PICKING';
+ break;
+ case 'done':
+ if (state === 'SAVING') {
+ state = 'CONFIRMED';
+ updateBarContent('confirmed');
+ setTimeout(() => {
+ hideBar();
+ hideHighlight();
+ stopScrollTracking();
+ if (variantObserver) { variantObserver.disconnect(); variantObserver = null; }
+ clearSession();
+ selectedElement = null;
+ currentSessionId = null;
+ selectedAction = 'impeccable';
+ state = 'PICKING';
+ }, 1800);
+ return;
+ }
+ if (arrivedVariants === 0 && expectedVariants > 0 && msg.file) {
+ console.log('[impeccable] No HMR detected. Fetching variants from source file...');
+ injectVariantsFromSource(msg.file, currentSessionId);
+ return;
+ }
+ state = 'CYCLING';
+ updateBarContent('cycling');
+ break;
+ case 'error':
+ console.error('[impeccable] Error:', msg.message);
+ showToast('Error: ' + msg.message, 5000);
+ hideBar();
+ state = 'PICKING';
+ break;
+ }
+ };
+
+ evtSource.onerror = () => {
+ // EventSource auto-reconnects. Log once.
+ console.log('[impeccable] SSE connection lost. Reconnecting...');
+ };
+ }
+
+ function sendEvent(msg) {
+ msg.token = TOKEN;
+ 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));
+ }
+
+ // ---------------------------------------------------------------------------
+ // Event handlers
+ // ---------------------------------------------------------------------------
+
+ function handleMouseMove(e) {
+ if (state !== 'PICKING') return;
+ const target = document.elementFromPoint(e.clientX, e.clientY);
+ if (!target || !pickable(target) || target === hoveredElement) return;
+ hoveredElement = target;
+ showHighlight(target);
+ }
+
+ function handleClick(e) {
+ // Close action picker on any outside click
+ if (pickerEl?.style.display !== 'none' && !own(e.target)) {
+ hideActionPicker();
+ }
+ if (state !== 'PICKING') return;
+ if (own(e.target)) return;
+ if (!hoveredElement || !pickable(hoveredElement)) return;
+ e.preventDefault();
+ e.stopPropagation();
+ selectedElement = hoveredElement;
+ state = 'CONFIGURING';
+ showHighlight(selectedElement);
+ showBar('configure');
+ startScrollTracking();
+ }
+
+ function handleKeyDown(e) {
+ if (e.key === 'Escape') {
+ e.preventDefault();
+ if (pickerEl?.style.display !== 'none') { hideActionPicker(); return; }
+ if (state === 'CONFIGURING') { hideBar(); stopScrollTracking(); state = 'PICKING'; return; }
+ if (state === 'CYCLING') { handleDiscard(); return; }
+ if (state === 'SAVING' || state === 'CONFIRMED') return; // don't interrupt
+ if (state === 'PICKING') { hideHighlight(); state = 'IDLE'; return; }
+ }
+
+ if (state === 'PICKING' && hoveredElement) {
+ let next = null;
+ if (e.key === 'ArrowDown' && !e.shiftKey) {
+ next = hoveredElement.nextElementSibling;
+ while (next && !pickable(next)) next = next.nextElementSibling;
+ } else if (e.key === 'ArrowUp' && !e.shiftKey) {
+ next = hoveredElement.previousElementSibling;
+ while (next && !pickable(next)) next = next.previousElementSibling;
+ } else if (e.key === 'ArrowUp' && e.shiftKey) {
+ next = hoveredElement.parentElement;
+ if (next && !pickable(next)) next = null;
+ } else if (e.key === 'ArrowDown' && e.shiftKey) {
+ next = hoveredElement.firstElementChild;
+ while (next && !pickable(next)) next = next.nextElementSibling;
+ } else if (e.key === 'Enter') {
+ e.preventDefault();
+ selectedElement = hoveredElement;
+ state = 'CONFIGURING';
+ showHighlight(selectedElement);
+ showBar('configure');
+ startScrollTracking();
+ return;
+ }
+ if (next) {
+ e.preventDefault();
+ hoveredElement = next;
+ showHighlight(next);
+ next.scrollIntoView({ block: 'nearest', behavior: 'smooth' });
+ }
+ return;
+ }
+
+ if (state === 'CYCLING') {
+ if (e.key === 'ArrowLeft') { e.preventDefault(); cycleVariant(-1); }
+ if (e.key === 'ArrowRight') { e.preventDefault(); cycleVariant(1); }
+ if (e.key === 'Enter') { e.preventDefault(); handleAccept(); }
+ }
+ }
+
+ function handleGo() {
+ if (!selectedElement || state !== 'CONFIGURING') return;
+ const input = document.getElementById(PREFIX + '-input');
+ const prompt = input ? input.value.trim() : '';
+
+ currentSessionId = id8();
+ expectedVariants = selectedCount;
+ arrivedVariants = 0;
+ visibleVariant = 0;
+
+ sendEvent({
+ type: 'generate', id: currentSessionId,
+ action: selectedAction,
+ freeformPrompt: prompt || undefined,
+ count: selectedCount,
+ pageUrl: location.pathname,
+ element: extractContext(selectedElement),
+ });
+
+ state = 'GENERATING';
+ showBar('generating');
+ saveSession();
+ if (variantObserver) variantObserver.disconnect();
+ variantObserver = startVariantObserver(currentSessionId);
+ }
+
+ function handleAccept() {
+ if (!currentSessionId || arrivedVariants === 0) return;
+ sendEvent({ type: 'accept', id: currentSessionId, variantId: String(visibleVariant) });
+ markSessionHandled();
+ state = 'SAVING';
+ updateBarContent('saving');
+ // Don't cleanup yet — wait for the "done" WS message to show confirmation
+ }
+
+ function handleDiscard() {
+ if (!currentSessionId) return;
+ sendEvent({ type: 'discard', id: currentSessionId });
+ markSessionHandled();
+ state = 'SAVING';
+ updateBarContent('saving');
+ // Wait for "done" WS message to show confirmation and dismiss
+ }
+
+ // ---------------------------------------------------------------------------
+ // Session persistence via localStorage
+ // ---------------------------------------------------------------------------
+ // Survives page reloads, browser close/reopen, HMR, and accidental refreshes.
+
+ const LS_KEY = PREFIX + '-session';
+
+ function saveSession() {
+ if (!currentSessionId) return;
+ 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 */ }
+ }
+
+ function loadSession() {
+ try {
+ const raw = localStorage.getItem(LS_KEY);
+ return raw ? JSON.parse(raw) : null;
+ } catch { return null; }
+ }
+
+ function clearSession() {
+ try { localStorage.removeItem(LS_KEY); } catch {}
+ }
+
+ /** Mark session as handled (accepted/discarded). The agent will clean up
+ * the source, but until it does the wrapper is still in the HTML. This
+ * prevents resumeSession from picking it up again after reload. */
+ function markSessionHandled() {
+ if (!currentSessionId) return;
+ try {
+ localStorage.setItem(LS_KEY + '-handled', currentSessionId);
+ } catch {}
+ }
+
+ function isSessionHandled(id) {
+ try {
+ return localStorage.getItem(LS_KEY + '-handled') === id;
+ } catch { return false; }
+ }
+
+ function clearHandled() {
+ try { localStorage.removeItem(LS_KEY + '-handled'); } catch {}
+ }
+
+ function cleanup() {
+ hideBar();
+ hideHighlight();
+ stopScrollTracking();
+ if (variantObserver) { variantObserver.disconnect(); variantObserver = null; }
+ clearSession();
+ selectedElement = null;
+ currentSessionId = null;
+ selectedAction = 'impeccable';
+ state = 'PICKING';
+ }
+
+ // ---------------------------------------------------------------------------
+ // Toast
+ // ---------------------------------------------------------------------------
+
+ function showToast(message, duration) {
+ if (toastEl) toastEl.remove();
+ toastEl = el('div', {
+ position: 'fixed', bottom: '16px', left: '50%',
+ transform: 'translateX(-50%) translateY(8px)',
+ background: C.ink, color: C.white,
+ fontFamily: FONT, fontSize: '12px',
+ padding: '8px 16px', borderRadius: '8px',
+ zIndex: Z.toast, opacity: '0',
+ transition: 'opacity 0.25s ' + EASE + ', transform 0.25s ' + EASE,
+ pointerEvents: 'none', maxWidth: '420px', textAlign: 'center',
+ });
+ toastEl.id = PREFIX + '-toast';
+ toastEl.textContent = message;
+ document.body.appendChild(toastEl);
+ requestAnimationFrame(() => {
+ toastEl.style.opacity = '1';
+ toastEl.style.transform = 'translateX(-50%) translateY(0)';
+ });
+ setTimeout(() => {
+ if (toastEl) {
+ toastEl.style.opacity = '0';
+ toastEl.style.transform = 'translateX(-50%) translateY(8px)';
+ setTimeout(() => { if (toastEl) { toastEl.remove(); toastEl = null; } }, 250);
+ }
+ }, duration);
+ }
+
+ // ---------------------------------------------------------------------------
+ // Init
+ // ---------------------------------------------------------------------------
+
+ // Resume an active variant session after HMR/page reload.
+ // If a [data-impeccable-variants] wrapper exists in the DOM, the agent wrote
+ // variants before HMR fired. Pick up where we left off.
+ function resumeSession() {
+ const wrapper = document.querySelector('[data-impeccable-variants]');
+ if (!wrapper) { clearSession(); clearHandled(); return false; }
+
+ const sessionId = wrapper.dataset.impeccableVariants;
+
+ // Don't resume if this session was already accepted/discarded
+ if (isSessionHandled(sessionId)) return false;
+
+ currentSessionId = sessionId;
+ expectedVariants = parseInt(wrapper.dataset.impeccableVariantCount || '0');
+ const variants = wrapper.querySelectorAll('[data-impeccable-variant]:not([data-impeccable-variant="original"])');
+ arrivedVariants = variants.length;
+
+ // Restore visible variant from localStorage if available, else default to 1
+ const saved = loadSession();
+ visibleVariant = (saved && saved.id === sessionId && saved.visible > 0 && saved.visible <= arrivedVariants)
+ ? saved.visible : (arrivedVariants > 0 ? 1 : 0);
+
+ // Find the visible variant's content element for highlight positioning
+ const visEl = wrapper.querySelector('[data-impeccable-variant="' + visibleVariant + '"] > :first-child');
+ selectedElement = visEl || wrapper.parentElement;
+
+ // Set display state BEFORE starting observer (avoid triggering it)
+ if (visibleVariant > 0) showVariantInDOM(currentSessionId, visibleVariant);
+
+ state = arrivedVariants >= expectedVariants ? 'CYCLING' : 'GENERATING';
+ showBar(state === 'CYCLING' ? 'cycling' : 'generating');
+ startScrollTracking();
+ saveSession();
+
+ // Start observing for more variants AFTER initial setup
+ if (variantObserver) variantObserver.disconnect();
+ variantObserver = startVariantObserver(currentSessionId);
+ return true;
+ }
+
+ function init() {
+ initHighlight();
+ initBar();
+ initActionPicker();
+ document.addEventListener('mousemove', handleMouseMove, true);
+ document.addEventListener('click', handleClick, true);
+ document.addEventListener('keydown', handleKeyDown, true);
+ connectSSE();
+
+ // Check for an active session to resume (variant wrapper already in DOM after HMR)
+ if (!resumeSession()) {
+ console.log('[impeccable] Live variant mode ready. Hover over elements to pick one.');
+ } else {
+ console.log('[impeccable] Resumed active variant session ' + currentSessionId + ' (' + arrivedVariants + '/' + expectedVariants + ' variants).');
+ }
+ }
+
+ if (document.readyState === 'loading') {
+ document.addEventListener('DOMContentLoaded', init);
+ } else {
+ init();
+ }
+})();
diff --git a/.rovodev/skills/impeccable/scripts/live-poll.mjs b/.rovodev/skills/impeccable/scripts/live-poll.mjs
new file mode 100644
index 000000000..52859416c
--- /dev/null
+++ b/.rovodev/skills/impeccable/scripts/live-poll.mjs
@@ -0,0 +1,123 @@
+/**
+ * CLI client for the live variant mode poll/reply protocol.
+ *
+ * Usage:
+ * npx impeccable poll # Block until browser event, print JSON
+ * npx impeccable poll --timeout=60000 # Custom timeout (ms)
+ * npx impeccable poll --reply <id> done # Reply "done" to event <id>
+ * npx impeccable poll --reply <id> error "msg" # Reply with error
+ */
+
+import fs from 'node:fs';
+import path from 'node:path';
+import os from 'node:os';
+
+const LIVE_PID_FILE = path.join(os.tmpdir(), 'impeccable-live.json');
+
+function readServerInfo() {
+ try {
+ return JSON.parse(fs.readFileSync(LIVE_PID_FILE, 'utf-8'));
+ } catch {
+ console.error('No running live server found. Start one with: npx impeccable live');
+ process.exit(1);
+ }
+}
+
+export async function pollCli() {
+ const args = process.argv.slice(2);
+
+ if (args.includes('--help') || args.includes('-h')) {
+ console.log(`Usage: impeccable poll [options]
+
+Wait for a browser event from the live variant server, or reply to one.
+
+Modes:
+ poll Block until a browser event arrives, print JSON
+ poll --reply <id> done Reply "done" to event <id>
+ poll --reply <id> error "msg" Reply with an error message
+
+Options:
+ --timeout=MS Poll timeout in milliseconds (default: 120000)
+ --help Show this help message`);
+ process.exit(0);
+ }
+
+ const info = readServerInfo();
+ const base = `http://localhost:${info.port}`;
+
+ // Reply mode: npx impeccable poll --reply <id> <status> [--file path] [message]
+ const replyIdx = args.indexOf('--reply');
+ if (replyIdx !== -1) {
+ const id = args[replyIdx + 1];
+ const status = args[replyIdx + 2] || 'done';
+ const fileIdx = args.indexOf('--file');
+ const filePath = fileIdx !== -1 && fileIdx + 1 < args.length ? args[fileIdx + 1] : undefined;
+ // Message is any remaining positional arg that isn't a flag
+ const message = args.find((a, i) => i > replyIdx + 2 && !a.startsWith('--') && i !== fileIdx + 1) || undefined;
+
+ if (!id) {
+ console.error('Usage: npx impeccable poll --reply <id> <status> [--file path] [message]');
+ process.exit(1);
+ }
+
+ 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);
+ }
+
+ // Success — silent exit (agent doesn't need output for replies)
+ } catch (err) {
+ if (err.cause?.code === 'ECONNREFUSED') {
+ console.error('Live server not running. Start one with: npx impeccable live');
+ } else {
+ console.error('Reply failed:', err.message);
+ }
+ process.exit(1);
+ }
+ return;
+ }
+
+ // Poll mode: block until browser event
+ const timeoutArg = args.find(a => a.startsWith('--timeout='));
+ const timeout = timeoutArg ? parseInt(timeoutArg.split('=')[1], 10) : 120000;
+
+ try {
+ const res = await fetch(`${base}/poll?token=${info.token}&timeout=${timeout}`);
+
+ if (res.status === 401) {
+ console.error('Authentication failed. The server token may have changed.');
+ console.error('Try restarting: npx impeccable live stop && npx impeccable live');
+ process.exit(1);
+ }
+
+ if (!res.ok) {
+ console.error(`Poll failed: ${res.status} ${res.statusText}`);
+ process.exit(1);
+ }
+
+ const event = await res.json();
+ // Print the event as JSON — the agent reads this from stdout
+ console.log(JSON.stringify(event));
+ } catch (err) {
+ if (err.cause?.code === 'ECONNREFUSED') {
+ console.error('Live server not running. Start one with: npx impeccable live');
+ } else {
+ console.error('Poll failed:', err.message);
+ }
+ process.exit(1);
+ }
+}
diff --git a/.rovodev/skills/impeccable/scripts/live-server.mjs b/.rovodev/skills/impeccable/scripts/live-server.mjs
new file mode 100644
index 000000000..d436bad58
--- /dev/null
+++ b/.rovodev/skills/impeccable/scripts/live-server.mjs
@@ -0,0 +1,416 @@
+#!/usr/bin/env node
+/**
+ * Live variant mode server (self-contained, zero dependencies).
+ *
+ * Serves the browser script (/live.js), the detection overlay (/detect.js),
+ * uses Server-Sent Events (SSE) for server→browser push, and HTTP POST for
+ * browser→server events. Agent communicates via HTTP long-poll (/poll).
+ *
+ * Usage:
+ * node <scripts_path>/live-server.mjs # start
+ * node <scripts_path>/live-server.mjs stop # stop
+ * node <scripts_path>/live-server.mjs --help
+ */
+
+import http from 'node:http';
+import { randomUUID } from 'node:crypto';
+import fs from 'node:fs';
+import path from 'node:path';
+import os from 'node:os';
+import net from 'node:net';
+import { fileURLToPath } from 'node:url';
+
+const __dirname = path.dirname(fileURLToPath(import.meta.url));
+const LIVE_PID_FILE = path.join(os.tmpdir(), 'impeccable-live.json');
+const DEFAULT_POLL_TIMEOUT = 120_000;
+
+// ---------------------------------------------------------------------------
+// Port detection
+// ---------------------------------------------------------------------------
+
+async function findOpenPort(start = 8400) {
+ return new Promise((resolve) => {
+ const srv = net.createServer();
+ srv.listen(start, '127.0.0.1', () => {
+ const port = srv.address().port;
+ srv.close(() => resolve(port));
+ });
+ srv.on('error', () => resolve(findOpenPort(start + 1)));
+ });
+}
+
+// ---------------------------------------------------------------------------
+// Session state
+// ---------------------------------------------------------------------------
+
+const state = {
+ token: null,
+ port: null,
+ sseClients: new Set(), // SSE response objects (server→browser push)
+ pendingEvents: [], // browser events waiting for agent poll
+ pendingPolls: [], // agent poll callbacks waiting for browser events
+ exitTimer: null,
+};
+
+function enqueueEvent(event) {
+ if (state.pendingPolls.length > 0) {
+ state.pendingPolls.shift()(event);
+ } else {
+ state.pendingEvents.push(event);
+ }
+}
+
+/** Push a message to all connected SSE clients. */
+function broadcast(msg) {
+ const data = 'data: ' + JSON.stringify(msg) + '\n\n';
+ for (const res of state.sseClients) {
+ try { res.write(data); } catch { /* client gone */ }
+ }
+}
+
+// ---------------------------------------------------------------------------
+// Load scripts
+// ---------------------------------------------------------------------------
+
+function loadBrowserScripts() {
+ // Detection script: look relative to the skill scripts dir, then fall back
+ // to the npm package location (src/detect-antipatterns-browser.js)
+ const detectPaths = [
+ path.join(__dirname, '..', '..', '..', '..', 'src', 'detect-antipatterns-browser.js'),
+ path.join(process.cwd(), 'node_modules', 'impeccable', 'src', 'detect-antipatterns-browser.js'),
+ ];
+ let detectScript = '';
+ for (const p of detectPaths) {
+ try { detectScript = fs.readFileSync(p, 'utf-8'); break; } catch { /* try next */ }
+ }
+
+ const livePath = path.join(__dirname, 'live-browser.js');
+ let liveScript = '';
+ try {
+ liveScript = fs.readFileSync(livePath, 'utf-8');
+ } catch {
+ process.stderr.write('Error: live-browser.js not found at ' + livePath + '\n');
+ process.exit(1);
+ }
+
+ return { detectScript, liveScript };
+}
+
+function hasProjectContext() {
+ try {
+ fs.accessSync(path.join(process.cwd(), '.impeccable.md'), fs.constants.R_OK);
+ return true;
+ } catch { return false; }
+}
+
+// ---------------------------------------------------------------------------
+// Validation (inline — no external import needed for self-contained script)
+// ---------------------------------------------------------------------------
+
+const VISUAL_ACTIONS = [
+ 'impeccable', 'bolder', 'quieter', 'distill', 'polish', 'typeset',
+ 'colorize', 'layout', 'adapt', 'animate', 'delight', 'overdrive',
+];
+
+function validateEvent(msg) {
+ if (!msg || typeof msg !== 'object' || !msg.type) return 'Missing or invalid message';
+ switch (msg.type) {
+ case 'generate':
+ if (!msg.id || typeof msg.id !== 'string') return 'generate: missing id';
+ if (!msg.action || !VISUAL_ACTIONS.includes(msg.action)) return 'generate: invalid action';
+ if (!Number.isInteger(msg.count) || msg.count < 1 || msg.count > 8) return 'generate: count must be 1-8';
+ if (!msg.element || !msg.element.outerHTML) return 'generate: missing element context';
+ return null;
+ case 'accept':
+ if (!msg.id) return 'accept: missing id';
+ if (!msg.variantId) return 'accept: missing variantId';
+ return null;
+ case 'discard':
+ return msg.id ? null : 'discard: missing id';
+ case 'exit':
+ return null;
+ default:
+ return 'Unknown event type: ' + msg.type;
+ }
+}
+
+// ---------------------------------------------------------------------------
+// HTTP request handler
+// ---------------------------------------------------------------------------
+
+function createRequestHandler({ detectScript, liveScriptWithToken }) {
+ return (req, res) => {
+ const url = new URL(req.url, `http://localhost:${state.port}`);
+ res.setHeader('Access-Control-Allow-Origin', '*');
+ res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS');
+ res.setHeader('Access-Control-Allow-Headers', 'Content-Type');
+ if (req.method === 'OPTIONS') { res.writeHead(204); res.end(); return; }
+
+ const p = url.pathname;
+
+ // --- Scripts ---
+ if (p === '/live.js') {
+ res.writeHead(200, { 'Content-Type': 'application/javascript' });
+ res.end(liveScriptWithToken);
+ return;
+ }
+ if (p === '/detect.js' || p === '/') {
+ if (!detectScript) { res.writeHead(404); res.end('Not available'); return; }
+ res.writeHead(200, { 'Content-Type': 'application/javascript' });
+ res.end(detectScript);
+ return;
+ }
+
+ // --- Health ---
+ if (p === '/health') {
+ res.writeHead(200, { 'Content-Type': 'application/json' });
+ res.end(JSON.stringify({
+ status: 'ok', port: state.port, mode: 'variant',
+ hasProjectContext: hasProjectContext(),
+ connectedClients: state.sseClients.size,
+ }));
+ return;
+ }
+
+ // --- Source file (no-HMR fallback) ---
+ if (p === '/source') {
+ const token = url.searchParams.get('token');
+ if (token !== state.token) { res.writeHead(401); res.end('Unauthorized'); return; }
+ const filePath = url.searchParams.get('path');
+ if (!filePath || filePath.includes('..')) { res.writeHead(400); res.end('Bad path'); return; }
+ const absPath = path.resolve(process.cwd(), filePath);
+ if (!absPath.startsWith(process.cwd())) { res.writeHead(403); res.end('Forbidden'); return; }
+ try {
+ res.writeHead(200, { 'Content-Type': 'text/html; charset=utf-8' });
+ res.end(fs.readFileSync(absPath, 'utf-8'));
+ } catch { res.writeHead(404); res.end('File not found'); }
+ return;
+ }
+
+ // --- SSE: server→browser push (replaces WebSocket) ---
+ if (p === '/events' && req.method === 'GET') {
+ const token = url.searchParams.get('token');
+ if (token !== state.token) { res.writeHead(401); res.end('Unauthorized'); return; }
+ res.writeHead(200, {
+ 'Content-Type': 'text/event-stream',
+ 'Cache-Control': 'no-cache',
+ 'Connection': 'keep-alive',
+ });
+ res.write('data: ' + JSON.stringify({
+ type: 'connected',
+ hasProjectContext: hasProjectContext(),
+ }) + '\n\n');
+
+ state.sseClients.add(res);
+ clearTimeout(state.exitTimer);
+
+ req.on('close', () => {
+ state.sseClients.delete(res);
+ if (state.sseClients.size === 0) {
+ clearTimeout(state.exitTimer);
+ state.exitTimer = setTimeout(() => {
+ if (state.sseClients.size === 0) enqueueEvent({ type: 'exit' });
+ }, 8000);
+ }
+ });
+ return;
+ }
+
+ // --- Browser→server events (replaces WebSocket messages) ---
+ if (p === '/events' && req.method === 'POST') {
+ let body = '';
+ req.on('data', (c) => { body += c; });
+ req.on('end', () => {
+ let msg;
+ try { msg = JSON.parse(body); } catch {
+ res.writeHead(400, { 'Content-Type': 'application/json' });
+ res.end(JSON.stringify({ error: 'Invalid JSON' }));
+ return;
+ }
+ if (msg.token !== state.token) {
+ res.writeHead(401, { 'Content-Type': 'application/json' });
+ res.end(JSON.stringify({ error: 'Unauthorized' }));
+ return;
+ }
+ const error = validateEvent(msg);
+ if (error) {
+ res.writeHead(400, { 'Content-Type': 'application/json' });
+ res.end(JSON.stringify({ error }));
+ return;
+ }
+ enqueueEvent(msg);
+ res.writeHead(200, { 'Content-Type': 'application/json' });
+ res.end(JSON.stringify({ ok: true }));
+ });
+ return;
+ }
+
+ // --- Stop ---
+ if (p === '/stop') {
+ const token = url.searchParams.get('token');
+ if (token !== state.token) { res.writeHead(401); res.end('Unauthorized'); return; }
+ res.writeHead(200, { 'Content-Type': 'text/plain' });
+ res.end('stopping');
+ shutdown();
+ return;
+ }
+
+ // --- Agent poll ---
+ if (p === '/poll' && req.method === 'GET') {
+ handlePollGet(req, res, url);
+ return;
+ }
+ if (p === '/poll' && req.method === 'POST') {
+ handlePollPost(req, res);
+ return;
+ }
+
+ res.writeHead(404); res.end('Not found');
+ };
+}
+
+// ---------------------------------------------------------------------------
+// Agent poll endpoints (unchanged from WS version)
+// ---------------------------------------------------------------------------
+
+function handlePollGet(req, res, url) {
+ 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 timeout = parseInt(url.searchParams.get('timeout') || DEFAULT_POLL_TIMEOUT, 10);
+ if (state.pendingEvents.length > 0) {
+ res.writeHead(200, { 'Content-Type': 'application/json' });
+ res.end(JSON.stringify(state.pendingEvents.shift()));
+ return;
+ }
+ const timer = setTimeout(() => {
+ const idx = state.pendingPolls.indexOf(resolve);
+ if (idx !== -1) state.pendingPolls.splice(idx, 1);
+ res.writeHead(200, { 'Content-Type': 'application/json' });
+ res.end(JSON.stringify({ type: 'timeout' }));
+ }, timeout);
+ function resolve(event) {
+ clearTimeout(timer);
+ res.writeHead(200, { 'Content-Type': 'application/json' });
+ res.end(JSON.stringify(event));
+ }
+ state.pendingPolls.push(resolve);
+ req.on('close', () => {
+ clearTimeout(timer);
+ const idx = state.pendingPolls.indexOf(resolve);
+ if (idx !== -1) state.pendingPolls.splice(idx, 1);
+ });
+}
+
+function handlePollPost(req, res) {
+ let body = '';
+ req.on('data', (c) => { body += c; });
+ req.on('end', () => {
+ let msg;
+ try { msg = JSON.parse(body); } catch {
+ res.writeHead(400, { 'Content-Type': 'application/json' });
+ res.end(JSON.stringify({ error: 'Invalid JSON' }));
+ return;
+ }
+ if (msg.token !== state.token) {
+ res.writeHead(401, { 'Content-Type': 'application/json' });
+ res.end(JSON.stringify({ error: 'Unauthorized' }));
+ return;
+ }
+ // Forward the reply to the browser via SSE
+ broadcast({ type: msg.type || 'done', id: msg.id, message: msg.message, file: msg.file, data: msg.data });
+ res.writeHead(200, { 'Content-Type': 'application/json' });
+ res.end(JSON.stringify({ ok: true }));
+ });
+}
+
+// ---------------------------------------------------------------------------
+// Lifecycle
+// ---------------------------------------------------------------------------
+
+let httpServer = null;
+
+function shutdown() {
+ try { fs.unlinkSync(LIVE_PID_FILE); } catch {}
+ for (const res of state.sseClients) { try { res.end(); } catch {} }
+ state.sseClients.clear();
+ for (const resolve of state.pendingPolls) resolve({ type: 'exit' });
+ state.pendingPolls.length = 0;
+ if (httpServer) httpServer.close();
+ process.exit(0);
+}
+
+// ---------------------------------------------------------------------------
+// Main
+// ---------------------------------------------------------------------------
+
+const args = process.argv.slice(2);
+
+if (args.includes('--help') || args.includes('-h')) {
+ console.log(`Usage: node live-server.mjs [options]
+
+Start the live variant mode server (zero dependencies).
+
+Commands:
+ (default) Start the server
+ stop Stop a running server
+
+Options:
+ --port=PORT Use a specific port (default: auto-detect starting at 8400)
+ --help Show this help
+
+Endpoints:
+ /live.js Browser script (element picker + variant cycling)
+ /detect.js Detection overlay (backwards compatible)
+ /events SSE stream (server→browser) + POST (browser→server)
+ /poll Long-poll for agent CLI
+ /source Raw source file reader (no-HMR fallback)
+ /health Health check`);
+ process.exit(0);
+}
+
+if (args.includes('stop')) {
+ try {
+ const info = JSON.parse(fs.readFileSync(LIVE_PID_FILE, 'utf-8'));
+ 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 { console.log('No running live server found.'); }
+ process.exit(0);
+}
+
+// Check for existing session
+try {
+ const existing = JSON.parse(fs.readFileSync(LIVE_PID_FILE, 'utf-8'));
+ 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 {}
+
+state.token = randomUUID();
+const portArg = args.find(a => a.startsWith('--port='));
+state.port = portArg ? parseInt(portArg.split('=')[1], 10) : await findOpenPort();
+
+const { detectScript, liveScript } = loadBrowserScripts();
+const liveScriptWithToken =
+ `window.__IMPECCABLE_TOKEN__ = '${state.token}';\n` +
+ `window.__IMPECCABLE_PORT__ = ${state.port};\n` +
+ liveScript;
+
+httpServer = http.createServer(createRequestHandler({ detectScript, liveScriptWithToken }));
+
+httpServer.listen(state.port, '127.0.0.1', () => {
+ fs.writeFileSync(LIVE_PID_FILE, JSON.stringify({ 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`);
+ console.log(`Inject: <script src="${url}/live.js"><\/script>`);
+ console.log(`Stop: node ${path.basename(fileURLToPath(import.meta.url))} stop`);
+});
+
+process.on('SIGINT', shutdown);
+process.on('SIGTERM', shutdown);
diff --git a/.rovodev/skills/impeccable/scripts/live-wrap.mjs b/.rovodev/skills/impeccable/scripts/live-wrap.mjs
new file mode 100644
index 000000000..f1c838cdd
--- /dev/null
+++ b/.rovodev/skills/impeccable/scripts/live-wrap.mjs
@@ -0,0 +1,298 @@
+/**
+ * CLI helper: find an element in source and wrap it in a variant container.
+ *
+ * Usage:
+ * npx impeccable wrap --id SESSION_ID --count N --query "hero-combined-left" [--file path]
+ *
+ * Searches project files for the element matching the query (class name, ID, or
+ * text snippet), wraps it with the variant scaffolding, and prints the file path
+ * + line range where the agent should insert variant HTML.
+ *
+ * This replaces 3-4 agent tool calls (grep + read + edit) with a single CLI call.
+ */
+
+import fs from 'node:fs';
+import path from 'node:path';
+
+const EXTENSIONS = ['.html', '.jsx', '.tsx', '.vue', '.svelte', '.astro'];
+
+export async function wrapCli() {
+ const args = process.argv.slice(2);
+
+ if (args.includes('--help') || args.includes('-h')) {
+ console.log(`Usage: impeccable wrap [options]
+
+Find an element in source and wrap it in a variant container.
+
+Required:
+ --id ID Session ID for the variant wrapper
+ --count N Number of expected variants (1-8)
+
+Element identification (at least one required):
+ --element-id ID HTML id attribute of the element
+ --classes A,B,C Comma-separated CSS class names
+ --tag TAG Tag name (div, section, etc.)
+ --query TEXT Fallback: raw text to search for
+
+Optional:
+ --file PATH Source file to search in (skips auto-detection)
+ --help Show this help message
+
+Output (JSON):
+ { file, startLine, endLine, insertLine, commentSyntax }
+
+The agent should insert variant HTML at insertLine.`);
+ process.exit(0);
+ }
+
+ const id = argVal(args, '--id');
+ const count = parseInt(argVal(args, '--count') || '3');
+ const elementId = argVal(args, '--element-id');
+ const classes = argVal(args, '--classes');
+ const tag = argVal(args, '--tag');
+ const query = argVal(args, '--query');
+ const filePath = argVal(args, '--file');
+
+ if (!id) { console.error('Missing --id'); process.exit(1); }
+ if (!elementId && !classes && !query) {
+ console.error('Need at least one of: --element-id, --classes, --query');
+ process.exit(1);
+ }
+
+ // Build search queries in priority order (most specific first)
+ const queries = buildSearchQueries(elementId, classes, tag, query);
+
+ // Find the source file
+ let targetFile = filePath;
+ let matchedQuery = null;
+ if (!targetFile) {
+ for (const q of queries) {
+ targetFile = findFileWithQuery(q, process.cwd());
+ if (targetFile) { matchedQuery = q; break; }
+ }
+ if (!targetFile) {
+ console.error(JSON.stringify({ error: 'Could not find element in project files. Searched for: ' + queries.join(', ') }));
+ process.exit(1);
+ }
+ } else {
+ matchedQuery = queries[0];
+ }
+
+ const content = fs.readFileSync(targetFile, 'utf-8');
+ const lines = content.split('\n');
+
+ // Find the element, trying each query in priority order
+ let match = null;
+ for (const q of queries) {
+ match = findElement(lines, q);
+ if (match) break;
+ }
+ if (!match) {
+ console.error(JSON.stringify({ error: 'Found file but could not locate element in ' + targetFile + '. Searched for: ' + queries.join(', ') }));
+ process.exit(1);
+ }
+
+ const { startLine, endLine } = match;
+ const commentSyntax = detectCommentSyntax(targetFile);
+ const indent = lines[startLine].match(/^(\s*)/)[1];
+
+ // Extract the original element
+ const originalLines = lines.slice(startLine, endLine + 1);
+ const originalIndented = originalLines.map(l => indent + ' ' + l.trimStart()).join('\n');
+
+ // Build the wrapper
+ const wrapperLines = [
+ indent + commentSyntax.open + ' impeccable-variants-start ' + id + ' ' + commentSyntax.close,
+ indent + '<div data-impeccable-variants="' + id + '" data-impeccable-variant-count="' + count + '" style="display: contents">',
+ indent + ' ' + commentSyntax.open + ' Original ' + commentSyntax.close,
+ indent + ' <div data-impeccable-variant="original">',
+ originalIndented,
+ indent + ' </div>',
+ indent + ' ' + commentSyntax.open + ' Variants: insert below this line ' + commentSyntax.close,
+ indent + '</div>',
+ indent + commentSyntax.open + ' impeccable-variants-end ' + id + ' ' + commentSyntax.close,
+ ];
+
+ // Replace the original element with the wrapper
+ const newLines = [
+ ...lines.slice(0, startLine),
+ ...wrapperLines,
+ ...lines.slice(endLine + 1),
+ ];
+ fs.writeFileSync(targetFile, newLines.join('\n'), 'utf-8');
+
+ // Calculate insert line (the "insert below this line" comment)
+ const insertLine = startLine + 6; // 0-indexed in the new file
+
+ console.log(JSON.stringify({
+ file: path.relative(process.cwd(), targetFile),
+ startLine: startLine + 1, // 1-indexed for the agent
+ endLine: startLine + wrapperLines.length, // 1-indexed
+ insertLine: insertLine + 1, // 1-indexed: where variants go
+ commentSyntax: commentSyntax,
+ originalLineCount: originalLines.length,
+ }));
+}
+
+// ---------------------------------------------------------------------------
+// Helpers
+// ---------------------------------------------------------------------------
+
+function argVal(args, flag) {
+ const idx = args.indexOf(flag);
+ return idx !== -1 && idx + 1 < args.length ? args[idx + 1] : null;
+}
+
+/**
+ * Build search query strings in priority order (most specific first).
+ * ID is most reliable, then specific class combos, then single classes, then raw query.
+ */
+function buildSearchQueries(elementId, classes, tag, query) {
+ const queries = [];
+
+ // 1. ID is the most specific
+ if (elementId) {
+ queries.push('id="' + elementId + '"');
+ }
+
+ // 2. Full class attribute match (for elements with distinctive multi-class combos)
+ if (classes) {
+ const classList = classes.split(',').map(c => c.trim()).filter(Boolean);
+ if (classList.length > 1) {
+ // Try the most distinctive class first (longest, most specific)
+ const sorted = [...classList].sort((a, b) => b.length - a.length);
+ queries.push('class="' + classList.join(' ') + '"'); // exact full match
+ queries.push(sorted[0]); // most distinctive single class
+ } else if (classList.length === 1) {
+ queries.push(classList[0]);
+ }
+ }
+
+ // 3. Tag + class combo (e.g., <section class="hero">)
+ if (tag && classes) {
+ const firstClass = classes.split(',')[0].trim();
+ queries.push('<' + tag + ' class="' + firstClass);
+ }
+
+ // 4. Raw fallback query
+ if (query) {
+ queries.push(query);
+ }
+
+ return queries;
+}
+
+function detectCommentSyntax(filePath) {
+ const ext = path.extname(filePath).toLowerCase();
+ if (ext === '.jsx' || ext === '.tsx') {
+ return { open: '{/*', close: '*/}' };
+ }
+ // HTML, Vue, Svelte, Astro all use HTML comments
+ return { open: '<!--', close: '-->' };
+}
+
+/**
+ * Search project files for the query string (class name, ID, etc.)
+ * Returns the first matching file path, or null.
+ */
+function findFileWithQuery(query, cwd) {
+ const searchDirs = ['src', 'app', 'pages', 'components', 'public', 'views', 'templates', '.'];
+ const seen = new Set();
+
+ for (const dir of searchDirs) {
+ const absDir = path.join(cwd, dir);
+ if (!fs.existsSync(absDir)) continue;
+ const result = searchDir(absDir, query, seen, 0);
+ if (result) return result;
+ }
+ return null;
+}
+
+function searchDir(dir, query, seen, depth) {
+ if (depth > 5) return null; // don't go too deep
+ const realDir = fs.realpathSync(dir);
+ if (seen.has(realDir)) return null;
+ seen.add(realDir);
+
+ let entries;
+ try { entries = fs.readdirSync(dir, { withFileTypes: true }); }
+ catch { return null; }
+
+ // Check files first
+ for (const entry of entries) {
+ if (!entry.isFile()) continue;
+ const ext = path.extname(entry.name).toLowerCase();
+ if (!EXTENSIONS.includes(ext)) continue;
+
+ const filePath = path.join(dir, entry.name);
+ try {
+ const content = fs.readFileSync(filePath, 'utf-8');
+ if (content.includes(query)) return filePath;
+ } catch { /* skip unreadable files */ }
+ }
+
+ // Then recurse into directories
+ for (const entry of entries) {
+ if (!entry.isDirectory()) continue;
+ if (entry.name === 'node_modules' || entry.name === '.git' || entry.name === 'dist' || entry.name === 'build') continue;
+ const result = searchDir(path.join(dir, entry.name), query, seen, depth + 1);
+ if (result) return result;
+ }
+
+ return null;
+}
+
+/**
+ * Find the element's start and end line in the file.
+ * The query is a class name, ID, or text snippet.
+ * We find the line containing the query, then find the matching closing tag.
+ */
+function findElement(lines, query) {
+ // Find the line containing the query
+ let startLine = -1;
+ for (let i = 0; i < lines.length; i++) {
+ if (lines[i].includes(query)) {
+ // Make sure this looks like a tag opening, not a comment or string
+ const line = lines[i].trim();
+ if (line.startsWith('<!--') || line.startsWith('{/*') || line.startsWith('//')) continue;
+ // Skip lines inside data-impeccable-variant containers (already wrapped)
+ if (lines[i].includes('data-impeccable-variant')) continue;
+ startLine = i;
+ break;
+ }
+ }
+
+ if (startLine === -1) return null;
+
+ // Find the end of this element by counting open/close tags
+ const endLine = findClosingLine(lines, startLine);
+ return { startLine, endLine };
+}
+
+/**
+ * Starting from a line with an opening tag, find the line with the matching
+ * closing tag by counting tag nesting depth.
+ */
+function findClosingLine(lines, start) {
+ // Extract the tag name from the opening line
+ const openMatch = lines[start].match(/<(\w+)[\s>]/);
+ if (!openMatch) return start; // self-closing or text-only line
+
+ const tagName = openMatch[1];
+ let depth = 0;
+
+ for (let i = start; i < lines.length; i++) {
+ const line = lines[i];
+ // Count opening tags (not self-closing)
+ const opens = (line.match(new RegExp('<' + tagName + '[\\s>]', 'g')) || []).length;
+ const selfCloses = (line.match(new RegExp('<' + tagName + '[^>]*/>', 'g')) || []).length;
+ const closes = (line.match(new RegExp('</' + tagName + '\\s*>', 'g')) || []).length;
+
+ depth += opens - selfCloses - closes;
+
+ if (depth <= 0) return i;
+ }
+
+ // If we can't find the close, return a reasonable guess
+ return Math.min(start + 50, lines.length - 1);
+}
diff --git a/.trae-cn/skills/impeccable/reference/live.md b/.trae-cn/skills/impeccable/reference/live.md
index 53b64a21a..ba0e9b0c5 100644
--- a/.trae-cn/skills/impeccable/reference/live.md
+++ b/.trae-cn/skills/impeccable/reference/live.md
@@ -10,7 +10,7 @@ Launch interactive live variant mode: select elements in the browser, pick a des
1. Read `.impeccable.md` if it exists. Keep the design context in mind for variant generation.
2. Start the live variant server:
```bash
- npx impeccable live &
+ node {{scripts_path}}/live-server.mjs &
```
3. Note the **port** and **token** printed to stdout.
@@ -53,7 +53,7 @@ Run a blocking poll loop. On each iteration, wait for a browser event and respon
```
LOOP:
- Run: npx impeccable poll
+ Run: node {{scripts_path}}/live-poll.mjs
Read the JSON output. Dispatch based on the "type" field:
TYPE "generate":
@@ -85,7 +85,7 @@ The event contains: `{id, action, freeformPrompt, count, pageUrl, element}`.
Use the `wrap` helper to find the element and create the variant container:
```bash
-npx impeccable wrap --id EVENT_ID --count EVENT_COUNT --element-id "ELEMENT_ID" --classes "class1,class2" --tag "div"
+node {{scripts_path}}/live-wrap.mjs --id EVENT_ID --count EVENT_COUNT --element-id "ELEMENT_ID" --classes "class1,class2" --tag "div"
```
Pass the element's id (`event.element.id`), classes (`event.element.classes` joined with commas), and tag name. The command searches in priority order: ID match first, then class names, then tag+class combo. If `event.pageUrl` hints at the file (e.g., `/` is usually `index.html`), pass `--file PATH` to skip the search.
@@ -136,10 +136,14 @@ The first variant should NOT have `style="display: none"` (it should be visible
### Step 3: Signal completion
+Include `--file` so the browser can fetch variants directly if the dev server lacks HMR:
+
```bash
-npx impeccable poll --reply EVENT_ID done
+node {{scripts_path}}/live-poll.mjs --reply EVENT_ID done --file RELATIVE_PATH
```
+The file path should be relative to the project root (e.g., `public/index.html`, `src/App.tsx`).
+
## Handle Accept
The event contains: `{id, variantId}`.
@@ -151,7 +155,7 @@ The user accepted a specific variant. For v1 (inspection mode):
4. Remove any scoped CSS blocks (between `impeccable-variants-css-start` and `impeccable-variants-css-end` markers).
5. Reply:
```bash
- npx impeccable poll --reply SESSION_ID done
+ node {{scripts_path}}/live-poll.mjs --reply SESSION_ID done
```
## Handle Discard
@@ -163,7 +167,7 @@ The event contains: `{id}`.
3. Remove any scoped CSS blocks for this session.
4. Reply:
```bash
- npx impeccable poll --reply SESSION_ID done
+ node {{scripts_path}}/live-poll.mjs --reply SESSION_ID done
```
## Cleanup (on exit)
@@ -174,7 +178,7 @@ When the loop ends:
2. **Remove any leftover variant wrappers** (search for `impeccable-variants-start` markers and clean up).
3. **Stop the server**:
```bash
- npx impeccable live stop
+ node {{scripts_path}}/live-server.mjs stop
```
## Variant Generation Guidelines
diff --git a/.trae-cn/skills/impeccable/scripts/live-browser.js b/.trae-cn/skills/impeccable/scripts/live-browser.js
new file mode 100644
index 000000000..7a26c9829
--- /dev/null
+++ b/.trae-cn/skills/impeccable/scripts/live-browser.js
@@ -0,0 +1,1220 @@
+/**
+ * Impeccable Live Variant Mode — Browser Script
+ *
+ * Injected into the user's page via <script src="http://localhost:PORT/live.js">.
+ * The server prepends window.__IMPECCABLE_TOKEN__ and window.__IMPECCABLE_PORT__
+ * before this code.
+ *
+ * UI: a single floating bar that morphs between three states —
+ * configure (pick action + go), generating (progressive dots), and cycling
+ * (prev/next + accept/discard). Feels like Spotlight, not a modal.
+ */
+(function () {
+ 'use strict';
+ if (typeof window === 'undefined') return;
+
+ // Guard against double-init. Bun's HTML loader may process the <script> tag
+ // and create a bundled copy alongside the external load, or HMR may re-execute.
+ // Check BEFORE reading token/port to catch all cases.
+ if (window.__IMPECCABLE_LIVE_INIT__) return;
+ window.__IMPECCABLE_LIVE_INIT__ = true;
+
+ const TOKEN = window.__IMPECCABLE_TOKEN__;
+ const PORT = window.__IMPECCABLE_PORT__;
+ if (!TOKEN || !PORT) {
+ window.__IMPECCABLE_LIVE_INIT__ = false; // reset so the real load can init
+ return;
+ }
+
+ // ---------------------------------------------------------------------------
+ // Design tokens
+ // ---------------------------------------------------------------------------
+
+ const C = {
+ brand: 'oklch(55% 0.25 350)',
+ brandHov: 'oklch(48% 0.25 350)',
+ brandSoft: 'oklch(55% 0.25 350 / 0.12)',
+ ink: 'oklch(15% 0.01 350)',
+ ash: 'oklch(55% 0 0)',
+ paper: 'oklch(98% 0.005 350 / 0.92)',
+ paperSolid:'oklch(98% 0.005 350)',
+ mist: 'oklch(90% 0.01 350 / 0.6)',
+ white: 'oklch(99% 0 0)',
+ };
+ const FONT = 'system-ui, -apple-system, sans-serif';
+ const MONO = 'ui-monospace, SFMono-Regular, Menlo, monospace';
+ const Z = { highlight: 99990, bar: 99995, picker: 99997, toast: 99999 };
+ const EASE = 'cubic-bezier(0.22, 1, 0.36, 1)'; // ease-out-quint
+ const PREFIX = 'impeccable-live';
+
+ const SKIP_TAGS = new Set([
+ 'html', 'head', 'body', 'script', 'style', 'link', 'meta', 'noscript', 'br', 'wbr',
+ ]);
+
+ const ACTIONS = [
+ { value: 'impeccable', label: 'Freeform' },
+ { value: 'bolder', label: 'Bolder' },
+ { value: 'quieter', label: 'Quieter' },
+ { value: 'distill', label: 'Distill' },
+ { value: 'polish', label: 'Polish' },
+ { value: 'typeset', label: 'Typeset' },
+ { value: 'colorize', label: 'Colorize' },
+ { value: 'layout', label: 'Layout' },
+ { value: 'adapt', label: 'Adapt' },
+ { value: 'animate', label: 'Animate' },
+ { value: 'delight', label: 'Delight' },
+ { value: 'overdrive', label: 'Overdrive' },
+ ];
+
+ // ---------------------------------------------------------------------------
+ // State
+ // ---------------------------------------------------------------------------
+
+ let state = 'IDLE';
+ let hoveredElement = null;
+ let selectedElement = null;
+ let currentSessionId = null;
+ let expectedVariants = 0;
+ let arrivedVariants = 0;
+ let visibleVariant = 0;
+ let variantObserver = null;
+ let hasProjectContext = false;
+ let selectedAction = 'impeccable';
+ let selectedCount = 3;
+
+ // UI refs
+ let highlightEl = null;
+ let tooltipEl = null;
+ let barEl = null;
+ let pickerEl = null;
+ let toastEl = null;
+ let scrollRaf = null;
+
+ // ---------------------------------------------------------------------------
+ // Helpers
+ // ---------------------------------------------------------------------------
+
+ function own(el) {
+ return el && (el.id?.startsWith(PREFIX) || el.closest?.('[id^="' + PREFIX + '"]'));
+ }
+
+ function pickable(el) {
+ if (!el || el.nodeType !== 1) return false;
+ if (SKIP_TAGS.has(el.tagName.toLowerCase())) return false;
+ if (own(el)) return false;
+ const r = el.getBoundingClientRect();
+ return r.width >= 20 && r.height >= 20;
+ }
+
+ function desc(el) {
+ if (!el) return '';
+ let s = el.tagName.toLowerCase();
+ if (el.id) s += '#' + el.id;
+ else if (el.classList.length) s += '.' + [...el.classList].slice(0, 2).join('.');
+ return s;
+ }
+
+ function id8() { return crypto.randomUUID().replace(/-/g, '').slice(0, 8); }
+
+ // ---------------------------------------------------------------------------
+ // Highlight overlay
+ // ---------------------------------------------------------------------------
+
+ function initHighlight() {
+ highlightEl = document.createElement('div');
+ highlightEl.id = PREFIX + '-highlight';
+ Object.assign(highlightEl.style, {
+ position: 'fixed', top: '0', left: '0', width: '0', height: '0',
+ border: '2px solid ' + C.brand, borderRadius: '3px',
+ pointerEvents: 'none', zIndex: Z.highlight, boxSizing: 'border-box',
+ transition: 'top 0.08s ease, left 0.08s ease, width 0.08s ease, height 0.08s ease, opacity 0.15s ease',
+ display: 'none', opacity: '0',
+ });
+ document.body.appendChild(highlightEl);
+
+ tooltipEl = document.createElement('div');
+ tooltipEl.id = PREFIX + '-tooltip';
+ Object.assign(tooltipEl.style, {
+ position: 'fixed',
+ background: C.ink, color: C.white,
+ fontFamily: MONO, fontSize: '10px', fontWeight: '500',
+ padding: '2px 6px', borderRadius: '3px',
+ zIndex: Z.highlight + 1, pointerEvents: 'none',
+ whiteSpace: 'nowrap', display: 'none',
+ letterSpacing: '0.02em',
+ });
+ document.body.appendChild(tooltipEl);
+ }
+
+ function showHighlight(el) {
+ if (!el || !highlightEl) return;
+ const r = el.getBoundingClientRect();
+ Object.assign(highlightEl.style, {
+ top: (r.top - 2) + 'px', left: (r.left - 2) + 'px',
+ width: (r.width + 4) + 'px', height: (r.height + 4) + 'px',
+ display: 'block', opacity: '1',
+ });
+ tooltipEl.textContent = desc(el);
+ const tipTop = r.top - 20;
+ Object.assign(tooltipEl.style, {
+ top: (tipTop < 4 ? r.bottom + 4 : tipTop) + 'px',
+ left: Math.max(4, r.left) + 'px', display: 'block',
+ });
+ }
+
+ function hideHighlight() {
+ if (highlightEl) { highlightEl.style.opacity = '0'; highlightEl.style.display = 'none'; }
+ if (tooltipEl) tooltipEl.style.display = 'none';
+ }
+
+ // ---------------------------------------------------------------------------
+ // Element context extraction
+ // ---------------------------------------------------------------------------
+
+ function extractContext(el) {
+ const cs = getComputedStyle(el);
+ const r = el.getBoundingClientRect();
+ const props = {};
+ for (const sheet of document.styleSheets) {
+ try {
+ for (const rule of sheet.cssRules) {
+ if (rule.style) for (let i = 0; i < rule.style.length; i++) {
+ const p = rule.style[i];
+ if (p.startsWith('--') && !props[p]) {
+ const v = cs.getPropertyValue(p).trim();
+ if (v) props[p] = v;
+ }
+ }
+ }
+ } catch { /* cross-origin */ }
+ }
+ return {
+ tagName: el.tagName.toLowerCase(), id: el.id || null,
+ classes: [...el.classList],
+ textContent: (el.textContent || '').slice(0, 500),
+ outerHTML: el.outerHTML.slice(0, 10000),
+ computedStyles: {
+ 'font-family': cs.fontFamily, 'font-size': cs.fontSize,
+ 'font-weight': cs.fontWeight, 'line-height': cs.lineHeight,
+ 'color': cs.color, 'background': cs.background,
+ 'background-color': cs.backgroundColor,
+ 'padding': cs.padding, 'margin': cs.margin,
+ 'display': cs.display, 'position': cs.position,
+ 'gap': cs.gap, 'border-radius': cs.borderRadius,
+ 'box-shadow': cs.boxShadow,
+ },
+ cssCustomProperties: props,
+ parentContext: el.parentElement
+ ? '<' + el.parentElement.tagName.toLowerCase()
+ + (el.parentElement.id ? ' id="' + el.parentElement.id + '"' : '')
+ + (el.parentElement.className ? ' class="' + el.parentElement.className + '"' : '')
+ + '>'
+ : null,
+ boundingRect: { width: Math.round(r.width), height: Math.round(r.height) },
+ };
+ }
+
+ // ---------------------------------------------------------------------------
+ // The Bar — one floating element, three modes
+ // ---------------------------------------------------------------------------
+
+ function initBar() {
+ barEl = document.createElement('div');
+ barEl.id = PREFIX + '-bar';
+ Object.assign(barEl.style, {
+ position: 'fixed', zIndex: Z.bar,
+ display: 'none', opacity: '0',
+ transform: 'translateY(6px)',
+ transition: 'opacity 0.25s ' + EASE + ', transform 0.3s ' + EASE,
+ // Visual
+ background: C.paper,
+ backdropFilter: 'blur(16px)', WebkitBackdropFilter: 'blur(16px)',
+ border: '1px solid ' + C.mist,
+ borderRadius: '10px',
+ boxShadow: '0 4px 20px oklch(0% 0 0 / 0.08), 0 1px 3px oklch(0% 0 0 / 0.06)',
+ fontFamily: FONT, fontSize: '13px', color: C.ink,
+ padding: '6px',
+ maxWidth: '460px', minWidth: '320px',
+ });
+ document.body.appendChild(barEl);
+ }
+
+ function positionBar() {
+ if (!barEl || !selectedElement) return;
+ const r = selectedElement.getBoundingClientRect();
+ const barH = barEl.offsetHeight || 44;
+ const barW = barEl.offsetWidth || 380;
+ let top = r.bottom + 8;
+ let left = r.left + (r.width - barW) / 2;
+ // Keep in viewport
+ if (top + barH + 8 > window.innerHeight) top = r.top - barH - 8;
+ if (top < 8) top = 8;
+ if (left < 8) left = 8;
+ if (left + barW > window.innerWidth - 8) left = window.innerWidth - barW - 8;
+ Object.assign(barEl.style, { top: top + 'px', left: left + 'px' });
+ }
+
+ function showBar(mode) {
+ barEl.innerHTML = '';
+ if (mode === 'configure') barEl.appendChild(buildConfigureRow());
+ else if (mode === 'generating') barEl.appendChild(buildGeneratingRow());
+ else if (mode === 'cycling') barEl.appendChild(buildCyclingRow());
+ barEl.style.display = 'block';
+ positionBar();
+ requestAnimationFrame(() => {
+ barEl.style.opacity = '1';
+ barEl.style.transform = 'translateY(0)';
+ });
+ }
+
+ function hideBar() {
+ if (!barEl) return;
+ barEl.style.opacity = '0';
+ barEl.style.transform = 'translateY(6px)';
+ setTimeout(() => { if (barEl) barEl.style.display = 'none'; }, 250);
+ hideActionPicker();
+ }
+
+ function updateBarContent(mode) {
+ if (!barEl || barEl.style.display === 'none') return;
+ barEl.innerHTML = '';
+ // Reset bar styling
+ barEl.style.background = C.paper;
+ barEl.style.border = '1px solid ' + C.mist;
+ if (mode === 'configure') barEl.appendChild(buildConfigureRow());
+ else if (mode === 'generating') barEl.appendChild(buildGeneratingRow());
+ else if (mode === 'cycling') barEl.appendChild(buildCyclingRow());
+ else if (mode === 'saving') barEl.appendChild(buildSavingRow());
+ else if (mode === 'confirmed') {
+ barEl.appendChild(buildConfirmedRow());
+ barEl.style.background = 'oklch(95% 0.05 145)';
+ barEl.style.border = '1px solid oklch(75% 0.12 145 / 0.4)';
+ }
+ }
+
+ // --- Configure row ---
+
+ function buildConfigureRow() {
+ const row = el('div', {
+ display: 'flex', alignItems: 'center', gap: '4px',
+ });
+
+ // Action pill
+ const pill = el('button', {
+ display: 'inline-flex', alignItems: 'center', gap: '4px',
+ padding: '5px 10px', borderRadius: '6px',
+ background: C.ink, color: C.white,
+ fontFamily: FONT, fontSize: '12px', fontWeight: '500',
+ border: 'none', cursor: 'pointer',
+ transition: 'background 0.12s ease, transform 0.1s ease',
+ whiteSpace: 'nowrap', flexShrink: '0',
+ });
+ pill.textContent = actionLabel() + ' \u25BE';
+ pill.addEventListener('mouseenter', () => pill.style.background = C.brandHov);
+ pill.addEventListener('mouseleave', () => pill.style.background = C.ink);
+ pill.addEventListener('mousedown', () => pill.style.transform = 'scale(0.97)');
+ pill.addEventListener('mouseup', () => pill.style.transform = 'scale(1)');
+ pill.addEventListener('click', (e) => { e.stopPropagation(); toggleActionPicker(); });
+ row.appendChild(pill);
+
+ // Freeform input
+ const input = document.createElement('input');
+ input.id = PREFIX + '-input';
+ input.type = 'text';
+ input.placeholder = selectedAction === 'impeccable' ? 'describe what you want...' : 'refine further (optional)...';
+ Object.assign(input.style, {
+ flex: '1', minWidth: '0',
+ padding: '5px 8px', borderRadius: '6px',
+ border: '1px solid transparent', background: 'transparent',
+ fontFamily: FONT, fontSize: '12px', color: C.ink,
+ outline: 'none',
+ transition: 'border-color 0.15s ease, background 0.15s ease',
+ });
+ input.addEventListener('focus', () => {
+ input.style.borderColor = C.mist;
+ input.style.background = C.white;
+ });
+ input.addEventListener('blur', () => {
+ input.style.borderColor = 'transparent';
+ input.style.background = 'transparent';
+ });
+ input.addEventListener('keydown', (e) => {
+ e.stopPropagation(); // Don't trigger element picker keyboard nav
+ if (e.key === 'Enter') { e.preventDefault(); handleGo(); }
+ if (e.key === 'Escape') { e.preventDefault(); input.blur(); hideBar(); state = 'PICKING'; }
+ });
+ row.appendChild(input);
+
+ // Variant count toggle
+ const count = el('button', {
+ padding: '4px 6px', borderRadius: '5px',
+ border: '1px solid ' + C.mist, background: 'transparent',
+ fontFamily: MONO, fontSize: '11px', fontWeight: '600',
+ color: C.ash, cursor: 'pointer',
+ transition: 'color 0.12s ease, border-color 0.12s ease',
+ flexShrink: '0', whiteSpace: 'nowrap',
+ });
+ count.textContent = '\u00D7' + selectedCount;
+ count.title = 'Variants: click to change';
+ count.addEventListener('mouseenter', () => { count.style.color = C.ink; count.style.borderColor = C.ink; });
+ count.addEventListener('mouseleave', () => { count.style.color = C.ash; count.style.borderColor = C.mist; });
+ count.addEventListener('click', (e) => {
+ e.stopPropagation();
+ selectedCount = selectedCount >= 4 ? 2 : selectedCount + 1;
+ count.textContent = '\u00D7' + selectedCount;
+ });
+ row.appendChild(count);
+
+ // Go button
+ const go = el('button', {
+ padding: '5px 12px', borderRadius: '6px',
+ border: 'none', background: C.brand, color: C.white,
+ fontFamily: FONT, fontSize: '12px', fontWeight: '600',
+ cursor: 'pointer',
+ transition: 'background 0.12s ease, transform 0.1s ease',
+ flexShrink: '0', whiteSpace: 'nowrap',
+ });
+ go.textContent = 'Go \u2192';
+ go.addEventListener('mouseenter', () => go.style.background = C.brandHov);
+ go.addEventListener('mouseleave', () => go.style.background = C.brand);
+ go.addEventListener('mousedown', () => go.style.transform = 'scale(0.97)');
+ go.addEventListener('mouseup', () => go.style.transform = 'scale(1)');
+ go.addEventListener('click', (e) => { e.stopPropagation(); handleGo(); });
+ row.appendChild(go);
+
+ // Auto-focus input after a beat
+ setTimeout(() => input.focus(), 60);
+ return row;
+ }
+
+ // --- Generating row ---
+
+ function buildGeneratingRow() {
+ const row = el('div', {
+ display: 'flex', alignItems: 'center', gap: '8px',
+ padding: '2px 4px',
+ });
+
+ // Action label
+ const label = el('span', {
+ fontWeight: '600', fontSize: '12px', color: C.ink,
+ flexShrink: '0', whiteSpace: 'nowrap',
+ });
+ label.textContent = actionLabel();
+ row.appendChild(label);
+
+ // Dots
+ row.appendChild(buildDots(false));
+
+ // Status
+ const status = el('span', {
+ fontSize: '11px', color: C.ash, whiteSpace: 'nowrap',
+ marginLeft: 'auto',
+ });
+ status.textContent = arrivedVariants < expectedVariants
+ ? 'Generating ' + (arrivedVariants + 1) + ' of ' + expectedVariants + '...'
+ : 'Done';
+ row.appendChild(status);
+
+ return row;
+ }
+
+ // --- Cycling row ---
+
+ function buildCyclingRow() {
+ const row = el('div', {
+ display: 'flex', alignItems: 'center', gap: '6px',
+ padding: '1px 2px',
+ });
+
+ // Prev
+ const prev = navBtn('\u2190');
+ prev.addEventListener('click', (e) => { e.stopPropagation(); cycleVariant(-1); });
+ if (visibleVariant <= 1) prev.style.opacity = '0.3';
+ row.appendChild(prev);
+
+ // Dots (clickable)
+ row.appendChild(buildDots(true));
+
+ // Counter
+ const counter = el('span', {
+ fontFamily: MONO, fontSize: '11px', fontWeight: '500',
+ color: C.ash, minWidth: '24px', textAlign: 'center',
+ });
+ counter.textContent = visibleVariant + '/' + arrivedVariants;
+ row.appendChild(counter);
+
+ // Next
+ const next = navBtn('\u2192');
+ next.addEventListener('click', (e) => { e.stopPropagation(); cycleVariant(1); });
+ if (visibleVariant >= arrivedVariants) next.style.opacity = '0.3';
+ row.appendChild(next);
+
+ // Spacer
+ row.appendChild(el('div', { flex: '1' }));
+
+ // Accept
+ const accept = el('button', {
+ padding: '4px 10px', borderRadius: '5px',
+ border: 'none', background: C.ink, color: C.white,
+ fontFamily: FONT, fontSize: '11px', fontWeight: '600',
+ cursor: 'pointer', transition: 'background 0.12s ease',
+ whiteSpace: 'nowrap',
+ });
+ accept.textContent = '\u2713 Accept';
+ accept.addEventListener('mouseenter', () => accept.style.background = C.brand);
+ accept.addEventListener('mouseleave', () => accept.style.background = C.ink);
+ accept.addEventListener('click', (e) => { e.stopPropagation(); handleAccept(); });
+ if (arrivedVariants === 0) { accept.style.opacity = '0.3'; accept.style.pointerEvents = 'none'; }
+ row.appendChild(accept);
+
+ // Discard
+ const discard = el('button', {
+ padding: '4px 6px', borderRadius: '5px',
+ border: '1px solid ' + C.mist, background: 'transparent',
+ fontFamily: FONT, fontSize: '11px', color: C.ash,
+ cursor: 'pointer', transition: 'color 0.12s ease, border-color 0.12s ease',
+ });
+ discard.textContent = '\u2715';
+ discard.title = 'Discard all variants';
+ discard.addEventListener('mouseenter', () => { discard.style.color = C.ink; discard.style.borderColor = C.ink; });
+ discard.addEventListener('mouseleave', () => { discard.style.color = C.ash; discard.style.borderColor = C.mist; });
+ discard.addEventListener('click', (e) => { e.stopPropagation(); handleDiscard(); });
+ row.appendChild(discard);
+
+ return row;
+ }
+
+ // --- Shared UI builders ---
+
+ // --- Saving row (waiting for agent to process accept/discard) ---
+
+ function buildSavingRow() {
+ const row = el('div', {
+ display: 'flex', alignItems: 'center', gap: '8px',
+ padding: '2px 8px',
+ });
+ const spinner = el('div', {
+ width: '14px', height: '14px', borderRadius: '50%',
+ border: '2px solid ' + C.mist,
+ borderTopColor: C.brand,
+ animation: 'impeccable-spin 0.6s linear infinite',
+ flexShrink: '0',
+ });
+ row.appendChild(spinner);
+ const label = el('span', {
+ fontSize: '12px', color: C.ash, fontWeight: '500',
+ });
+ label.textContent = 'Applying variant...';
+ row.appendChild(label);
+
+ // Inject the keyframes if not already present
+ if (!document.getElementById(PREFIX + '-keyframes')) {
+ const style = document.createElement('style');
+ style.id = PREFIX + '-keyframes';
+ style.textContent = '@keyframes impeccable-spin { to { transform: rotate(360deg); } }';
+ document.head.appendChild(style);
+ }
+ return row;
+ }
+
+ // --- Confirmed row (green success, auto-dismisses) ---
+
+ function buildConfirmedRow() {
+ const row = el('div', {
+ display: 'flex', alignItems: 'center', gap: '8px',
+ padding: '2px 8px',
+ });
+ const check = el('span', {
+ fontSize: '15px', lineHeight: '1', flexShrink: '0',
+ color: 'oklch(45% 0.15 145)',
+ });
+ check.textContent = '\u2713';
+ row.appendChild(check);
+ const label = el('span', {
+ fontSize: '12px', color: 'oklch(35% 0.1 145)', fontWeight: '600',
+ });
+ label.textContent = 'Variant applied';
+ row.appendChild(label);
+ return row;
+ }
+
+ // --- Shared UI builders ---
+
+ function buildDots(clickable) {
+ const container = el('div', {
+ display: 'flex', alignItems: 'center', gap: '4px',
+ });
+ for (let i = 1; i <= expectedVariants; i++) {
+ const arrived = i <= arrivedVariants;
+ const active = i === visibleVariant;
+ const dot = el('div', {
+ width: '7px', height: '7px', borderRadius: '50%',
+ background: active ? C.brand : (arrived ? C.ash : 'transparent'),
+ border: '1.5px solid ' + (arrived ? C.brand : C.mist),
+ transition: 'all 0.2s ' + EASE,
+ cursor: (clickable && arrived) ? 'pointer' : 'default',
+ transform: arrived ? 'scale(1)' : 'scale(0.6)',
+ opacity: arrived ? '1' : '0.4',
+ });
+ if (clickable && arrived) {
+ const idx = i;
+ dot.addEventListener('click', (e) => {
+ e.stopPropagation();
+ visibleVariant = idx;
+ showVariantInDOM(currentSessionId, idx);
+ updateSelectedElement();
+ updateBarContent('cycling');
+ });
+ }
+ container.appendChild(dot);
+ }
+ return container;
+ }
+
+ function navBtn(text) {
+ const b = el('button', {
+ width: '26px', height: '26px', borderRadius: '5px',
+ border: '1px solid ' + C.mist, background: 'transparent',
+ color: C.ink, fontFamily: FONT, fontSize: '13px',
+ cursor: 'pointer', display: 'flex', alignItems: 'center', justifyContent: 'center',
+ transition: 'border-color 0.12s ease, background 0.12s ease',
+ padding: '0', lineHeight: '1',
+ });
+ b.textContent = text;
+ b.addEventListener('mouseenter', () => { b.style.borderColor = C.ink; });
+ b.addEventListener('mouseleave', () => { b.style.borderColor = C.mist; });
+ return b;
+ }
+
+ function actionLabel() {
+ const a = ACTIONS.find(a => a.value === selectedAction);
+ return a ? a.label : 'Freeform';
+ }
+
+ function el(tag, styles) {
+ const e = document.createElement(tag);
+ if (styles) Object.assign(e.style, styles);
+ return e;
+ }
+
+ // ---------------------------------------------------------------------------
+ // Action picker popover
+ // ---------------------------------------------------------------------------
+
+ function initActionPicker() {
+ pickerEl = document.createElement('div');
+ pickerEl.id = PREFIX + '-picker';
+ Object.assign(pickerEl.style, {
+ position: 'fixed', zIndex: Z.picker,
+ display: 'none', opacity: '0',
+ transform: 'scale(0.96) translateY(4px)',
+ transformOrigin: 'bottom left',
+ transition: 'opacity 0.18s ' + EASE + ', transform 0.2s ' + EASE,
+ background: C.paperSolid,
+ border: '1px solid ' + C.mist,
+ borderRadius: '10px',
+ boxShadow: '0 8px 30px oklch(0% 0 0 / 0.10), 0 2px 6px oklch(0% 0 0 / 0.06)',
+ padding: '6px',
+ fontFamily: FONT,
+ });
+
+ // Build the chip grid
+ const grid = el('div', {
+ display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', gap: '3px',
+ });
+
+ ACTIONS.forEach(action => {
+ const chip = el('button', {
+ padding: '6px 8px', borderRadius: '6px',
+ border: 'none',
+ background: action.value === selectedAction ? C.brandSoft : 'transparent',
+ color: action.value === selectedAction ? C.brand : C.ink,
+ fontFamily: FONT, fontSize: '11px', fontWeight: '500',
+ cursor: 'pointer',
+ transition: 'background 0.1s ease, color 0.1s ease',
+ textAlign: 'center', whiteSpace: 'nowrap',
+ });
+ chip.textContent = action.label;
+ chip.dataset.action = action.value;
+ chip.addEventListener('mouseenter', () => {
+ if (action.value !== selectedAction) chip.style.background = C.brandSoft;
+ });
+ chip.addEventListener('mouseleave', () => {
+ chip.style.background = action.value === selectedAction ? C.brandSoft : 'transparent';
+ });
+ chip.addEventListener('click', (e) => {
+ e.stopPropagation();
+ selectedAction = action.value;
+ hideActionPicker();
+ updateBarContent('configure');
+ });
+ grid.appendChild(chip);
+ });
+
+ pickerEl.appendChild(grid);
+ document.body.appendChild(pickerEl);
+ }
+
+ function toggleActionPicker() {
+ if (pickerEl.style.display !== 'none') { hideActionPicker(); return; }
+ // Rebuild chips to reflect current selection
+ pickerEl.querySelectorAll('button').forEach(chip => {
+ const isActive = chip.dataset.action === selectedAction;
+ chip.style.background = isActive ? C.brandSoft : 'transparent';
+ chip.style.color = isActive ? C.brand : C.ink;
+ });
+ // Position above the bar
+ const barRect = barEl.getBoundingClientRect();
+ const pickerH = 90; // approximate
+ let top = barRect.top - pickerH - 6;
+ if (top < 8) top = barRect.bottom + 6;
+ Object.assign(pickerEl.style, {
+ top: top + 'px', left: barRect.left + 'px',
+ display: 'block',
+ });
+ requestAnimationFrame(() => {
+ pickerEl.style.opacity = '1';
+ pickerEl.style.transform = 'scale(1) translateY(0)';
+ });
+ }
+
+ function hideActionPicker() {
+ if (!pickerEl) return;
+ pickerEl.style.opacity = '0';
+ pickerEl.style.transform = 'scale(0.96) translateY(4px)';
+ setTimeout(() => { if (pickerEl) pickerEl.style.display = 'none'; }, 180);
+ }
+
+ // ---------------------------------------------------------------------------
+ // Variant cycling in DOM
+ // ---------------------------------------------------------------------------
+
+ function showVariantInDOM(sessionId, num) {
+ const wrapper = document.querySelector('[data-impeccable-variants="' + sessionId + '"]');
+ if (!wrapper) return;
+ for (const child of wrapper.children) {
+ const v = child.dataset ? child.dataset.impeccableVariant : null;
+ if (!v) continue;
+ child.style.display = (v === String(num)) ? '' : 'none';
+ }
+ }
+
+ /**
+ * No-HMR fallback: fetch the raw source file from the live server,
+ * parse it, extract the variant wrapper, and inject it into the live DOM.
+ * This works even when the dev server caches HTML (Bun, static servers).
+ */
+ function injectVariantsFromSource(filePath, sessionId) {
+ const url = 'http://localhost:' + PORT + '/source?token=' + TOKEN + '&path=' + encodeURIComponent(filePath);
+ fetch(url)
+ .then(r => { if (!r.ok) throw new Error(r.status); return r.text(); })
+ .then(html => {
+ // Parse the raw source HTML
+ const parser = new DOMParser();
+ const doc = parser.parseFromString(html, 'text/html');
+ const srcWrapper = doc.querySelector('[data-impeccable-variants="' + sessionId + '"]');
+ if (!srcWrapper) {
+ console.error('[impeccable] Variant wrapper not found in source file.');
+ return;
+ }
+
+ // Find the original element in the live DOM.
+ // The original is inside the wrapper in the source. We find the
+ // corresponding element in the live DOM by matching the first child's
+ // tag + classes from the original snapshot.
+ const origContent = srcWrapper.querySelector('[data-impeccable-variant="original"] > :first-child');
+ if (!origContent) return;
+
+ const tag = origContent.tagName.toLowerCase();
+ const cls = origContent.className;
+ let liveEl = null;
+ if (origContent.id) {
+ liveEl = document.getElementById(origContent.id);
+ } else if (cls) {
+ // Find by tag + exact class match
+ const candidates = document.querySelectorAll(tag + '.' + cls.split(' ')[0]);
+ for (const c of candidates) {
+ if (c.className === cls && !own(c)) { liveEl = c; break; }
+ }
+ }
+
+ if (!liveEl) {
+ console.error('[impeccable] Could not find original element in live DOM.');
+ return;
+ }
+
+ // Replace the live element with the full wrapper from source
+ const wrapper = srcWrapper.cloneNode(true);
+ liveEl.parentElement.replaceChild(wrapper, liveEl);
+
+ // Update state: count variants, show the first one
+ 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);
+
+ // Update selectedElement to the visible variant's content
+ const visEl = wrapper.querySelector('[data-impeccable-variant="1"] > :first-child');
+ selectedElement = visEl || wrapper.parentElement;
+
+ state = 'CYCLING';
+ updateBarContent('cycling');
+ saveSession();
+ console.log('[impeccable] Injected ' + arrivedVariants + ' variants from source file.');
+ })
+ .catch(err => {
+ console.error('[impeccable] Failed to fetch source:', err);
+ showToast('Could not load variants. Try refreshing the page.', 5000);
+ });
+ }
+
+ function cycleVariant(dir) {
+ const next = visibleVariant + dir;
+ if (next < 1 || next > arrivedVariants) return;
+ visibleVariant = next;
+ showVariantInDOM(currentSessionId, next);
+ updateSelectedElement();
+ updateBarContent('cycling');
+ saveSession();
+ }
+
+ function updateSelectedElement() {
+ if (!currentSessionId) return;
+ const wrapper = document.querySelector('[data-impeccable-variants="' + currentSessionId + '"]');
+ if (!wrapper) return;
+ const visEl = wrapper.querySelector('[data-impeccable-variant="' + visibleVariant + '"] > :first-child');
+ if (visEl) selectedElement = visEl;
+ }
+
+ // ---------------------------------------------------------------------------
+ // MutationObserver for progressive variant reveal
+ // ---------------------------------------------------------------------------
+
+ function startVariantObserver(sessionId) {
+ let updating = false; // re-entrancy guard
+
+ const obs = new MutationObserver((mutations) => {
+ if (updating) return;
+
+ // Only react to mutations that add nodes with data-impeccable-variant,
+ // or mutations inside the variant wrapper. Ignore our own bar/UI changes.
+ let dominated = false;
+ for (const m of mutations) {
+ if (m.target.closest?.('[data-impeccable-variants]')) { dominated = true; break; }
+ for (const n of m.addedNodes) {
+ if (n.nodeType === 1 && (n.dataset?.impeccableVariants || n.dataset?.impeccableVariant)) {
+ dominated = true; break;
+ }
+ }
+ if (dominated) break;
+ }
+ if (!dominated) return;
+
+ const wrapper = document.querySelector('[data-impeccable-variants="' + sessionId + '"]');
+ if (!wrapper) return;
+
+ const variants = wrapper.querySelectorAll('[data-impeccable-variant]:not([data-impeccable-variant="original"])');
+ const count = variants.length;
+
+ // Nothing new
+ if (count <= arrivedVariants) return;
+
+ updating = true;
+ arrivedVariants = count;
+ if (visibleVariant === 0 && arrivedVariants > 0) {
+ visibleVariant = 1;
+ showVariantInDOM(sessionId, 1);
+ }
+
+ const expected = parseInt(wrapper.dataset.impeccableVariantCount || '0');
+ if (expected > 0) expectedVariants = expected;
+
+ if (arrivedVariants >= expectedVariants && expectedVariants > 0) {
+ state = 'CYCLING';
+ updateBarContent('cycling');
+ } else if (state === 'GENERATING') {
+ updateBarContent('generating');
+ }
+ saveSession();
+ updating = false;
+ });
+
+ obs.observe(document.body, { childList: true, subtree: true });
+ return obs;
+ }
+
+ // ---------------------------------------------------------------------------
+ // Bar scroll tracking
+ // ---------------------------------------------------------------------------
+
+ function startScrollTracking() {
+ function tick() {
+ if (state === 'CONFIGURING' || state === 'GENERATING' || state === 'CYCLING') {
+ positionBar();
+ showHighlight(selectedElement);
+ }
+ scrollRaf = requestAnimationFrame(tick);
+ }
+ scrollRaf = requestAnimationFrame(tick);
+ }
+
+ function stopScrollTracking() {
+ if (scrollRaf) { cancelAnimationFrame(scrollRaf); scrollRaf = null; }
+ }
+
+ // ---------------------------------------------------------------------------
+ // SSE (server→browser) + fetch POST (browser→server)
+ // Zero-dependency replacement for WebSocket.
+ // ---------------------------------------------------------------------------
+
+ let evtSource = null;
+
+ function connectSSE() {
+ evtSource = new EventSource('http://localhost:' + PORT + '/events?token=' + TOKEN);
+
+ evtSource.onmessage = (e) => {
+ let msg; try { msg = JSON.parse(e.data); } catch { return; }
+ switch (msg.type) {
+ case 'connected':
+ hasProjectContext = !!msg.hasProjectContext;
+ if (!hasProjectContext) showToast('No .impeccable.md found. Variants will be brand-agnostic.', 6000);
+ console.log('[impeccable] Live mode connected.');
+ if (state === 'IDLE') state = 'PICKING';
+ break;
+ case 'done':
+ if (state === 'SAVING') {
+ state = 'CONFIRMED';
+ updateBarContent('confirmed');
+ setTimeout(() => {
+ hideBar();
+ hideHighlight();
+ stopScrollTracking();
+ if (variantObserver) { variantObserver.disconnect(); variantObserver = null; }
+ clearSession();
+ selectedElement = null;
+ currentSessionId = null;
+ selectedAction = 'impeccable';
+ state = 'PICKING';
+ }, 1800);
+ return;
+ }
+ if (arrivedVariants === 0 && expectedVariants > 0 && msg.file) {
+ console.log('[impeccable] No HMR detected. Fetching variants from source file...');
+ injectVariantsFromSource(msg.file, currentSessionId);
+ return;
+ }
+ state = 'CYCLING';
+ updateBarContent('cycling');
+ break;
+ case 'error':
+ console.error('[impeccable] Error:', msg.message);
+ showToast('Error: ' + msg.message, 5000);
+ hideBar();
+ state = 'PICKING';
+ break;
+ }
+ };
+
+ evtSource.onerror = () => {
+ // EventSource auto-reconnects. Log once.
+ console.log('[impeccable] SSE connection lost. Reconnecting...');
+ };
+ }
+
+ function sendEvent(msg) {
+ msg.token = TOKEN;
+ 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));
+ }
+
+ // ---------------------------------------------------------------------------
+ // Event handlers
+ // ---------------------------------------------------------------------------
+
+ function handleMouseMove(e) {
+ if (state !== 'PICKING') return;
+ const target = document.elementFromPoint(e.clientX, e.clientY);
+ if (!target || !pickable(target) || target === hoveredElement) return;
+ hoveredElement = target;
+ showHighlight(target);
+ }
+
+ function handleClick(e) {
+ // Close action picker on any outside click
+ if (pickerEl?.style.display !== 'none' && !own(e.target)) {
+ hideActionPicker();
+ }
+ if (state !== 'PICKING') return;
+ if (own(e.target)) return;
+ if (!hoveredElement || !pickable(hoveredElement)) return;
+ e.preventDefault();
+ e.stopPropagation();
+ selectedElement = hoveredElement;
+ state = 'CONFIGURING';
+ showHighlight(selectedElement);
+ showBar('configure');
+ startScrollTracking();
+ }
+
+ function handleKeyDown(e) {
+ if (e.key === 'Escape') {
+ e.preventDefault();
+ if (pickerEl?.style.display !== 'none') { hideActionPicker(); return; }
+ if (state === 'CONFIGURING') { hideBar(); stopScrollTracking(); state = 'PICKING'; return; }
+ if (state === 'CYCLING') { handleDiscard(); return; }
+ if (state === 'SAVING' || state === 'CONFIRMED') return; // don't interrupt
+ if (state === 'PICKING') { hideHighlight(); state = 'IDLE'; return; }
+ }
+
+ if (state === 'PICKING' && hoveredElement) {
+ let next = null;
+ if (e.key === 'ArrowDown' && !e.shiftKey) {
+ next = hoveredElement.nextElementSibling;
+ while (next && !pickable(next)) next = next.nextElementSibling;
+ } else if (e.key === 'ArrowUp' && !e.shiftKey) {
+ next = hoveredElement.previousElementSibling;
+ while (next && !pickable(next)) next = next.previousElementSibling;
+ } else if (e.key === 'ArrowUp' && e.shiftKey) {
+ next = hoveredElement.parentElement;
+ if (next && !pickable(next)) next = null;
+ } else if (e.key === 'ArrowDown' && e.shiftKey) {
+ next = hoveredElement.firstElementChild;
+ while (next && !pickable(next)) next = next.nextElementSibling;
+ } else if (e.key === 'Enter') {
+ e.preventDefault();
+ selectedElement = hoveredElement;
+ state = 'CONFIGURING';
+ showHighlight(selectedElement);
+ showBar('configure');
+ startScrollTracking();
+ return;
+ }
+ if (next) {
+ e.preventDefault();
+ hoveredElement = next;
+ showHighlight(next);
+ next.scrollIntoView({ block: 'nearest', behavior: 'smooth' });
+ }
+ return;
+ }
+
+ if (state === 'CYCLING') {
+ if (e.key === 'ArrowLeft') { e.preventDefault(); cycleVariant(-1); }
+ if (e.key === 'ArrowRight') { e.preventDefault(); cycleVariant(1); }
+ if (e.key === 'Enter') { e.preventDefault(); handleAccept(); }
+ }
+ }
+
+ function handleGo() {
+ if (!selectedElement || state !== 'CONFIGURING') return;
+ const input = document.getElementById(PREFIX + '-input');
+ const prompt = input ? input.value.trim() : '';
+
+ currentSessionId = id8();
+ expectedVariants = selectedCount;
+ arrivedVariants = 0;
+ visibleVariant = 0;
+
+ sendEvent({
+ type: 'generate', id: currentSessionId,
+ action: selectedAction,
+ freeformPrompt: prompt || undefined,
+ count: selectedCount,
+ pageUrl: location.pathname,
+ element: extractContext(selectedElement),
+ });
+
+ state = 'GENERATING';
+ showBar('generating');
+ saveSession();
+ if (variantObserver) variantObserver.disconnect();
+ variantObserver = startVariantObserver(currentSessionId);
+ }
+
+ function handleAccept() {
+ if (!currentSessionId || arrivedVariants === 0) return;
+ sendEvent({ type: 'accept', id: currentSessionId, variantId: String(visibleVariant) });
+ markSessionHandled();
+ state = 'SAVING';
+ updateBarContent('saving');
+ // Don't cleanup yet — wait for the "done" WS message to show confirmation
+ }
+
+ function handleDiscard() {
+ if (!currentSessionId) return;
+ sendEvent({ type: 'discard', id: currentSessionId });
+ markSessionHandled();
+ state = 'SAVING';
+ updateBarContent('saving');
+ // Wait for "done" WS message to show confirmation and dismiss
+ }
+
+ // ---------------------------------------------------------------------------
+ // Session persistence via localStorage
+ // ---------------------------------------------------------------------------
+ // Survives page reloads, browser close/reopen, HMR, and accidental refreshes.
+
+ const LS_KEY = PREFIX + '-session';
+
+ function saveSession() {
+ if (!currentSessionId) return;
+ 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 */ }
+ }
+
+ function loadSession() {
+ try {
+ const raw = localStorage.getItem(LS_KEY);
+ return raw ? JSON.parse(raw) : null;
+ } catch { return null; }
+ }
+
+ function clearSession() {
+ try { localStorage.removeItem(LS_KEY); } catch {}
+ }
+
+ /** Mark session as handled (accepted/discarded). The agent will clean up
+ * the source, but until it does the wrapper is still in the HTML. This
+ * prevents resumeSession from picking it up again after reload. */
+ function markSessionHandled() {
+ if (!currentSessionId) return;
+ try {
+ localStorage.setItem(LS_KEY + '-handled', currentSessionId);
+ } catch {}
+ }
+
+ function isSessionHandled(id) {
+ try {
+ return localStorage.getItem(LS_KEY + '-handled') === id;
+ } catch { return false; }
+ }
+
+ function clearHandled() {
+ try { localStorage.removeItem(LS_KEY + '-handled'); } catch {}
+ }
+
+ function cleanup() {
+ hideBar();
+ hideHighlight();
+ stopScrollTracking();
+ if (variantObserver) { variantObserver.disconnect(); variantObserver = null; }
+ clearSession();
+ selectedElement = null;
+ currentSessionId = null;
+ selectedAction = 'impeccable';
+ state = 'PICKING';
+ }
+
+ // ---------------------------------------------------------------------------
+ // Toast
+ // ---------------------------------------------------------------------------
+
+ function showToast(message, duration) {
+ if (toastEl) toastEl.remove();
+ toastEl = el('div', {
+ position: 'fixed', bottom: '16px', left: '50%',
+ transform: 'translateX(-50%) translateY(8px)',
+ background: C.ink, color: C.white,
+ fontFamily: FONT, fontSize: '12px',
+ padding: '8px 16px', borderRadius: '8px',
+ zIndex: Z.toast, opacity: '0',
+ transition: 'opacity 0.25s ' + EASE + ', transform 0.25s ' + EASE,
+ pointerEvents: 'none', maxWidth: '420px', textAlign: 'center',
+ });
+ toastEl.id = PREFIX + '-toast';
+ toastEl.textContent = message;
+ document.body.appendChild(toastEl);
+ requestAnimationFrame(() => {
+ toastEl.style.opacity = '1';
+ toastEl.style.transform = 'translateX(-50%) translateY(0)';
+ });
+ setTimeout(() => {
+ if (toastEl) {
+ toastEl.style.opacity = '0';
+ toastEl.style.transform = 'translateX(-50%) translateY(8px)';
+ setTimeout(() => { if (toastEl) { toastEl.remove(); toastEl = null; } }, 250);
+ }
+ }, duration);
+ }
+
+ // ---------------------------------------------------------------------------
+ // Init
+ // ---------------------------------------------------------------------------
+
+ // Resume an active variant session after HMR/page reload.
+ // If a [data-impeccable-variants] wrapper exists in the DOM, the agent wrote
+ // variants before HMR fired. Pick up where we left off.
+ function resumeSession() {
+ const wrapper = document.querySelector('[data-impeccable-variants]');
+ if (!wrapper) { clearSession(); clearHandled(); return false; }
+
+ const sessionId = wrapper.dataset.impeccableVariants;
+
+ // Don't resume if this session was already accepted/discarded
+ if (isSessionHandled(sessionId)) return false;
+
+ currentSessionId = sessionId;
+ expectedVariants = parseInt(wrapper.dataset.impeccableVariantCount || '0');
+ const variants = wrapper.querySelectorAll('[data-impeccable-variant]:not([data-impeccable-variant="original"])');
+ arrivedVariants = variants.length;
+
+ // Restore visible variant from localStorage if available, else default to 1
+ const saved = loadSession();
+ visibleVariant = (saved && saved.id === sessionId && saved.visible > 0 && saved.visible <= arrivedVariants)
+ ? saved.visible : (arrivedVariants > 0 ? 1 : 0);
+
+ // Find the visible variant's content element for highlight positioning
+ const visEl = wrapper.querySelector('[data-impeccable-variant="' + visibleVariant + '"] > :first-child');
+ selectedElement = visEl || wrapper.parentElement;
+
+ // Set display state BEFORE starting observer (avoid triggering it)
+ if (visibleVariant > 0) showVariantInDOM(currentSessionId, visibleVariant);
+
+ state = arrivedVariants >= expectedVariants ? 'CYCLING' : 'GENERATING';
+ showBar(state === 'CYCLING' ? 'cycling' : 'generating');
+ startScrollTracking();
+ saveSession();
+
+ // Start observing for more variants AFTER initial setup
+ if (variantObserver) variantObserver.disconnect();
+ variantObserver = startVariantObserver(currentSessionId);
+ return true;
+ }
+
+ function init() {
+ initHighlight();
+ initBar();
+ initActionPicker();
+ document.addEventListener('mousemove', handleMouseMove, true);
+ document.addEventListener('click', handleClick, true);
+ document.addEventListener('keydown', handleKeyDown, true);
+ connectSSE();
+
+ // Check for an active session to resume (variant wrapper already in DOM after HMR)
+ if (!resumeSession()) {
+ console.log('[impeccable] Live variant mode ready. Hover over elements to pick one.');
+ } else {
+ console.log('[impeccable] Resumed active variant session ' + currentSessionId + ' (' + arrivedVariants + '/' + expectedVariants + ' variants).');
+ }
+ }
+
+ if (document.readyState === 'loading') {
+ document.addEventListener('DOMContentLoaded', init);
+ } else {
+ init();
+ }
+})();
diff --git a/.trae-cn/skills/impeccable/scripts/live-poll.mjs b/.trae-cn/skills/impeccable/scripts/live-poll.mjs
new file mode 100644
index 000000000..52859416c
--- /dev/null
+++ b/.trae-cn/skills/impeccable/scripts/live-poll.mjs
@@ -0,0 +1,123 @@
+/**
+ * CLI client for the live variant mode poll/reply protocol.
+ *
+ * Usage:
+ * npx impeccable poll # Block until browser event, print JSON
+ * npx impeccable poll --timeout=60000 # Custom timeout (ms)
+ * npx impeccable poll --reply <id> done # Reply "done" to event <id>
+ * npx impeccable poll --reply <id> error "msg" # Reply with error
+ */
+
+import fs from 'node:fs';
+import path from 'node:path';
+import os from 'node:os';
+
+const LIVE_PID_FILE = path.join(os.tmpdir(), 'impeccable-live.json');
+
+function readServerInfo() {
+ try {
+ return JSON.parse(fs.readFileSync(LIVE_PID_FILE, 'utf-8'));
+ } catch {
+ console.error('No running live server found. Start one with: npx impeccable live');
+ process.exit(1);
+ }
+}
+
+export async function pollCli() {
+ const args = process.argv.slice(2);
+
+ if (args.includes('--help') || args.includes('-h')) {
+ console.log(`Usage: impeccable poll [options]
+
+Wait for a browser event from the live variant server, or reply to one.
+
+Modes:
+ poll Block until a browser event arrives, print JSON
+ poll --reply <id> done Reply "done" to event <id>
+ poll --reply <id> error "msg" Reply with an error message
+
+Options:
+ --timeout=MS Poll timeout in milliseconds (default: 120000)
+ --help Show this help message`);
+ process.exit(0);
+ }
+
+ const info = readServerInfo();
+ const base = `http://localhost:${info.port}`;
+
+ // Reply mode: npx impeccable poll --reply <id> <status> [--file path] [message]
+ const replyIdx = args.indexOf('--reply');
+ if (replyIdx !== -1) {
+ const id = args[replyIdx + 1];
+ const status = args[replyIdx + 2] || 'done';
+ const fileIdx = args.indexOf('--file');
+ const filePath = fileIdx !== -1 && fileIdx + 1 < args.length ? args[fileIdx + 1] : undefined;
+ // Message is any remaining positional arg that isn't a flag
+ const message = args.find((a, i) => i > replyIdx + 2 && !a.startsWith('--') && i !== fileIdx + 1) || undefined;
+
+ if (!id) {
+ console.error('Usage: npx impeccable poll --reply <id> <status> [--file path] [message]');
+ process.exit(1);
+ }
+
+ 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);
+ }
+
+ // Success — silent exit (agent doesn't need output for replies)
+ } catch (err) {
+ if (err.cause?.code === 'ECONNREFUSED') {
+ console.error('Live server not running. Start one with: npx impeccable live');
+ } else {
+ console.error('Reply failed:', err.message);
+ }
+ process.exit(1);
+ }
+ return;
+ }
+
+ // Poll mode: block until browser event
+ const timeoutArg = args.find(a => a.startsWith('--timeout='));
+ const timeout = timeoutArg ? parseInt(timeoutArg.split('=')[1], 10) : 120000;
+
+ try {
+ const res = await fetch(`${base}/poll?token=${info.token}&timeout=${timeout}`);
+
+ if (res.status === 401) {
+ console.error('Authentication failed. The server token may have changed.');
+ console.error('Try restarting: npx impeccable live stop && npx impeccable live');
+ process.exit(1);
+ }
+
+ if (!res.ok) {
+ console.error(`Poll failed: ${res.status} ${res.statusText}`);
+ process.exit(1);
+ }
+
+ const event = await res.json();
+ // Print the event as JSON — the agent reads this from stdout
+ console.log(JSON.stringify(event));
+ } catch (err) {
+ if (err.cause?.code === 'ECONNREFUSED') {
+ console.error('Live server not running. Start one with: npx impeccable live');
+ } else {
+ console.error('Poll failed:', err.message);
+ }
+ process.exit(1);
+ }
+}
diff --git a/.trae-cn/skills/impeccable/scripts/live-server.mjs b/.trae-cn/skills/impeccable/scripts/live-server.mjs
new file mode 100644
index 000000000..d436bad58
--- /dev/null
+++ b/.trae-cn/skills/impeccable/scripts/live-server.mjs
@@ -0,0 +1,416 @@
+#!/usr/bin/env node
+/**
+ * Live variant mode server (self-contained, zero dependencies).
+ *
+ * Serves the browser script (/live.js), the detection overlay (/detect.js),
+ * uses Server-Sent Events (SSE) for server→browser push, and HTTP POST for
+ * browser→server events. Agent communicates via HTTP long-poll (/poll).
+ *
+ * Usage:
+ * node <scripts_path>/live-server.mjs # start
+ * node <scripts_path>/live-server.mjs stop # stop
+ * node <scripts_path>/live-server.mjs --help
+ */
+
+import http from 'node:http';
+import { randomUUID } from 'node:crypto';
+import fs from 'node:fs';
+import path from 'node:path';
+import os from 'node:os';
+import net from 'node:net';
+import { fileURLToPath } from 'node:url';
+
+const __dirname = path.dirname(fileURLToPath(import.meta.url));
+const LIVE_PID_FILE = path.join(os.tmpdir(), 'impeccable-live.json');
+const DEFAULT_POLL_TIMEOUT = 120_000;
+
+// ---------------------------------------------------------------------------
+// Port detection
+// ---------------------------------------------------------------------------
+
+async function findOpenPort(start = 8400) {
+ return new Promise((resolve) => {
+ const srv = net.createServer();
+ srv.listen(start, '127.0.0.1', () => {
+ const port = srv.address().port;
+ srv.close(() => resolve(port));
+ });
+ srv.on('error', () => resolve(findOpenPort(start + 1)));
+ });
+}
+
+// ---------------------------------------------------------------------------
+// Session state
+// ---------------------------------------------------------------------------
+
+const state = {
+ token: null,
+ port: null,
+ sseClients: new Set(), // SSE response objects (server→browser push)
+ pendingEvents: [], // browser events waiting for agent poll
+ pendingPolls: [], // agent poll callbacks waiting for browser events
+ exitTimer: null,
+};
+
+function enqueueEvent(event) {
+ if (state.pendingPolls.length > 0) {
+ state.pendingPolls.shift()(event);
+ } else {
+ state.pendingEvents.push(event);
+ }
+}
+
+/** Push a message to all connected SSE clients. */
+function broadcast(msg) {
+ const data = 'data: ' + JSON.stringify(msg) + '\n\n';
+ for (const res of state.sseClients) {
+ try { res.write(data); } catch { /* client gone */ }
+ }
+}
+
+// ---------------------------------------------------------------------------
+// Load scripts
+// ---------------------------------------------------------------------------
+
+function loadBrowserScripts() {
+ // Detection script: look relative to the skill scripts dir, then fall back
+ // to the npm package location (src/detect-antipatterns-browser.js)
+ const detectPaths = [
+ path.join(__dirname, '..', '..', '..', '..', 'src', 'detect-antipatterns-browser.js'),
+ path.join(process.cwd(), 'node_modules', 'impeccable', 'src', 'detect-antipatterns-browser.js'),
+ ];
+ let detectScript = '';
+ for (const p of detectPaths) {
+ try { detectScript = fs.readFileSync(p, 'utf-8'); break; } catch { /* try next */ }
+ }
+
+ const livePath = path.join(__dirname, 'live-browser.js');
+ let liveScript = '';
+ try {
+ liveScript = fs.readFileSync(livePath, 'utf-8');
+ } catch {
+ process.stderr.write('Error: live-browser.js not found at ' + livePath + '\n');
+ process.exit(1);
+ }
+
+ return { detectScript, liveScript };
+}
+
+function hasProjectContext() {
+ try {
+ fs.accessSync(path.join(process.cwd(), '.impeccable.md'), fs.constants.R_OK);
+ return true;
+ } catch { return false; }
+}
+
+// ---------------------------------------------------------------------------
+// Validation (inline — no external import needed for self-contained script)
+// ---------------------------------------------------------------------------
+
+const VISUAL_ACTIONS = [
+ 'impeccable', 'bolder', 'quieter', 'distill', 'polish', 'typeset',
+ 'colorize', 'layout', 'adapt', 'animate', 'delight', 'overdrive',
+];
+
+function validateEvent(msg) {
+ if (!msg || typeof msg !== 'object' || !msg.type) return 'Missing or invalid message';
+ switch (msg.type) {
+ case 'generate':
+ if (!msg.id || typeof msg.id !== 'string') return 'generate: missing id';
+ if (!msg.action || !VISUAL_ACTIONS.includes(msg.action)) return 'generate: invalid action';
+ if (!Number.isInteger(msg.count) || msg.count < 1 || msg.count > 8) return 'generate: count must be 1-8';
+ if (!msg.element || !msg.element.outerHTML) return 'generate: missing element context';
+ return null;
+ case 'accept':
+ if (!msg.id) return 'accept: missing id';
+ if (!msg.variantId) return 'accept: missing variantId';
+ return null;
+ case 'discard':
+ return msg.id ? null : 'discard: missing id';
+ case 'exit':
+ return null;
+ default:
+ return 'Unknown event type: ' + msg.type;
+ }
+}
+
+// ---------------------------------------------------------------------------
+// HTTP request handler
+// ---------------------------------------------------------------------------
+
+function createRequestHandler({ detectScript, liveScriptWithToken }) {
+ return (req, res) => {
+ const url = new URL(req.url, `http://localhost:${state.port}`);
+ res.setHeader('Access-Control-Allow-Origin', '*');
+ res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS');
+ res.setHeader('Access-Control-Allow-Headers', 'Content-Type');
+ if (req.method === 'OPTIONS') { res.writeHead(204); res.end(); return; }
+
+ const p = url.pathname;
+
+ // --- Scripts ---
+ if (p === '/live.js') {
+ res.writeHead(200, { 'Content-Type': 'application/javascript' });
+ res.end(liveScriptWithToken);
+ return;
+ }
+ if (p === '/detect.js' || p === '/') {
+ if (!detectScript) { res.writeHead(404); res.end('Not available'); return; }
+ res.writeHead(200, { 'Content-Type': 'application/javascript' });
+ res.end(detectScript);
+ return;
+ }
+
+ // --- Health ---
+ if (p === '/health') {
+ res.writeHead(200, { 'Content-Type': 'application/json' });
+ res.end(JSON.stringify({
+ status: 'ok', port: state.port, mode: 'variant',
+ hasProjectContext: hasProjectContext(),
+ connectedClients: state.sseClients.size,
+ }));
+ return;
+ }
+
+ // --- Source file (no-HMR fallback) ---
+ if (p === '/source') {
+ const token = url.searchParams.get('token');
+ if (token !== state.token) { res.writeHead(401); res.end('Unauthorized'); return; }
+ const filePath = url.searchParams.get('path');
+ if (!filePath || filePath.includes('..')) { res.writeHead(400); res.end('Bad path'); return; }
+ const absPath = path.resolve(process.cwd(), filePath);
+ if (!absPath.startsWith(process.cwd())) { res.writeHead(403); res.end('Forbidden'); return; }
+ try {
+ res.writeHead(200, { 'Content-Type': 'text/html; charset=utf-8' });
+ res.end(fs.readFileSync(absPath, 'utf-8'));
+ } catch { res.writeHead(404); res.end('File not found'); }
+ return;
+ }
+
+ // --- SSE: server→browser push (replaces WebSocket) ---
+ if (p === '/events' && req.method === 'GET') {
+ const token = url.searchParams.get('token');
+ if (token !== state.token) { res.writeHead(401); res.end('Unauthorized'); return; }
+ res.writeHead(200, {
+ 'Content-Type': 'text/event-stream',
+ 'Cache-Control': 'no-cache',
+ 'Connection': 'keep-alive',
+ });
+ res.write('data: ' + JSON.stringify({
+ type: 'connected',
+ hasProjectContext: hasProjectContext(),
+ }) + '\n\n');
+
+ state.sseClients.add(res);
+ clearTimeout(state.exitTimer);
+
+ req.on('close', () => {
+ state.sseClients.delete(res);
+ if (state.sseClients.size === 0) {
+ clearTimeout(state.exitTimer);
+ state.exitTimer = setTimeout(() => {
+ if (state.sseClients.size === 0) enqueueEvent({ type: 'exit' });
+ }, 8000);
+ }
+ });
+ return;
+ }
+
+ // --- Browser→server events (replaces WebSocket messages) ---
+ if (p === '/events' && req.method === 'POST') {
+ let body = '';
+ req.on('data', (c) => { body += c; });
+ req.on('end', () => {
+ let msg;
+ try { msg = JSON.parse(body); } catch {
+ res.writeHead(400, { 'Content-Type': 'application/json' });
+ res.end(JSON.stringify({ error: 'Invalid JSON' }));
+ return;
+ }
+ if (msg.token !== state.token) {
+ res.writeHead(401, { 'Content-Type': 'application/json' });
+ res.end(JSON.stringify({ error: 'Unauthorized' }));
+ return;
+ }
+ const error = validateEvent(msg);
+ if (error) {
+ res.writeHead(400, { 'Content-Type': 'application/json' });
+ res.end(JSON.stringify({ error }));
+ return;
+ }
+ enqueueEvent(msg);
+ res.writeHead(200, { 'Content-Type': 'application/json' });
+ res.end(JSON.stringify({ ok: true }));
+ });
+ return;
+ }
+
+ // --- Stop ---
+ if (p === '/stop') {
+ const token = url.searchParams.get('token');
+ if (token !== state.token) { res.writeHead(401); res.end('Unauthorized'); return; }
+ res.writeHead(200, { 'Content-Type': 'text/plain' });
+ res.end('stopping');
+ shutdown();
+ return;
+ }
+
+ // --- Agent poll ---
+ if (p === '/poll' && req.method === 'GET') {
+ handlePollGet(req, res, url);
+ return;
+ }
+ if (p === '/poll' && req.method === 'POST') {
+ handlePollPost(req, res);
+ return;
+ }
+
+ res.writeHead(404); res.end('Not found');
+ };
+}
+
+// ---------------------------------------------------------------------------
+// Agent poll endpoints (unchanged from WS version)
+// ---------------------------------------------------------------------------
+
+function handlePollGet(req, res, url) {
+ 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 timeout = parseInt(url.searchParams.get('timeout') || DEFAULT_POLL_TIMEOUT, 10);
+ if (state.pendingEvents.length > 0) {
+ res.writeHead(200, { 'Content-Type': 'application/json' });
+ res.end(JSON.stringify(state.pendingEvents.shift()));
+ return;
+ }
+ const timer = setTimeout(() => {
+ const idx = state.pendingPolls.indexOf(resolve);
+ if (idx !== -1) state.pendingPolls.splice(idx, 1);
+ res.writeHead(200, { 'Content-Type': 'application/json' });
+ res.end(JSON.stringify({ type: 'timeout' }));
+ }, timeout);
+ function resolve(event) {
+ clearTimeout(timer);
+ res.writeHead(200, { 'Content-Type': 'application/json' });
+ res.end(JSON.stringify(event));
+ }
+ state.pendingPolls.push(resolve);
+ req.on('close', () => {
+ clearTimeout(timer);
+ const idx = state.pendingPolls.indexOf(resolve);
+ if (idx !== -1) state.pendingPolls.splice(idx, 1);
+ });
+}
+
+function handlePollPost(req, res) {
+ let body = '';
+ req.on('data', (c) => { body += c; });
+ req.on('end', () => {
+ let msg;
+ try { msg = JSON.parse(body); } catch {
+ res.writeHead(400, { 'Content-Type': 'application/json' });
+ res.end(JSON.stringify({ error: 'Invalid JSON' }));
+ return;
+ }
+ if (msg.token !== state.token) {
+ res.writeHead(401, { 'Content-Type': 'application/json' });
+ res.end(JSON.stringify({ error: 'Unauthorized' }));
+ return;
+ }
+ // Forward the reply to the browser via SSE
+ broadcast({ type: msg.type || 'done', id: msg.id, message: msg.message, file: msg.file, data: msg.data });
+ res.writeHead(200, { 'Content-Type': 'application/json' });
+ res.end(JSON.stringify({ ok: true }));
+ });
+}
+
+// ---------------------------------------------------------------------------
+// Lifecycle
+// ---------------------------------------------------------------------------
+
+let httpServer = null;
+
+function shutdown() {
+ try { fs.unlinkSync(LIVE_PID_FILE); } catch {}
+ for (const res of state.sseClients) { try { res.end(); } catch {} }
+ state.sseClients.clear();
+ for (const resolve of state.pendingPolls) resolve({ type: 'exit' });
+ state.pendingPolls.length = 0;
+ if (httpServer) httpServer.close();
+ process.exit(0);
+}
+
+// ---------------------------------------------------------------------------
+// Main
+// ---------------------------------------------------------------------------
+
+const args = process.argv.slice(2);
+
+if (args.includes('--help') || args.includes('-h')) {
+ console.log(`Usage: node live-server.mjs [options]
+
+Start the live variant mode server (zero dependencies).
+
+Commands:
+ (default) Start the server
+ stop Stop a running server
+
+Options:
+ --port=PORT Use a specific port (default: auto-detect starting at 8400)
+ --help Show this help
+
+Endpoints:
+ /live.js Browser script (element picker + variant cycling)
+ /detect.js Detection overlay (backwards compatible)
+ /events SSE stream (server→browser) + POST (browser→server)
+ /poll Long-poll for agent CLI
+ /source Raw source file reader (no-HMR fallback)
+ /health Health check`);
+ process.exit(0);
+}
+
+if (args.includes('stop')) {
+ try {
+ const info = JSON.parse(fs.readFileSync(LIVE_PID_FILE, 'utf-8'));
+ 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 { console.log('No running live server found.'); }
+ process.exit(0);
+}
+
+// Check for existing session
+try {
+ const existing = JSON.parse(fs.readFileSync(LIVE_PID_FILE, 'utf-8'));
+ 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 {}
+
+state.token = randomUUID();
+const portArg = args.find(a => a.startsWith('--port='));
+state.port = portArg ? parseInt(portArg.split('=')[1], 10) : await findOpenPort();
+
+const { detectScript, liveScript } = loadBrowserScripts();
+const liveScriptWithToken =
+ `window.__IMPECCABLE_TOKEN__ = '${state.token}';\n` +
+ `window.__IMPECCABLE_PORT__ = ${state.port};\n` +
+ liveScript;
+
+httpServer = http.createServer(createRequestHandler({ detectScript, liveScriptWithToken }));
+
+httpServer.listen(state.port, '127.0.0.1', () => {
+ fs.writeFileSync(LIVE_PID_FILE, JSON.stringify({ 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`);
+ console.log(`Inject: <script src="${url}/live.js"><\/script>`);
+ console.log(`Stop: node ${path.basename(fileURLToPath(import.meta.url))} stop`);
+});
+
+process.on('SIGINT', shutdown);
+process.on('SIGTERM', shutdown);
diff --git a/.trae-cn/skills/impeccable/scripts/live-wrap.mjs b/.trae-cn/skills/impeccable/scripts/live-wrap.mjs
new file mode 100644
index 000000000..f1c838cdd
--- /dev/null
+++ b/.trae-cn/skills/impeccable/scripts/live-wrap.mjs
@@ -0,0 +1,298 @@
+/**
+ * CLI helper: find an element in source and wrap it in a variant container.
+ *
+ * Usage:
+ * npx impeccable wrap --id SESSION_ID --count N --query "hero-combined-left" [--file path]
+ *
+ * Searches project files for the element matching the query (class name, ID, or
+ * text snippet), wraps it with the variant scaffolding, and prints the file path
+ * + line range where the agent should insert variant HTML.
+ *
+ * This replaces 3-4 agent tool calls (grep + read + edit) with a single CLI call.
+ */
+
+import fs from 'node:fs';
+import path from 'node:path';
+
+const EXTENSIONS = ['.html', '.jsx', '.tsx', '.vue', '.svelte', '.astro'];
+
+export async function wrapCli() {
+ const args = process.argv.slice(2);
+
+ if (args.includes('--help') || args.includes('-h')) {
+ console.log(`Usage: impeccable wrap [options]
+
+Find an element in source and wrap it in a variant container.
+
+Required:
+ --id ID Session ID for the variant wrapper
+ --count N Number of expected variants (1-8)
+
+Element identification (at least one required):
+ --element-id ID HTML id attribute of the element
+ --classes A,B,C Comma-separated CSS class names
+ --tag TAG Tag name (div, section, etc.)
+ --query TEXT Fallback: raw text to search for
+
+Optional:
+ --file PATH Source file to search in (skips auto-detection)
+ --help Show this help message
+
+Output (JSON):
+ { file, startLine, endLine, insertLine, commentSyntax }
+
+The agent should insert variant HTML at insertLine.`);
+ process.exit(0);
+ }
+
+ const id = argVal(args, '--id');
+ const count = parseInt(argVal(args, '--count') || '3');
+ const elementId = argVal(args, '--element-id');
+ const classes = argVal(args, '--classes');
+ const tag = argVal(args, '--tag');
+ const query = argVal(args, '--query');
+ const filePath = argVal(args, '--file');
+
+ if (!id) { console.error('Missing --id'); process.exit(1); }
+ if (!elementId && !classes && !query) {
+ console.error('Need at least one of: --element-id, --classes, --query');
+ process.exit(1);
+ }
+
+ // Build search queries in priority order (most specific first)
+ const queries = buildSearchQueries(elementId, classes, tag, query);
+
+ // Find the source file
+ let targetFile = filePath;
+ let matchedQuery = null;
+ if (!targetFile) {
+ for (const q of queries) {
+ targetFile = findFileWithQuery(q, process.cwd());
+ if (targetFile) { matchedQuery = q; break; }
+ }
+ if (!targetFile) {
+ console.error(JSON.stringify({ error: 'Could not find element in project files. Searched for: ' + queries.join(', ') }));
+ process.exit(1);
+ }
+ } else {
+ matchedQuery = queries[0];
+ }
+
+ const content = fs.readFileSync(targetFile, 'utf-8');
+ const lines = content.split('\n');
+
+ // Find the element, trying each query in priority order
+ let match = null;
+ for (const q of queries) {
+ match = findElement(lines, q);
+ if (match) break;
+ }
+ if (!match) {
+ console.error(JSON.stringify({ error: 'Found file but could not locate element in ' + targetFile + '. Searched for: ' + queries.join(', ') }));
+ process.exit(1);
+ }
+
+ const { startLine, endLine } = match;
+ const commentSyntax = detectCommentSyntax(targetFile);
+ const indent = lines[startLine].match(/^(\s*)/)[1];
+
+ // Extract the original element
+ const originalLines = lines.slice(startLine, endLine + 1);
+ const originalIndented = originalLines.map(l => indent + ' ' + l.trimStart()).join('\n');
+
+ // Build the wrapper
+ const wrapperLines = [
+ indent + commentSyntax.open + ' impeccable-variants-start ' + id + ' ' + commentSyntax.close,
+ indent + '<div data-impeccable-variants="' + id + '" data-impeccable-variant-count="' + count + '" style="display: contents">',
+ indent + ' ' + commentSyntax.open + ' Original ' + commentSyntax.close,
+ indent + ' <div data-impeccable-variant="original">',
+ originalIndented,
+ indent + ' </div>',
+ indent + ' ' + commentSyntax.open + ' Variants: insert below this line ' + commentSyntax.close,
+ indent + '</div>',
+ indent + commentSyntax.open + ' impeccable-variants-end ' + id + ' ' + commentSyntax.close,
+ ];
+
+ // Replace the original element with the wrapper
+ const newLines = [
+ ...lines.slice(0, startLine),
+ ...wrapperLines,
+ ...lines.slice(endLine + 1),
+ ];
+ fs.writeFileSync(targetFile, newLines.join('\n'), 'utf-8');
+
+ // Calculate insert line (the "insert below this line" comment)
+ const insertLine = startLine + 6; // 0-indexed in the new file
+
+ console.log(JSON.stringify({
+ file: path.relative(process.cwd(), targetFile),
+ startLine: startLine + 1, // 1-indexed for the agent
+ endLine: startLine + wrapperLines.length, // 1-indexed
+ insertLine: insertLine + 1, // 1-indexed: where variants go
+ commentSyntax: commentSyntax,
+ originalLineCount: originalLines.length,
+ }));
+}
+
+// ---------------------------------------------------------------------------
+// Helpers
+// ---------------------------------------------------------------------------
+
+function argVal(args, flag) {
+ const idx = args.indexOf(flag);
+ return idx !== -1 && idx + 1 < args.length ? args[idx + 1] : null;
+}
+
+/**
+ * Build search query strings in priority order (most specific first).
+ * ID is most reliable, then specific class combos, then single classes, then raw query.
+ */
+function buildSearchQueries(elementId, classes, tag, query) {
+ const queries = [];
+
+ // 1. ID is the most specific
+ if (elementId) {
+ queries.push('id="' + elementId + '"');
+ }
+
+ // 2. Full class attribute match (for elements with distinctive multi-class combos)
+ if (classes) {
+ const classList = classes.split(',').map(c => c.trim()).filter(Boolean);
+ if (classList.length > 1) {
+ // Try the most distinctive class first (longest, most specific)
+ const sorted = [...classList].sort((a, b) => b.length - a.length);
+ queries.push('class="' + classList.join(' ') + '"'); // exact full match
+ queries.push(sorted[0]); // most distinctive single class
+ } else if (classList.length === 1) {
+ queries.push(classList[0]);
+ }
+ }
+
+ // 3. Tag + class combo (e.g., <section class="hero">)
+ if (tag && classes) {
+ const firstClass = classes.split(',')[0].trim();
+ queries.push('<' + tag + ' class="' + firstClass);
+ }
+
+ // 4. Raw fallback query
+ if (query) {
+ queries.push(query);
+ }
+
+ return queries;
+}
+
+function detectCommentSyntax(filePath) {
+ const ext = path.extname(filePath).toLowerCase();
+ if (ext === '.jsx' || ext === '.tsx') {
+ return { open: '{/*', close: '*/}' };
+ }
+ // HTML, Vue, Svelte, Astro all use HTML comments
+ return { open: '<!--', close: '-->' };
+}
+
+/**
+ * Search project files for the query string (class name, ID, etc.)
+ * Returns the first matching file path, or null.
+ */
+function findFileWithQuery(query, cwd) {
+ const searchDirs = ['src', 'app', 'pages', 'components', 'public', 'views', 'templates', '.'];
+ const seen = new Set();
+
+ for (const dir of searchDirs) {
+ const absDir = path.join(cwd, dir);
+ if (!fs.existsSync(absDir)) continue;
+ const result = searchDir(absDir, query, seen, 0);
+ if (result) return result;
+ }
+ return null;
+}
+
+function searchDir(dir, query, seen, depth) {
+ if (depth > 5) return null; // don't go too deep
+ const realDir = fs.realpathSync(dir);
+ if (seen.has(realDir)) return null;
+ seen.add(realDir);
+
+ let entries;
+ try { entries = fs.readdirSync(dir, { withFileTypes: true }); }
+ catch { return null; }
+
+ // Check files first
+ for (const entry of entries) {
+ if (!entry.isFile()) continue;
+ const ext = path.extname(entry.name).toLowerCase();
+ if (!EXTENSIONS.includes(ext)) continue;
+
+ const filePath = path.join(dir, entry.name);
+ try {
+ const content = fs.readFileSync(filePath, 'utf-8');
+ if (content.includes(query)) return filePath;
+ } catch { /* skip unreadable files */ }
+ }
+
+ // Then recurse into directories
+ for (const entry of entries) {
+ if (!entry.isDirectory()) continue;
+ if (entry.name === 'node_modules' || entry.name === '.git' || entry.name === 'dist' || entry.name === 'build') continue;
+ const result = searchDir(path.join(dir, entry.name), query, seen, depth + 1);
+ if (result) return result;
+ }
+
+ return null;
+}
+
+/**
+ * Find the element's start and end line in the file.
+ * The query is a class name, ID, or text snippet.
+ * We find the line containing the query, then find the matching closing tag.
+ */
+function findElement(lines, query) {
+ // Find the line containing the query
+ let startLine = -1;
+ for (let i = 0; i < lines.length; i++) {
+ if (lines[i].includes(query)) {
+ // Make sure this looks like a tag opening, not a comment or string
+ const line = lines[i].trim();
+ if (line.startsWith('<!--') || line.startsWith('{/*') || line.startsWith('//')) continue;
+ // Skip lines inside data-impeccable-variant containers (already wrapped)
+ if (lines[i].includes('data-impeccable-variant')) continue;
+ startLine = i;
+ break;
+ }
+ }
+
+ if (startLine === -1) return null;
+
+ // Find the end of this element by counting open/close tags
+ const endLine = findClosingLine(lines, startLine);
+ return { startLine, endLine };
+}
+
+/**
+ * Starting from a line with an opening tag, find the line with the matching
+ * closing tag by counting tag nesting depth.
+ */
+function findClosingLine(lines, start) {
+ // Extract the tag name from the opening line
+ const openMatch = lines[start].match(/<(\w+)[\s>]/);
+ if (!openMatch) return start; // self-closing or text-only line
+
+ const tagName = openMatch[1];
+ let depth = 0;
+
+ for (let i = start; i < lines.length; i++) {
+ const line = lines[i];
+ // Count opening tags (not self-closing)
+ const opens = (line.match(new RegExp('<' + tagName + '[\\s>]', 'g')) || []).length;
+ const selfCloses = (line.match(new RegExp('<' + tagName + '[^>]*/>', 'g')) || []).length;
+ const closes = (line.match(new RegExp('</' + tagName + '\\s*>', 'g')) || []).length;
+
+ depth += opens - selfCloses - closes;
+
+ if (depth <= 0) return i;
+ }
+
+ // If we can't find the close, return a reasonable guess
+ return Math.min(start + 50, lines.length - 1);
+}
diff --git a/.trae/skills/impeccable/reference/live.md b/.trae/skills/impeccable/reference/live.md
index 53b64a21a..ba0e9b0c5 100644
--- a/.trae/skills/impeccable/reference/live.md
+++ b/.trae/skills/impeccable/reference/live.md
@@ -10,7 +10,7 @@ Launch interactive live variant mode: select elements in the browser, pick a des
1. Read `.impeccable.md` if it exists. Keep the design context in mind for variant generation.
2. Start the live variant server:
```bash
- npx impeccable live &
+ node {{scripts_path}}/live-server.mjs &
```
3. Note the **port** and **token** printed to stdout.
@@ -53,7 +53,7 @@ Run a blocking poll loop. On each iteration, wait for a browser event and respon
```
LOOP:
- Run: npx impeccable poll
+ Run: node {{scripts_path}}/live-poll.mjs
Read the JSON output. Dispatch based on the "type" field:
TYPE "generate":
@@ -85,7 +85,7 @@ The event contains: `{id, action, freeformPrompt, count, pageUrl, element}`.
Use the `wrap` helper to find the element and create the variant container:
```bash
-npx impeccable wrap --id EVENT_ID --count EVENT_COUNT --element-id "ELEMENT_ID" --classes "class1,class2" --tag "div"
+node {{scripts_path}}/live-wrap.mjs --id EVENT_ID --count EVENT_COUNT --element-id "ELEMENT_ID" --classes "class1,class2" --tag "div"
```
Pass the element's id (`event.element.id`), classes (`event.element.classes` joined with commas), and tag name. The command searches in priority order: ID match first, then class names, then tag+class combo. If `event.pageUrl` hints at the file (e.g., `/` is usually `index.html`), pass `--file PATH` to skip the search.
@@ -136,10 +136,14 @@ The first variant should NOT have `style="display: none"` (it should be visible
### Step 3: Signal completion
+Include `--file` so the browser can fetch variants directly if the dev server lacks HMR:
+
```bash
-npx impeccable poll --reply EVENT_ID done
+node {{scripts_path}}/live-poll.mjs --reply EVENT_ID done --file RELATIVE_PATH
```
+The file path should be relative to the project root (e.g., `public/index.html`, `src/App.tsx`).
+
## Handle Accept
The event contains: `{id, variantId}`.
@@ -151,7 +155,7 @@ The user accepted a specific variant. For v1 (inspection mode):
4. Remove any scoped CSS blocks (between `impeccable-variants-css-start` and `impeccable-variants-css-end` markers).
5. Reply:
```bash
- npx impeccable poll --reply SESSION_ID done
+ node {{scripts_path}}/live-poll.mjs --reply SESSION_ID done
```
## Handle Discard
@@ -163,7 +167,7 @@ The event contains: `{id}`.
3. Remove any scoped CSS blocks for this session.
4. Reply:
```bash
- npx impeccable poll --reply SESSION_ID done
+ node {{scripts_path}}/live-poll.mjs --reply SESSION_ID done
```
## Cleanup (on exit)
@@ -174,7 +178,7 @@ When the loop ends:
2. **Remove any leftover variant wrappers** (search for `impeccable-variants-start` markers and clean up).
3. **Stop the server**:
```bash
- npx impeccable live stop
+ node {{scripts_path}}/live-server.mjs stop
```
## Variant Generation Guidelines
diff --git a/.trae/skills/impeccable/scripts/live-browser.js b/.trae/skills/impeccable/scripts/live-browser.js
new file mode 100644
index 000000000..7a26c9829
--- /dev/null
+++ b/.trae/skills/impeccable/scripts/live-browser.js
@@ -0,0 +1,1220 @@
+/**
+ * Impeccable Live Variant Mode — Browser Script
+ *
+ * Injected into the user's page via <script src="http://localhost:PORT/live.js">.
+ * The server prepends window.__IMPECCABLE_TOKEN__ and window.__IMPECCABLE_PORT__
+ * before this code.
+ *
+ * UI: a single floating bar that morphs between three states —
+ * configure (pick action + go), generating (progressive dots), and cycling
+ * (prev/next + accept/discard). Feels like Spotlight, not a modal.
+ */
+(function () {
+ 'use strict';
+ if (typeof window === 'undefined') return;
+
+ // Guard against double-init. Bun's HTML loader may process the <script> tag
+ // and create a bundled copy alongside the external load, or HMR may re-execute.
+ // Check BEFORE reading token/port to catch all cases.
+ if (window.__IMPECCABLE_LIVE_INIT__) return;
+ window.__IMPECCABLE_LIVE_INIT__ = true;
+
+ const TOKEN = window.__IMPECCABLE_TOKEN__;
+ const PORT = window.__IMPECCABLE_PORT__;
+ if (!TOKEN || !PORT) {
+ window.__IMPECCABLE_LIVE_INIT__ = false; // reset so the real load can init
+ return;
+ }
+
+ // ---------------------------------------------------------------------------
+ // Design tokens
+ // ---------------------------------------------------------------------------
+
+ const C = {
+ brand: 'oklch(55% 0.25 350)',
+ brandHov: 'oklch(48% 0.25 350)',
+ brandSoft: 'oklch(55% 0.25 350 / 0.12)',
+ ink: 'oklch(15% 0.01 350)',
+ ash: 'oklch(55% 0 0)',
+ paper: 'oklch(98% 0.005 350 / 0.92)',
+ paperSolid:'oklch(98% 0.005 350)',
+ mist: 'oklch(90% 0.01 350 / 0.6)',
+ white: 'oklch(99% 0 0)',
+ };
+ const FONT = 'system-ui, -apple-system, sans-serif';
+ const MONO = 'ui-monospace, SFMono-Regular, Menlo, monospace';
+ const Z = { highlight: 99990, bar: 99995, picker: 99997, toast: 99999 };
+ const EASE = 'cubic-bezier(0.22, 1, 0.36, 1)'; // ease-out-quint
+ const PREFIX = 'impeccable-live';
+
+ const SKIP_TAGS = new Set([
+ 'html', 'head', 'body', 'script', 'style', 'link', 'meta', 'noscript', 'br', 'wbr',
+ ]);
+
+ const ACTIONS = [
+ { value: 'impeccable', label: 'Freeform' },
+ { value: 'bolder', label: 'Bolder' },
+ { value: 'quieter', label: 'Quieter' },
+ { value: 'distill', label: 'Distill' },
+ { value: 'polish', label: 'Polish' },
+ { value: 'typeset', label: 'Typeset' },
+ { value: 'colorize', label: 'Colorize' },
+ { value: 'layout', label: 'Layout' },
+ { value: 'adapt', label: 'Adapt' },
+ { value: 'animate', label: 'Animate' },
+ { value: 'delight', label: 'Delight' },
+ { value: 'overdrive', label: 'Overdrive' },
+ ];
+
+ // ---------------------------------------------------------------------------
+ // State
+ // ---------------------------------------------------------------------------
+
+ let state = 'IDLE';
+ let hoveredElement = null;
+ let selectedElement = null;
+ let currentSessionId = null;
+ let expectedVariants = 0;
+ let arrivedVariants = 0;
+ let visibleVariant = 0;
+ let variantObserver = null;
+ let hasProjectContext = false;
+ let selectedAction = 'impeccable';
+ let selectedCount = 3;
+
+ // UI refs
+ let highlightEl = null;
+ let tooltipEl = null;
+ let barEl = null;
+ let pickerEl = null;
+ let toastEl = null;
+ let scrollRaf = null;
+
+ // ---------------------------------------------------------------------------
+ // Helpers
+ // ---------------------------------------------------------------------------
+
+ function own(el) {
+ return el && (el.id?.startsWith(PREFIX) || el.closest?.('[id^="' + PREFIX + '"]'));
+ }
+
+ function pickable(el) {
+ if (!el || el.nodeType !== 1) return false;
+ if (SKIP_TAGS.has(el.tagName.toLowerCase())) return false;
+ if (own(el)) return false;
+ const r = el.getBoundingClientRect();
+ return r.width >= 20 && r.height >= 20;
+ }
+
+ function desc(el) {
+ if (!el) return '';
+ let s = el.tagName.toLowerCase();
+ if (el.id) s += '#' + el.id;
+ else if (el.classList.length) s += '.' + [...el.classList].slice(0, 2).join('.');
+ return s;
+ }
+
+ function id8() { return crypto.randomUUID().replace(/-/g, '').slice(0, 8); }
+
+ // ---------------------------------------------------------------------------
+ // Highlight overlay
+ // ---------------------------------------------------------------------------
+
+ function initHighlight() {
+ highlightEl = document.createElement('div');
+ highlightEl.id = PREFIX + '-highlight';
+ Object.assign(highlightEl.style, {
+ position: 'fixed', top: '0', left: '0', width: '0', height: '0',
+ border: '2px solid ' + C.brand, borderRadius: '3px',
+ pointerEvents: 'none', zIndex: Z.highlight, boxSizing: 'border-box',
+ transition: 'top 0.08s ease, left 0.08s ease, width 0.08s ease, height 0.08s ease, opacity 0.15s ease',
+ display: 'none', opacity: '0',
+ });
+ document.body.appendChild(highlightEl);
+
+ tooltipEl = document.createElement('div');
+ tooltipEl.id = PREFIX + '-tooltip';
+ Object.assign(tooltipEl.style, {
+ position: 'fixed',
+ background: C.ink, color: C.white,
+ fontFamily: MONO, fontSize: '10px', fontWeight: '500',
+ padding: '2px 6px', borderRadius: '3px',
+ zIndex: Z.highlight + 1, pointerEvents: 'none',
+ whiteSpace: 'nowrap', display: 'none',
+ letterSpacing: '0.02em',
+ });
+ document.body.appendChild(tooltipEl);
+ }
+
+ function showHighlight(el) {
+ if (!el || !highlightEl) return;
+ const r = el.getBoundingClientRect();
+ Object.assign(highlightEl.style, {
+ top: (r.top - 2) + 'px', left: (r.left - 2) + 'px',
+ width: (r.width + 4) + 'px', height: (r.height + 4) + 'px',
+ display: 'block', opacity: '1',
+ });
+ tooltipEl.textContent = desc(el);
+ const tipTop = r.top - 20;
+ Object.assign(tooltipEl.style, {
+ top: (tipTop < 4 ? r.bottom + 4 : tipTop) + 'px',
+ left: Math.max(4, r.left) + 'px', display: 'block',
+ });
+ }
+
+ function hideHighlight() {
+ if (highlightEl) { highlightEl.style.opacity = '0'; highlightEl.style.display = 'none'; }
+ if (tooltipEl) tooltipEl.style.display = 'none';
+ }
+
+ // ---------------------------------------------------------------------------
+ // Element context extraction
+ // ---------------------------------------------------------------------------
+
+ function extractContext(el) {
+ const cs = getComputedStyle(el);
+ const r = el.getBoundingClientRect();
+ const props = {};
+ for (const sheet of document.styleSheets) {
+ try {
+ for (const rule of sheet.cssRules) {
+ if (rule.style) for (let i = 0; i < rule.style.length; i++) {
+ const p = rule.style[i];
+ if (p.startsWith('--') && !props[p]) {
+ const v = cs.getPropertyValue(p).trim();
+ if (v) props[p] = v;
+ }
+ }
+ }
+ } catch { /* cross-origin */ }
+ }
+ return {
+ tagName: el.tagName.toLowerCase(), id: el.id || null,
+ classes: [...el.classList],
+ textContent: (el.textContent || '').slice(0, 500),
+ outerHTML: el.outerHTML.slice(0, 10000),
+ computedStyles: {
+ 'font-family': cs.fontFamily, 'font-size': cs.fontSize,
+ 'font-weight': cs.fontWeight, 'line-height': cs.lineHeight,
+ 'color': cs.color, 'background': cs.background,
+ 'background-color': cs.backgroundColor,
+ 'padding': cs.padding, 'margin': cs.margin,
+ 'display': cs.display, 'position': cs.position,
+ 'gap': cs.gap, 'border-radius': cs.borderRadius,
+ 'box-shadow': cs.boxShadow,
+ },
+ cssCustomProperties: props,
+ parentContext: el.parentElement
+ ? '<' + el.parentElement.tagName.toLowerCase()
+ + (el.parentElement.id ? ' id="' + el.parentElement.id + '"' : '')
+ + (el.parentElement.className ? ' class="' + el.parentElement.className + '"' : '')
+ + '>'
+ : null,
+ boundingRect: { width: Math.round(r.width), height: Math.round(r.height) },
+ };
+ }
+
+ // ---------------------------------------------------------------------------
+ // The Bar — one floating element, three modes
+ // ---------------------------------------------------------------------------
+
+ function initBar() {
+ barEl = document.createElement('div');
+ barEl.id = PREFIX + '-bar';
+ Object.assign(barEl.style, {
+ position: 'fixed', zIndex: Z.bar,
+ display: 'none', opacity: '0',
+ transform: 'translateY(6px)',
+ transition: 'opacity 0.25s ' + EASE + ', transform 0.3s ' + EASE,
+ // Visual
+ background: C.paper,
+ backdropFilter: 'blur(16px)', WebkitBackdropFilter: 'blur(16px)',
+ border: '1px solid ' + C.mist,
+ borderRadius: '10px',
+ boxShadow: '0 4px 20px oklch(0% 0 0 / 0.08), 0 1px 3px oklch(0% 0 0 / 0.06)',
+ fontFamily: FONT, fontSize: '13px', color: C.ink,
+ padding: '6px',
+ maxWidth: '460px', minWidth: '320px',
+ });
+ document.body.appendChild(barEl);
+ }
+
+ function positionBar() {
+ if (!barEl || !selectedElement) return;
+ const r = selectedElement.getBoundingClientRect();
+ const barH = barEl.offsetHeight || 44;
+ const barW = barEl.offsetWidth || 380;
+ let top = r.bottom + 8;
+ let left = r.left + (r.width - barW) / 2;
+ // Keep in viewport
+ if (top + barH + 8 > window.innerHeight) top = r.top - barH - 8;
+ if (top < 8) top = 8;
+ if (left < 8) left = 8;
+ if (left + barW > window.innerWidth - 8) left = window.innerWidth - barW - 8;
+ Object.assign(barEl.style, { top: top + 'px', left: left + 'px' });
+ }
+
+ function showBar(mode) {
+ barEl.innerHTML = '';
+ if (mode === 'configure') barEl.appendChild(buildConfigureRow());
+ else if (mode === 'generating') barEl.appendChild(buildGeneratingRow());
+ else if (mode === 'cycling') barEl.appendChild(buildCyclingRow());
+ barEl.style.display = 'block';
+ positionBar();
+ requestAnimationFrame(() => {
+ barEl.style.opacity = '1';
+ barEl.style.transform = 'translateY(0)';
+ });
+ }
+
+ function hideBar() {
+ if (!barEl) return;
+ barEl.style.opacity = '0';
+ barEl.style.transform = 'translateY(6px)';
+ setTimeout(() => { if (barEl) barEl.style.display = 'none'; }, 250);
+ hideActionPicker();
+ }
+
+ function updateBarContent(mode) {
+ if (!barEl || barEl.style.display === 'none') return;
+ barEl.innerHTML = '';
+ // Reset bar styling
+ barEl.style.background = C.paper;
+ barEl.style.border = '1px solid ' + C.mist;
+ if (mode === 'configure') barEl.appendChild(buildConfigureRow());
+ else if (mode === 'generating') barEl.appendChild(buildGeneratingRow());
+ else if (mode === 'cycling') barEl.appendChild(buildCyclingRow());
+ else if (mode === 'saving') barEl.appendChild(buildSavingRow());
+ else if (mode === 'confirmed') {
+ barEl.appendChild(buildConfirmedRow());
+ barEl.style.background = 'oklch(95% 0.05 145)';
+ barEl.style.border = '1px solid oklch(75% 0.12 145 / 0.4)';
+ }
+ }
+
+ // --- Configure row ---
+
+ function buildConfigureRow() {
+ const row = el('div', {
+ display: 'flex', alignItems: 'center', gap: '4px',
+ });
+
+ // Action pill
+ const pill = el('button', {
+ display: 'inline-flex', alignItems: 'center', gap: '4px',
+ padding: '5px 10px', borderRadius: '6px',
+ background: C.ink, color: C.white,
+ fontFamily: FONT, fontSize: '12px', fontWeight: '500',
+ border: 'none', cursor: 'pointer',
+ transition: 'background 0.12s ease, transform 0.1s ease',
+ whiteSpace: 'nowrap', flexShrink: '0',
+ });
+ pill.textContent = actionLabel() + ' \u25BE';
+ pill.addEventListener('mouseenter', () => pill.style.background = C.brandHov);
+ pill.addEventListener('mouseleave', () => pill.style.background = C.ink);
+ pill.addEventListener('mousedown', () => pill.style.transform = 'scale(0.97)');
+ pill.addEventListener('mouseup', () => pill.style.transform = 'scale(1)');
+ pill.addEventListener('click', (e) => { e.stopPropagation(); toggleActionPicker(); });
+ row.appendChild(pill);
+
+ // Freeform input
+ const input = document.createElement('input');
+ input.id = PREFIX + '-input';
+ input.type = 'text';
+ input.placeholder = selectedAction === 'impeccable' ? 'describe what you want...' : 'refine further (optional)...';
+ Object.assign(input.style, {
+ flex: '1', minWidth: '0',
+ padding: '5px 8px', borderRadius: '6px',
+ border: '1px solid transparent', background: 'transparent',
+ fontFamily: FONT, fontSize: '12px', color: C.ink,
+ outline: 'none',
+ transition: 'border-color 0.15s ease, background 0.15s ease',
+ });
+ input.addEventListener('focus', () => {
+ input.style.borderColor = C.mist;
+ input.style.background = C.white;
+ });
+ input.addEventListener('blur', () => {
+ input.style.borderColor = 'transparent';
+ input.style.background = 'transparent';
+ });
+ input.addEventListener('keydown', (e) => {
+ e.stopPropagation(); // Don't trigger element picker keyboard nav
+ if (e.key === 'Enter') { e.preventDefault(); handleGo(); }
+ if (e.key === 'Escape') { e.preventDefault(); input.blur(); hideBar(); state = 'PICKING'; }
+ });
+ row.appendChild(input);
+
+ // Variant count toggle
+ const count = el('button', {
+ padding: '4px 6px', borderRadius: '5px',
+ border: '1px solid ' + C.mist, background: 'transparent',
+ fontFamily: MONO, fontSize: '11px', fontWeight: '600',
+ color: C.ash, cursor: 'pointer',
+ transition: 'color 0.12s ease, border-color 0.12s ease',
+ flexShrink: '0', whiteSpace: 'nowrap',
+ });
+ count.textContent = '\u00D7' + selectedCount;
+ count.title = 'Variants: click to change';
+ count.addEventListener('mouseenter', () => { count.style.color = C.ink; count.style.borderColor = C.ink; });
+ count.addEventListener('mouseleave', () => { count.style.color = C.ash; count.style.borderColor = C.mist; });
+ count.addEventListener('click', (e) => {
+ e.stopPropagation();
+ selectedCount = selectedCount >= 4 ? 2 : selectedCount + 1;
+ count.textContent = '\u00D7' + selectedCount;
+ });
+ row.appendChild(count);
+
+ // Go button
+ const go = el('button', {
+ padding: '5px 12px', borderRadius: '6px',
+ border: 'none', background: C.brand, color: C.white,
+ fontFamily: FONT, fontSize: '12px', fontWeight: '600',
+ cursor: 'pointer',
+ transition: 'background 0.12s ease, transform 0.1s ease',
+ flexShrink: '0', whiteSpace: 'nowrap',
+ });
+ go.textContent = 'Go \u2192';
+ go.addEventListener('mouseenter', () => go.style.background = C.brandHov);
+ go.addEventListener('mouseleave', () => go.style.background = C.brand);
+ go.addEventListener('mousedown', () => go.style.transform = 'scale(0.97)');
+ go.addEventListener('mouseup', () => go.style.transform = 'scale(1)');
+ go.addEventListener('click', (e) => { e.stopPropagation(); handleGo(); });
+ row.appendChild(go);
+
+ // Auto-focus input after a beat
+ setTimeout(() => input.focus(), 60);
+ return row;
+ }
+
+ // --- Generating row ---
+
+ function buildGeneratingRow() {
+ const row = el('div', {
+ display: 'flex', alignItems: 'center', gap: '8px',
+ padding: '2px 4px',
+ });
+
+ // Action label
+ const label = el('span', {
+ fontWeight: '600', fontSize: '12px', color: C.ink,
+ flexShrink: '0', whiteSpace: 'nowrap',
+ });
+ label.textContent = actionLabel();
+ row.appendChild(label);
+
+ // Dots
+ row.appendChild(buildDots(false));
+
+ // Status
+ const status = el('span', {
+ fontSize: '11px', color: C.ash, whiteSpace: 'nowrap',
+ marginLeft: 'auto',
+ });
+ status.textContent = arrivedVariants < expectedVariants
+ ? 'Generating ' + (arrivedVariants + 1) + ' of ' + expectedVariants + '...'
+ : 'Done';
+ row.appendChild(status);
+
+ return row;
+ }
+
+ // --- Cycling row ---
+
+ function buildCyclingRow() {
+ const row = el('div', {
+ display: 'flex', alignItems: 'center', gap: '6px',
+ padding: '1px 2px',
+ });
+
+ // Prev
+ const prev = navBtn('\u2190');
+ prev.addEventListener('click', (e) => { e.stopPropagation(); cycleVariant(-1); });
+ if (visibleVariant <= 1) prev.style.opacity = '0.3';
+ row.appendChild(prev);
+
+ // Dots (clickable)
+ row.appendChild(buildDots(true));
+
+ // Counter
+ const counter = el('span', {
+ fontFamily: MONO, fontSize: '11px', fontWeight: '500',
+ color: C.ash, minWidth: '24px', textAlign: 'center',
+ });
+ counter.textContent = visibleVariant + '/' + arrivedVariants;
+ row.appendChild(counter);
+
+ // Next
+ const next = navBtn('\u2192');
+ next.addEventListener('click', (e) => { e.stopPropagation(); cycleVariant(1); });
+ if (visibleVariant >= arrivedVariants) next.style.opacity = '0.3';
+ row.appendChild(next);
+
+ // Spacer
+ row.appendChild(el('div', { flex: '1' }));
+
+ // Accept
+ const accept = el('button', {
+ padding: '4px 10px', borderRadius: '5px',
+ border: 'none', background: C.ink, color: C.white,
+ fontFamily: FONT, fontSize: '11px', fontWeight: '600',
+ cursor: 'pointer', transition: 'background 0.12s ease',
+ whiteSpace: 'nowrap',
+ });
+ accept.textContent = '\u2713 Accept';
+ accept.addEventListener('mouseenter', () => accept.style.background = C.brand);
+ accept.addEventListener('mouseleave', () => accept.style.background = C.ink);
+ accept.addEventListener('click', (e) => { e.stopPropagation(); handleAccept(); });
+ if (arrivedVariants === 0) { accept.style.opacity = '0.3'; accept.style.pointerEvents = 'none'; }
+ row.appendChild(accept);
+
+ // Discard
+ const discard = el('button', {
+ padding: '4px 6px', borderRadius: '5px',
+ border: '1px solid ' + C.mist, background: 'transparent',
+ fontFamily: FONT, fontSize: '11px', color: C.ash,
+ cursor: 'pointer', transition: 'color 0.12s ease, border-color 0.12s ease',
+ });
+ discard.textContent = '\u2715';
+ discard.title = 'Discard all variants';
+ discard.addEventListener('mouseenter', () => { discard.style.color = C.ink; discard.style.borderColor = C.ink; });
+ discard.addEventListener('mouseleave', () => { discard.style.color = C.ash; discard.style.borderColor = C.mist; });
+ discard.addEventListener('click', (e) => { e.stopPropagation(); handleDiscard(); });
+ row.appendChild(discard);
+
+ return row;
+ }
+
+ // --- Shared UI builders ---
+
+ // --- Saving row (waiting for agent to process accept/discard) ---
+
+ function buildSavingRow() {
+ const row = el('div', {
+ display: 'flex', alignItems: 'center', gap: '8px',
+ padding: '2px 8px',
+ });
+ const spinner = el('div', {
+ width: '14px', height: '14px', borderRadius: '50%',
+ border: '2px solid ' + C.mist,
+ borderTopColor: C.brand,
+ animation: 'impeccable-spin 0.6s linear infinite',
+ flexShrink: '0',
+ });
+ row.appendChild(spinner);
+ const label = el('span', {
+ fontSize: '12px', color: C.ash, fontWeight: '500',
+ });
+ label.textContent = 'Applying variant...';
+ row.appendChild(label);
+
+ // Inject the keyframes if not already present
+ if (!document.getElementById(PREFIX + '-keyframes')) {
+ const style = document.createElement('style');
+ style.id = PREFIX + '-keyframes';
+ style.textContent = '@keyframes impeccable-spin { to { transform: rotate(360deg); } }';
+ document.head.appendChild(style);
+ }
+ return row;
+ }
+
+ // --- Confirmed row (green success, auto-dismisses) ---
+
+ function buildConfirmedRow() {
+ const row = el('div', {
+ display: 'flex', alignItems: 'center', gap: '8px',
+ padding: '2px 8px',
+ });
+ const check = el('span', {
+ fontSize: '15px', lineHeight: '1', flexShrink: '0',
+ color: 'oklch(45% 0.15 145)',
+ });
+ check.textContent = '\u2713';
+ row.appendChild(check);
+ const label = el('span', {
+ fontSize: '12px', color: 'oklch(35% 0.1 145)', fontWeight: '600',
+ });
+ label.textContent = 'Variant applied';
+ row.appendChild(label);
+ return row;
+ }
+
+ // --- Shared UI builders ---
+
+ function buildDots(clickable) {
+ const container = el('div', {
+ display: 'flex', alignItems: 'center', gap: '4px',
+ });
+ for (let i = 1; i <= expectedVariants; i++) {
+ const arrived = i <= arrivedVariants;
+ const active = i === visibleVariant;
+ const dot = el('div', {
+ width: '7px', height: '7px', borderRadius: '50%',
+ background: active ? C.brand : (arrived ? C.ash : 'transparent'),
+ border: '1.5px solid ' + (arrived ? C.brand : C.mist),
+ transition: 'all 0.2s ' + EASE,
+ cursor: (clickable && arrived) ? 'pointer' : 'default',
+ transform: arrived ? 'scale(1)' : 'scale(0.6)',
+ opacity: arrived ? '1' : '0.4',
+ });
+ if (clickable && arrived) {
+ const idx = i;
+ dot.addEventListener('click', (e) => {
+ e.stopPropagation();
+ visibleVariant = idx;
+ showVariantInDOM(currentSessionId, idx);
+ updateSelectedElement();
+ updateBarContent('cycling');
+ });
+ }
+ container.appendChild(dot);
+ }
+ return container;
+ }
+
+ function navBtn(text) {
+ const b = el('button', {
+ width: '26px', height: '26px', borderRadius: '5px',
+ border: '1px solid ' + C.mist, background: 'transparent',
+ color: C.ink, fontFamily: FONT, fontSize: '13px',
+ cursor: 'pointer', display: 'flex', alignItems: 'center', justifyContent: 'center',
+ transition: 'border-color 0.12s ease, background 0.12s ease',
+ padding: '0', lineHeight: '1',
+ });
+ b.textContent = text;
+ b.addEventListener('mouseenter', () => { b.style.borderColor = C.ink; });
+ b.addEventListener('mouseleave', () => { b.style.borderColor = C.mist; });
+ return b;
+ }
+
+ function actionLabel() {
+ const a = ACTIONS.find(a => a.value === selectedAction);
+ return a ? a.label : 'Freeform';
+ }
+
+ function el(tag, styles) {
+ const e = document.createElement(tag);
+ if (styles) Object.assign(e.style, styles);
+ return e;
+ }
+
+ // ---------------------------------------------------------------------------
+ // Action picker popover
+ // ---------------------------------------------------------------------------
+
+ function initActionPicker() {
+ pickerEl = document.createElement('div');
+ pickerEl.id = PREFIX + '-picker';
+ Object.assign(pickerEl.style, {
+ position: 'fixed', zIndex: Z.picker,
+ display: 'none', opacity: '0',
+ transform: 'scale(0.96) translateY(4px)',
+ transformOrigin: 'bottom left',
+ transition: 'opacity 0.18s ' + EASE + ', transform 0.2s ' + EASE,
+ background: C.paperSolid,
+ border: '1px solid ' + C.mist,
+ borderRadius: '10px',
+ boxShadow: '0 8px 30px oklch(0% 0 0 / 0.10), 0 2px 6px oklch(0% 0 0 / 0.06)',
+ padding: '6px',
+ fontFamily: FONT,
+ });
+
+ // Build the chip grid
+ const grid = el('div', {
+ display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', gap: '3px',
+ });
+
+ ACTIONS.forEach(action => {
+ const chip = el('button', {
+ padding: '6px 8px', borderRadius: '6px',
+ border: 'none',
+ background: action.value === selectedAction ? C.brandSoft : 'transparent',
+ color: action.value === selectedAction ? C.brand : C.ink,
+ fontFamily: FONT, fontSize: '11px', fontWeight: '500',
+ cursor: 'pointer',
+ transition: 'background 0.1s ease, color 0.1s ease',
+ textAlign: 'center', whiteSpace: 'nowrap',
+ });
+ chip.textContent = action.label;
+ chip.dataset.action = action.value;
+ chip.addEventListener('mouseenter', () => {
+ if (action.value !== selectedAction) chip.style.background = C.brandSoft;
+ });
+ chip.addEventListener('mouseleave', () => {
+ chip.style.background = action.value === selectedAction ? C.brandSoft : 'transparent';
+ });
+ chip.addEventListener('click', (e) => {
+ e.stopPropagation();
+ selectedAction = action.value;
+ hideActionPicker();
+ updateBarContent('configure');
+ });
+ grid.appendChild(chip);
+ });
+
+ pickerEl.appendChild(grid);
+ document.body.appendChild(pickerEl);
+ }
+
+ function toggleActionPicker() {
+ if (pickerEl.style.display !== 'none') { hideActionPicker(); return; }
+ // Rebuild chips to reflect current selection
+ pickerEl.querySelectorAll('button').forEach(chip => {
+ const isActive = chip.dataset.action === selectedAction;
+ chip.style.background = isActive ? C.brandSoft : 'transparent';
+ chip.style.color = isActive ? C.brand : C.ink;
+ });
+ // Position above the bar
+ const barRect = barEl.getBoundingClientRect();
+ const pickerH = 90; // approximate
+ let top = barRect.top - pickerH - 6;
+ if (top < 8) top = barRect.bottom + 6;
+ Object.assign(pickerEl.style, {
+ top: top + 'px', left: barRect.left + 'px',
+ display: 'block',
+ });
+ requestAnimationFrame(() => {
+ pickerEl.style.opacity = '1';
+ pickerEl.style.transform = 'scale(1) translateY(0)';
+ });
+ }
+
+ function hideActionPicker() {
+ if (!pickerEl) return;
+ pickerEl.style.opacity = '0';
+ pickerEl.style.transform = 'scale(0.96) translateY(4px)';
+ setTimeout(() => { if (pickerEl) pickerEl.style.display = 'none'; }, 180);
+ }
+
+ // ---------------------------------------------------------------------------
+ // Variant cycling in DOM
+ // ---------------------------------------------------------------------------
+
+ function showVariantInDOM(sessionId, num) {
+ const wrapper = document.querySelector('[data-impeccable-variants="' + sessionId + '"]');
+ if (!wrapper) return;
+ for (const child of wrapper.children) {
+ const v = child.dataset ? child.dataset.impeccableVariant : null;
+ if (!v) continue;
+ child.style.display = (v === String(num)) ? '' : 'none';
+ }
+ }
+
+ /**
+ * No-HMR fallback: fetch the raw source file from the live server,
+ * parse it, extract the variant wrapper, and inject it into the live DOM.
+ * This works even when the dev server caches HTML (Bun, static servers).
+ */
+ function injectVariantsFromSource(filePath, sessionId) {
+ const url = 'http://localhost:' + PORT + '/source?token=' + TOKEN + '&path=' + encodeURIComponent(filePath);
+ fetch(url)
+ .then(r => { if (!r.ok) throw new Error(r.status); return r.text(); })
+ .then(html => {
+ // Parse the raw source HTML
+ const parser = new DOMParser();
+ const doc = parser.parseFromString(html, 'text/html');
+ const srcWrapper = doc.querySelector('[data-impeccable-variants="' + sessionId + '"]');
+ if (!srcWrapper) {
+ console.error('[impeccable] Variant wrapper not found in source file.');
+ return;
+ }
+
+ // Find the original element in the live DOM.
+ // The original is inside the wrapper in the source. We find the
+ // corresponding element in the live DOM by matching the first child's
+ // tag + classes from the original snapshot.
+ const origContent = srcWrapper.querySelector('[data-impeccable-variant="original"] > :first-child');
+ if (!origContent) return;
+
+ const tag = origContent.tagName.toLowerCase();
+ const cls = origContent.className;
+ let liveEl = null;
+ if (origContent.id) {
+ liveEl = document.getElementById(origContent.id);
+ } else if (cls) {
+ // Find by tag + exact class match
+ const candidates = document.querySelectorAll(tag + '.' + cls.split(' ')[0]);
+ for (const c of candidates) {
+ if (c.className === cls && !own(c)) { liveEl = c; break; }
+ }
+ }
+
+ if (!liveEl) {
+ console.error('[impeccable] Could not find original element in live DOM.');
+ return;
+ }
+
+ // Replace the live element with the full wrapper from source
+ const wrapper = srcWrapper.cloneNode(true);
+ liveEl.parentElement.replaceChild(wrapper, liveEl);
+
+ // Update state: count variants, show the first one
+ 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);
+
+ // Update selectedElement to the visible variant's content
+ const visEl = wrapper.querySelector('[data-impeccable-variant="1"] > :first-child');
+ selectedElement = visEl || wrapper.parentElement;
+
+ state = 'CYCLING';
+ updateBarContent('cycling');
+ saveSession();
+ console.log('[impeccable] Injected ' + arrivedVariants + ' variants from source file.');
+ })
+ .catch(err => {
+ console.error('[impeccable] Failed to fetch source:', err);
+ showToast('Could not load variants. Try refreshing the page.', 5000);
+ });
+ }
+
+ function cycleVariant(dir) {
+ const next = visibleVariant + dir;
+ if (next < 1 || next > arrivedVariants) return;
+ visibleVariant = next;
+ showVariantInDOM(currentSessionId, next);
+ updateSelectedElement();
+ updateBarContent('cycling');
+ saveSession();
+ }
+
+ function updateSelectedElement() {
+ if (!currentSessionId) return;
+ const wrapper = document.querySelector('[data-impeccable-variants="' + currentSessionId + '"]');
+ if (!wrapper) return;
+ const visEl = wrapper.querySelector('[data-impeccable-variant="' + visibleVariant + '"] > :first-child');
+ if (visEl) selectedElement = visEl;
+ }
+
+ // ---------------------------------------------------------------------------
+ // MutationObserver for progressive variant reveal
+ // ---------------------------------------------------------------------------
+
+ function startVariantObserver(sessionId) {
+ let updating = false; // re-entrancy guard
+
+ const obs = new MutationObserver((mutations) => {
+ if (updating) return;
+
+ // Only react to mutations that add nodes with data-impeccable-variant,
+ // or mutations inside the variant wrapper. Ignore our own bar/UI changes.
+ let dominated = false;
+ for (const m of mutations) {
+ if (m.target.closest?.('[data-impeccable-variants]')) { dominated = true; break; }
+ for (const n of m.addedNodes) {
+ if (n.nodeType === 1 && (n.dataset?.impeccableVariants || n.dataset?.impeccableVariant)) {
+ dominated = true; break;
+ }
+ }
+ if (dominated) break;
+ }
+ if (!dominated) return;
+
+ const wrapper = document.querySelector('[data-impeccable-variants="' + sessionId + '"]');
+ if (!wrapper) return;
+
+ const variants = wrapper.querySelectorAll('[data-impeccable-variant]:not([data-impeccable-variant="original"])');
+ const count = variants.length;
+
+ // Nothing new
+ if (count <= arrivedVariants) return;
+
+ updating = true;
+ arrivedVariants = count;
+ if (visibleVariant === 0 && arrivedVariants > 0) {
+ visibleVariant = 1;
+ showVariantInDOM(sessionId, 1);
+ }
+
+ const expected = parseInt(wrapper.dataset.impeccableVariantCount || '0');
+ if (expected > 0) expectedVariants = expected;
+
+ if (arrivedVariants >= expectedVariants && expectedVariants > 0) {
+ state = 'CYCLING';
+ updateBarContent('cycling');
+ } else if (state === 'GENERATING') {
+ updateBarContent('generating');
+ }
+ saveSession();
+ updating = false;
+ });
+
+ obs.observe(document.body, { childList: true, subtree: true });
+ return obs;
+ }
+
+ // ---------------------------------------------------------------------------
+ // Bar scroll tracking
+ // ---------------------------------------------------------------------------
+
+ function startScrollTracking() {
+ function tick() {
+ if (state === 'CONFIGURING' || state === 'GENERATING' || state === 'CYCLING') {
+ positionBar();
+ showHighlight(selectedElement);
+ }
+ scrollRaf = requestAnimationFrame(tick);
+ }
+ scrollRaf = requestAnimationFrame(tick);
+ }
+
+ function stopScrollTracking() {
+ if (scrollRaf) { cancelAnimationFrame(scrollRaf); scrollRaf = null; }
+ }
+
+ // ---------------------------------------------------------------------------
+ // SSE (server→browser) + fetch POST (browser→server)
+ // Zero-dependency replacement for WebSocket.
+ // ---------------------------------------------------------------------------
+
+ let evtSource = null;
+
+ function connectSSE() {
+ evtSource = new EventSource('http://localhost:' + PORT + '/events?token=' + TOKEN);
+
+ evtSource.onmessage = (e) => {
+ let msg; try { msg = JSON.parse(e.data); } catch { return; }
+ switch (msg.type) {
+ case 'connected':
+ hasProjectContext = !!msg.hasProjectContext;
+ if (!hasProjectContext) showToast('No .impeccable.md found. Variants will be brand-agnostic.', 6000);
+ console.log('[impeccable] Live mode connected.');
+ if (state === 'IDLE') state = 'PICKING';
+ break;
+ case 'done':
+ if (state === 'SAVING') {
+ state = 'CONFIRMED';
+ updateBarContent('confirmed');
+ setTimeout(() => {
+ hideBar();
+ hideHighlight();
+ stopScrollTracking();
+ if (variantObserver) { variantObserver.disconnect(); variantObserver = null; }
+ clearSession();
+ selectedElement = null;
+ currentSessionId = null;
+ selectedAction = 'impeccable';
+ state = 'PICKING';
+ }, 1800);
+ return;
+ }
+ if (arrivedVariants === 0 && expectedVariants > 0 && msg.file) {
+ console.log('[impeccable] No HMR detected. Fetching variants from source file...');
+ injectVariantsFromSource(msg.file, currentSessionId);
+ return;
+ }
+ state = 'CYCLING';
+ updateBarContent('cycling');
+ break;
+ case 'error':
+ console.error('[impeccable] Error:', msg.message);
+ showToast('Error: ' + msg.message, 5000);
+ hideBar();
+ state = 'PICKING';
+ break;
+ }
+ };
+
+ evtSource.onerror = () => {
+ // EventSource auto-reconnects. Log once.
+ console.log('[impeccable] SSE connection lost. Reconnecting...');
+ };
+ }
+
+ function sendEvent(msg) {
+ msg.token = TOKEN;
+ 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));
+ }
+
+ // ---------------------------------------------------------------------------
+ // Event handlers
+ // ---------------------------------------------------------------------------
+
+ function handleMouseMove(e) {
+ if (state !== 'PICKING') return;
+ const target = document.elementFromPoint(e.clientX, e.clientY);
+ if (!target || !pickable(target) || target === hoveredElement) return;
+ hoveredElement = target;
+ showHighlight(target);
+ }
+
+ function handleClick(e) {
+ // Close action picker on any outside click
+ if (pickerEl?.style.display !== 'none' && !own(e.target)) {
+ hideActionPicker();
+ }
+ if (state !== 'PICKING') return;
+ if (own(e.target)) return;
+ if (!hoveredElement || !pickable(hoveredElement)) return;
+ e.preventDefault();
+ e.stopPropagation();
+ selectedElement = hoveredElement;
+ state = 'CONFIGURING';
+ showHighlight(selectedElement);
+ showBar('configure');
+ startScrollTracking();
+ }
+
+ function handleKeyDown(e) {
+ if (e.key === 'Escape') {
+ e.preventDefault();
+ if (pickerEl?.style.display !== 'none') { hideActionPicker(); return; }
+ if (state === 'CONFIGURING') { hideBar(); stopScrollTracking(); state = 'PICKING'; return; }
+ if (state === 'CYCLING') { handleDiscard(); return; }
+ if (state === 'SAVING' || state === 'CONFIRMED') return; // don't interrupt
+ if (state === 'PICKING') { hideHighlight(); state = 'IDLE'; return; }
+ }
+
+ if (state === 'PICKING' && hoveredElement) {
+ let next = null;
+ if (e.key === 'ArrowDown' && !e.shiftKey) {
+ next = hoveredElement.nextElementSibling;
+ while (next && !pickable(next)) next = next.nextElementSibling;
+ } else if (e.key === 'ArrowUp' && !e.shiftKey) {
+ next = hoveredElement.previousElementSibling;
+ while (next && !pickable(next)) next = next.previousElementSibling;
+ } else if (e.key === 'ArrowUp' && e.shiftKey) {
+ next = hoveredElement.parentElement;
+ if (next && !pickable(next)) next = null;
+ } else if (e.key === 'ArrowDown' && e.shiftKey) {
+ next = hoveredElement.firstElementChild;
+ while (next && !pickable(next)) next = next.nextElementSibling;
+ } else if (e.key === 'Enter') {
+ e.preventDefault();
+ selectedElement = hoveredElement;
+ state = 'CONFIGURING';
+ showHighlight(selectedElement);
+ showBar('configure');
+ startScrollTracking();
+ return;
+ }
+ if (next) {
+ e.preventDefault();
+ hoveredElement = next;
+ showHighlight(next);
+ next.scrollIntoView({ block: 'nearest', behavior: 'smooth' });
+ }
+ return;
+ }
+
+ if (state === 'CYCLING') {
+ if (e.key === 'ArrowLeft') { e.preventDefault(); cycleVariant(-1); }
+ if (e.key === 'ArrowRight') { e.preventDefault(); cycleVariant(1); }
+ if (e.key === 'Enter') { e.preventDefault(); handleAccept(); }
+ }
+ }
+
+ function handleGo() {
+ if (!selectedElement || state !== 'CONFIGURING') return;
+ const input = document.getElementById(PREFIX + '-input');
+ const prompt = input ? input.value.trim() : '';
+
+ currentSessionId = id8();
+ expectedVariants = selectedCount;
+ arrivedVariants = 0;
+ visibleVariant = 0;
+
+ sendEvent({
+ type: 'generate', id: currentSessionId,
+ action: selectedAction,
+ freeformPrompt: prompt || undefined,
+ count: selectedCount,
+ pageUrl: location.pathname,
+ element: extractContext(selectedElement),
+ });
+
+ state = 'GENERATING';
+ showBar('generating');
+ saveSession();
+ if (variantObserver) variantObserver.disconnect();
+ variantObserver = startVariantObserver(currentSessionId);
+ }
+
+ function handleAccept() {
+ if (!currentSessionId || arrivedVariants === 0) return;
+ sendEvent({ type: 'accept', id: currentSessionId, variantId: String(visibleVariant) });
+ markSessionHandled();
+ state = 'SAVING';
+ updateBarContent('saving');
+ // Don't cleanup yet — wait for the "done" WS message to show confirmation
+ }
+
+ function handleDiscard() {
+ if (!currentSessionId) return;
+ sendEvent({ type: 'discard', id: currentSessionId });
+ markSessionHandled();
+ state = 'SAVING';
+ updateBarContent('saving');
+ // Wait for "done" WS message to show confirmation and dismiss
+ }
+
+ // ---------------------------------------------------------------------------
+ // Session persistence via localStorage
+ // ---------------------------------------------------------------------------
+ // Survives page reloads, browser close/reopen, HMR, and accidental refreshes.
+
+ const LS_KEY = PREFIX + '-session';
+
+ function saveSession() {
+ if (!currentSessionId) return;
+ 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 */ }
+ }
+
+ function loadSession() {
+ try {
+ const raw = localStorage.getItem(LS_KEY);
+ return raw ? JSON.parse(raw) : null;
+ } catch { return null; }
+ }
+
+ function clearSession() {
+ try { localStorage.removeItem(LS_KEY); } catch {}
+ }
+
+ /** Mark session as handled (accepted/discarded). The agent will clean up
+ * the source, but until it does the wrapper is still in the HTML. This
+ * prevents resumeSession from picking it up again after reload. */
+ function markSessionHandled() {
+ if (!currentSessionId) return;
+ try {
+ localStorage.setItem(LS_KEY + '-handled', currentSessionId);
+ } catch {}
+ }
+
+ function isSessionHandled(id) {
+ try {
+ return localStorage.getItem(LS_KEY + '-handled') === id;
+ } catch { return false; }
+ }
+
+ function clearHandled() {
+ try { localStorage.removeItem(LS_KEY + '-handled'); } catch {}
+ }
+
+ function cleanup() {
+ hideBar();
+ hideHighlight();
+ stopScrollTracking();
+ if (variantObserver) { variantObserver.disconnect(); variantObserver = null; }
+ clearSession();
+ selectedElement = null;
+ currentSessionId = null;
+ selectedAction = 'impeccable';
+ state = 'PICKING';
+ }
+
+ // ---------------------------------------------------------------------------
+ // Toast
+ // ---------------------------------------------------------------------------
+
+ function showToast(message, duration) {
+ if (toastEl) toastEl.remove();
+ toastEl = el('div', {
+ position: 'fixed', bottom: '16px', left: '50%',
+ transform: 'translateX(-50%) translateY(8px)',
+ background: C.ink, color: C.white,
+ fontFamily: FONT, fontSize: '12px',
+ padding: '8px 16px', borderRadius: '8px',
+ zIndex: Z.toast, opacity: '0',
+ transition: 'opacity 0.25s ' + EASE + ', transform 0.25s ' + EASE,
+ pointerEvents: 'none', maxWidth: '420px', textAlign: 'center',
+ });
+ toastEl.id = PREFIX + '-toast';
+ toastEl.textContent = message;
+ document.body.appendChild(toastEl);
+ requestAnimationFrame(() => {
+ toastEl.style.opacity = '1';
+ toastEl.style.transform = 'translateX(-50%) translateY(0)';
+ });
+ setTimeout(() => {
+ if (toastEl) {
+ toastEl.style.opacity = '0';
+ toastEl.style.transform = 'translateX(-50%) translateY(8px)';
+ setTimeout(() => { if (toastEl) { toastEl.remove(); toastEl = null; } }, 250);
+ }
+ }, duration);
+ }
+
+ // ---------------------------------------------------------------------------
+ // Init
+ // ---------------------------------------------------------------------------
+
+ // Resume an active variant session after HMR/page reload.
+ // If a [data-impeccable-variants] wrapper exists in the DOM, the agent wrote
+ // variants before HMR fired. Pick up where we left off.
+ function resumeSession() {
+ const wrapper = document.querySelector('[data-impeccable-variants]');
+ if (!wrapper) { clearSession(); clearHandled(); return false; }
+
+ const sessionId = wrapper.dataset.impeccableVariants;
+
+ // Don't resume if this session was already accepted/discarded
+ if (isSessionHandled(sessionId)) return false;
+
+ currentSessionId = sessionId;
+ expectedVariants = parseInt(wrapper.dataset.impeccableVariantCount || '0');
+ const variants = wrapper.querySelectorAll('[data-impeccable-variant]:not([data-impeccable-variant="original"])');
+ arrivedVariants = variants.length;
+
+ // Restore visible variant from localStorage if available, else default to 1
+ const saved = loadSession();
+ visibleVariant = (saved && saved.id === sessionId && saved.visible > 0 && saved.visible <= arrivedVariants)
+ ? saved.visible : (arrivedVariants > 0 ? 1 : 0);
+
+ // Find the visible variant's content element for highlight positioning
+ const visEl = wrapper.querySelector('[data-impeccable-variant="' + visibleVariant + '"] > :first-child');
+ selectedElement = visEl || wrapper.parentElement;
+
+ // Set display state BEFORE starting observer (avoid triggering it)
+ if (visibleVariant > 0) showVariantInDOM(currentSessionId, visibleVariant);
+
+ state = arrivedVariants >= expectedVariants ? 'CYCLING' : 'GENERATING';
+ showBar(state === 'CYCLING' ? 'cycling' : 'generating');
+ startScrollTracking();
+ saveSession();
+
+ // Start observing for more variants AFTER initial setup
+ if (variantObserver) variantObserver.disconnect();
+ variantObserver = startVariantObserver(currentSessionId);
+ return true;
+ }
+
+ function init() {
+ initHighlight();
+ initBar();
+ initActionPicker();
+ document.addEventListener('mousemove', handleMouseMove, true);
+ document.addEventListener('click', handleClick, true);
+ document.addEventListener('keydown', handleKeyDown, true);
+ connectSSE();
+
+ // Check for an active session to resume (variant wrapper already in DOM after HMR)
+ if (!resumeSession()) {
+ console.log('[impeccable] Live variant mode ready. Hover over elements to pick one.');
+ } else {
+ console.log('[impeccable] Resumed active variant session ' + currentSessionId + ' (' + arrivedVariants + '/' + expectedVariants + ' variants).');
+ }
+ }
+
+ if (document.readyState === 'loading') {
+ document.addEventListener('DOMContentLoaded', init);
+ } else {
+ init();
+ }
+})();
diff --git a/.trae/skills/impeccable/scripts/live-poll.mjs b/.trae/skills/impeccable/scripts/live-poll.mjs
new file mode 100644
index 000000000..52859416c
--- /dev/null
+++ b/.trae/skills/impeccable/scripts/live-poll.mjs
@@ -0,0 +1,123 @@
+/**
+ * CLI client for the live variant mode poll/reply protocol.
+ *
+ * Usage:
+ * npx impeccable poll # Block until browser event, print JSON
+ * npx impeccable poll --timeout=60000 # Custom timeout (ms)
+ * npx impeccable poll --reply <id> done # Reply "done" to event <id>
+ * npx impeccable poll --reply <id> error "msg" # Reply with error
+ */
+
+import fs from 'node:fs';
+import path from 'node:path';
+import os from 'node:os';
+
+const LIVE_PID_FILE = path.join(os.tmpdir(), 'impeccable-live.json');
+
+function readServerInfo() {
+ try {
+ return JSON.parse(fs.readFileSync(LIVE_PID_FILE, 'utf-8'));
+ } catch {
+ console.error('No running live server found. Start one with: npx impeccable live');
+ process.exit(1);
+ }
+}
+
+export async function pollCli() {
+ const args = process.argv.slice(2);
+
+ if (args.includes('--help') || args.includes('-h')) {
+ console.log(`Usage: impeccable poll [options]
+
+Wait for a browser event from the live variant server, or reply to one.
+
+Modes:
+ poll Block until a browser event arrives, print JSON
+ poll --reply <id> done Reply "done" to event <id>
+ poll --reply <id> error "msg" Reply with an error message
+
+Options:
+ --timeout=MS Poll timeout in milliseconds (default: 120000)
+ --help Show this help message`);
+ process.exit(0);
+ }
+
+ const info = readServerInfo();
+ const base = `http://localhost:${info.port}`;
+
+ // Reply mode: npx impeccable poll --reply <id> <status> [--file path] [message]
+ const replyIdx = args.indexOf('--reply');
+ if (replyIdx !== -1) {
+ const id = args[replyIdx + 1];
+ const status = args[replyIdx + 2] || 'done';
+ const fileIdx = args.indexOf('--file');
+ const filePath = fileIdx !== -1 && fileIdx + 1 < args.length ? args[fileIdx + 1] : undefined;
+ // Message is any remaining positional arg that isn't a flag
+ const message = args.find((a, i) => i > replyIdx + 2 && !a.startsWith('--') && i !== fileIdx + 1) || undefined;
+
+ if (!id) {
+ console.error('Usage: npx impeccable poll --reply <id> <status> [--file path] [message]');
+ process.exit(1);
+ }
+
+ 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);
+ }
+
+ // Success — silent exit (agent doesn't need output for replies)
+ } catch (err) {
+ if (err.cause?.code === 'ECONNREFUSED') {
+ console.error('Live server not running. Start one with: npx impeccable live');
+ } else {
+ console.error('Reply failed:', err.message);
+ }
+ process.exit(1);
+ }
+ return;
+ }
+
+ // Poll mode: block until browser event
+ const timeoutArg = args.find(a => a.startsWith('--timeout='));
+ const timeout = timeoutArg ? parseInt(timeoutArg.split('=')[1], 10) : 120000;
+
+ try {
+ const res = await fetch(`${base}/poll?token=${info.token}&timeout=${timeout}`);
+
+ if (res.status === 401) {
+ console.error('Authentication failed. The server token may have changed.');
+ console.error('Try restarting: npx impeccable live stop && npx impeccable live');
+ process.exit(1);
+ }
+
+ if (!res.ok) {
+ console.error(`Poll failed: ${res.status} ${res.statusText}`);
+ process.exit(1);
+ }
+
+ const event = await res.json();
+ // Print the event as JSON — the agent reads this from stdout
+ console.log(JSON.stringify(event));
+ } catch (err) {
+ if (err.cause?.code === 'ECONNREFUSED') {
+ console.error('Live server not running. Start one with: npx impeccable live');
+ } else {
+ console.error('Poll failed:', err.message);
+ }
+ process.exit(1);
+ }
+}
diff --git a/.trae/skills/impeccable/scripts/live-server.mjs b/.trae/skills/impeccable/scripts/live-server.mjs
new file mode 100644
index 000000000..d436bad58
--- /dev/null
+++ b/.trae/skills/impeccable/scripts/live-server.mjs
@@ -0,0 +1,416 @@
+#!/usr/bin/env node
+/**
+ * Live variant mode server (self-contained, zero dependencies).
+ *
+ * Serves the browser script (/live.js), the detection overlay (/detect.js),
+ * uses Server-Sent Events (SSE) for server→browser push, and HTTP POST for
+ * browser→server events. Agent communicates via HTTP long-poll (/poll).
+ *
+ * Usage:
+ * node <scripts_path>/live-server.mjs # start
+ * node <scripts_path>/live-server.mjs stop # stop
+ * node <scripts_path>/live-server.mjs --help
+ */
+
+import http from 'node:http';
+import { randomUUID } from 'node:crypto';
+import fs from 'node:fs';
+import path from 'node:path';
+import os from 'node:os';
+import net from 'node:net';
+import { fileURLToPath } from 'node:url';
+
+const __dirname = path.dirname(fileURLToPath(import.meta.url));
+const LIVE_PID_FILE = path.join(os.tmpdir(), 'impeccable-live.json');
+const DEFAULT_POLL_TIMEOUT = 120_000;
+
+// ---------------------------------------------------------------------------
+// Port detection
+// ---------------------------------------------------------------------------
+
+async function findOpenPort(start = 8400) {
+ return new Promise((resolve) => {
+ const srv = net.createServer();
+ srv.listen(start, '127.0.0.1', () => {
+ const port = srv.address().port;
+ srv.close(() => resolve(port));
+ });
+ srv.on('error', () => resolve(findOpenPort(start + 1)));
+ });
+}
+
+// ---------------------------------------------------------------------------
+// Session state
+// ---------------------------------------------------------------------------
+
+const state = {
+ token: null,
+ port: null,
+ sseClients: new Set(), // SSE response objects (server→browser push)
+ pendingEvents: [], // browser events waiting for agent poll
+ pendingPolls: [], // agent poll callbacks waiting for browser events
+ exitTimer: null,
+};
+
+function enqueueEvent(event) {
+ if (state.pendingPolls.length > 0) {
+ state.pendingPolls.shift()(event);
+ } else {
+ state.pendingEvents.push(event);
+ }
+}
+
+/** Push a message to all connected SSE clients. */
+function broadcast(msg) {
+ const data = 'data: ' + JSON.stringify(msg) + '\n\n';
+ for (const res of state.sseClients) {
+ try { res.write(data); } catch { /* client gone */ }
+ }
+}
+
+// ---------------------------------------------------------------------------
+// Load scripts
+// ---------------------------------------------------------------------------
+
+function loadBrowserScripts() {
+ // Detection script: look relative to the skill scripts dir, then fall back
+ // to the npm package location (src/detect-antipatterns-browser.js)
+ const detectPaths = [
+ path.join(__dirname, '..', '..', '..', '..', 'src', 'detect-antipatterns-browser.js'),
+ path.join(process.cwd(), 'node_modules', 'impeccable', 'src', 'detect-antipatterns-browser.js'),
+ ];
+ let detectScript = '';
+ for (const p of detectPaths) {
+ try { detectScript = fs.readFileSync(p, 'utf-8'); break; } catch { /* try next */ }
+ }
+
+ const livePath = path.join(__dirname, 'live-browser.js');
+ let liveScript = '';
+ try {
+ liveScript = fs.readFileSync(livePath, 'utf-8');
+ } catch {
+ process.stderr.write('Error: live-browser.js not found at ' + livePath + '\n');
+ process.exit(1);
+ }
+
+ return { detectScript, liveScript };
+}
+
+function hasProjectContext() {
+ try {
+ fs.accessSync(path.join(process.cwd(), '.impeccable.md'), fs.constants.R_OK);
+ return true;
+ } catch { return false; }
+}
+
+// ---------------------------------------------------------------------------
+// Validation (inline — no external import needed for self-contained script)
+// ---------------------------------------------------------------------------
+
+const VISUAL_ACTIONS = [
+ 'impeccable', 'bolder', 'quieter', 'distill', 'polish', 'typeset',
+ 'colorize', 'layout', 'adapt', 'animate', 'delight', 'overdrive',
+];
+
+function validateEvent(msg) {
+ if (!msg || typeof msg !== 'object' || !msg.type) return 'Missing or invalid message';
+ switch (msg.type) {
+ case 'generate':
+ if (!msg.id || typeof msg.id !== 'string') return 'generate: missing id';
+ if (!msg.action || !VISUAL_ACTIONS.includes(msg.action)) return 'generate: invalid action';
+ if (!Number.isInteger(msg.count) || msg.count < 1 || msg.count > 8) return 'generate: count must be 1-8';
+ if (!msg.element || !msg.element.outerHTML) return 'generate: missing element context';
+ return null;
+ case 'accept':
+ if (!msg.id) return 'accept: missing id';
+ if (!msg.variantId) return 'accept: missing variantId';
+ return null;
+ case 'discard':
+ return msg.id ? null : 'discard: missing id';
+ case 'exit':
+ return null;
+ default:
+ return 'Unknown event type: ' + msg.type;
+ }
+}
+
+// ---------------------------------------------------------------------------
+// HTTP request handler
+// ---------------------------------------------------------------------------
+
+function createRequestHandler({ detectScript, liveScriptWithToken }) {
+ return (req, res) => {
+ const url = new URL(req.url, `http://localhost:${state.port}`);
+ res.setHeader('Access-Control-Allow-Origin', '*');
+ res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS');
+ res.setHeader('Access-Control-Allow-Headers', 'Content-Type');
+ if (req.method === 'OPTIONS') { res.writeHead(204); res.end(); return; }
+
+ const p = url.pathname;
+
+ // --- Scripts ---
+ if (p === '/live.js') {
+ res.writeHead(200, { 'Content-Type': 'application/javascript' });
+ res.end(liveScriptWithToken);
+ return;
+ }
+ if (p === '/detect.js' || p === '/') {
+ if (!detectScript) { res.writeHead(404); res.end('Not available'); return; }
+ res.writeHead(200, { 'Content-Type': 'application/javascript' });
+ res.end(detectScript);
+ return;
+ }
+
+ // --- Health ---
+ if (p === '/health') {
+ res.writeHead(200, { 'Content-Type': 'application/json' });
+ res.end(JSON.stringify({
+ status: 'ok', port: state.port, mode: 'variant',
+ hasProjectContext: hasProjectContext(),
+ connectedClients: state.sseClients.size,
+ }));
+ return;
+ }
+
+ // --- Source file (no-HMR fallback) ---
+ if (p === '/source') {
+ const token = url.searchParams.get('token');
+ if (token !== state.token) { res.writeHead(401); res.end('Unauthorized'); return; }
+ const filePath = url.searchParams.get('path');
+ if (!filePath || filePath.includes('..')) { res.writeHead(400); res.end('Bad path'); return; }
+ const absPath = path.resolve(process.cwd(), filePath);
+ if (!absPath.startsWith(process.cwd())) { res.writeHead(403); res.end('Forbidden'); return; }
+ try {
+ res.writeHead(200, { 'Content-Type': 'text/html; charset=utf-8' });
+ res.end(fs.readFileSync(absPath, 'utf-8'));
+ } catch { res.writeHead(404); res.end('File not found'); }
+ return;
+ }
+
+ // --- SSE: server→browser push (replaces WebSocket) ---
+ if (p === '/events' && req.method === 'GET') {
+ const token = url.searchParams.get('token');
+ if (token !== state.token) { res.writeHead(401); res.end('Unauthorized'); return; }
+ res.writeHead(200, {
+ 'Content-Type': 'text/event-stream',
+ 'Cache-Control': 'no-cache',
+ 'Connection': 'keep-alive',
+ });
+ res.write('data: ' + JSON.stringify({
+ type: 'connected',
+ hasProjectContext: hasProjectContext(),
+ }) + '\n\n');
+
+ state.sseClients.add(res);
+ clearTimeout(state.exitTimer);
+
+ req.on('close', () => {
+ state.sseClients.delete(res);
+ if (state.sseClients.size === 0) {
+ clearTimeout(state.exitTimer);
+ state.exitTimer = setTimeout(() => {
+ if (state.sseClients.size === 0) enqueueEvent({ type: 'exit' });
+ }, 8000);
+ }
+ });
+ return;
+ }
+
+ // --- Browser→server events (replaces WebSocket messages) ---
+ if (p === '/events' && req.method === 'POST') {
+ let body = '';
+ req.on('data', (c) => { body += c; });
+ req.on('end', () => {
+ let msg;
+ try { msg = JSON.parse(body); } catch {
+ res.writeHead(400, { 'Content-Type': 'application/json' });
+ res.end(JSON.stringify({ error: 'Invalid JSON' }));
+ return;
+ }
+ if (msg.token !== state.token) {
+ res.writeHead(401, { 'Content-Type': 'application/json' });
+ res.end(JSON.stringify({ error: 'Unauthorized' }));
+ return;
+ }
+ const error = validateEvent(msg);
+ if (error) {
+ res.writeHead(400, { 'Content-Type': 'application/json' });
+ res.end(JSON.stringify({ error }));
+ return;
+ }
+ enqueueEvent(msg);
+ res.writeHead(200, { 'Content-Type': 'application/json' });
+ res.end(JSON.stringify({ ok: true }));
+ });
+ return;
+ }
+
+ // --- Stop ---
+ if (p === '/stop') {
+ const token = url.searchParams.get('token');
+ if (token !== state.token) { res.writeHead(401); res.end('Unauthorized'); return; }
+ res.writeHead(200, { 'Content-Type': 'text/plain' });
+ res.end('stopping');
+ shutdown();
+ return;
+ }
+
+ // --- Agent poll ---
+ if (p === '/poll' && req.method === 'GET') {
+ handlePollGet(req, res, url);
+ return;
+ }
+ if (p === '/poll' && req.method === 'POST') {
+ handlePollPost(req, res);
+ return;
+ }
+
+ res.writeHead(404); res.end('Not found');
+ };
+}
+
+// ---------------------------------------------------------------------------
+// Agent poll endpoints (unchanged from WS version)
+// ---------------------------------------------------------------------------
+
+function handlePollGet(req, res, url) {
+ 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 timeout = parseInt(url.searchParams.get('timeout') || DEFAULT_POLL_TIMEOUT, 10);
+ if (state.pendingEvents.length > 0) {
+ res.writeHead(200, { 'Content-Type': 'application/json' });
+ res.end(JSON.stringify(state.pendingEvents.shift()));
+ return;
+ }
+ const timer = setTimeout(() => {
+ const idx = state.pendingPolls.indexOf(resolve);
+ if (idx !== -1) state.pendingPolls.splice(idx, 1);
+ res.writeHead(200, { 'Content-Type': 'application/json' });
+ res.end(JSON.stringify({ type: 'timeout' }));
+ }, timeout);
+ function resolve(event) {
+ clearTimeout(timer);
+ res.writeHead(200, { 'Content-Type': 'application/json' });
+ res.end(JSON.stringify(event));
+ }
+ state.pendingPolls.push(resolve);
+ req.on('close', () => {
+ clearTimeout(timer);
+ const idx = state.pendingPolls.indexOf(resolve);
+ if (idx !== -1) state.pendingPolls.splice(idx, 1);
+ });
+}
+
+function handlePollPost(req, res) {
+ let body = '';
+ req.on('data', (c) => { body += c; });
+ req.on('end', () => {
+ let msg;
+ try { msg = JSON.parse(body); } catch {
+ res.writeHead(400, { 'Content-Type': 'application/json' });
+ res.end(JSON.stringify({ error: 'Invalid JSON' }));
+ return;
+ }
+ if (msg.token !== state.token) {
+ res.writeHead(401, { 'Content-Type': 'application/json' });
+ res.end(JSON.stringify({ error: 'Unauthorized' }));
+ return;
+ }
+ // Forward the reply to the browser via SSE
+ broadcast({ type: msg.type || 'done', id: msg.id, message: msg.message, file: msg.file, data: msg.data });
+ res.writeHead(200, { 'Content-Type': 'application/json' });
+ res.end(JSON.stringify({ ok: true }));
+ });
+}
+
+// ---------------------------------------------------------------------------
+// Lifecycle
+// ---------------------------------------------------------------------------
+
+let httpServer = null;
+
+function shutdown() {
+ try { fs.unlinkSync(LIVE_PID_FILE); } catch {}
+ for (const res of state.sseClients) { try { res.end(); } catch {} }
+ state.sseClients.clear();
+ for (const resolve of state.pendingPolls) resolve({ type: 'exit' });
+ state.pendingPolls.length = 0;
+ if (httpServer) httpServer.close();
+ process.exit(0);
+}
+
+// ---------------------------------------------------------------------------
+// Main
+// ---------------------------------------------------------------------------
+
+const args = process.argv.slice(2);
+
+if (args.includes('--help') || args.includes('-h')) {
+ console.log(`Usage: node live-server.mjs [options]
+
+Start the live variant mode server (zero dependencies).
+
+Commands:
+ (default) Start the server
+ stop Stop a running server
+
+Options:
+ --port=PORT Use a specific port (default: auto-detect starting at 8400)
+ --help Show this help
+
+Endpoints:
+ /live.js Browser script (element picker + variant cycling)
+ /detect.js Detection overlay (backwards compatible)
+ /events SSE stream (server→browser) + POST (browser→server)
+ /poll Long-poll for agent CLI
+ /source Raw source file reader (no-HMR fallback)
+ /health Health check`);
+ process.exit(0);
+}
+
+if (args.includes('stop')) {
+ try {
+ const info = JSON.parse(fs.readFileSync(LIVE_PID_FILE, 'utf-8'));
+ 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 { console.log('No running live server found.'); }
+ process.exit(0);
+}
+
+// Check for existing session
+try {
+ const existing = JSON.parse(fs.readFileSync(LIVE_PID_FILE, 'utf-8'));
+ 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 {}
+
+state.token = randomUUID();
+const portArg = args.find(a => a.startsWith('--port='));
+state.port = portArg ? parseInt(portArg.split('=')[1], 10) : await findOpenPort();
+
+const { detectScript, liveScript } = loadBrowserScripts();
+const liveScriptWithToken =
+ `window.__IMPECCABLE_TOKEN__ = '${state.token}';\n` +
+ `window.__IMPECCABLE_PORT__ = ${state.port};\n` +
+ liveScript;
+
+httpServer = http.createServer(createRequestHandler({ detectScript, liveScriptWithToken }));
+
+httpServer.listen(state.port, '127.0.0.1', () => {
+ fs.writeFileSync(LIVE_PID_FILE, JSON.stringify({ 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`);
+ console.log(`Inject: <script src="${url}/live.js"><\/script>`);
+ console.log(`Stop: node ${path.basename(fileURLToPath(import.meta.url))} stop`);
+});
+
+process.on('SIGINT', shutdown);
+process.on('SIGTERM', shutdown);
diff --git a/.trae/skills/impeccable/scripts/live-wrap.mjs b/.trae/skills/impeccable/scripts/live-wrap.mjs
new file mode 100644
index 000000000..f1c838cdd
--- /dev/null
+++ b/.trae/skills/impeccable/scripts/live-wrap.mjs
@@ -0,0 +1,298 @@
+/**
+ * CLI helper: find an element in source and wrap it in a variant container.
+ *
+ * Usage:
+ * npx impeccable wrap --id SESSION_ID --count N --query "hero-combined-left" [--file path]
+ *
+ * Searches project files for the element matching the query (class name, ID, or
+ * text snippet), wraps it with the variant scaffolding, and prints the file path
+ * + line range where the agent should insert variant HTML.
+ *
+ * This replaces 3-4 agent tool calls (grep + read + edit) with a single CLI call.
+ */
+
+import fs from 'node:fs';
+import path from 'node:path';
+
+const EXTENSIONS = ['.html', '.jsx', '.tsx', '.vue', '.svelte', '.astro'];
+
+export async function wrapCli() {
+ const args = process.argv.slice(2);
+
+ if (args.includes('--help') || args.includes('-h')) {
+ console.log(`Usage: impeccable wrap [options]
+
+Find an element in source and wrap it in a variant container.
+
+Required:
+ --id ID Session ID for the variant wrapper
+ --count N Number of expected variants (1-8)
+
+Element identification (at least one required):
+ --element-id ID HTML id attribute of the element
+ --classes A,B,C Comma-separated CSS class names
+ --tag TAG Tag name (div, section, etc.)
+ --query TEXT Fallback: raw text to search for
+
+Optional:
+ --file PATH Source file to search in (skips auto-detection)
+ --help Show this help message
+
+Output (JSON):
+ { file, startLine, endLine, insertLine, commentSyntax }
+
+The agent should insert variant HTML at insertLine.`);
+ process.exit(0);
+ }
+
+ const id = argVal(args, '--id');
+ const count = parseInt(argVal(args, '--count') || '3');
+ const elementId = argVal(args, '--element-id');
+ const classes = argVal(args, '--classes');
+ const tag = argVal(args, '--tag');
+ const query = argVal(args, '--query');
+ const filePath = argVal(args, '--file');
+
+ if (!id) { console.error('Missing --id'); process.exit(1); }
+ if (!elementId && !classes && !query) {
+ console.error('Need at least one of: --element-id, --classes, --query');
+ process.exit(1);
+ }
+
+ // Build search queries in priority order (most specific first)
+ const queries = buildSearchQueries(elementId, classes, tag, query);
+
+ // Find the source file
+ let targetFile = filePath;
+ let matchedQuery = null;
+ if (!targetFile) {
+ for (const q of queries) {
+ targetFile = findFileWithQuery(q, process.cwd());
+ if (targetFile) { matchedQuery = q; break; }
+ }
+ if (!targetFile) {
+ console.error(JSON.stringify({ error: 'Could not find element in project files. Searched for: ' + queries.join(', ') }));
+ process.exit(1);
+ }
+ } else {
+ matchedQuery = queries[0];
+ }
+
+ const content = fs.readFileSync(targetFile, 'utf-8');
+ const lines = content.split('\n');
+
+ // Find the element, trying each query in priority order
+ let match = null;
+ for (const q of queries) {
+ match = findElement(lines, q);
+ if (match) break;
+ }
+ if (!match) {
+ console.error(JSON.stringify({ error: 'Found file but could not locate element in ' + targetFile + '. Searched for: ' + queries.join(', ') }));
+ process.exit(1);
+ }
+
+ const { startLine, endLine } = match;
+ const commentSyntax = detectCommentSyntax(targetFile);
+ const indent = lines[startLine].match(/^(\s*)/)[1];
+
+ // Extract the original element
+ const originalLines = lines.slice(startLine, endLine + 1);
+ const originalIndented = originalLines.map(l => indent + ' ' + l.trimStart()).join('\n');
+
+ // Build the wrapper
+ const wrapperLines = [
+ indent + commentSyntax.open + ' impeccable-variants-start ' + id + ' ' + commentSyntax.close,
+ indent + '<div data-impeccable-variants="' + id + '" data-impeccable-variant-count="' + count + '" style="display: contents">',
+ indent + ' ' + commentSyntax.open + ' Original ' + commentSyntax.close,
+ indent + ' <div data-impeccable-variant="original">',
+ originalIndented,
+ indent + ' </div>',
+ indent + ' ' + commentSyntax.open + ' Variants: insert below this line ' + commentSyntax.close,
+ indent + '</div>',
+ indent + commentSyntax.open + ' impeccable-variants-end ' + id + ' ' + commentSyntax.close,
+ ];
+
+ // Replace the original element with the wrapper
+ const newLines = [
+ ...lines.slice(0, startLine),
+ ...wrapperLines,
+ ...lines.slice(endLine + 1),
+ ];
+ fs.writeFileSync(targetFile, newLines.join('\n'), 'utf-8');
+
+ // Calculate insert line (the "insert below this line" comment)
+ const insertLine = startLine + 6; // 0-indexed in the new file
+
+ console.log(JSON.stringify({
+ file: path.relative(process.cwd(), targetFile),
+ startLine: startLine + 1, // 1-indexed for the agent
+ endLine: startLine + wrapperLines.length, // 1-indexed
+ insertLine: insertLine + 1, // 1-indexed: where variants go
+ commentSyntax: commentSyntax,
+ originalLineCount: originalLines.length,
+ }));
+}
+
+// ---------------------------------------------------------------------------
+// Helpers
+// ---------------------------------------------------------------------------
+
+function argVal(args, flag) {
+ const idx = args.indexOf(flag);
+ return idx !== -1 && idx + 1 < args.length ? args[idx + 1] : null;
+}
+
+/**
+ * Build search query strings in priority order (most specific first).
+ * ID is most reliable, then specific class combos, then single classes, then raw query.
+ */
+function buildSearchQueries(elementId, classes, tag, query) {
+ const queries = [];
+
+ // 1. ID is the most specific
+ if (elementId) {
+ queries.push('id="' + elementId + '"');
+ }
+
+ // 2. Full class attribute match (for elements with distinctive multi-class combos)
+ if (classes) {
+ const classList = classes.split(',').map(c => c.trim()).filter(Boolean);
+ if (classList.length > 1) {
+ // Try the most distinctive class first (longest, most specific)
+ const sorted = [...classList].sort((a, b) => b.length - a.length);
+ queries.push('class="' + classList.join(' ') + '"'); // exact full match
+ queries.push(sorted[0]); // most distinctive single class
+ } else if (classList.length === 1) {
+ queries.push(classList[0]);
+ }
+ }
+
+ // 3. Tag + class combo (e.g., <section class="hero">)
+ if (tag && classes) {
+ const firstClass = classes.split(',')[0].trim();
+ queries.push('<' + tag + ' class="' + firstClass);
+ }
+
+ // 4. Raw fallback query
+ if (query) {
+ queries.push(query);
+ }
+
+ return queries;
+}
+
+function detectCommentSyntax(filePath) {
+ const ext = path.extname(filePath).toLowerCase();
+ if (ext === '.jsx' || ext === '.tsx') {
+ return { open: '{/*', close: '*/}' };
+ }
+ // HTML, Vue, Svelte, Astro all use HTML comments
+ return { open: '<!--', close: '-->' };
+}
+
+/**
+ * Search project files for the query string (class name, ID, etc.)
+ * Returns the first matching file path, or null.
+ */
+function findFileWithQuery(query, cwd) {
+ const searchDirs = ['src', 'app', 'pages', 'components', 'public', 'views', 'templates', '.'];
+ const seen = new Set();
+
+ for (const dir of searchDirs) {
+ const absDir = path.join(cwd, dir);
+ if (!fs.existsSync(absDir)) continue;
+ const result = searchDir(absDir, query, seen, 0);
+ if (result) return result;
+ }
+ return null;
+}
+
+function searchDir(dir, query, seen, depth) {
+ if (depth > 5) return null; // don't go too deep
+ const realDir = fs.realpathSync(dir);
+ if (seen.has(realDir)) return null;
+ seen.add(realDir);
+
+ let entries;
+ try { entries = fs.readdirSync(dir, { withFileTypes: true }); }
+ catch { return null; }
+
+ // Check files first
+ for (const entry of entries) {
+ if (!entry.isFile()) continue;
+ const ext = path.extname(entry.name).toLowerCase();
+ if (!EXTENSIONS.includes(ext)) continue;
+
+ const filePath = path.join(dir, entry.name);
+ try {
+ const content = fs.readFileSync(filePath, 'utf-8');
+ if (content.includes(query)) return filePath;
+ } catch { /* skip unreadable files */ }
+ }
+
+ // Then recurse into directories
+ for (const entry of entries) {
+ if (!entry.isDirectory()) continue;
+ if (entry.name === 'node_modules' || entry.name === '.git' || entry.name === 'dist' || entry.name === 'build') continue;
+ const result = searchDir(path.join(dir, entry.name), query, seen, depth + 1);
+ if (result) return result;
+ }
+
+ return null;
+}
+
+/**
+ * Find the element's start and end line in the file.
+ * The query is a class name, ID, or text snippet.
+ * We find the line containing the query, then find the matching closing tag.
+ */
+function findElement(lines, query) {
+ // Find the line containing the query
+ let startLine = -1;
+ for (let i = 0; i < lines.length; i++) {
+ if (lines[i].includes(query)) {
+ // Make sure this looks like a tag opening, not a comment or string
+ const line = lines[i].trim();
+ if (line.startsWith('<!--') || line.startsWith('{/*') || line.startsWith('//')) continue;
+ // Skip lines inside data-impeccable-variant containers (already wrapped)
+ if (lines[i].includes('data-impeccable-variant')) continue;
+ startLine = i;
+ break;
+ }
+ }
+
+ if (startLine === -1) return null;
+
+ // Find the end of this element by counting open/close tags
+ const endLine = findClosingLine(lines, startLine);
+ return { startLine, endLine };
+}
+
+/**
+ * Starting from a line with an opening tag, find the line with the matching
+ * closing tag by counting tag nesting depth.
+ */
+function findClosingLine(lines, start) {
+ // Extract the tag name from the opening line
+ const openMatch = lines[start].match(/<(\w+)[\s>]/);
+ if (!openMatch) return start; // self-closing or text-only line
+
+ const tagName = openMatch[1];
+ let depth = 0;
+
+ for (let i = start; i < lines.length; i++) {
+ const line = lines[i];
+ // Count opening tags (not self-closing)
+ const opens = (line.match(new RegExp('<' + tagName + '[\\s>]', 'g')) || []).length;
+ const selfCloses = (line.match(new RegExp('<' + tagName + '[^>]*/>', 'g')) || []).length;
+ const closes = (line.match(new RegExp('</' + tagName + '\\s*>', 'g')) || []).length;
+
+ depth += opens - selfCloses - closes;
+
+ if (depth <= 0) return i;
+ }
+
+ // If we can't find the close, return a reasonable guess
+ return Math.min(start + 50, lines.length - 1);
+}
diff --git a/bin/cli.js b/bin/cli.js
index beb16a1b2..b3aa1f37c 100755
--- a/bin/cli.js
+++ b/bin/cli.js
@@ -53,16 +53,16 @@ if (command === 'detect') {
const { detectCli } = await import('../src/detect-antipatterns.mjs');
await detectCli();
} else if (command === 'live') {
+ // Delegate to the self-contained skill script (also works via node scripts_path/live-server.mjs)
process.argv = [process.argv[0], process.argv[1], ...args.slice(1)];
- const { liveCli } = await import('../src/detect-antipatterns.mjs');
- await liveCli();
+ await import('../source/skills/impeccable/scripts/live-server.mjs');
} else if (command === 'poll') {
process.argv = [process.argv[0], process.argv[1], ...args.slice(1)];
- const { pollCli } = await import('../src/live/poll.mjs');
+ const { pollCli } = await import('../source/skills/impeccable/scripts/live-poll.mjs');
await pollCli();
} else if (command === 'wrap') {
process.argv = [process.argv[0], process.argv[1], ...args.slice(1)];
- const { wrapCli } = await import('../src/live/wrap.mjs');
+ const { wrapCli } = await import('../source/skills/impeccable/scripts/live-wrap.mjs');
await wrapCli();
} else if (command === 'skills') {
const { run } = await import('./commands/skills.mjs');
diff --git a/package.json b/package.json
index 0a8a6a383..a5bcb7c6a 100644
--- a/package.json
+++ b/package.json
@@ -57,8 +57,7 @@
},
"dependencies": {
"jsdom": "^29.0.0",
- "marked": "^16.1.0",
- "ws": "^8.20.0"
+ "marked": "^16.1.0"
},
"optionalDependencies": {
"puppeteer": "^24.39.1"
diff --git a/source/skills/impeccable/reference/live.md b/source/skills/impeccable/reference/live.md
index 6f7a1e1de..ba0e9b0c5 100644
--- a/source/skills/impeccable/reference/live.md
+++ b/source/skills/impeccable/reference/live.md
@@ -10,7 +10,7 @@ Launch interactive live variant mode: select elements in the browser, pick a des
1. Read `.impeccable.md` if it exists. Keep the design context in mind for variant generation.
2. Start the live variant server:
```bash
- npx impeccable live &
+ node {{scripts_path}}/live-server.mjs &
```
3. Note the **port** and **token** printed to stdout.
@@ -53,7 +53,7 @@ Run a blocking poll loop. On each iteration, wait for a browser event and respon
```
LOOP:
- Run: npx impeccable poll
+ Run: node {{scripts_path}}/live-poll.mjs
Read the JSON output. Dispatch based on the "type" field:
TYPE "generate":
@@ -85,7 +85,7 @@ The event contains: `{id, action, freeformPrompt, count, pageUrl, element}`.
Use the `wrap` helper to find the element and create the variant container:
```bash
-npx impeccable wrap --id EVENT_ID --count EVENT_COUNT --element-id "ELEMENT_ID" --classes "class1,class2" --tag "div"
+node {{scripts_path}}/live-wrap.mjs --id EVENT_ID --count EVENT_COUNT --element-id "ELEMENT_ID" --classes "class1,class2" --tag "div"
```
Pass the element's id (`event.element.id`), classes (`event.element.classes` joined with commas), and tag name. The command searches in priority order: ID match first, then class names, then tag+class combo. If `event.pageUrl` hints at the file (e.g., `/` is usually `index.html`), pass `--file PATH` to skip the search.
@@ -139,7 +139,7 @@ The first variant should NOT have `style="display: none"` (it should be visible
Include `--file` so the browser can fetch variants directly if the dev server lacks HMR:
```bash
-npx impeccable poll --reply EVENT_ID done --file RELATIVE_PATH
+node {{scripts_path}}/live-poll.mjs --reply EVENT_ID done --file RELATIVE_PATH
```
The file path should be relative to the project root (e.g., `public/index.html`, `src/App.tsx`).
@@ -155,7 +155,7 @@ The user accepted a specific variant. For v1 (inspection mode):
4. Remove any scoped CSS blocks (between `impeccable-variants-css-start` and `impeccable-variants-css-end` markers).
5. Reply:
```bash
- npx impeccable poll --reply SESSION_ID done
+ node {{scripts_path}}/live-poll.mjs --reply SESSION_ID done
```
## Handle Discard
@@ -167,7 +167,7 @@ The event contains: `{id}`.
3. Remove any scoped CSS blocks for this session.
4. Reply:
```bash
- npx impeccable poll --reply SESSION_ID done
+ node {{scripts_path}}/live-poll.mjs --reply SESSION_ID done
```
## Cleanup (on exit)
@@ -178,7 +178,7 @@ When the loop ends:
2. **Remove any leftover variant wrappers** (search for `impeccable-variants-start` markers and clean up).
3. **Stop the server**:
```bash
- npx impeccable live stop
+ node {{scripts_path}}/live-server.mjs stop
```
## Variant Generation Guidelines
diff --git a/source/skills/impeccable/scripts/live-browser.js b/source/skills/impeccable/scripts/live-browser.js
new file mode 100644
index 000000000..7a26c9829
--- /dev/null
+++ b/source/skills/impeccable/scripts/live-browser.js
@@ -0,0 +1,1220 @@
+/**
+ * Impeccable Live Variant Mode — Browser Script
+ *
+ * Injected into the user's page via <script src="http://localhost:PORT/live.js">.
+ * The server prepends window.__IMPECCABLE_TOKEN__ and window.__IMPECCABLE_PORT__
+ * before this code.
+ *
+ * UI: a single floating bar that morphs between three states —
+ * configure (pick action + go), generating (progressive dots), and cycling
+ * (prev/next + accept/discard). Feels like Spotlight, not a modal.
+ */
+(function () {
+ 'use strict';
+ if (typeof window === 'undefined') return;
+
+ // Guard against double-init. Bun's HTML loader may process the <script> tag
+ // and create a bundled copy alongside the external load, or HMR may re-execute.
+ // Check BEFORE reading token/port to catch all cases.
+ if (window.__IMPECCABLE_LIVE_INIT__) return;
+ window.__IMPECCABLE_LIVE_INIT__ = true;
+
+ const TOKEN = window.__IMPECCABLE_TOKEN__;
+ const PORT = window.__IMPECCABLE_PORT__;
+ if (!TOKEN || !PORT) {
+ window.__IMPECCABLE_LIVE_INIT__ = false; // reset so the real load can init
+ return;
+ }
+
+ // ---------------------------------------------------------------------------
+ // Design tokens
+ // ---------------------------------------------------------------------------
+
+ const C = {
+ brand: 'oklch(55% 0.25 350)',
+ brandHov: 'oklch(48% 0.25 350)',
+ brandSoft: 'oklch(55% 0.25 350 / 0.12)',
+ ink: 'oklch(15% 0.01 350)',
+ ash: 'oklch(55% 0 0)',
+ paper: 'oklch(98% 0.005 350 / 0.92)',
+ paperSolid:'oklch(98% 0.005 350)',
+ mist: 'oklch(90% 0.01 350 / 0.6)',
+ white: 'oklch(99% 0 0)',
+ };
+ const FONT = 'system-ui, -apple-system, sans-serif';
+ const MONO = 'ui-monospace, SFMono-Regular, Menlo, monospace';
+ const Z = { highlight: 99990, bar: 99995, picker: 99997, toast: 99999 };
+ const EASE = 'cubic-bezier(0.22, 1, 0.36, 1)'; // ease-out-quint
+ const PREFIX = 'impeccable-live';
+
+ const SKIP_TAGS = new Set([
+ 'html', 'head', 'body', 'script', 'style', 'link', 'meta', 'noscript', 'br', 'wbr',
+ ]);
+
+ const ACTIONS = [
+ { value: 'impeccable', label: 'Freeform' },
+ { value: 'bolder', label: 'Bolder' },
+ { value: 'quieter', label: 'Quieter' },
+ { value: 'distill', label: 'Distill' },
+ { value: 'polish', label: 'Polish' },
+ { value: 'typeset', label: 'Typeset' },
+ { value: 'colorize', label: 'Colorize' },
+ { value: 'layout', label: 'Layout' },
+ { value: 'adapt', label: 'Adapt' },
+ { value: 'animate', label: 'Animate' },
+ { value: 'delight', label: 'Delight' },
+ { value: 'overdrive', label: 'Overdrive' },
+ ];
+
+ // ---------------------------------------------------------------------------
+ // State
+ // ---------------------------------------------------------------------------
+
+ let state = 'IDLE';
+ let hoveredElement = null;
+ let selectedElement = null;
+ let currentSessionId = null;
+ let expectedVariants = 0;
+ let arrivedVariants = 0;
+ let visibleVariant = 0;
+ let variantObserver = null;
+ let hasProjectContext = false;
+ let selectedAction = 'impeccable';
+ let selectedCount = 3;
+
+ // UI refs
+ let highlightEl = null;
+ let tooltipEl = null;
+ let barEl = null;
+ let pickerEl = null;
+ let toastEl = null;
+ let scrollRaf = null;
+
+ // ---------------------------------------------------------------------------
+ // Helpers
+ // ---------------------------------------------------------------------------
+
+ function own(el) {
+ return el && (el.id?.startsWith(PREFIX) || el.closest?.('[id^="' + PREFIX + '"]'));
+ }
+
+ function pickable(el) {
+ if (!el || el.nodeType !== 1) return false;
+ if (SKIP_TAGS.has(el.tagName.toLowerCase())) return false;
+ if (own(el)) return false;
+ const r = el.getBoundingClientRect();
+ return r.width >= 20 && r.height >= 20;
+ }
+
+ function desc(el) {
+ if (!el) return '';
+ let s = el.tagName.toLowerCase();
+ if (el.id) s += '#' + el.id;
+ else if (el.classList.length) s += '.' + [...el.classList].slice(0, 2).join('.');
+ return s;
+ }
+
+ function id8() { return crypto.randomUUID().replace(/-/g, '').slice(0, 8); }
+
+ // ---------------------------------------------------------------------------
+ // Highlight overlay
+ // ---------------------------------------------------------------------------
+
+ function initHighlight() {
+ highlightEl = document.createElement('div');
+ highlightEl.id = PREFIX + '-highlight';
+ Object.assign(highlightEl.style, {
+ position: 'fixed', top: '0', left: '0', width: '0', height: '0',
+ border: '2px solid ' + C.brand, borderRadius: '3px',
+ pointerEvents: 'none', zIndex: Z.highlight, boxSizing: 'border-box',
+ transition: 'top 0.08s ease, left 0.08s ease, width 0.08s ease, height 0.08s ease, opacity 0.15s ease',
+ display: 'none', opacity: '0',
+ });
+ document.body.appendChild(highlightEl);
+
+ tooltipEl = document.createElement('div');
+ tooltipEl.id = PREFIX + '-tooltip';
+ Object.assign(tooltipEl.style, {
+ position: 'fixed',
+ background: C.ink, color: C.white,
+ fontFamily: MONO, fontSize: '10px', fontWeight: '500',
+ padding: '2px 6px', borderRadius: '3px',
+ zIndex: Z.highlight + 1, pointerEvents: 'none',
+ whiteSpace: 'nowrap', display: 'none',
+ letterSpacing: '0.02em',
+ });
+ document.body.appendChild(tooltipEl);
+ }
+
+ function showHighlight(el) {
+ if (!el || !highlightEl) return;
+ const r = el.getBoundingClientRect();
+ Object.assign(highlightEl.style, {
+ top: (r.top - 2) + 'px', left: (r.left - 2) + 'px',
+ width: (r.width + 4) + 'px', height: (r.height + 4) + 'px',
+ display: 'block', opacity: '1',
+ });
+ tooltipEl.textContent = desc(el);
+ const tipTop = r.top - 20;
+ Object.assign(tooltipEl.style, {
+ top: (tipTop < 4 ? r.bottom + 4 : tipTop) + 'px',
+ left: Math.max(4, r.left) + 'px', display: 'block',
+ });
+ }
+
+ function hideHighlight() {
+ if (highlightEl) { highlightEl.style.opacity = '0'; highlightEl.style.display = 'none'; }
+ if (tooltipEl) tooltipEl.style.display = 'none';
+ }
+
+ // ---------------------------------------------------------------------------
+ // Element context extraction
+ // ---------------------------------------------------------------------------
+
+ function extractContext(el) {
+ const cs = getComputedStyle(el);
+ const r = el.getBoundingClientRect();
+ const props = {};
+ for (const sheet of document.styleSheets) {
+ try {
+ for (const rule of sheet.cssRules) {
+ if (rule.style) for (let i = 0; i < rule.style.length; i++) {
+ const p = rule.style[i];
+ if (p.startsWith('--') && !props[p]) {
+ const v = cs.getPropertyValue(p).trim();
+ if (v) props[p] = v;
+ }
+ }
+ }
+ } catch { /* cross-origin */ }
+ }
+ return {
+ tagName: el.tagName.toLowerCase(), id: el.id || null,
+ classes: [...el.classList],
+ textContent: (el.textContent || '').slice(0, 500),
+ outerHTML: el.outerHTML.slice(0, 10000),
+ computedStyles: {
+ 'font-family': cs.fontFamily, 'font-size': cs.fontSize,
+ 'font-weight': cs.fontWeight, 'line-height': cs.lineHeight,
+ 'color': cs.color, 'background': cs.background,
+ 'background-color': cs.backgroundColor,
+ 'padding': cs.padding, 'margin': cs.margin,
+ 'display': cs.display, 'position': cs.position,
+ 'gap': cs.gap, 'border-radius': cs.borderRadius,
+ 'box-shadow': cs.boxShadow,
+ },
+ cssCustomProperties: props,
+ parentContext: el.parentElement
+ ? '<' + el.parentElement.tagName.toLowerCase()
+ + (el.parentElement.id ? ' id="' + el.parentElement.id + '"' : '')
+ + (el.parentElement.className ? ' class="' + el.parentElement.className + '"' : '')
+ + '>'
+ : null,
+ boundingRect: { width: Math.round(r.width), height: Math.round(r.height) },
+ };
+ }
+
+ // ---------------------------------------------------------------------------
+ // The Bar — one floating element, three modes
+ // ---------------------------------------------------------------------------
+
+ function initBar() {
+ barEl = document.createElement('div');
+ barEl.id = PREFIX + '-bar';
+ Object.assign(barEl.style, {
+ position: 'fixed', zIndex: Z.bar,
+ display: 'none', opacity: '0',
+ transform: 'translateY(6px)',
+ transition: 'opacity 0.25s ' + EASE + ', transform 0.3s ' + EASE,
+ // Visual
+ background: C.paper,
+ backdropFilter: 'blur(16px)', WebkitBackdropFilter: 'blur(16px)',
+ border: '1px solid ' + C.mist,
+ borderRadius: '10px',
+ boxShadow: '0 4px 20px oklch(0% 0 0 / 0.08), 0 1px 3px oklch(0% 0 0 / 0.06)',
+ fontFamily: FONT, fontSize: '13px', color: C.ink,
+ padding: '6px',
+ maxWidth: '460px', minWidth: '320px',
+ });
+ document.body.appendChild(barEl);
+ }
+
+ function positionBar() {
+ if (!barEl || !selectedElement) return;
+ const r = selectedElement.getBoundingClientRect();
+ const barH = barEl.offsetHeight || 44;
+ const barW = barEl.offsetWidth || 380;
+ let top = r.bottom + 8;
+ let left = r.left + (r.width - barW) / 2;
+ // Keep in viewport
+ if (top + barH + 8 > window.innerHeight) top = r.top - barH - 8;
+ if (top < 8) top = 8;
+ if (left < 8) left = 8;
+ if (left + barW > window.innerWidth - 8) left = window.innerWidth - barW - 8;
+ Object.assign(barEl.style, { top: top + 'px', left: left + 'px' });
+ }
+
+ function showBar(mode) {
+ barEl.innerHTML = '';
+ if (mode === 'configure') barEl.appendChild(buildConfigureRow());
+ else if (mode === 'generating') barEl.appendChild(buildGeneratingRow());
+ else if (mode === 'cycling') barEl.appendChild(buildCyclingRow());
+ barEl.style.display = 'block';
+ positionBar();
+ requestAnimationFrame(() => {
+ barEl.style.opacity = '1';
+ barEl.style.transform = 'translateY(0)';
+ });
+ }
+
+ function hideBar() {
+ if (!barEl) return;
+ barEl.style.opacity = '0';
+ barEl.style.transform = 'translateY(6px)';
+ setTimeout(() => { if (barEl) barEl.style.display = 'none'; }, 250);
+ hideActionPicker();
+ }
+
+ function updateBarContent(mode) {
+ if (!barEl || barEl.style.display === 'none') return;
+ barEl.innerHTML = '';
+ // Reset bar styling
+ barEl.style.background = C.paper;
+ barEl.style.border = '1px solid ' + C.mist;
+ if (mode === 'configure') barEl.appendChild(buildConfigureRow());
+ else if (mode === 'generating') barEl.appendChild(buildGeneratingRow());
+ else if (mode === 'cycling') barEl.appendChild(buildCyclingRow());
+ else if (mode === 'saving') barEl.appendChild(buildSavingRow());
+ else if (mode === 'confirmed') {
+ barEl.appendChild(buildConfirmedRow());
+ barEl.style.background = 'oklch(95% 0.05 145)';
+ barEl.style.border = '1px solid oklch(75% 0.12 145 / 0.4)';
+ }
+ }
+
+ // --- Configure row ---
+
+ function buildConfigureRow() {
+ const row = el('div', {
+ display: 'flex', alignItems: 'center', gap: '4px',
+ });
+
+ // Action pill
+ const pill = el('button', {
+ display: 'inline-flex', alignItems: 'center', gap: '4px',
+ padding: '5px 10px', borderRadius: '6px',
+ background: C.ink, color: C.white,
+ fontFamily: FONT, fontSize: '12px', fontWeight: '500',
+ border: 'none', cursor: 'pointer',
+ transition: 'background 0.12s ease, transform 0.1s ease',
+ whiteSpace: 'nowrap', flexShrink: '0',
+ });
+ pill.textContent = actionLabel() + ' \u25BE';
+ pill.addEventListener('mouseenter', () => pill.style.background = C.brandHov);
+ pill.addEventListener('mouseleave', () => pill.style.background = C.ink);
+ pill.addEventListener('mousedown', () => pill.style.transform = 'scale(0.97)');
+ pill.addEventListener('mouseup', () => pill.style.transform = 'scale(1)');
+ pill.addEventListener('click', (e) => { e.stopPropagation(); toggleActionPicker(); });
+ row.appendChild(pill);
+
+ // Freeform input
+ const input = document.createElement('input');
+ input.id = PREFIX + '-input';
+ input.type = 'text';
+ input.placeholder = selectedAction === 'impeccable' ? 'describe what you want...' : 'refine further (optional)...';
+ Object.assign(input.style, {
+ flex: '1', minWidth: '0',
+ padding: '5px 8px', borderRadius: '6px',
+ border: '1px solid transparent', background: 'transparent',
+ fontFamily: FONT, fontSize: '12px', color: C.ink,
+ outline: 'none',
+ transition: 'border-color 0.15s ease, background 0.15s ease',
+ });
+ input.addEventListener('focus', () => {
+ input.style.borderColor = C.mist;
+ input.style.background = C.white;
+ });
+ input.addEventListener('blur', () => {
+ input.style.borderColor = 'transparent';
+ input.style.background = 'transparent';
+ });
+ input.addEventListener('keydown', (e) => {
+ e.stopPropagation(); // Don't trigger element picker keyboard nav
+ if (e.key === 'Enter') { e.preventDefault(); handleGo(); }
+ if (e.key === 'Escape') { e.preventDefault(); input.blur(); hideBar(); state = 'PICKING'; }
+ });
+ row.appendChild(input);
+
+ // Variant count toggle
+ const count = el('button', {
+ padding: '4px 6px', borderRadius: '5px',
+ border: '1px solid ' + C.mist, background: 'transparent',
+ fontFamily: MONO, fontSize: '11px', fontWeight: '600',
+ color: C.ash, cursor: 'pointer',
+ transition: 'color 0.12s ease, border-color 0.12s ease',
+ flexShrink: '0', whiteSpace: 'nowrap',
+ });
+ count.textContent = '\u00D7' + selectedCount;
+ count.title = 'Variants: click to change';
+ count.addEventListener('mouseenter', () => { count.style.color = C.ink; count.style.borderColor = C.ink; });
+ count.addEventListener('mouseleave', () => { count.style.color = C.ash; count.style.borderColor = C.mist; });
+ count.addEventListener('click', (e) => {
+ e.stopPropagation();
+ selectedCount = selectedCount >= 4 ? 2 : selectedCount + 1;
+ count.textContent = '\u00D7' + selectedCount;
+ });
+ row.appendChild(count);
+
+ // Go button
+ const go = el('button', {
+ padding: '5px 12px', borderRadius: '6px',
+ border: 'none', background: C.brand, color: C.white,
+ fontFamily: FONT, fontSize: '12px', fontWeight: '600',
+ cursor: 'pointer',
+ transition: 'background 0.12s ease, transform 0.1s ease',
+ flexShrink: '0', whiteSpace: 'nowrap',
+ });
+ go.textContent = 'Go \u2192';
+ go.addEventListener('mouseenter', () => go.style.background = C.brandHov);
+ go.addEventListener('mouseleave', () => go.style.background = C.brand);
+ go.addEventListener('mousedown', () => go.style.transform = 'scale(0.97)');
+ go.addEventListener('mouseup', () => go.style.transform = 'scale(1)');
+ go.addEventListener('click', (e) => { e.stopPropagation(); handleGo(); });
+ row.appendChild(go);
+
+ // Auto-focus input after a beat
+ setTimeout(() => input.focus(), 60);
+ return row;
+ }
+
+ // --- Generating row ---
+
+ function buildGeneratingRow() {
+ const row = el('div', {
+ display: 'flex', alignItems: 'center', gap: '8px',
+ padding: '2px 4px',
+ });
+
+ // Action label
+ const label = el('span', {
+ fontWeight: '600', fontSize: '12px', color: C.ink,
+ flexShrink: '0', whiteSpace: 'nowrap',
+ });
+ label.textContent = actionLabel();
+ row.appendChild(label);
+
+ // Dots
+ row.appendChild(buildDots(false));
+
+ // Status
+ const status = el('span', {
+ fontSize: '11px', color: C.ash, whiteSpace: 'nowrap',
+ marginLeft: 'auto',
+ });
+ status.textContent = arrivedVariants < expectedVariants
+ ? 'Generating ' + (arrivedVariants + 1) + ' of ' + expectedVariants + '...'
+ : 'Done';
+ row.appendChild(status);
+
+ return row;
+ }
+
+ // --- Cycling row ---
+
+ function buildCyclingRow() {
+ const row = el('div', {
+ display: 'flex', alignItems: 'center', gap: '6px',
+ padding: '1px 2px',
+ });
+
+ // Prev
+ const prev = navBtn('\u2190');
+ prev.addEventListener('click', (e) => { e.stopPropagation(); cycleVariant(-1); });
+ if (visibleVariant <= 1) prev.style.opacity = '0.3';
+ row.appendChild(prev);
+
+ // Dots (clickable)
+ row.appendChild(buildDots(true));
+
+ // Counter
+ const counter = el('span', {
+ fontFamily: MONO, fontSize: '11px', fontWeight: '500',
+ color: C.ash, minWidth: '24px', textAlign: 'center',
+ });
+ counter.textContent = visibleVariant + '/' + arrivedVariants;
+ row.appendChild(counter);
+
+ // Next
+ const next = navBtn('\u2192');
+ next.addEventListener('click', (e) => { e.stopPropagation(); cycleVariant(1); });
+ if (visibleVariant >= arrivedVariants) next.style.opacity = '0.3';
+ row.appendChild(next);
+
+ // Spacer
+ row.appendChild(el('div', { flex: '1' }));
+
+ // Accept
+ const accept = el('button', {
+ padding: '4px 10px', borderRadius: '5px',
+ border: 'none', background: C.ink, color: C.white,
+ fontFamily: FONT, fontSize: '11px', fontWeight: '600',
+ cursor: 'pointer', transition: 'background 0.12s ease',
+ whiteSpace: 'nowrap',
+ });
+ accept.textContent = '\u2713 Accept';
+ accept.addEventListener('mouseenter', () => accept.style.background = C.brand);
+ accept.addEventListener('mouseleave', () => accept.style.background = C.ink);
+ accept.addEventListener('click', (e) => { e.stopPropagation(); handleAccept(); });
+ if (arrivedVariants === 0) { accept.style.opacity = '0.3'; accept.style.pointerEvents = 'none'; }
+ row.appendChild(accept);
+
+ // Discard
+ const discard = el('button', {
+ padding: '4px 6px', borderRadius: '5px',
+ border: '1px solid ' + C.mist, background: 'transparent',
+ fontFamily: FONT, fontSize: '11px', color: C.ash,
+ cursor: 'pointer', transition: 'color 0.12s ease, border-color 0.12s ease',
+ });
+ discard.textContent = '\u2715';
+ discard.title = 'Discard all variants';
+ discard.addEventListener('mouseenter', () => { discard.style.color = C.ink; discard.style.borderColor = C.ink; });
+ discard.addEventListener('mouseleave', () => { discard.style.color = C.ash; discard.style.borderColor = C.mist; });
+ discard.addEventListener('click', (e) => { e.stopPropagation(); handleDiscard(); });
+ row.appendChild(discard);
+
+ return row;
+ }
+
+ // --- Shared UI builders ---
+
+ // --- Saving row (waiting for agent to process accept/discard) ---
+
+ function buildSavingRow() {
+ const row = el('div', {
+ display: 'flex', alignItems: 'center', gap: '8px',
+ padding: '2px 8px',
+ });
+ const spinner = el('div', {
+ width: '14px', height: '14px', borderRadius: '50%',
+ border: '2px solid ' + C.mist,
+ borderTopColor: C.brand,
+ animation: 'impeccable-spin 0.6s linear infinite',
+ flexShrink: '0',
+ });
+ row.appendChild(spinner);
+ const label = el('span', {
+ fontSize: '12px', color: C.ash, fontWeight: '500',
+ });
+ label.textContent = 'Applying variant...';
+ row.appendChild(label);
+
+ // Inject the keyframes if not already present
+ if (!document.getElementById(PREFIX + '-keyframes')) {
+ const style = document.createElement('style');
+ style.id = PREFIX + '-keyframes';
+ style.textContent = '@keyframes impeccable-spin { to { transform: rotate(360deg); } }';
+ document.head.appendChild(style);
+ }
+ return row;
+ }
+
+ // --- Confirmed row (green success, auto-dismisses) ---
+
+ function buildConfirmedRow() {
+ const row = el('div', {
+ display: 'flex', alignItems: 'center', gap: '8px',
+ padding: '2px 8px',
+ });
+ const check = el('span', {
+ fontSize: '15px', lineHeight: '1', flexShrink: '0',
+ color: 'oklch(45% 0.15 145)',
+ });
+ check.textContent = '\u2713';
+ row.appendChild(check);
+ const label = el('span', {
+ fontSize: '12px', color: 'oklch(35% 0.1 145)', fontWeight: '600',
+ });
+ label.textContent = 'Variant applied';
+ row.appendChild(label);
+ return row;
+ }
+
+ // --- Shared UI builders ---
+
+ function buildDots(clickable) {
+ const container = el('div', {
+ display: 'flex', alignItems: 'center', gap: '4px',
+ });
+ for (let i = 1; i <= expectedVariants; i++) {
+ const arrived = i <= arrivedVariants;
+ const active = i === visibleVariant;
+ const dot = el('div', {
+ width: '7px', height: '7px', borderRadius: '50%',
+ background: active ? C.brand : (arrived ? C.ash : 'transparent'),
+ border: '1.5px solid ' + (arrived ? C.brand : C.mist),
+ transition: 'all 0.2s ' + EASE,
+ cursor: (clickable && arrived) ? 'pointer' : 'default',
+ transform: arrived ? 'scale(1)' : 'scale(0.6)',
+ opacity: arrived ? '1' : '0.4',
+ });
+ if (clickable && arrived) {
+ const idx = i;
+ dot.addEventListener('click', (e) => {
+ e.stopPropagation();
+ visibleVariant = idx;
+ showVariantInDOM(currentSessionId, idx);
+ updateSelectedElement();
+ updateBarContent('cycling');
+ });
+ }
+ container.appendChild(dot);
+ }
+ return container;
+ }
+
+ function navBtn(text) {
+ const b = el('button', {
+ width: '26px', height: '26px', borderRadius: '5px',
+ border: '1px solid ' + C.mist, background: 'transparent',
+ color: C.ink, fontFamily: FONT, fontSize: '13px',
+ cursor: 'pointer', display: 'flex', alignItems: 'center', justifyContent: 'center',
+ transition: 'border-color 0.12s ease, background 0.12s ease',
+ padding: '0', lineHeight: '1',
+ });
+ b.textContent = text;
+ b.addEventListener('mouseenter', () => { b.style.borderColor = C.ink; });
+ b.addEventListener('mouseleave', () => { b.style.borderColor = C.mist; });
+ return b;
+ }
+
+ function actionLabel() {
+ const a = ACTIONS.find(a => a.value === selectedAction);
+ return a ? a.label : 'Freeform';
+ }
+
+ function el(tag, styles) {
+ const e = document.createElement(tag);
+ if (styles) Object.assign(e.style, styles);
+ return e;
+ }
+
+ // ---------------------------------------------------------------------------
+ // Action picker popover
+ // ---------------------------------------------------------------------------
+
+ function initActionPicker() {
+ pickerEl = document.createElement('div');
+ pickerEl.id = PREFIX + '-picker';
+ Object.assign(pickerEl.style, {
+ position: 'fixed', zIndex: Z.picker,
+ display: 'none', opacity: '0',
+ transform: 'scale(0.96) translateY(4px)',
+ transformOrigin: 'bottom left',
+ transition: 'opacity 0.18s ' + EASE + ', transform 0.2s ' + EASE,
+ background: C.paperSolid,
+ border: '1px solid ' + C.mist,
+ borderRadius: '10px',
+ boxShadow: '0 8px 30px oklch(0% 0 0 / 0.10), 0 2px 6px oklch(0% 0 0 / 0.06)',
+ padding: '6px',
+ fontFamily: FONT,
+ });
+
+ // Build the chip grid
+ const grid = el('div', {
+ display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', gap: '3px',
+ });
+
+ ACTIONS.forEach(action => {
+ const chip = el('button', {
+ padding: '6px 8px', borderRadius: '6px',
+ border: 'none',
+ background: action.value === selectedAction ? C.brandSoft : 'transparent',
+ color: action.value === selectedAction ? C.brand : C.ink,
+ fontFamily: FONT, fontSize: '11px', fontWeight: '500',
+ cursor: 'pointer',
+ transition: 'background 0.1s ease, color 0.1s ease',
+ textAlign: 'center', whiteSpace: 'nowrap',
+ });
+ chip.textContent = action.label;
+ chip.dataset.action = action.value;
+ chip.addEventListener('mouseenter', () => {
+ if (action.value !== selectedAction) chip.style.background = C.brandSoft;
+ });
+ chip.addEventListener('mouseleave', () => {
+ chip.style.background = action.value === selectedAction ? C.brandSoft : 'transparent';
+ });
+ chip.addEventListener('click', (e) => {
+ e.stopPropagation();
+ selectedAction = action.value;
+ hideActionPicker();
+ updateBarContent('configure');
+ });
+ grid.appendChild(chip);
+ });
+
+ pickerEl.appendChild(grid);
+ document.body.appendChild(pickerEl);
+ }
+
+ function toggleActionPicker() {
+ if (pickerEl.style.display !== 'none') { hideActionPicker(); return; }
+ // Rebuild chips to reflect current selection
+ pickerEl.querySelectorAll('button').forEach(chip => {
+ const isActive = chip.dataset.action === selectedAction;
+ chip.style.background = isActive ? C.brandSoft : 'transparent';
+ chip.style.color = isActive ? C.brand : C.ink;
+ });
+ // Position above the bar
+ const barRect = barEl.getBoundingClientRect();
+ const pickerH = 90; // approximate
+ let top = barRect.top - pickerH - 6;
+ if (top < 8) top = barRect.bottom + 6;
+ Object.assign(pickerEl.style, {
+ top: top + 'px', left: barRect.left + 'px',
+ display: 'block',
+ });
+ requestAnimationFrame(() => {
+ pickerEl.style.opacity = '1';
+ pickerEl.style.transform = 'scale(1) translateY(0)';
+ });
+ }
+
+ function hideActionPicker() {
+ if (!pickerEl) return;
+ pickerEl.style.opacity = '0';
+ pickerEl.style.transform = 'scale(0.96) translateY(4px)';
+ setTimeout(() => { if (pickerEl) pickerEl.style.display = 'none'; }, 180);
+ }
+
+ // ---------------------------------------------------------------------------
+ // Variant cycling in DOM
+ // ---------------------------------------------------------------------------
+
+ function showVariantInDOM(sessionId, num) {
+ const wrapper = document.querySelector('[data-impeccable-variants="' + sessionId + '"]');
+ if (!wrapper) return;
+ for (const child of wrapper.children) {
+ const v = child.dataset ? child.dataset.impeccableVariant : null;
+ if (!v) continue;
+ child.style.display = (v === String(num)) ? '' : 'none';
+ }
+ }
+
+ /**
+ * No-HMR fallback: fetch the raw source file from the live server,
+ * parse it, extract the variant wrapper, and inject it into the live DOM.
+ * This works even when the dev server caches HTML (Bun, static servers).
+ */
+ function injectVariantsFromSource(filePath, sessionId) {
+ const url = 'http://localhost:' + PORT + '/source?token=' + TOKEN + '&path=' + encodeURIComponent(filePath);
+ fetch(url)
+ .then(r => { if (!r.ok) throw new Error(r.status); return r.text(); })
+ .then(html => {
+ // Parse the raw source HTML
+ const parser = new DOMParser();
+ const doc = parser.parseFromString(html, 'text/html');
+ const srcWrapper = doc.querySelector('[data-impeccable-variants="' + sessionId + '"]');
+ if (!srcWrapper) {
+ console.error('[impeccable] Variant wrapper not found in source file.');
+ return;
+ }
+
+ // Find the original element in the live DOM.
+ // The original is inside the wrapper in the source. We find the
+ // corresponding element in the live DOM by matching the first child's
+ // tag + classes from the original snapshot.
+ const origContent = srcWrapper.querySelector('[data-impeccable-variant="original"] > :first-child');
+ if (!origContent) return;
+
+ const tag = origContent.tagName.toLowerCase();
+ const cls = origContent.className;
+ let liveEl = null;
+ if (origContent.id) {
+ liveEl = document.getElementById(origContent.id);
+ } else if (cls) {
+ // Find by tag + exact class match
+ const candidates = document.querySelectorAll(tag + '.' + cls.split(' ')[0]);
+ for (const c of candidates) {
+ if (c.className === cls && !own(c)) { liveEl = c; break; }
+ }
+ }
+
+ if (!liveEl) {
+ console.error('[impeccable] Could not find original element in live DOM.');
+ return;
+ }
+
+ // Replace the live element with the full wrapper from source
+ const wrapper = srcWrapper.cloneNode(true);
+ liveEl.parentElement.replaceChild(wrapper, liveEl);
+
+ // Update state: count variants, show the first one
+ 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);
+
+ // Update selectedElement to the visible variant's content
+ const visEl = wrapper.querySelector('[data-impeccable-variant="1"] > :first-child');
+ selectedElement = visEl || wrapper.parentElement;
+
+ state = 'CYCLING';
+ updateBarContent('cycling');
+ saveSession();
+ console.log('[impeccable] Injected ' + arrivedVariants + ' variants from source file.');
+ })
+ .catch(err => {
+ console.error('[impeccable] Failed to fetch source:', err);
+ showToast('Could not load variants. Try refreshing the page.', 5000);
+ });
+ }
+
+ function cycleVariant(dir) {
+ const next = visibleVariant + dir;
+ if (next < 1 || next > arrivedVariants) return;
+ visibleVariant = next;
+ showVariantInDOM(currentSessionId, next);
+ updateSelectedElement();
+ updateBarContent('cycling');
+ saveSession();
+ }
+
+ function updateSelectedElement() {
+ if (!currentSessionId) return;
+ const wrapper = document.querySelector('[data-impeccable-variants="' + currentSessionId + '"]');
+ if (!wrapper) return;
+ const visEl = wrapper.querySelector('[data-impeccable-variant="' + visibleVariant + '"] > :first-child');
+ if (visEl) selectedElement = visEl;
+ }
+
+ // ---------------------------------------------------------------------------
+ // MutationObserver for progressive variant reveal
+ // ---------------------------------------------------------------------------
+
+ function startVariantObserver(sessionId) {
+ let updating = false; // re-entrancy guard
+
+ const obs = new MutationObserver((mutations) => {
+ if (updating) return;
+
+ // Only react to mutations that add nodes with data-impeccable-variant,
+ // or mutations inside the variant wrapper. Ignore our own bar/UI changes.
+ let dominated = false;
+ for (const m of mutations) {
+ if (m.target.closest?.('[data-impeccable-variants]')) { dominated = true; break; }
+ for (const n of m.addedNodes) {
+ if (n.nodeType === 1 && (n.dataset?.impeccableVariants || n.dataset?.impeccableVariant)) {
+ dominated = true; break;
+ }
+ }
+ if (dominated) break;
+ }
+ if (!dominated) return;
+
+ const wrapper = document.querySelector('[data-impeccable-variants="' + sessionId + '"]');
+ if (!wrapper) return;
+
+ const variants = wrapper.querySelectorAll('[data-impeccable-variant]:not([data-impeccable-variant="original"])');
+ const count = variants.length;
+
+ // Nothing new
+ if (count <= arrivedVariants) return;
+
+ updating = true;
+ arrivedVariants = count;
+ if (visibleVariant === 0 && arrivedVariants > 0) {
+ visibleVariant = 1;
+ showVariantInDOM(sessionId, 1);
+ }
+
+ const expected = parseInt(wrapper.dataset.impeccableVariantCount || '0');
+ if (expected > 0) expectedVariants = expected;
+
+ if (arrivedVariants >= expectedVariants && expectedVariants > 0) {
+ state = 'CYCLING';
+ updateBarContent('cycling');
+ } else if (state === 'GENERATING') {
+ updateBarContent('generating');
+ }
+ saveSession();
+ updating = false;
+ });
+
+ obs.observe(document.body, { childList: true, subtree: true });
+ return obs;
+ }
+
+ // ---------------------------------------------------------------------------
+ // Bar scroll tracking
+ // ---------------------------------------------------------------------------
+
+ function startScrollTracking() {
+ function tick() {
+ if (state === 'CONFIGURING' || state === 'GENERATING' || state === 'CYCLING') {
+ positionBar();
+ showHighlight(selectedElement);
+ }
+ scrollRaf = requestAnimationFrame(tick);
+ }
+ scrollRaf = requestAnimationFrame(tick);
+ }
+
+ function stopScrollTracking() {
+ if (scrollRaf) { cancelAnimationFrame(scrollRaf); scrollRaf = null; }
+ }
+
+ // ---------------------------------------------------------------------------
+ // SSE (server→browser) + fetch POST (browser→server)
+ // Zero-dependency replacement for WebSocket.
+ // ---------------------------------------------------------------------------
+
+ let evtSource = null;
+
+ function connectSSE() {
+ evtSource = new EventSource('http://localhost:' + PORT + '/events?token=' + TOKEN);
+
+ evtSource.onmessage = (e) => {
+ let msg; try { msg = JSON.parse(e.data); } catch { return; }
+ switch (msg.type) {
+ case 'connected':
+ hasProjectContext = !!msg.hasProjectContext;
+ if (!hasProjectContext) showToast('No .impeccable.md found. Variants will be brand-agnostic.', 6000);
+ console.log('[impeccable] Live mode connected.');
+ if (state === 'IDLE') state = 'PICKING';
+ break;
+ case 'done':
+ if (state === 'SAVING') {
+ state = 'CONFIRMED';
+ updateBarContent('confirmed');
+ setTimeout(() => {
+ hideBar();
+ hideHighlight();
+ stopScrollTracking();
+ if (variantObserver) { variantObserver.disconnect(); variantObserver = null; }
+ clearSession();
+ selectedElement = null;
+ currentSessionId = null;
+ selectedAction = 'impeccable';
+ state = 'PICKING';
+ }, 1800);
+ return;
+ }
+ if (arrivedVariants === 0 && expectedVariants > 0 && msg.file) {
+ console.log('[impeccable] No HMR detected. Fetching variants from source file...');
+ injectVariantsFromSource(msg.file, currentSessionId);
+ return;
+ }
+ state = 'CYCLING';
+ updateBarContent('cycling');
+ break;
+ case 'error':
+ console.error('[impeccable] Error:', msg.message);
+ showToast('Error: ' + msg.message, 5000);
+ hideBar();
+ state = 'PICKING';
+ break;
+ }
+ };
+
+ evtSource.onerror = () => {
+ // EventSource auto-reconnects. Log once.
+ console.log('[impeccable] SSE connection lost. Reconnecting...');
+ };
+ }
+
+ function sendEvent(msg) {
+ msg.token = TOKEN;
+ 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));
+ }
+
+ // ---------------------------------------------------------------------------
+ // Event handlers
+ // ---------------------------------------------------------------------------
+
+ function handleMouseMove(e) {
+ if (state !== 'PICKING') return;
+ const target = document.elementFromPoint(e.clientX, e.clientY);
+ if (!target || !pickable(target) || target === hoveredElement) return;
+ hoveredElement = target;
+ showHighlight(target);
+ }
+
+ function handleClick(e) {
+ // Close action picker on any outside click
+ if (pickerEl?.style.display !== 'none' && !own(e.target)) {
+ hideActionPicker();
+ }
+ if (state !== 'PICKING') return;
+ if (own(e.target)) return;
+ if (!hoveredElement || !pickable(hoveredElement)) return;
+ e.preventDefault();
+ e.stopPropagation();
+ selectedElement = hoveredElement;
+ state = 'CONFIGURING';
+ showHighlight(selectedElement);
+ showBar('configure');
+ startScrollTracking();
+ }
+
+ function handleKeyDown(e) {
+ if (e.key === 'Escape') {
+ e.preventDefault();
+ if (pickerEl?.style.display !== 'none') { hideActionPicker(); return; }
+ if (state === 'CONFIGURING') { hideBar(); stopScrollTracking(); state = 'PICKING'; return; }
+ if (state === 'CYCLING') { handleDiscard(); return; }
+ if (state === 'SAVING' || state === 'CONFIRMED') return; // don't interrupt
+ if (state === 'PICKING') { hideHighlight(); state = 'IDLE'; return; }
+ }
+
+ if (state === 'PICKING' && hoveredElement) {
+ let next = null;
+ if (e.key === 'ArrowDown' && !e.shiftKey) {
+ next = hoveredElement.nextElementSibling;
+ while (next && !pickable(next)) next = next.nextElementSibling;
+ } else if (e.key === 'ArrowUp' && !e.shiftKey) {
+ next = hoveredElement.previousElementSibling;
+ while (next && !pickable(next)) next = next.previousElementSibling;
+ } else if (e.key === 'ArrowUp' && e.shiftKey) {
+ next = hoveredElement.parentElement;
+ if (next && !pickable(next)) next = null;
+ } else if (e.key === 'ArrowDown' && e.shiftKey) {
+ next = hoveredElement.firstElementChild;
+ while (next && !pickable(next)) next = next.nextElementSibling;
+ } else if (e.key === 'Enter') {
+ e.preventDefault();
+ selectedElement = hoveredElement;
+ state = 'CONFIGURING';
+ showHighlight(selectedElement);
+ showBar('configure');
+ startScrollTracking();
+ return;
+ }
+ if (next) {
+ e.preventDefault();
+ hoveredElement = next;
+ showHighlight(next);
+ next.scrollIntoView({ block: 'nearest', behavior: 'smooth' });
+ }
+ return;
+ }
+
+ if (state === 'CYCLING') {
+ if (e.key === 'ArrowLeft') { e.preventDefault(); cycleVariant(-1); }
+ if (e.key === 'ArrowRight') { e.preventDefault(); cycleVariant(1); }
+ if (e.key === 'Enter') { e.preventDefault(); handleAccept(); }
+ }
+ }
+
+ function handleGo() {
+ if (!selectedElement || state !== 'CONFIGURING') return;
+ const input = document.getElementById(PREFIX + '-input');
+ const prompt = input ? input.value.trim() : '';
+
+ currentSessionId = id8();
+ expectedVariants = selectedCount;
+ arrivedVariants = 0;
+ visibleVariant = 0;
+
+ sendEvent({
+ type: 'generate', id: currentSessionId,
+ action: selectedAction,
+ freeformPrompt: prompt || undefined,
+ count: selectedCount,
+ pageUrl: location.pathname,
+ element: extractContext(selectedElement),
+ });
+
+ state = 'GENERATING';
+ showBar('generating');
+ saveSession();
+ if (variantObserver) variantObserver.disconnect();
+ variantObserver = startVariantObserver(currentSessionId);
+ }
+
+ function handleAccept() {
+ if (!currentSessionId || arrivedVariants === 0) return;
+ sendEvent({ type: 'accept', id: currentSessionId, variantId: String(visibleVariant) });
+ markSessionHandled();
+ state = 'SAVING';
+ updateBarContent('saving');
+ // Don't cleanup yet — wait for the "done" WS message to show confirmation
+ }
+
+ function handleDiscard() {
+ if (!currentSessionId) return;
+ sendEvent({ type: 'discard', id: currentSessionId });
+ markSessionHandled();
+ state = 'SAVING';
+ updateBarContent('saving');
+ // Wait for "done" WS message to show confirmation and dismiss
+ }
+
+ // ---------------------------------------------------------------------------
+ // Session persistence via localStorage
+ // ---------------------------------------------------------------------------
+ // Survives page reloads, browser close/reopen, HMR, and accidental refreshes.
+
+ const LS_KEY = PREFIX + '-session';
+
+ function saveSession() {
+ if (!currentSessionId) return;
+ 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 */ }
+ }
+
+ function loadSession() {
+ try {
+ const raw = localStorage.getItem(LS_KEY);
+ return raw ? JSON.parse(raw) : null;
+ } catch { return null; }
+ }
+
+ function clearSession() {
+ try { localStorage.removeItem(LS_KEY); } catch {}
+ }
+
+ /** Mark session as handled (accepted/discarded). The agent will clean up
+ * the source, but until it does the wrapper is still in the HTML. This
+ * prevents resumeSession from picking it up again after reload. */
+ function markSessionHandled() {
+ if (!currentSessionId) return;
+ try {
+ localStorage.setItem(LS_KEY + '-handled', currentSessionId);
+ } catch {}
+ }
+
+ function isSessionHandled(id) {
+ try {
+ return localStorage.getItem(LS_KEY + '-handled') === id;
+ } catch { return false; }
+ }
+
+ function clearHandled() {
+ try { localStorage.removeItem(LS_KEY + '-handled'); } catch {}
+ }
+
+ function cleanup() {
+ hideBar();
+ hideHighlight();
+ stopScrollTracking();
+ if (variantObserver) { variantObserver.disconnect(); variantObserver = null; }
+ clearSession();
+ selectedElement = null;
+ currentSessionId = null;
+ selectedAction = 'impeccable';
+ state = 'PICKING';
+ }
+
+ // ---------------------------------------------------------------------------
+ // Toast
+ // ---------------------------------------------------------------------------
+
+ function showToast(message, duration) {
+ if (toastEl) toastEl.remove();
+ toastEl = el('div', {
+ position: 'fixed', bottom: '16px', left: '50%',
+ transform: 'translateX(-50%) translateY(8px)',
+ background: C.ink, color: C.white,
+ fontFamily: FONT, fontSize: '12px',
+ padding: '8px 16px', borderRadius: '8px',
+ zIndex: Z.toast, opacity: '0',
+ transition: 'opacity 0.25s ' + EASE + ', transform 0.25s ' + EASE,
+ pointerEvents: 'none', maxWidth: '420px', textAlign: 'center',
+ });
+ toastEl.id = PREFIX + '-toast';
+ toastEl.textContent = message;
+ document.body.appendChild(toastEl);
+ requestAnimationFrame(() => {
+ toastEl.style.opacity = '1';
+ toastEl.style.transform = 'translateX(-50%) translateY(0)';
+ });
+ setTimeout(() => {
+ if (toastEl) {
+ toastEl.style.opacity = '0';
+ toastEl.style.transform = 'translateX(-50%) translateY(8px)';
+ setTimeout(() => { if (toastEl) { toastEl.remove(); toastEl = null; } }, 250);
+ }
+ }, duration);
+ }
+
+ // ---------------------------------------------------------------------------
+ // Init
+ // ---------------------------------------------------------------------------
+
+ // Resume an active variant session after HMR/page reload.
+ // If a [data-impeccable-variants] wrapper exists in the DOM, the agent wrote
+ // variants before HMR fired. Pick up where we left off.
+ function resumeSession() {
+ const wrapper = document.querySelector('[data-impeccable-variants]');
+ if (!wrapper) { clearSession(); clearHandled(); return false; }
+
+ const sessionId = wrapper.dataset.impeccableVariants;
+
+ // Don't resume if this session was already accepted/discarded
+ if (isSessionHandled(sessionId)) return false;
+
+ currentSessionId = sessionId;
+ expectedVariants = parseInt(wrapper.dataset.impeccableVariantCount || '0');
+ const variants = wrapper.querySelectorAll('[data-impeccable-variant]:not([data-impeccable-variant="original"])');
+ arrivedVariants = variants.length;
+
+ // Restore visible variant from localStorage if available, else default to 1
+ const saved = loadSession();
+ visibleVariant = (saved && saved.id === sessionId && saved.visible > 0 && saved.visible <= arrivedVariants)
+ ? saved.visible : (arrivedVariants > 0 ? 1 : 0);
+
+ // Find the visible variant's content element for highlight positioning
+ const visEl = wrapper.querySelector('[data-impeccable-variant="' + visibleVariant + '"] > :first-child');
+ selectedElement = visEl || wrapper.parentElement;
+
+ // Set display state BEFORE starting observer (avoid triggering it)
+ if (visibleVariant > 0) showVariantInDOM(currentSessionId, visibleVariant);
+
+ state = arrivedVariants >= expectedVariants ? 'CYCLING' : 'GENERATING';
+ showBar(state === 'CYCLING' ? 'cycling' : 'generating');
+ startScrollTracking();
+ saveSession();
+
+ // Start observing for more variants AFTER initial setup
+ if (variantObserver) variantObserver.disconnect();
+ variantObserver = startVariantObserver(currentSessionId);
+ return true;
+ }
+
+ function init() {
+ initHighlight();
+ initBar();
+ initActionPicker();
+ document.addEventListener('mousemove', handleMouseMove, true);
+ document.addEventListener('click', handleClick, true);
+ document.addEventListener('keydown', handleKeyDown, true);
+ connectSSE();
+
+ // Check for an active session to resume (variant wrapper already in DOM after HMR)
+ if (!resumeSession()) {
+ console.log('[impeccable] Live variant mode ready. Hover over elements to pick one.');
+ } else {
+ console.log('[impeccable] Resumed active variant session ' + currentSessionId + ' (' + arrivedVariants + '/' + expectedVariants + ' variants).');
+ }
+ }
+
+ if (document.readyState === 'loading') {
+ document.addEventListener('DOMContentLoaded', init);
+ } else {
+ init();
+ }
+})();
diff --git a/source/skills/impeccable/scripts/live-poll.mjs b/source/skills/impeccable/scripts/live-poll.mjs
new file mode 100644
index 000000000..52859416c
--- /dev/null
+++ b/source/skills/impeccable/scripts/live-poll.mjs
@@ -0,0 +1,123 @@
+/**
+ * CLI client for the live variant mode poll/reply protocol.
+ *
+ * Usage:
+ * npx impeccable poll # Block until browser event, print JSON
+ * npx impeccable poll --timeout=60000 # Custom timeout (ms)
+ * npx impeccable poll --reply <id> done # Reply "done" to event <id>
+ * npx impeccable poll --reply <id> error "msg" # Reply with error
+ */
+
+import fs from 'node:fs';
+import path from 'node:path';
+import os from 'node:os';
+
+const LIVE_PID_FILE = path.join(os.tmpdir(), 'impeccable-live.json');
+
+function readServerInfo() {
+ try {
+ return JSON.parse(fs.readFileSync(LIVE_PID_FILE, 'utf-8'));
+ } catch {
+ console.error('No running live server found. Start one with: npx impeccable live');
+ process.exit(1);
+ }
+}
+
+export async function pollCli() {
+ const args = process.argv.slice(2);
+
+ if (args.includes('--help') || args.includes('-h')) {
+ console.log(`Usage: impeccable poll [options]
+
+Wait for a browser event from the live variant server, or reply to one.
+
+Modes:
+ poll Block until a browser event arrives, print JSON
+ poll --reply <id> done Reply "done" to event <id>
+ poll --reply <id> error "msg" Reply with an error message
+
+Options:
+ --timeout=MS Poll timeout in milliseconds (default: 120000)
+ --help Show this help message`);
+ process.exit(0);
+ }
+
+ const info = readServerInfo();
+ const base = `http://localhost:${info.port}`;
+
+ // Reply mode: npx impeccable poll --reply <id> <status> [--file path] [message]
+ const replyIdx = args.indexOf('--reply');
+ if (replyIdx !== -1) {
+ const id = args[replyIdx + 1];
+ const status = args[replyIdx + 2] || 'done';
+ const fileIdx = args.indexOf('--file');
+ const filePath = fileIdx !== -1 && fileIdx + 1 < args.length ? args[fileIdx + 1] : undefined;
+ // Message is any remaining positional arg that isn't a flag
+ const message = args.find((a, i) => i > replyIdx + 2 && !a.startsWith('--') && i !== fileIdx + 1) || undefined;
+
+ if (!id) {
+ console.error('Usage: npx impeccable poll --reply <id> <status> [--file path] [message]');
+ process.exit(1);
+ }
+
+ 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);
+ }
+
+ // Success — silent exit (agent doesn't need output for replies)
+ } catch (err) {
+ if (err.cause?.code === 'ECONNREFUSED') {
+ console.error('Live server not running. Start one with: npx impeccable live');
+ } else {
+ console.error('Reply failed:', err.message);
+ }
+ process.exit(1);
+ }
+ return;
+ }
+
+ // Poll mode: block until browser event
+ const timeoutArg = args.find(a => a.startsWith('--timeout='));
+ const timeout = timeoutArg ? parseInt(timeoutArg.split('=')[1], 10) : 120000;
+
+ try {
+ const res = await fetch(`${base}/poll?token=${info.token}&timeout=${timeout}`);
+
+ if (res.status === 401) {
+ console.error('Authentication failed. The server token may have changed.');
+ console.error('Try restarting: npx impeccable live stop && npx impeccable live');
+ process.exit(1);
+ }
+
+ if (!res.ok) {
+ console.error(`Poll failed: ${res.status} ${res.statusText}`);
+ process.exit(1);
+ }
+
+ const event = await res.json();
+ // Print the event as JSON — the agent reads this from stdout
+ console.log(JSON.stringify(event));
+ } catch (err) {
+ if (err.cause?.code === 'ECONNREFUSED') {
+ console.error('Live server not running. Start one with: npx impeccable live');
+ } else {
+ console.error('Poll failed:', err.message);
+ }
+ process.exit(1);
+ }
+}
diff --git a/source/skills/impeccable/scripts/live-server.mjs b/source/skills/impeccable/scripts/live-server.mjs
new file mode 100644
index 000000000..d436bad58
--- /dev/null
+++ b/source/skills/impeccable/scripts/live-server.mjs
@@ -0,0 +1,416 @@
+#!/usr/bin/env node
+/**
+ * Live variant mode server (self-contained, zero dependencies).
+ *
+ * Serves the browser script (/live.js), the detection overlay (/detect.js),
+ * uses Server-Sent Events (SSE) for server→browser push, and HTTP POST for
+ * browser→server events. Agent communicates via HTTP long-poll (/poll).
+ *
+ * Usage:
+ * node <scripts_path>/live-server.mjs # start
+ * node <scripts_path>/live-server.mjs stop # stop
+ * node <scripts_path>/live-server.mjs --help
+ */
+
+import http from 'node:http';
+import { randomUUID } from 'node:crypto';
+import fs from 'node:fs';
+import path from 'node:path';
+import os from 'node:os';
+import net from 'node:net';
+import { fileURLToPath } from 'node:url';
+
+const __dirname = path.dirname(fileURLToPath(import.meta.url));
+const LIVE_PID_FILE = path.join(os.tmpdir(), 'impeccable-live.json');
+const DEFAULT_POLL_TIMEOUT = 120_000;
+
+// ---------------------------------------------------------------------------
+// Port detection
+// ---------------------------------------------------------------------------
+
+async function findOpenPort(start = 8400) {
+ return new Promise((resolve) => {
+ const srv = net.createServer();
+ srv.listen(start, '127.0.0.1', () => {
+ const port = srv.address().port;
+ srv.close(() => resolve(port));
+ });
+ srv.on('error', () => resolve(findOpenPort(start + 1)));
+ });
+}
+
+// ---------------------------------------------------------------------------
+// Session state
+// ---------------------------------------------------------------------------
+
+const state = {
+ token: null,
+ port: null,
+ sseClients: new Set(), // SSE response objects (server→browser push)
+ pendingEvents: [], // browser events waiting for agent poll
+ pendingPolls: [], // agent poll callbacks waiting for browser events
+ exitTimer: null,
+};
+
+function enqueueEvent(event) {
+ if (state.pendingPolls.length > 0) {
+ state.pendingPolls.shift()(event);
+ } else {
+ state.pendingEvents.push(event);
+ }
+}
+
+/** Push a message to all connected SSE clients. */
+function broadcast(msg) {
+ const data = 'data: ' + JSON.stringify(msg) + '\n\n';
+ for (const res of state.sseClients) {
+ try { res.write(data); } catch { /* client gone */ }
+ }
+}
+
+// ---------------------------------------------------------------------------
+// Load scripts
+// ---------------------------------------------------------------------------
+
+function loadBrowserScripts() {
+ // Detection script: look relative to the skill scripts dir, then fall back
+ // to the npm package location (src/detect-antipatterns-browser.js)
+ const detectPaths = [
+ path.join(__dirname, '..', '..', '..', '..', 'src', 'detect-antipatterns-browser.js'),
+ path.join(process.cwd(), 'node_modules', 'impeccable', 'src', 'detect-antipatterns-browser.js'),
+ ];
+ let detectScript = '';
+ for (const p of detectPaths) {
+ try { detectScript = fs.readFileSync(p, 'utf-8'); break; } catch { /* try next */ }
+ }
+
+ const livePath = path.join(__dirname, 'live-browser.js');
+ let liveScript = '';
+ try {
+ liveScript = fs.readFileSync(livePath, 'utf-8');
+ } catch {
+ process.stderr.write('Error: live-browser.js not found at ' + livePath + '\n');
+ process.exit(1);
+ }
+
+ return { detectScript, liveScript };
+}
+
+function hasProjectContext() {
+ try {
+ fs.accessSync(path.join(process.cwd(), '.impeccable.md'), fs.constants.R_OK);
+ return true;
+ } catch { return false; }
+}
+
+// ---------------------------------------------------------------------------
+// Validation (inline — no external import needed for self-contained script)
+// ---------------------------------------------------------------------------
+
+const VISUAL_ACTIONS = [
+ 'impeccable', 'bolder', 'quieter', 'distill', 'polish', 'typeset',
+ 'colorize', 'layout', 'adapt', 'animate', 'delight', 'overdrive',
+];
+
+function validateEvent(msg) {
+ if (!msg || typeof msg !== 'object' || !msg.type) return 'Missing or invalid message';
+ switch (msg.type) {
+ case 'generate':
+ if (!msg.id || typeof msg.id !== 'string') return 'generate: missing id';
+ if (!msg.action || !VISUAL_ACTIONS.includes(msg.action)) return 'generate: invalid action';
+ if (!Number.isInteger(msg.count) || msg.count < 1 || msg.count > 8) return 'generate: count must be 1-8';
+ if (!msg.element || !msg.element.outerHTML) return 'generate: missing element context';
+ return null;
+ case 'accept':
+ if (!msg.id) return 'accept: missing id';
+ if (!msg.variantId) return 'accept: missing variantId';
+ return null;
+ case 'discard':
+ return msg.id ? null : 'discard: missing id';
+ case 'exit':
+ return null;
+ default:
+ return 'Unknown event type: ' + msg.type;
+ }
+}
+
+// ---------------------------------------------------------------------------
+// HTTP request handler
+// ---------------------------------------------------------------------------
+
+function createRequestHandler({ detectScript, liveScriptWithToken }) {
+ return (req, res) => {
+ const url = new URL(req.url, `http://localhost:${state.port}`);
+ res.setHeader('Access-Control-Allow-Origin', '*');
+ res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS');
+ res.setHeader('Access-Control-Allow-Headers', 'Content-Type');
+ if (req.method === 'OPTIONS') { res.writeHead(204); res.end(); return; }
+
+ const p = url.pathname;
+
+ // --- Scripts ---
+ if (p === '/live.js') {
+ res.writeHead(200, { 'Content-Type': 'application/javascript' });
+ res.end(liveScriptWithToken);
+ return;
+ }
+ if (p === '/detect.js' || p === '/') {
+ if (!detectScript) { res.writeHead(404); res.end('Not available'); return; }
+ res.writeHead(200, { 'Content-Type': 'application/javascript' });
+ res.end(detectScript);
+ return;
+ }
+
+ // --- Health ---
+ if (p === '/health') {
+ res.writeHead(200, { 'Content-Type': 'application/json' });
+ res.end(JSON.stringify({
+ status: 'ok', port: state.port, mode: 'variant',
+ hasProjectContext: hasProjectContext(),
+ connectedClients: state.sseClients.size,
+ }));
+ return;
+ }
+
+ // --- Source file (no-HMR fallback) ---
+ if (p === '/source') {
+ const token = url.searchParams.get('token');
+ if (token !== state.token) { res.writeHead(401); res.end('Unauthorized'); return; }
+ const filePath = url.searchParams.get('path');
+ if (!filePath || filePath.includes('..')) { res.writeHead(400); res.end('Bad path'); return; }
+ const absPath = path.resolve(process.cwd(), filePath);
+ if (!absPath.startsWith(process.cwd())) { res.writeHead(403); res.end('Forbidden'); return; }
+ try {
+ res.writeHead(200, { 'Content-Type': 'text/html; charset=utf-8' });
+ res.end(fs.readFileSync(absPath, 'utf-8'));
+ } catch { res.writeHead(404); res.end('File not found'); }
+ return;
+ }
+
+ // --- SSE: server→browser push (replaces WebSocket) ---
+ if (p === '/events' && req.method === 'GET') {
+ const token = url.searchParams.get('token');
+ if (token !== state.token) { res.writeHead(401); res.end('Unauthorized'); return; }
+ res.writeHead(200, {
+ 'Content-Type': 'text/event-stream',
+ 'Cache-Control': 'no-cache',
+ 'Connection': 'keep-alive',
+ });
+ res.write('data: ' + JSON.stringify({
+ type: 'connected',
+ hasProjectContext: hasProjectContext(),
+ }) + '\n\n');
+
+ state.sseClients.add(res);
+ clearTimeout(state.exitTimer);
+
+ req.on('close', () => {
+ state.sseClients.delete(res);
+ if (state.sseClients.size === 0) {
+ clearTimeout(state.exitTimer);
+ state.exitTimer = setTimeout(() => {
+ if (state.sseClients.size === 0) enqueueEvent({ type: 'exit' });
+ }, 8000);
+ }
+ });
+ return;
+ }
+
+ // --- Browser→server events (replaces WebSocket messages) ---
+ if (p === '/events' && req.method === 'POST') {
+ let body = '';
+ req.on('data', (c) => { body += c; });
+ req.on('end', () => {
+ let msg;
+ try { msg = JSON.parse(body); } catch {
+ res.writeHead(400, { 'Content-Type': 'application/json' });
+ res.end(JSON.stringify({ error: 'Invalid JSON' }));
+ return;
+ }
+ if (msg.token !== state.token) {
+ res.writeHead(401, { 'Content-Type': 'application/json' });
+ res.end(JSON.stringify({ error: 'Unauthorized' }));
+ return;
+ }
+ const error = validateEvent(msg);
+ if (error) {
+ res.writeHead(400, { 'Content-Type': 'application/json' });
+ res.end(JSON.stringify({ error }));
+ return;
+ }
+ enqueueEvent(msg);
+ res.writeHead(200, { 'Content-Type': 'application/json' });
+ res.end(JSON.stringify({ ok: true }));
+ });
+ return;
+ }
+
+ // --- Stop ---
+ if (p === '/stop') {
+ const token = url.searchParams.get('token');
+ if (token !== state.token) { res.writeHead(401); res.end('Unauthorized'); return; }
+ res.writeHead(200, { 'Content-Type': 'text/plain' });
+ res.end('stopping');
+ shutdown();
+ return;
+ }
+
+ // --- Agent poll ---
+ if (p === '/poll' && req.method === 'GET') {
+ handlePollGet(req, res, url);
+ return;
+ }
+ if (p === '/poll' && req.method === 'POST') {
+ handlePollPost(req, res);
+ return;
+ }
+
+ res.writeHead(404); res.end('Not found');
+ };
+}
+
+// ---------------------------------------------------------------------------
+// Agent poll endpoints (unchanged from WS version)
+// ---------------------------------------------------------------------------
+
+function handlePollGet(req, res, url) {
+ 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 timeout = parseInt(url.searchParams.get('timeout') || DEFAULT_POLL_TIMEOUT, 10);
+ if (state.pendingEvents.length > 0) {
+ res.writeHead(200, { 'Content-Type': 'application/json' });
+ res.end(JSON.stringify(state.pendingEvents.shift()));
+ return;
+ }
+ const timer = setTimeout(() => {
+ const idx = state.pendingPolls.indexOf(resolve);
+ if (idx !== -1) state.pendingPolls.splice(idx, 1);
+ res.writeHead(200, { 'Content-Type': 'application/json' });
+ res.end(JSON.stringify({ type: 'timeout' }));
+ }, timeout);
+ function resolve(event) {
+ clearTimeout(timer);
+ res.writeHead(200, { 'Content-Type': 'application/json' });
+ res.end(JSON.stringify(event));
+ }
+ state.pendingPolls.push(resolve);
+ req.on('close', () => {
+ clearTimeout(timer);
+ const idx = state.pendingPolls.indexOf(resolve);
+ if (idx !== -1) state.pendingPolls.splice(idx, 1);
+ });
+}
+
+function handlePollPost(req, res) {
+ let body = '';
+ req.on('data', (c) => { body += c; });
+ req.on('end', () => {
+ let msg;
+ try { msg = JSON.parse(body); } catch {
+ res.writeHead(400, { 'Content-Type': 'application/json' });
+ res.end(JSON.stringify({ error: 'Invalid JSON' }));
+ return;
+ }
+ if (msg.token !== state.token) {
+ res.writeHead(401, { 'Content-Type': 'application/json' });
+ res.end(JSON.stringify({ error: 'Unauthorized' }));
+ return;
+ }
+ // Forward the reply to the browser via SSE
+ broadcast({ type: msg.type || 'done', id: msg.id, message: msg.message, file: msg.file, data: msg.data });
+ res.writeHead(200, { 'Content-Type': 'application/json' });
+ res.end(JSON.stringify({ ok: true }));
+ });
+}
+
+// ---------------------------------------------------------------------------
+// Lifecycle
+// ---------------------------------------------------------------------------
+
+let httpServer = null;
+
+function shutdown() {
+ try { fs.unlinkSync(LIVE_PID_FILE); } catch {}
+ for (const res of state.sseClients) { try { res.end(); } catch {} }
+ state.sseClients.clear();
+ for (const resolve of state.pendingPolls) resolve({ type: 'exit' });
+ state.pendingPolls.length = 0;
+ if (httpServer) httpServer.close();
+ process.exit(0);
+}
+
+// ---------------------------------------------------------------------------
+// Main
+// ---------------------------------------------------------------------------
+
+const args = process.argv.slice(2);
+
+if (args.includes('--help') || args.includes('-h')) {
+ console.log(`Usage: node live-server.mjs [options]
+
+Start the live variant mode server (zero dependencies).
+
+Commands:
+ (default) Start the server
+ stop Stop a running server
+
+Options:
+ --port=PORT Use a specific port (default: auto-detect starting at 8400)
+ --help Show this help
+
+Endpoints:
+ /live.js Browser script (element picker + variant cycling)
+ /detect.js Detection overlay (backwards compatible)
+ /events SSE stream (server→browser) + POST (browser→server)
+ /poll Long-poll for agent CLI
+ /source Raw source file reader (no-HMR fallback)
+ /health Health check`);
+ process.exit(0);
+}
+
+if (args.includes('stop')) {
+ try {
+ const info = JSON.parse(fs.readFileSync(LIVE_PID_FILE, 'utf-8'));
+ 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 { console.log('No running live server found.'); }
+ process.exit(0);
+}
+
+// Check for existing session
+try {
+ const existing = JSON.parse(fs.readFileSync(LIVE_PID_FILE, 'utf-8'));
+ 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 {}
+
+state.token = randomUUID();
+const portArg = args.find(a => a.startsWith('--port='));
+state.port = portArg ? parseInt(portArg.split('=')[1], 10) : await findOpenPort();
+
+const { detectScript, liveScript } = loadBrowserScripts();
+const liveScriptWithToken =
+ `window.__IMPECCABLE_TOKEN__ = '${state.token}';\n` +
+ `window.__IMPECCABLE_PORT__ = ${state.port};\n` +
+ liveScript;
+
+httpServer = http.createServer(createRequestHandler({ detectScript, liveScriptWithToken }));
+
+httpServer.listen(state.port, '127.0.0.1', () => {
+ fs.writeFileSync(LIVE_PID_FILE, JSON.stringify({ 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`);
+ console.log(`Inject: <script src="${url}/live.js"><\/script>`);
+ console.log(`Stop: node ${path.basename(fileURLToPath(import.meta.url))} stop`);
+});
+
+process.on('SIGINT', shutdown);
+process.on('SIGTERM', shutdown);
diff --git a/source/skills/impeccable/scripts/live-wrap.mjs b/source/skills/impeccable/scripts/live-wrap.mjs
new file mode 100644
index 000000000..f1c838cdd
--- /dev/null
+++ b/source/skills/impeccable/scripts/live-wrap.mjs
@@ -0,0 +1,298 @@
+/**
+ * CLI helper: find an element in source and wrap it in a variant container.
+ *
+ * Usage:
+ * npx impeccable wrap --id SESSION_ID --count N --query "hero-combined-left" [--file path]
+ *
+ * Searches project files for the element matching the query (class name, ID, or
+ * text snippet), wraps it with the variant scaffolding, and prints the file path
+ * + line range where the agent should insert variant HTML.
+ *
+ * This replaces 3-4 agent tool calls (grep + read + edit) with a single CLI call.
+ */
+
+import fs from 'node:fs';
+import path from 'node:path';
+
+const EXTENSIONS = ['.html', '.jsx', '.tsx', '.vue', '.svelte', '.astro'];
+
+export async function wrapCli() {
+ const args = process.argv.slice(2);
+
+ if (args.includes('--help') || args.includes('-h')) {
+ console.log(`Usage: impeccable wrap [options]
+
+Find an element in source and wrap it in a variant container.
+
+Required:
+ --id ID Session ID for the variant wrapper
+ --count N Number of expected variants (1-8)
+
+Element identification (at least one required):
+ --element-id ID HTML id attribute of the element
+ --classes A,B,C Comma-separated CSS class names
+ --tag TAG Tag name (div, section, etc.)
+ --query TEXT Fallback: raw text to search for
+
+Optional:
+ --file PATH Source file to search in (skips auto-detection)
+ --help Show this help message
+
+Output (JSON):
+ { file, startLine, endLine, insertLine, commentSyntax }
+
+The agent should insert variant HTML at insertLine.`);
+ process.exit(0);
+ }
+
+ const id = argVal(args, '--id');
+ const count = parseInt(argVal(args, '--count') || '3');
+ const elementId = argVal(args, '--element-id');
+ const classes = argVal(args, '--classes');
+ const tag = argVal(args, '--tag');
+ const query = argVal(args, '--query');
+ const filePath = argVal(args, '--file');
+
+ if (!id) { console.error('Missing --id'); process.exit(1); }
+ if (!elementId && !classes && !query) {
+ console.error('Need at least one of: --element-id, --classes, --query');
+ process.exit(1);
+ }
+
+ // Build search queries in priority order (most specific first)
+ const queries = buildSearchQueries(elementId, classes, tag, query);
+
+ // Find the source file
+ let targetFile = filePath;
+ let matchedQuery = null;
+ if (!targetFile) {
+ for (const q of queries) {
+ targetFile = findFileWithQuery(q, process.cwd());
+ if (targetFile) { matchedQuery = q; break; }
+ }
+ if (!targetFile) {
+ console.error(JSON.stringify({ error: 'Could not find element in project files. Searched for: ' + queries.join(', ') }));
+ process.exit(1);
+ }
+ } else {
+ matchedQuery = queries[0];
+ }
+
+ const content = fs.readFileSync(targetFile, 'utf-8');
+ const lines = content.split('\n');
+
+ // Find the element, trying each query in priority order
+ let match = null;
+ for (const q of queries) {
+ match = findElement(lines, q);
+ if (match) break;
+ }
+ if (!match) {
+ console.error(JSON.stringify({ error: 'Found file but could not locate element in ' + targetFile + '. Searched for: ' + queries.join(', ') }));
+ process.exit(1);
+ }
+
+ const { startLine, endLine } = match;
+ const commentSyntax = detectCommentSyntax(targetFile);
+ const indent = lines[startLine].match(/^(\s*)/)[1];
+
+ // Extract the original element
+ const originalLines = lines.slice(startLine, endLine + 1);
+ const originalIndented = originalLines.map(l => indent + ' ' + l.trimStart()).join('\n');
+
+ // Build the wrapper
+ const wrapperLines = [
+ indent + commentSyntax.open + ' impeccable-variants-start ' + id + ' ' + commentSyntax.close,
+ indent + '<div data-impeccable-variants="' + id + '" data-impeccable-variant-count="' + count + '" style="display: contents">',
+ indent + ' ' + commentSyntax.open + ' Original ' + commentSyntax.close,
+ indent + ' <div data-impeccable-variant="original">',
+ originalIndented,
+ indent + ' </div>',
+ indent + ' ' + commentSyntax.open + ' Variants: insert below this line ' + commentSyntax.close,
+ indent + '</div>',
+ indent + commentSyntax.open + ' impeccable-variants-end ' + id + ' ' + commentSyntax.close,
+ ];
+
+ // Replace the original element with the wrapper
+ const newLines = [
+ ...lines.slice(0, startLine),
+ ...wrapperLines,
+ ...lines.slice(endLine + 1),
+ ];
+ fs.writeFileSync(targetFile, newLines.join('\n'), 'utf-8');
+
+ // Calculate insert line (the "insert below this line" comment)
+ const insertLine = startLine + 6; // 0-indexed in the new file
+
+ console.log(JSON.stringify({
+ file: path.relative(process.cwd(), targetFile),
+ startLine: startLine + 1, // 1-indexed for the agent
+ endLine: startLine + wrapperLines.length, // 1-indexed
+ insertLine: insertLine + 1, // 1-indexed: where variants go
+ commentSyntax: commentSyntax,
+ originalLineCount: originalLines.length,
+ }));
+}
+
+// ---------------------------------------------------------------------------
+// Helpers
+// ---------------------------------------------------------------------------
+
+function argVal(args, flag) {
+ const idx = args.indexOf(flag);
+ return idx !== -1 && idx + 1 < args.length ? args[idx + 1] : null;
+}
+
+/**
+ * Build search query strings in priority order (most specific first).
+ * ID is most reliable, then specific class combos, then single classes, then raw query.
+ */
+function buildSearchQueries(elementId, classes, tag, query) {
+ const queries = [];
+
+ // 1. ID is the most specific
+ if (elementId) {
+ queries.push('id="' + elementId + '"');
+ }
+
+ // 2. Full class attribute match (for elements with distinctive multi-class combos)
+ if (classes) {
+ const classList = classes.split(',').map(c => c.trim()).filter(Boolean);
+ if (classList.length > 1) {
+ // Try the most distinctive class first (longest, most specific)
+ const sorted = [...classList].sort((a, b) => b.length - a.length);
+ queries.push('class="' + classList.join(' ') + '"'); // exact full match
+ queries.push(sorted[0]); // most distinctive single class
+ } else if (classList.length === 1) {
+ queries.push(classList[0]);
+ }
+ }
+
+ // 3. Tag + class combo (e.g., <section class="hero">)
+ if (tag && classes) {
+ const firstClass = classes.split(',')[0].trim();
+ queries.push('<' + tag + ' class="' + firstClass);
+ }
+
+ // 4. Raw fallback query
+ if (query) {
+ queries.push(query);
+ }
+
+ return queries;
+}
+
+function detectCommentSyntax(filePath) {
+ const ext = path.extname(filePath).toLowerCase();
+ if (ext === '.jsx' || ext === '.tsx') {
+ return { open: '{/*', close: '*/}' };
+ }
+ // HTML, Vue, Svelte, Astro all use HTML comments
+ return { open: '<!--', close: '-->' };
+}
+
+/**
+ * Search project files for the query string (class name, ID, etc.)
+ * Returns the first matching file path, or null.
+ */
+function findFileWithQuery(query, cwd) {
+ const searchDirs = ['src', 'app', 'pages', 'components', 'public', 'views', 'templates', '.'];
+ const seen = new Set();
+
+ for (const dir of searchDirs) {
+ const absDir = path.join(cwd, dir);
+ if (!fs.existsSync(absDir)) continue;
+ const result = searchDir(absDir, query, seen, 0);
+ if (result) return result;
+ }
+ return null;
+}
+
+function searchDir(dir, query, seen, depth) {
+ if (depth > 5) return null; // don't go too deep
+ const realDir = fs.realpathSync(dir);
+ if (seen.has(realDir)) return null;
+ seen.add(realDir);
+
+ let entries;
+ try { entries = fs.readdirSync(dir, { withFileTypes: true }); }
+ catch { return null; }
+
+ // Check files first
+ for (const entry of entries) {
+ if (!entry.isFile()) continue;
+ const ext = path.extname(entry.name).toLowerCase();
+ if (!EXTENSIONS.includes(ext)) continue;
+
+ const filePath = path.join(dir, entry.name);
+ try {
+ const content = fs.readFileSync(filePath, 'utf-8');
+ if (content.includes(query)) return filePath;
+ } catch { /* skip unreadable files */ }
+ }
+
+ // Then recurse into directories
+ for (const entry of entries) {
+ if (!entry.isDirectory()) continue;
+ if (entry.name === 'node_modules' || entry.name === '.git' || entry.name === 'dist' || entry.name === 'build') continue;
+ const result = searchDir(path.join(dir, entry.name), query, seen, depth + 1);
+ if (result) return result;
+ }
+
+ return null;
+}
+
+/**
+ * Find the element's start and end line in the file.
+ * The query is a class name, ID, or text snippet.
+ * We find the line containing the query, then find the matching closing tag.
+ */
+function findElement(lines, query) {
+ // Find the line containing the query
+ let startLine = -1;
+ for (let i = 0; i < lines.length; i++) {
+ if (lines[i].includes(query)) {
+ // Make sure this looks like a tag opening, not a comment or string
+ const line = lines[i].trim();
+ if (line.startsWith('<!--') || line.startsWith('{/*') || line.startsWith('//')) continue;
+ // Skip lines inside data-impeccable-variant containers (already wrapped)
+ if (lines[i].includes('data-impeccable-variant')) continue;
+ startLine = i;
+ break;
+ }
+ }
+
+ if (startLine === -1) return null;
+
+ // Find the end of this element by counting open/close tags
+ const endLine = findClosingLine(lines, startLine);
+ return { startLine, endLine };
+}
+
+/**
+ * Starting from a line with an opening tag, find the line with the matching
+ * closing tag by counting tag nesting depth.
+ */
+function findClosingLine(lines, start) {
+ // Extract the tag name from the opening line
+ const openMatch = lines[start].match(/<(\w+)[\s>]/);
+ if (!openMatch) return start; // self-closing or text-only line
+
+ const tagName = openMatch[1];
+ let depth = 0;
+
+ for (let i = start; i < lines.length; i++) {
+ const line = lines[i];
+ // Count opening tags (not self-closing)
+ const opens = (line.match(new RegExp('<' + tagName + '[\\s>]', 'g')) || []).length;
+ const selfCloses = (line.match(new RegExp('<' + tagName + '[^>]*/>', 'g')) || []).length;
+ const closes = (line.match(new RegExp('</' + tagName + '\\s*>', 'g')) || []).length;
+
+ depth += opens - selfCloses - closes;
+
+ if (depth <= 0) return i;
+ }
+
+ // If we can't find the close, return a reasonable guess
+ return Math.min(start + 50, lines.length - 1);
+}
diff --git a/src/live/browser.js b/src/live/browser.js
index 02dad6343..7a26c9829 100644
--- a/src/live/browser.js
+++ b/src/live/browser.js
@@ -71,7 +71,6 @@
// ---------------------------------------------------------------------------
let state = 'IDLE';
- let ws = null;
let hoveredElement = null;
let selectedElement = null;
let currentSessionId = null;
@@ -866,28 +865,26 @@
}
// ---------------------------------------------------------------------------
- // WebSocket
+ // SSE (server→browser) + fetch POST (browser→server)
+ // Zero-dependency replacement for WebSocket.
// ---------------------------------------------------------------------------
- function connectWS() {
- ws = new WebSocket('ws://localhost:' + PORT + '/ws');
- ws.onopen = () => ws.send(JSON.stringify({ type: 'auth', token: TOKEN }));
- ws.onmessage = (e) => {
+ let evtSource = null;
+
+ function connectSSE() {
+ evtSource = new EventSource('http://localhost:' + PORT + '/events?token=' + TOKEN);
+
+ evtSource.onmessage = (e) => {
let msg; try { msg = JSON.parse(e.data); } catch { return; }
switch (msg.type) {
- case 'auth_ok':
+ case 'connected':
hasProjectContext = !!msg.hasProjectContext;
if (!hasProjectContext) showToast('No .impeccable.md found. Variants will be brand-agnostic.', 6000);
console.log('[impeccable] Live mode connected.');
- // Only go to PICKING if we're not already in a resumed session
if (state === 'IDLE') state = 'PICKING';
break;
- case 'auth_fail':
- console.error('[impeccable] Auth failed:', msg.reason);
- break;
case 'done':
if (state === 'SAVING') {
- // Accept/discard was processed. Show green confirmation, then dismiss.
state = 'CONFIRMED';
updateBarContent('confirmed');
setTimeout(() => {
@@ -903,8 +900,6 @@
}, 1800);
return;
}
- // If variants haven't appeared in the DOM (no HMR), fetch the raw
- // source file from the live server and inject variants into the DOM.
if (arrivedVariants === 0 && expectedVariants > 0 && msg.file) {
console.log('[impeccable] No HMR detected. Fetching variants from source file...');
injectVariantsFromSource(msg.file, currentSessionId);
@@ -921,12 +916,20 @@
break;
}
};
- ws.onclose = () => { setTimeout(connectWS, 3000); };
- ws.onerror = () => {};
+
+ evtSource.onerror = () => {
+ // EventSource auto-reconnects. Log once.
+ console.log('[impeccable] SSE connection lost. Reconnecting...');
+ };
}
- function sendWS(msg) {
- if (ws && ws.readyState === 1) ws.send(JSON.stringify(msg));
+ function sendEvent(msg) {
+ msg.token = TOKEN;
+ 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));
}
// ---------------------------------------------------------------------------
@@ -1017,7 +1020,7 @@
arrivedVariants = 0;
visibleVariant = 0;
- sendWS({
+ sendEvent({
type: 'generate', id: currentSessionId,
action: selectedAction,
freeformPrompt: prompt || undefined,
@@ -1035,7 +1038,7 @@
function handleAccept() {
if (!currentSessionId || arrivedVariants === 0) return;
- sendWS({ type: 'accept', id: currentSessionId, variantId: String(visibleVariant) });
+ sendEvent({ type: 'accept', id: currentSessionId, variantId: String(visibleVariant) });
markSessionHandled();
state = 'SAVING';
updateBarContent('saving');
@@ -1044,7 +1047,7 @@
function handleDiscard() {
if (!currentSessionId) return;
- sendWS({ type: 'discard', id: currentSessionId });
+ sendEvent({ type: 'discard', id: currentSessionId });
markSessionHandled();
state = 'SAVING';
updateBarContent('saving');
@@ -1199,7 +1202,7 @@
document.addEventListener('mousemove', handleMouseMove, true);
document.addEventListener('click', handleClick, true);
document.addEventListener('keydown', handleKeyDown, true);
- connectWS();
+ connectSSE();
// Check for an active session to resume (variant wrapper already in DOM after HMR)
if (!resumeSession()) {