Skip to content

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

JavaScript

Remove live commands from CLI, delete src/live, add server-lost cleanup

Paul Bakaus7011a523e0d2
diff --git a/.agents/skills/impeccable/scripts/live-browser.js b/.agents/skills/impeccable/scripts/live-browser.js
index 7a26c9829..72534661b 100644
--- a/.agents/skills/impeccable/scripts/live-browser.js
+++ b/.agents/skills/impeccable/scripts/live-browser.js
@@ -870,11 +870,14 @@
// ---------------------------------------------------------------------------
let evtSource = null;
+ let sseRetries = 0;
+ const SSE_MAX_RETRIES = 5;
function connectSSE() {
evtSource = new EventSource('http://localhost:' + PORT + '/events?token=' + TOKEN);
evtSource.onmessage = (e) => {
+ sseRetries = 0; // reset on any successful message
let msg; try { msg = JSON.parse(e.data); } catch { return; }
switch (msg.type) {
case 'connected':
@@ -918,11 +921,35 @@
};
evtSource.onerror = () => {
- // EventSource auto-reconnects. Log once.
- console.log('[impeccable] SSE connection lost. Reconnecting...');
+ sseRetries++;
+ if (sseRetries <= SSE_MAX_RETRIES) {
+ console.log('[impeccable] SSE connection lost. Retry ' + sseRetries + '/' + SSE_MAX_RETRIES + '...');
+ return; // EventSource auto-reconnects
+ }
+ // Server is gone. Clean up gracefully.
+ console.log('[impeccable] Live server unreachable. Cleaning up UI.');
+ evtSource.close();
+ evtSource = null;
+ handleServerLost();
};
}
+ /** Server died or became unreachable. Reset UI to a clean state. */
+ function handleServerLost() {
+ if (state === 'GENERATING' || state === 'CYCLING' || state === 'SAVING') {
+ showToast('Live server disconnected. Session ended.', 5000);
+ }
+ hideBar();
+ hideHighlight();
+ stopScrollTracking();
+ if (variantObserver) { variantObserver.disconnect(); variantObserver = null; }
+ clearSession();
+ selectedElement = null;
+ currentSessionId = null;
+ selectedAction = 'impeccable';
+ state = 'IDLE';
+ }
+
function sendEvent(msg) {
msg.token = TOKEN;
fetch('http://localhost:' + PORT + '/events', {
diff --git a/.claude/skills/impeccable/scripts/live-browser.js b/.claude/skills/impeccable/scripts/live-browser.js
index 7a26c9829..72534661b 100644
--- a/.claude/skills/impeccable/scripts/live-browser.js
+++ b/.claude/skills/impeccable/scripts/live-browser.js
@@ -870,11 +870,14 @@
// ---------------------------------------------------------------------------
let evtSource = null;
+ let sseRetries = 0;
+ const SSE_MAX_RETRIES = 5;
function connectSSE() {
evtSource = new EventSource('http://localhost:' + PORT + '/events?token=' + TOKEN);
evtSource.onmessage = (e) => {
+ sseRetries = 0; // reset on any successful message
let msg; try { msg = JSON.parse(e.data); } catch { return; }
switch (msg.type) {
case 'connected':
@@ -918,11 +921,35 @@
};
evtSource.onerror = () => {
- // EventSource auto-reconnects. Log once.
- console.log('[impeccable] SSE connection lost. Reconnecting...');
+ sseRetries++;
+ if (sseRetries <= SSE_MAX_RETRIES) {
+ console.log('[impeccable] SSE connection lost. Retry ' + sseRetries + '/' + SSE_MAX_RETRIES + '...');
+ return; // EventSource auto-reconnects
+ }
+ // Server is gone. Clean up gracefully.
+ console.log('[impeccable] Live server unreachable. Cleaning up UI.');
+ evtSource.close();
+ evtSource = null;
+ handleServerLost();
};
}
+ /** Server died or became unreachable. Reset UI to a clean state. */
+ function handleServerLost() {
+ if (state === 'GENERATING' || state === 'CYCLING' || state === 'SAVING') {
+ showToast('Live server disconnected. Session ended.', 5000);
+ }
+ hideBar();
+ hideHighlight();
+ stopScrollTracking();
+ if (variantObserver) { variantObserver.disconnect(); variantObserver = null; }
+ clearSession();
+ selectedElement = null;
+ currentSessionId = null;
+ selectedAction = 'impeccable';
+ state = 'IDLE';
+ }
+
function sendEvent(msg) {
msg.token = TOKEN;
fetch('http://localhost:' + PORT + '/events', {
diff --git a/.codex/skills/impeccable/scripts/live-browser.js b/.codex/skills/impeccable/scripts/live-browser.js
index 7a26c9829..72534661b 100644
--- a/.codex/skills/impeccable/scripts/live-browser.js
+++ b/.codex/skills/impeccable/scripts/live-browser.js
@@ -870,11 +870,14 @@
// ---------------------------------------------------------------------------
let evtSource = null;
+ let sseRetries = 0;
+ const SSE_MAX_RETRIES = 5;
function connectSSE() {
evtSource = new EventSource('http://localhost:' + PORT + '/events?token=' + TOKEN);
evtSource.onmessage = (e) => {
+ sseRetries = 0; // reset on any successful message
let msg; try { msg = JSON.parse(e.data); } catch { return; }
switch (msg.type) {
case 'connected':
@@ -918,11 +921,35 @@
};
evtSource.onerror = () => {
- // EventSource auto-reconnects. Log once.
- console.log('[impeccable] SSE connection lost. Reconnecting...');
+ sseRetries++;
+ if (sseRetries <= SSE_MAX_RETRIES) {
+ console.log('[impeccable] SSE connection lost. Retry ' + sseRetries + '/' + SSE_MAX_RETRIES + '...');
+ return; // EventSource auto-reconnects
+ }
+ // Server is gone. Clean up gracefully.
+ console.log('[impeccable] Live server unreachable. Cleaning up UI.');
+ evtSource.close();
+ evtSource = null;
+ handleServerLost();
};
}
+ /** Server died or became unreachable. Reset UI to a clean state. */
+ function handleServerLost() {
+ if (state === 'GENERATING' || state === 'CYCLING' || state === 'SAVING') {
+ showToast('Live server disconnected. Session ended.', 5000);
+ }
+ hideBar();
+ hideHighlight();
+ stopScrollTracking();
+ if (variantObserver) { variantObserver.disconnect(); variantObserver = null; }
+ clearSession();
+ selectedElement = null;
+ currentSessionId = null;
+ selectedAction = 'impeccable';
+ state = 'IDLE';
+ }
+
function sendEvent(msg) {
msg.token = TOKEN;
fetch('http://localhost:' + PORT + '/events', {
diff --git a/.cursor/skills/impeccable/scripts/live-browser.js b/.cursor/skills/impeccable/scripts/live-browser.js
index 7a26c9829..72534661b 100644
--- a/.cursor/skills/impeccable/scripts/live-browser.js
+++ b/.cursor/skills/impeccable/scripts/live-browser.js
@@ -870,11 +870,14 @@
// ---------------------------------------------------------------------------
let evtSource = null;
+ let sseRetries = 0;
+ const SSE_MAX_RETRIES = 5;
function connectSSE() {
evtSource = new EventSource('http://localhost:' + PORT + '/events?token=' + TOKEN);
evtSource.onmessage = (e) => {
+ sseRetries = 0; // reset on any successful message
let msg; try { msg = JSON.parse(e.data); } catch { return; }
switch (msg.type) {
case 'connected':
@@ -918,11 +921,35 @@
};
evtSource.onerror = () => {
- // EventSource auto-reconnects. Log once.
- console.log('[impeccable] SSE connection lost. Reconnecting...');
+ sseRetries++;
+ if (sseRetries <= SSE_MAX_RETRIES) {
+ console.log('[impeccable] SSE connection lost. Retry ' + sseRetries + '/' + SSE_MAX_RETRIES + '...');
+ return; // EventSource auto-reconnects
+ }
+ // Server is gone. Clean up gracefully.
+ console.log('[impeccable] Live server unreachable. Cleaning up UI.');
+ evtSource.close();
+ evtSource = null;
+ handleServerLost();
};
}
+ /** Server died or became unreachable. Reset UI to a clean state. */
+ function handleServerLost() {
+ if (state === 'GENERATING' || state === 'CYCLING' || state === 'SAVING') {
+ showToast('Live server disconnected. Session ended.', 5000);
+ }
+ hideBar();
+ hideHighlight();
+ stopScrollTracking();
+ if (variantObserver) { variantObserver.disconnect(); variantObserver = null; }
+ clearSession();
+ selectedElement = null;
+ currentSessionId = null;
+ selectedAction = 'impeccable';
+ state = 'IDLE';
+ }
+
function sendEvent(msg) {
msg.token = TOKEN;
fetch('http://localhost:' + PORT + '/events', {
diff --git a/.gemini/skills/impeccable/scripts/live-browser.js b/.gemini/skills/impeccable/scripts/live-browser.js
index 7a26c9829..72534661b 100644
--- a/.gemini/skills/impeccable/scripts/live-browser.js
+++ b/.gemini/skills/impeccable/scripts/live-browser.js
@@ -870,11 +870,14 @@
// ---------------------------------------------------------------------------
let evtSource = null;
+ let sseRetries = 0;
+ const SSE_MAX_RETRIES = 5;
function connectSSE() {
evtSource = new EventSource('http://localhost:' + PORT + '/events?token=' + TOKEN);
evtSource.onmessage = (e) => {
+ sseRetries = 0; // reset on any successful message
let msg; try { msg = JSON.parse(e.data); } catch { return; }
switch (msg.type) {
case 'connected':
@@ -918,11 +921,35 @@
};
evtSource.onerror = () => {
- // EventSource auto-reconnects. Log once.
- console.log('[impeccable] SSE connection lost. Reconnecting...');
+ sseRetries++;
+ if (sseRetries <= SSE_MAX_RETRIES) {
+ console.log('[impeccable] SSE connection lost. Retry ' + sseRetries + '/' + SSE_MAX_RETRIES + '...');
+ return; // EventSource auto-reconnects
+ }
+ // Server is gone. Clean up gracefully.
+ console.log('[impeccable] Live server unreachable. Cleaning up UI.');
+ evtSource.close();
+ evtSource = null;
+ handleServerLost();
};
}
+ /** Server died or became unreachable. Reset UI to a clean state. */
+ function handleServerLost() {
+ if (state === 'GENERATING' || state === 'CYCLING' || state === 'SAVING') {
+ showToast('Live server disconnected. Session ended.', 5000);
+ }
+ hideBar();
+ hideHighlight();
+ stopScrollTracking();
+ if (variantObserver) { variantObserver.disconnect(); variantObserver = null; }
+ clearSession();
+ selectedElement = null;
+ currentSessionId = null;
+ selectedAction = 'impeccable';
+ state = 'IDLE';
+ }
+
function sendEvent(msg) {
msg.token = TOKEN;
fetch('http://localhost:' + PORT + '/events', {
diff --git a/.kiro/skills/impeccable/scripts/live-browser.js b/.kiro/skills/impeccable/scripts/live-browser.js
index 7a26c9829..72534661b 100644
--- a/.kiro/skills/impeccable/scripts/live-browser.js
+++ b/.kiro/skills/impeccable/scripts/live-browser.js
@@ -870,11 +870,14 @@
// ---------------------------------------------------------------------------
let evtSource = null;
+ let sseRetries = 0;
+ const SSE_MAX_RETRIES = 5;
function connectSSE() {
evtSource = new EventSource('http://localhost:' + PORT + '/events?token=' + TOKEN);
evtSource.onmessage = (e) => {
+ sseRetries = 0; // reset on any successful message
let msg; try { msg = JSON.parse(e.data); } catch { return; }
switch (msg.type) {
case 'connected':
@@ -918,11 +921,35 @@
};
evtSource.onerror = () => {
- // EventSource auto-reconnects. Log once.
- console.log('[impeccable] SSE connection lost. Reconnecting...');
+ sseRetries++;
+ if (sseRetries <= SSE_MAX_RETRIES) {
+ console.log('[impeccable] SSE connection lost. Retry ' + sseRetries + '/' + SSE_MAX_RETRIES + '...');
+ return; // EventSource auto-reconnects
+ }
+ // Server is gone. Clean up gracefully.
+ console.log('[impeccable] Live server unreachable. Cleaning up UI.');
+ evtSource.close();
+ evtSource = null;
+ handleServerLost();
};
}
+ /** Server died or became unreachable. Reset UI to a clean state. */
+ function handleServerLost() {
+ if (state === 'GENERATING' || state === 'CYCLING' || state === 'SAVING') {
+ showToast('Live server disconnected. Session ended.', 5000);
+ }
+ hideBar();
+ hideHighlight();
+ stopScrollTracking();
+ if (variantObserver) { variantObserver.disconnect(); variantObserver = null; }
+ clearSession();
+ selectedElement = null;
+ currentSessionId = null;
+ selectedAction = 'impeccable';
+ state = 'IDLE';
+ }
+
function sendEvent(msg) {
msg.token = TOKEN;
fetch('http://localhost:' + PORT + '/events', {
diff --git a/.opencode/skills/impeccable/scripts/live-browser.js b/.opencode/skills/impeccable/scripts/live-browser.js
index 7a26c9829..72534661b 100644
--- a/.opencode/skills/impeccable/scripts/live-browser.js
+++ b/.opencode/skills/impeccable/scripts/live-browser.js
@@ -870,11 +870,14 @@
// ---------------------------------------------------------------------------
let evtSource = null;
+ let sseRetries = 0;
+ const SSE_MAX_RETRIES = 5;
function connectSSE() {
evtSource = new EventSource('http://localhost:' + PORT + '/events?token=' + TOKEN);
evtSource.onmessage = (e) => {
+ sseRetries = 0; // reset on any successful message
let msg; try { msg = JSON.parse(e.data); } catch { return; }
switch (msg.type) {
case 'connected':
@@ -918,11 +921,35 @@
};
evtSource.onerror = () => {
- // EventSource auto-reconnects. Log once.
- console.log('[impeccable] SSE connection lost. Reconnecting...');
+ sseRetries++;
+ if (sseRetries <= SSE_MAX_RETRIES) {
+ console.log('[impeccable] SSE connection lost. Retry ' + sseRetries + '/' + SSE_MAX_RETRIES + '...');
+ return; // EventSource auto-reconnects
+ }
+ // Server is gone. Clean up gracefully.
+ console.log('[impeccable] Live server unreachable. Cleaning up UI.');
+ evtSource.close();
+ evtSource = null;
+ handleServerLost();
};
}
+ /** Server died or became unreachable. Reset UI to a clean state. */
+ function handleServerLost() {
+ if (state === 'GENERATING' || state === 'CYCLING' || state === 'SAVING') {
+ showToast('Live server disconnected. Session ended.', 5000);
+ }
+ hideBar();
+ hideHighlight();
+ stopScrollTracking();
+ if (variantObserver) { variantObserver.disconnect(); variantObserver = null; }
+ clearSession();
+ selectedElement = null;
+ currentSessionId = null;
+ selectedAction = 'impeccable';
+ state = 'IDLE';
+ }
+
function sendEvent(msg) {
msg.token = TOKEN;
fetch('http://localhost:' + PORT + '/events', {
diff --git a/.pi/skills/impeccable/scripts/live-browser.js b/.pi/skills/impeccable/scripts/live-browser.js
index 7a26c9829..72534661b 100644
--- a/.pi/skills/impeccable/scripts/live-browser.js
+++ b/.pi/skills/impeccable/scripts/live-browser.js
@@ -870,11 +870,14 @@
// ---------------------------------------------------------------------------
let evtSource = null;
+ let sseRetries = 0;
+ const SSE_MAX_RETRIES = 5;
function connectSSE() {
evtSource = new EventSource('http://localhost:' + PORT + '/events?token=' + TOKEN);
evtSource.onmessage = (e) => {
+ sseRetries = 0; // reset on any successful message
let msg; try { msg = JSON.parse(e.data); } catch { return; }
switch (msg.type) {
case 'connected':
@@ -918,11 +921,35 @@
};
evtSource.onerror = () => {
- // EventSource auto-reconnects. Log once.
- console.log('[impeccable] SSE connection lost. Reconnecting...');
+ sseRetries++;
+ if (sseRetries <= SSE_MAX_RETRIES) {
+ console.log('[impeccable] SSE connection lost. Retry ' + sseRetries + '/' + SSE_MAX_RETRIES + '...');
+ return; // EventSource auto-reconnects
+ }
+ // Server is gone. Clean up gracefully.
+ console.log('[impeccable] Live server unreachable. Cleaning up UI.');
+ evtSource.close();
+ evtSource = null;
+ handleServerLost();
};
}
+ /** Server died or became unreachable. Reset UI to a clean state. */
+ function handleServerLost() {
+ if (state === 'GENERATING' || state === 'CYCLING' || state === 'SAVING') {
+ showToast('Live server disconnected. Session ended.', 5000);
+ }
+ hideBar();
+ hideHighlight();
+ stopScrollTracking();
+ if (variantObserver) { variantObserver.disconnect(); variantObserver = null; }
+ clearSession();
+ selectedElement = null;
+ currentSessionId = null;
+ selectedAction = 'impeccable';
+ state = 'IDLE';
+ }
+
function sendEvent(msg) {
msg.token = TOKEN;
fetch('http://localhost:' + PORT + '/events', {
diff --git a/.rovodev/skills/impeccable/scripts/live-browser.js b/.rovodev/skills/impeccable/scripts/live-browser.js
index 7a26c9829..72534661b 100644
--- a/.rovodev/skills/impeccable/scripts/live-browser.js
+++ b/.rovodev/skills/impeccable/scripts/live-browser.js
@@ -870,11 +870,14 @@
// ---------------------------------------------------------------------------
let evtSource = null;
+ let sseRetries = 0;
+ const SSE_MAX_RETRIES = 5;
function connectSSE() {
evtSource = new EventSource('http://localhost:' + PORT + '/events?token=' + TOKEN);
evtSource.onmessage = (e) => {
+ sseRetries = 0; // reset on any successful message
let msg; try { msg = JSON.parse(e.data); } catch { return; }
switch (msg.type) {
case 'connected':
@@ -918,11 +921,35 @@
};
evtSource.onerror = () => {
- // EventSource auto-reconnects. Log once.
- console.log('[impeccable] SSE connection lost. Reconnecting...');
+ sseRetries++;
+ if (sseRetries <= SSE_MAX_RETRIES) {
+ console.log('[impeccable] SSE connection lost. Retry ' + sseRetries + '/' + SSE_MAX_RETRIES + '...');
+ return; // EventSource auto-reconnects
+ }
+ // Server is gone. Clean up gracefully.
+ console.log('[impeccable] Live server unreachable. Cleaning up UI.');
+ evtSource.close();
+ evtSource = null;
+ handleServerLost();
};
}
+ /** Server died or became unreachable. Reset UI to a clean state. */
+ function handleServerLost() {
+ if (state === 'GENERATING' || state === 'CYCLING' || state === 'SAVING') {
+ showToast('Live server disconnected. Session ended.', 5000);
+ }
+ hideBar();
+ hideHighlight();
+ stopScrollTracking();
+ if (variantObserver) { variantObserver.disconnect(); variantObserver = null; }
+ clearSession();
+ selectedElement = null;
+ currentSessionId = null;
+ selectedAction = 'impeccable';
+ state = 'IDLE';
+ }
+
function sendEvent(msg) {
msg.token = TOKEN;
fetch('http://localhost:' + PORT + '/events', {
diff --git a/.trae-cn/skills/impeccable/scripts/live-browser.js b/.trae-cn/skills/impeccable/scripts/live-browser.js
index 7a26c9829..72534661b 100644
--- a/.trae-cn/skills/impeccable/scripts/live-browser.js
+++ b/.trae-cn/skills/impeccable/scripts/live-browser.js
@@ -870,11 +870,14 @@
// ---------------------------------------------------------------------------
let evtSource = null;
+ let sseRetries = 0;
+ const SSE_MAX_RETRIES = 5;
function connectSSE() {
evtSource = new EventSource('http://localhost:' + PORT + '/events?token=' + TOKEN);
evtSource.onmessage = (e) => {
+ sseRetries = 0; // reset on any successful message
let msg; try { msg = JSON.parse(e.data); } catch { return; }
switch (msg.type) {
case 'connected':
@@ -918,11 +921,35 @@
};
evtSource.onerror = () => {
- // EventSource auto-reconnects. Log once.
- console.log('[impeccable] SSE connection lost. Reconnecting...');
+ sseRetries++;
+ if (sseRetries <= SSE_MAX_RETRIES) {
+ console.log('[impeccable] SSE connection lost. Retry ' + sseRetries + '/' + SSE_MAX_RETRIES + '...');
+ return; // EventSource auto-reconnects
+ }
+ // Server is gone. Clean up gracefully.
+ console.log('[impeccable] Live server unreachable. Cleaning up UI.');
+ evtSource.close();
+ evtSource = null;
+ handleServerLost();
};
}
+ /** Server died or became unreachable. Reset UI to a clean state. */
+ function handleServerLost() {
+ if (state === 'GENERATING' || state === 'CYCLING' || state === 'SAVING') {
+ showToast('Live server disconnected. Session ended.', 5000);
+ }
+ hideBar();
+ hideHighlight();
+ stopScrollTracking();
+ if (variantObserver) { variantObserver.disconnect(); variantObserver = null; }
+ clearSession();
+ selectedElement = null;
+ currentSessionId = null;
+ selectedAction = 'impeccable';
+ state = 'IDLE';
+ }
+
function sendEvent(msg) {
msg.token = TOKEN;
fetch('http://localhost:' + PORT + '/events', {
diff --git a/.trae/skills/impeccable/scripts/live-browser.js b/.trae/skills/impeccable/scripts/live-browser.js
index 7a26c9829..72534661b 100644
--- a/.trae/skills/impeccable/scripts/live-browser.js
+++ b/.trae/skills/impeccable/scripts/live-browser.js
@@ -870,11 +870,14 @@
// ---------------------------------------------------------------------------
let evtSource = null;
+ let sseRetries = 0;
+ const SSE_MAX_RETRIES = 5;
function connectSSE() {
evtSource = new EventSource('http://localhost:' + PORT + '/events?token=' + TOKEN);
evtSource.onmessage = (e) => {
+ sseRetries = 0; // reset on any successful message
let msg; try { msg = JSON.parse(e.data); } catch { return; }
switch (msg.type) {
case 'connected':
@@ -918,11 +921,35 @@
};
evtSource.onerror = () => {
- // EventSource auto-reconnects. Log once.
- console.log('[impeccable] SSE connection lost. Reconnecting...');
+ sseRetries++;
+ if (sseRetries <= SSE_MAX_RETRIES) {
+ console.log('[impeccable] SSE connection lost. Retry ' + sseRetries + '/' + SSE_MAX_RETRIES + '...');
+ return; // EventSource auto-reconnects
+ }
+ // Server is gone. Clean up gracefully.
+ console.log('[impeccable] Live server unreachable. Cleaning up UI.');
+ evtSource.close();
+ evtSource = null;
+ handleServerLost();
};
}
+ /** Server died or became unreachable. Reset UI to a clean state. */
+ function handleServerLost() {
+ if (state === 'GENERATING' || state === 'CYCLING' || state === 'SAVING') {
+ showToast('Live server disconnected. Session ended.', 5000);
+ }
+ hideBar();
+ hideHighlight();
+ stopScrollTracking();
+ if (variantObserver) { variantObserver.disconnect(); variantObserver = null; }
+ clearSession();
+ selectedElement = null;
+ currentSessionId = null;
+ selectedAction = 'impeccable';
+ state = 'IDLE';
+ }
+
function sendEvent(msg) {
msg.token = TOKEN;
fetch('http://localhost:' + PORT + '/events', {
diff --git a/bin/cli.js b/bin/cli.js
index b3aa1f37c..881f964f8 100755
--- a/bin/cli.js
+++ b/bin/cli.js
@@ -5,8 +5,6 @@
*
* Usage:
* npx impeccable detect [file-or-dir-or-url...]
- * npx impeccable live [--port=PORT]
- * npx impeccable live stop
* npx impeccable skills help|install|update
* npx impeccable --help
*/
@@ -24,11 +22,6 @@ if (!command || command === '--help' || command === '-h') {
Commands:
detect [file-or-dir-or-url...] Scan for UI anti-patterns and design quality issues
- live [--port=PORT] Start live variant server (element picker + variant cycling)
- live stop Stop a running live server
- poll Wait for a browser event from the live server
- poll --reply <id> <status> Reply to a pending event (done, error)
- wrap --id ID --count N --query Q Find element in source and create variant wrapper
skills help List all available skills and commands
skills install Install impeccable skills into your project
skills update Update skills to the latest version
@@ -52,18 +45,6 @@ if (command === 'detect') {
process.argv = [process.argv[0], process.argv[1], ...args.slice(1)];
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)];
- 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('../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('../source/skills/impeccable/scripts/live-wrap.mjs');
- await wrapCli();
} else if (command === 'skills') {
const { run } = await import('./commands/skills.mjs');
await run(args.slice(1));
diff --git a/source/skills/impeccable/scripts/live-browser.js b/source/skills/impeccable/scripts/live-browser.js
index 7a26c9829..72534661b 100644
--- a/source/skills/impeccable/scripts/live-browser.js
+++ b/source/skills/impeccable/scripts/live-browser.js
@@ -870,11 +870,14 @@
// ---------------------------------------------------------------------------
let evtSource = null;
+ let sseRetries = 0;
+ const SSE_MAX_RETRIES = 5;
function connectSSE() {
evtSource = new EventSource('http://localhost:' + PORT + '/events?token=' + TOKEN);
evtSource.onmessage = (e) => {
+ sseRetries = 0; // reset on any successful message
let msg; try { msg = JSON.parse(e.data); } catch { return; }
switch (msg.type) {
case 'connected':
@@ -918,11 +921,35 @@
};
evtSource.onerror = () => {
- // EventSource auto-reconnects. Log once.
- console.log('[impeccable] SSE connection lost. Reconnecting...');
+ sseRetries++;
+ if (sseRetries <= SSE_MAX_RETRIES) {
+ console.log('[impeccable] SSE connection lost. Retry ' + sseRetries + '/' + SSE_MAX_RETRIES + '...');
+ return; // EventSource auto-reconnects
+ }
+ // Server is gone. Clean up gracefully.
+ console.log('[impeccable] Live server unreachable. Cleaning up UI.');
+ evtSource.close();
+ evtSource = null;
+ handleServerLost();
};
}
+ /** Server died or became unreachable. Reset UI to a clean state. */
+ function handleServerLost() {
+ if (state === 'GENERATING' || state === 'CYCLING' || state === 'SAVING') {
+ showToast('Live server disconnected. Session ended.', 5000);
+ }
+ hideBar();
+ hideHighlight();
+ stopScrollTracking();
+ if (variantObserver) { variantObserver.disconnect(); variantObserver = null; }
+ clearSession();
+ selectedElement = null;
+ currentSessionId = null;
+ selectedAction = 'impeccable';
+ state = 'IDLE';
+ }
+
function sendEvent(msg) {
msg.token = TOKEN;
fetch('http://localhost:' + PORT + '/events', {
diff --git a/src/detect-antipatterns.mjs b/src/detect-antipatterns.mjs
index b0d861ac3..8c4a22a15 100644
--- a/src/detect-antipatterns.mjs
+++ b/src/detect-antipatterns.mjs
@@ -3442,15 +3442,6 @@ async function main() {
process.exit(0);
}
-// ---------------------------------------------------------------------------
-// Live detection server
-// ---------------------------------------------------------------------------
-
-async function liveCli() {
- const { startLiveServer } = await import('./live/server.mjs');
- await startLiveServer();
-}
-
// ---------------------------------------------------------------------------
// Entry point
// ---------------------------------------------------------------------------
@@ -3475,7 +3466,6 @@ export {
buildImportGraph, resolveImport,
detectFrameworkConfig, isPortListening, FRAMEWORK_CONFIGS,
main as detectCli,
- liveCli,
};
// @browser-strip-end
diff --git a/src/live/browser.js b/src/live/browser.js
deleted file mode 100644
index 7a26c9829..000000000
--- a/src/live/browser.js
+++ /dev/null
@@ -1,1220 +0,0 @@
-/**
- * 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/src/live/poll.mjs b/src/live/poll.mjs
deleted file mode 100644
index 52859416c..000000000
--- a/src/live/poll.mjs
+++ /dev/null
@@ -1,123 +0,0 @@
-/**
- * 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/src/live/protocol.mjs b/src/live/protocol.mjs
deleted file mode 100644
index 4ddaddbe4..000000000
--- a/src/live/protocol.mjs
+++ /dev/null
@@ -1,79 +0,0 @@
-/**
- * Shared protocol constants and validation for the live variant mode.
- * Imported by both server.mjs and poll.mjs.
- */
-
-// Browser → Server event types
-export const EVENT = Object.freeze({
- GENERATE: 'generate',
- ACCEPT: 'accept',
- DISCARD: 'discard',
- EXIT: 'exit',
-});
-
-// Server → Browser message types
-export const MSG = Object.freeze({
- AUTH_OK: 'auth_ok',
- AUTH_FAIL: 'auth_fail',
- GENERATING: 'generating',
- DONE: 'done',
- ERROR: 'error',
-});
-
-// Poll return types (superset of EVENT — adds timeout)
-export const POLL = Object.freeze({
- ...EVENT,
- TIMEOUT: 'timeout',
-});
-
-// Commands that make sense for visual variant generation.
-// Shown in the browser action panel dropdown.
-export const VISUAL_ACTIONS = Object.freeze([
- 'impeccable', // default: freeform design pass
- 'bolder',
- 'quieter',
- 'distill',
- 'polish',
- 'typeset',
- 'colorize',
- 'layout',
- 'adapt',
- 'animate',
- 'delight',
- 'overdrive',
-]);
-
-/**
- * Validate a browser event before queuing it for the agent.
- * Returns null if valid, or an error string if not.
- */
-export function validateEvent(msg) {
- if (!msg || typeof msg !== 'object' || !msg.type) {
- return 'Missing or invalid message';
- }
-
- switch (msg.type) {
- case EVENT.GENERATE:
- if (!msg.id || typeof msg.id !== 'string') return 'generate: missing id';
- if (!msg.action || !VISUAL_ACTIONS.includes(msg.action)) return `generate: invalid action "${msg.action}"`;
- if (!Number.isInteger(msg.count) || msg.count < 1 || msg.count > 8) return 'generate: count must be 1-8';
- if (!msg.element || typeof msg.element !== 'object') return 'generate: missing element context';
- if (!msg.element.outerHTML) return 'generate: element must include outerHTML';
- return null;
-
- case EVENT.ACCEPT:
- if (!msg.id || typeof msg.id !== 'string') return 'accept: missing id';
- if (!msg.variantId) return 'accept: missing variantId';
- return null;
-
- case EVENT.DISCARD:
- if (!msg.id || typeof msg.id !== 'string') return 'discard: missing id';
- return null;
-
- case EVENT.EXIT:
- return null;
-
- default:
- return `Unknown event type: "${msg.type}"`;
- }
-}
diff --git a/src/live/server.mjs b/src/live/server.mjs
deleted file mode 100644
index d2e2a5e7c..000000000
--- a/src/live/server.mjs
+++ /dev/null
@@ -1,496 +0,0 @@
-/**
- * Live variant mode server.
- *
- * Serves the browser script (/live.js), the detection overlay (/detect.js),
- * manages a WebSocket connection to the browser, and exposes HTTP long-poll
- * endpoints so the agent CLI can receive events and send replies.
- *
- * Start: npx impeccable live
- * Stop: npx impeccable live stop
- * Health: curl http://localhost:PORT/health
- */
-
-import http from 'node:http';
-import { createHash, 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';
-import { WebSocketServer } from 'ws';
-import { validateEvent } from './protocol.mjs';
-
-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; // 2 minutes
-
-// ---------------------------------------------------------------------------
-// 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,
- wsClients: new Set(),
- // Queue: browser events waiting for the agent to poll
- pendingEvents: [],
- // Queue: agent poll response callbacks waiting for browser events
- pendingPolls: [],
- // Debounce timer for exit event (avoids false exits on transient disconnects)
- exitTimer: null,
-};
-
-/** Push an event from the browser into the queue or resolve a waiting poll. */
-function enqueueEvent(event) {
- if (state.pendingPolls.length > 0) {
- const resolve = state.pendingPolls.shift();
- resolve(event);
- } else {
- state.pendingEvents.push(event);
- }
-}
-
-/** Broadcast a message to all authenticated WS clients. */
-function broadcast(msg) {
- const data = JSON.stringify(msg);
- for (const ws of state.wsClients) {
- if (ws.readyState === 1 /* OPEN */) {
- ws.send(data);
- }
- }
-}
-
-// ---------------------------------------------------------------------------
-// Load scripts
-// ---------------------------------------------------------------------------
-
-function loadBrowserScripts() {
- const detectPath = path.join(__dirname, '..', 'detect-antipatterns-browser.js');
- const livePath = path.join(__dirname, 'browser.js');
-
- let detectScript = '';
- try {
- detectScript = fs.readFileSync(detectPath, 'utf-8');
- } catch {
- // Detection script is optional for the live variant server
- }
-
- let liveScript = '';
- try {
- liveScript = fs.readFileSync(livePath, 'utf-8');
- } catch {
- process.stderr.write('Error: Browser live script not found at ' + livePath + '\n');
- process.exit(1);
- }
-
- return { detectScript, liveScript };
-}
-
-// ---------------------------------------------------------------------------
-// Check for .impeccable.md
-// ---------------------------------------------------------------------------
-
-function hasProjectContext() {
- try {
- fs.accessSync(path.join(process.cwd(), '.impeccable.md'), fs.constants.R_OK);
- return true;
- } catch {
- return false;
- }
-}
-
-// ---------------------------------------------------------------------------
-// HTTP request handler
-// ---------------------------------------------------------------------------
-
-function createRequestHandler({ detectScript, liveScriptWithToken }) {
- return (req, res) => {
- const url = new URL(req.url, `http://localhost:${state.port}`);
-
- // CORS
- 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 pathname = url.pathname;
-
- // --- Public endpoints (no auth) ---
-
- if (pathname === '/live.js') {
- res.writeHead(200, { 'Content-Type': 'application/javascript' });
- res.end(liveScriptWithToken);
- return;
- }
-
- if (pathname === '/detect.js' || pathname === '/') {
- if (!detectScript) {
- res.writeHead(404);
- res.end('Detection script not available. Run npm run build:browser first.');
- return;
- }
- res.writeHead(200, { 'Content-Type': 'application/javascript' });
- res.end(detectScript);
- return;
- }
-
- if (pathname === '/health') {
- res.writeHead(200, { 'Content-Type': 'application/json' });
- res.end(JSON.stringify({
- status: 'ok',
- port: state.port,
- mode: 'variant',
- hasProjectContext: hasProjectContext(),
- connectedClients: state.wsClients.size,
- }));
- return;
- }
-
- // Read a project file from disk (for no-HMR fallback: the browser fetches
- // the raw source to inject variants when the dev server doesn't support HMR).
- if (pathname === '/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);
- // Safety: must be within the project directory
- if (!absPath.startsWith(process.cwd())) { res.writeHead(403); res.end('Forbidden'); return; }
- try {
- const content = fs.readFileSync(absPath, 'utf-8');
- res.writeHead(200, { 'Content-Type': 'text/html; charset=utf-8' });
- res.end(content);
- } catch {
- res.writeHead(404); res.end('File not found');
- }
- return;
- }
-
- // --- Authenticated endpoints ---
-
- const token = url.searchParams.get('token');
-
- if (pathname === '/stop') {
- if (token !== state.token) { res.writeHead(401); res.end('Unauthorized'); return; }
- res.writeHead(200, { 'Content-Type': 'text/plain' });
- res.end('stopping');
- shutdown();
- return;
- }
-
- if (pathname === '/poll') {
- if (req.method === 'GET') {
- handlePollGet(req, res, url);
- } else if (req.method === 'POST') {
- handlePollPost(req, res);
- } else {
- res.writeHead(405);
- res.end('Method not allowed');
- }
- return;
- }
-
- res.writeHead(404);
- res.end('Not found');
- };
-}
-
-// ---------------------------------------------------------------------------
-// Poll endpoints
-// ---------------------------------------------------------------------------
-
-/** GET /poll — agent blocks here until a browser event arrives. */
-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 there's already an event queued, return it immediately
- if (state.pendingEvents.length > 0) {
- const event = state.pendingEvents.shift();
- res.writeHead(200, { 'Content-Type': 'application/json' });
- res.end(JSON.stringify(event));
- return;
- }
-
- // Otherwise, wait for one
- const timer = setTimeout(() => {
- // Remove this callback from pendingPolls
- 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);
-
- // Clean up if the agent disconnects before we respond
- req.on('close', () => {
- clearTimeout(timer);
- const idx = state.pendingPolls.indexOf(resolve);
- if (idx !== -1) state.pendingPolls.splice(idx, 1);
- });
-}
-
-/** POST /poll — agent replies to a pending browser event. */
-function handlePollPost(req, res) {
- let body = '';
- req.on('data', (chunk) => { body += chunk; });
- 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
- broadcast({
- type: msg.type || 'done',
- id: msg.id,
- message: msg.message,
- data: msg.data,
- });
-
- res.writeHead(200, { 'Content-Type': 'application/json' });
- res.end(JSON.stringify({ ok: true }));
- });
-}
-
-// ---------------------------------------------------------------------------
-// WebSocket handling
-// ---------------------------------------------------------------------------
-
-function setupWebSocket(server) {
- const wss = new WebSocketServer({ server, path: '/ws' });
-
- wss.on('connection', (ws) => {
- let authenticated = false;
-
- ws.on('message', (raw) => {
- let msg;
- try {
- msg = JSON.parse(raw.toString());
- } catch {
- ws.send(JSON.stringify({ type: 'error', message: 'Invalid JSON' }));
- return;
- }
-
- // First message must be auth
- if (!authenticated) {
- if (msg.type === 'auth' && msg.token === state.token) {
- authenticated = true;
- state.wsClients.add(ws);
- // Cancel any pending exit timer (client reconnected)
- clearTimeout(state.exitTimer);
- ws.send(JSON.stringify({
- type: 'auth_ok',
- hasProjectContext: hasProjectContext(),
- }));
- } else {
- ws.send(JSON.stringify({ type: 'auth_fail', reason: 'Invalid token' }));
- ws.close();
- }
- return;
- }
-
- // Validated browser events go to the agent poll queue
- const error = validateEvent(msg);
- if (error) {
- ws.send(JSON.stringify({ type: 'error', message: error }));
- return;
- }
-
- enqueueEvent(msg);
- });
-
- ws.on('close', () => {
- state.wsClients.delete(ws);
- // If all browser clients disconnected, debounce before signaling exit.
- // The browser script reconnects within 3s, and HMR page reloads cause
- // brief disconnects. Wait 8s to avoid false exits.
- if (authenticated && state.wsClients.size === 0) {
- clearTimeout(state.exitTimer);
- state.exitTimer = setTimeout(() => {
- if (state.wsClients.size === 0) {
- enqueueEvent({ type: 'exit' });
- }
- }, 8000);
- }
- });
-
- ws.on('error', () => {
- state.wsClients.delete(ws);
- });
- });
-
- return wss;
-}
-
-// ---------------------------------------------------------------------------
-// Lifecycle
-// ---------------------------------------------------------------------------
-
-let httpServer = null;
-let wss = null;
-
-function shutdown() {
- try { fs.unlinkSync(LIVE_PID_FILE); } catch { /* ignore */ }
- // Close all WebSocket connections
- for (const ws of state.wsClients) {
- try { ws.close(); } catch { /* ignore */ }
- }
- state.wsClients.clear();
- // Resolve any pending polls with exit
- for (const resolve of state.pendingPolls) {
- resolve({ type: 'exit' });
- }
- state.pendingPolls.length = 0;
- if (wss) { try { wss.close(); } catch { /* ignore */ } }
- if (httpServer) { httpServer.close(); }
- process.exit(0);
-}
-
-/**
- * Start the live variant server.
- * Called from liveCli() in detect-antipatterns.mjs.
- */
-export async function startLiveServer({ port: requestedPort } = {}) {
- const args = process.argv.slice(2);
- const helpMode = args.includes('--help');
- const stopMode = args.includes('stop');
- const portArg = args.find(a => a.startsWith('--port='));
- const parsedPort = portArg ? parseInt(portArg.split('=')[1], 10) : null;
-
- if (helpMode) {
- console.log(`Usage: impeccable live [options]
-
-Start the live variant mode server. Serves the browser overlay script and
-bridges WebSocket connections from the browser to the agent poll CLI.
-
-Commands:
- live Start the server (default)
- live stop Stop a running live server
-
-Options:
- --port=PORT Use a specific port (default: auto-detect starting at 8400)
- --help Show this help message
-
-Endpoints:
- /live.js Browser script for element picker + variant cycling
- /detect.js Detection overlay script (backwards compatible)
- /health Health check
- /ws WebSocket endpoint for browser
- /poll Long-poll endpoint for agent CLI`);
- process.exit(0);
- }
-
- // Stop mode
- if (stopMode) {
- 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'));
- // Check if the process is actually running
- try {
- process.kill(existing.pid, 0);
- console.error(`Live server already running on port ${existing.port} (pid ${existing.pid}).`);
- console.error('Stop it first: npx impeccable live stop');
- process.exit(1);
- } catch {
- // Process is dead, clean up stale PID file
- fs.unlinkSync(LIVE_PID_FILE);
- }
- } catch {
- // No PID file — good
- }
-
- // Generate session token
- state.token = randomUUID();
- state.port = requestedPort || parsedPort || await findOpenPort();
-
- // Load scripts
- const { detectScript, liveScript } = loadBrowserScripts();
-
- // Inject token and port into the live browser script
- const liveScriptWithToken =
- `window.__IMPECCABLE_TOKEN__ = '${state.token}';\n` +
- `window.__IMPECCABLE_PORT__ = ${state.port};\n` +
- liveScript;
-
- // Create HTTP server
- httpServer = http.createServer(createRequestHandler({ detectScript, liveScriptWithToken }));
-
- // Attach WebSocket
- wss = setupWebSocket(httpServer);
-
- // Start listening
- httpServer.listen(state.port, '127.0.0.1', () => {
- // Write PID file with token so poll CLI can authenticate
- 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 variant server running on ${url}`);
- console.log(`Token: ${state.token}\n`);
- console.log(`Inject into your page source:`);
- console.log(` <script src="${url}/live.js"><\/script>\n`);
- console.log(`Or inject via browser console:`);
- console.log(` const s = document.createElement('script');`);
- console.log(` s.src = '${url}/live.js';`);
- console.log(` document.head.appendChild(s);\n`);
- console.log(`Agent poll: npx impeccable poll`);
- console.log(`Stop: npx impeccable live stop`);
- });
-
- process.on('SIGINT', shutdown);
- process.on('SIGTERM', shutdown);
-}
diff --git a/src/live/wrap.mjs b/src/live/wrap.mjs
deleted file mode 100644
index f1c838cdd..000000000
--- a/src/live/wrap.mjs
+++ /dev/null
@@ -1,298 +0,0 @@
-/**
- * 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);
-}