From 22ce112d1a59587cca8ada7c99f157b24264a1ae Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Pawe=C5=82=20Adamczak?=
Date: Sat, 20 Jun 2026 11:23:08 +0200
Subject: [PATCH 1/3] Add support for Antigravity 2.0
---
.github/ISSUE_TEMPLATE/feature_request.md | 1 +
.github/PULL_REQUEST_TEMPLATE.md | 2 +-
.github/workflows/sync-generated-output.yml | 1 +
AGENTS.md | 2 +-
README.md | 8 ++++-
cli/bin/commands/skills.mjs | 13 +++++--
cli/lib/download-providers.js | 1 +
docs/DEVELOP.md | 1 +
docs/HARNESSES.md | 39 ++++++++++++---------
scripts/build.js | 2 ++
scripts/lib/transformers/index.js | 1 +
scripts/lib/transformers/providers.js | 13 +++++++
scripts/lib/utils.js | 7 ++++
skill/scripts/pin.mjs | 2 +-
14 files changed, 70 insertions(+), 23 deletions(-)
diff --git a/.github/ISSUE_TEMPLATE/feature_request.md b/.github/ISSUE_TEMPLATE/feature_request.md
index 0920d04db..8b5717e20 100644
--- a/.github/ISSUE_TEMPLATE/feature_request.md
+++ b/.github/ISSUE_TEMPLATE/feature_request.md
@@ -24,6 +24,7 @@ assignees: ''
- [ ] Kiro
- [ ] OpenCode
- [ ] Qoder
+- [ ] Antigravity
- [ ] All providers
## Alternatives considered
diff --git a/.github/PULL_REQUEST_TEMPLATE.md b/.github/PULL_REQUEST_TEMPLATE.md
index 939728471..6eb80cd53 100644
--- a/.github/PULL_REQUEST_TEMPLATE.md
+++ b/.github/PULL_REQUEST_TEMPLATE.md
@@ -17,5 +17,5 @@
- [ ] Source files updated in `source/`
- [ ] `bun run build` ran successfully
- [ ] `bun test` passes
-- [ ] Tested with at least one provider (Cursor / Claude Code / Gemini CLI / Codex / Copilot / Kiro / OpenCode / Qoder)
+- [ ] Tested with at least one provider (Cursor / Claude Code / Gemini CLI / Codex / Copilot / Kiro / OpenCode / Qoder / Antigravity)
- [ ] README / DEVELOP.md updated if needed
diff --git a/.github/workflows/sync-generated-output.yml b/.github/workflows/sync-generated-output.yml
index 1ad298369..c7e7322e0 100644
--- a/.github/workflows/sync-generated-output.yml
+++ b/.github/workflows/sync-generated-output.yml
@@ -21,6 +21,7 @@ concurrency:
env:
GENERATED_PATHS: >-
+ .agent
.agents
.claude
.cursor
diff --git a/AGENTS.md b/AGENTS.md
index 94184019f..bd4731508 100644
--- a/AGENTS.md
+++ b/AGENTS.md
@@ -21,7 +21,7 @@ Run `bun run build` after changing anything in `skill/`, transformer code, or us
## Generated Provider Output Policy
-The root harness folders (`.agents/skills/`, `.claude/skills/`, `.cursor/skills/`, `.gemini/skills/`, `.github/skills/`, `.kiro/skills/`, `.opencode/skills/`, `.pi/skills/`, `.qoder/skills/`, `.rovodev/skills/`, `.trae*/skills/`) and `plugin/` stay tracked so `main` remains installable for direct GitHub, `npx skills`, and submodule users. They are still generated artifacts.
+The root harness folders (`.agents/skills/`, `.agent/skills/`, `.claude/skills/`, `.cursor/skills/`, `.gemini/skills/`, `.github/skills/`, `.kiro/skills/`, `.opencode/skills/`, `.pi/skills/`, `.qoder/skills/`, `.rovodev/skills/`, `.trae*/skills/`) and `plugin/` stay tracked so `main` remains installable for direct GitHub, `npx skills`, and submodule users. They are still generated artifacts.
Normal development should be source-first: stage changes in `skill/`, `scripts/`, `cli/`, `site/`, `extension/`, `functions/`, and `tests/`; leave generated harness churn unstaged unless the user asked for it. After source changes land on `main`, `.github/workflows/sync-generated-output.yml` runs `bun run build:release` and commits generated provider output directly back to `main`. Treat generated harness diffs as release artifacts and keep them out of feature PRs unless they are the point of the PR.
diff --git a/README.md b/README.md
index f93dd628c..f9d75a7f9 100644
--- a/README.md
+++ b/README.md
@@ -124,7 +124,7 @@ git add .gitmodules .impeccable .claude .cursor
git commit -m "Add Impeccable skills"
```
-Use the providers your project needs, for example `claude`, `cursor`, `gemini`, `codex`, `github`, `opencode`, `pi`, `qoder`, `trae`, `trae-cn`, or `rovo-dev`. The command links individual skill folders from `.impeccable/dist/universal/` and leaves existing real skill directories untouched unless you pass `--force`.
+Use the providers your project needs, for example `claude`, `cursor`, `gemini`, `codex`, `github`, `opencode`, `pi`, `qoder`, `trae`, `trae-cn`, `rovo-dev`, or `antigravity`. The command links individual skill folders from `.impeccable/dist/universal/` and leaves existing real skill directories untouched unless you pass `--force`.
To update later:
@@ -234,6 +234,11 @@ cp -r dist/qoder/.qoder your-project/
cp -r dist/qoder/.qoder/skills/* ~/.qoder/skills/
```
+**Antigravity:**
+```bash
+cp -r dist/antigravity/.agent your-project/
+```
+
## Usage
Once installed, every command runs through the single `/impeccable` skill:
@@ -319,6 +324,7 @@ Full detector docs: [impeccable.style/docs/detector](https://impeccable.style/do
- [Trae](https://trae.ai)
- [Rovo Dev](https://www.atlassian.com/software/rovo)
- [Qoder](https://qoder.com)
+- [Antigravity](https://antigravity.google)
## Community & Ecosystem
diff --git a/cli/bin/commands/skills.mjs b/cli/bin/commands/skills.mjs
index e1e20f137..83a75d2cc 100644
--- a/cli/bin/commands/skills.mjs
+++ b/cli/bin/commands/skills.mjs
@@ -23,9 +23,10 @@ const __dirname = dirname(fileURLToPath(import.meta.url));
const API_BASE = 'https://impeccable.style';
// Provider folder names in project roots
-const PROVIDER_DIRS = ['.claude', '.cursor', '.gemini', '.agents', '.github', '.kiro', '.opencode', '.pi', '.qoder', '.trae', '.trae-cn', '.rovodev'];
+const PROVIDER_DIRS = ['.claude', '.cursor', '.gemini', '.agents', '.agent', '.github', '.kiro', '.opencode', '.pi', '.qoder', '.trae', '.trae-cn', '.rovodev'];
const PROVIDER_ALIASES = {
agents: '.agents',
+ antigravity: '.agent',
claude: '.claude',
'claude-code': '.claude',
codex: '.agents',
@@ -44,6 +45,7 @@ const PROVIDER_ALIASES = {
};
const PROVIDER_DISPLAY = {
+ '.agent': { name: 'Antigravity', input: 'antigravity' },
'.agents': { name: 'Codex CLI', input: 'codex' },
'.claude': { name: 'Claude Code', input: 'claude' },
'.cursor': { name: 'Cursor', input: 'cursor' },
@@ -57,7 +59,7 @@ const PROVIDER_DISPLAY = {
'.trae': { name: 'Trae', input: 'trae' },
'.trae-cn': { name: 'Trae CN', input: 'trae-cn' },
};
-const PROVIDER_INPUT_ORDER = ['claude', 'codex', 'cursor', 'gemini', 'github', 'kiro', 'opencode', 'pi', 'qoder', 'trae', 'trae-cn', 'rovo-dev'];
+const PROVIDER_INPUT_ORDER = ['claude', 'codex', 'cursor', 'gemini', 'github', 'kiro', 'opencode', 'pi', 'qoder', 'trae', 'trae-cn', 'rovo-dev', 'antigravity'];
// When a project has no harness folder yet, infer the target from globally
// installed harnesses (~/.claude, ~/.codex, ...). Codex reads skills from
@@ -67,6 +69,11 @@ const GLOBAL_HARNESS_HINTS = [
{ home: '.codex', provider: '.agents' },
{ home: '.cursor', provider: '.cursor' },
{ home: '.gemini', provider: '.gemini' },
+ // Antigravity nests under ~/.gemini too, so any of these also trips the
+ // .gemini hint above (harmless double-detection -- both get pre-selected).
+ { home: '.gemini/antigravity', provider: '.agent' },
+ { home: '.gemini/antigravity-cli', provider: '.agent' },
+ { home: '.gemini/antigravity-ide', provider: '.agent' },
{ home: '.kiro', provider: '.kiro' },
{ home: '.opencode', provider: '.opencode' },
{ home: '.qoder', provider: '.qoder' },
@@ -513,7 +520,7 @@ async function copyOrExtractLocalBundle(sourceValue) {
*/
function normalizeForHash(content) {
return content
- .replace(/\.(claude|cursor|agents|github|gemini|codex|kiro|opencode|pi|qoder|trae|trae-cn|rovodev)\/skills\//g, '.PROVIDER/skills/');
+ .replace(/\.(claude|cursor|agents|agent|github|gemini|codex|kiro|opencode|pi|qoder|trae|trae-cn|rovodev)\/skills\//g, '.PROVIDER/skills/');
}
function hashSkillFile(filePath) {
diff --git a/cli/lib/download-providers.js b/cli/lib/download-providers.js
index d1c5cfd5b..6d39c9c0b 100644
--- a/cli/lib/download-providers.js
+++ b/cli/lib/download-providers.js
@@ -9,6 +9,7 @@ export const FILE_DOWNLOAD_PROVIDER_CONFIG_DIRS = Object.freeze({
opencode: '.opencode',
pi: '.pi',
qoder: '.qoder',
+ antigravity: '.agent',
});
export const FILE_DOWNLOAD_PROVIDERS = Object.freeze(
diff --git a/docs/DEVELOP.md b/docs/DEVELOP.md
index e8500ad37..dc2301d8d 100644
--- a/docs/DEVELOP.md
+++ b/docs/DEVELOP.md
@@ -165,6 +165,7 @@ The skill-behavior suite runs three providers (claude-haiku-4-5, gpt-5.4-mini, g
- [OpenCode Skills](https://opencode.ai/docs/skills/)
- [Pi Skills](https://github.com/badlogic/pi-mono/blob/main/packages/coding-agent/docs/skills.md)
- [Qoder Skills](https://docs.qoder.com/extensions/skills)
+- [Antigravity Skills](https://antigravity.google/docs/skills)
## Repository Structure
diff --git a/docs/HARNESSES.md b/docs/HARNESSES.md
index f7e43c0cb..09f1c3b7e 100644
--- a/docs/HARNESSES.md
+++ b/docs/HARNESSES.md
@@ -20,6 +20,7 @@ Last verified: 2026-04-28
| Qoder | https://docs.qoder.com/extensions/skills |
| Trae | TBD (no official skills docs found yet) |
| Rovo Dev | https://support.atlassian.com/rovo/docs/extend-rovo-dev-cli-with-agent-skills |
+| Antigravity | https://antigravity.google/docs/skills |
## Spec Compliance
@@ -31,22 +32,22 @@ Provider-specific extensions beyond the spec: `user-invocable`, `argument-hint`,
Fields marked with * are spec-standard. Others are provider extensions.
-| Field | Claude Code | Cursor | Gemini | Codex | Copilot | Kiro | OpenCode | Pi | Qoder | Rovo Dev |
-|-------|:-----------:|:------:|:------:|:-----:|:-------:|:----:|:--------:|:--:|:-----:|:--------:|
-| `name`* | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes |
-| `description`* | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes |
-| `license`* | Yes | Yes | Ignored | No | Yes | Yes | Yes | Yes | Yes | Yes |
-| `compatibility`* | Yes | Yes | Ignored | No | Yes | Yes | Yes | Yes | Yes | Yes |
-| `metadata`* | Yes | Yes | Ignored | No | Yes | Yes | Yes | Yes | Yes | Yes |
-| `allowed-tools`* | Yes | No | Ignored | No | No | No | Yes | Yes | Yes | Yes |
-| `user-invocable` | Yes | No | No | No | Yes | No | Yes | No | Yes | Yes |
-| `argument-hint` | Yes | No | No | No | Yes | No | Yes | No | Yes | Yes |
-| `disable-model-invocation` | Yes | Yes | No | No | Yes | No | Yes | Yes | TBD | TBD |
-| `model` | Yes | No | No | No | No | No | Yes | No | No | No |
-| `effort` | Yes | No | No | No | No | No | No | No | No | No |
-| `context` | Yes | No | No | No | No | No | No | No | No | No |
-| `agent` | Yes | No | No | No | No | No | Yes | No | No | No |
-| `hooks` | Yes | No | No | Yes | No | No | No | No | No | No |
+| Field | Claude Code | Cursor | Gemini | Codex | Copilot | Kiro | OpenCode | Pi | Qoder | Rovo Dev | Antigravity |
+|-------|:-----------:|:------:|:------:|:-----:|:-------:|:----:|:--------:|:--:|:-----:|:--------:|:-----------:|
+| `name`* | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes |
+| `description`* | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes |
+| `license`* | Yes | Yes | Ignored | No | Yes | Yes | Yes | Yes | Yes | Yes | Yes |
+| `compatibility`* | Yes | Yes | Ignored | No | Yes | Yes | Yes | Yes | Yes | Yes | Yes |
+| `metadata`* | Yes | Yes | Ignored | No | Yes | Yes | Yes | Yes | Yes | Yes | Yes |
+| `allowed-tools`* | Yes | No | Ignored | No | No | No | Yes | Yes | Yes | Yes | Yes |
+| `user-invocable` | Yes | No | No | No | Yes | No | Yes | No | Yes | Yes | No |
+| `argument-hint` | Yes | No | No | No | Yes | No | Yes | No | Yes | Yes | No |
+| `disable-model-invocation` | Yes | Yes | No | No | Yes | No | Yes | Yes | TBD | TBD | TBD |
+| `model` | Yes | No | No | No | No | No | Yes | No | No | No | No |
+| `effort` | Yes | No | No | No | No | No | No | No | No | No | No |
+| `context` | Yes | No | No | No | No | No | No | No | No | No | No |
+| `agent` | Yes | No | No | No | No | No | Yes | No | No | No | No |
+| `hooks` | Yes | No | No | Yes | No | No | No | No | No | No | No |
Notes:
- Gemini CLI validates only `name` and `description`; other spec fields are parsed but ignored.
@@ -54,6 +55,7 @@ Notes:
- Codex CLI hooks ship under `[features].hooks = true` (still flagged), require `/hooks` trust ceremony per-update, and are disabled on Windows.
- Kiro recognizes `user-invocable` and `disable-model-invocation` per community reports but does not formally document them.
- Unknown fields are silently ignored by all harnesses.
+- Antigravity's own skills spec documents `name`, `description`, `license`, `compatibility`, `metadata`, and `allowed-tools` with explicit constraints (e.g. `name` max 64 chars, `description` max 1024 chars, `compatibility` max 500 chars), confirming all six spec-standard fields are respected, not just parsed.
## Hook surface used by Impeccable
@@ -80,9 +82,12 @@ Notes:
| Trae China | `.trae-cn/skills/` | TBD |
| Trae International | `.trae/skills/` | TBD |
| Rovo Dev | `.rovodev/skills/` | `~/.rovodev/skills/` (user-level) |
+| Antigravity | `.agent/skills/` (legacy path, deliberately chosen — see note) | `.agents/skills/` (current default per Antigravity's own docs, but content-owned by Codex CLI's `agents` provider below) |
All harnesses support the `{skill-name}/SKILL.md` directory structure with optional `reference/`, `scripts/`, and `assets/` subdirectories.
+Antigravity's own docs state it now defaults to `.agents/skills/` (shared with Codex CLI) and keeps `.agent/skills/` only for backward compatibility. We ship to `.agent/skills/` anyway: `.agents/skills/impeccable/` is already generated content owned by the Codex `agents` provider, with `{{model}}` → `GPT` and `{{command_prefix}}` → `$` baked into the body text. Writing Antigravity's own Gemini/`/`-prefixed wording to that same path would either silently clobber Codex's output (same destination, two different generators) or require reworking Codex's wording — out of scope for this provider's addition. Net effect: a pure-Antigravity project gets correct content at the legacy path; a project with both Codex and Antigravity will also pick up the Codex-flavored copy at `.agents/skills/`, which still works, just with the wrong model name/prefix in the prose.
+
## Native Subagent Directory Structure
| Harness | Native directory | File format |
@@ -92,6 +97,8 @@ All harnesses support the `{skill-name}/SKILL.md` directory structure with optio
Impeccable keeps canonical agent prompts under `skill/agents/` and emits provider-native files only for harnesses with documented subagent formats. Claude reads its agents from the installed plugin; Codex auto-discovers the TOML bundled inside the installed skill's own `agents/` folder, so the normal skills install carries it with no separate sidecar.
+Antigravity has no equivalent here. Its `.agent/workflows/` directory (description-only frontmatter, saved prompts invoked via `/workflow-name` or called from another workflow) is a slash-command system like Gemini's `.gemini/commands/`, not an isolated, tool-restricted subagent dispatch. `skill/agents/manual-edit-applier.md` has no faithful mapping onto that model, so Impeccable does not generate Antigravity workflow files.
+
## Placeholder / Variable Substitution
Claude Code supports runtime variable substitution directly in SKILL.md bodies: `$ARGUMENTS`, `$0`-`$N`, `${CLAUDE_SKILL_DIR}`, `${CLAUDE_SESSION_ID}`. No other harness supports substitution in skills.
diff --git a/scripts/build.js b/scripts/build.js
index a405cc939..2cff4526c 100644
--- a/scripts/build.js
+++ b/scripts/build.js
@@ -501,6 +501,7 @@ This folder contains skills for all supported tools:
.gemini/ -> Gemini CLI
.codex/ -> Codex custom agents (Codex skills use .agents/)
.agents/ -> Codex CLI
+ .agent/ -> Antigravity
.github/ -> GitHub Copilot
.kiro/ -> Kiro
.opencode/ -> OpenCode
@@ -510,6 +511,7 @@ This folder contains skills for all supported tools:
To install, copy the relevant folder(s) into your project root.
For Codex, repo and user skill installs come from .agents/skills.
+For Antigravity, skills come from .agent/skills/.
These are hidden folders (dotfiles). Press Cmd+Shift+. in Finder to see them.
`);
diff --git a/scripts/lib/transformers/index.js b/scripts/lib/transformers/index.js
index 57f35ba6f..14a2d0d39 100644
--- a/scripts/lib/transformers/index.js
+++ b/scripts/lib/transformers/index.js
@@ -15,5 +15,6 @@ export const transformOpenCode = createTransformer(PROVIDERS.opencode);
export const transformPi = createTransformer(PROVIDERS.pi);
export const transformQoder = createTransformer(PROVIDERS.qoder);
export const transformRovoDev = createTransformer(PROVIDERS['rovo-dev']);
+export const transformAntigravity = createTransformer(PROVIDERS.antigravity);
export { createTransformer, PROVIDERS };
diff --git a/scripts/lib/transformers/providers.js b/scripts/lib/transformers/providers.js
index cd42c4f72..5b316e500 100644
--- a/scripts/lib/transformers/providers.js
+++ b/scripts/lib/transformers/providers.js
@@ -119,4 +119,17 @@ export const PROVIDERS = {
displayName: 'Rovo Dev',
frontmatterFields: ['user-invocable', 'argument-hint', 'license', 'compatibility', 'metadata', 'allowed-tools'],
},
+ 'antigravity': {
+ provider: 'antigravity',
+ providerTags: ['antigravity'],
+ // .agent/skills/ (legacy path) rather than .agents/skills/ (Antigravity's
+ // current default), since the latter is already Codex-flavored content
+ // owned by the `agents` provider below. No agentFormat: Antigravity
+ // Workflows don't map onto a tool-isolated subagent dispatch. See
+ // docs/HARNESSES.md (Skill Directory Structure, Native Subagent
+ // Directory Structure) for the full rationale.
+ configDir: '.agent',
+ displayName: 'Antigravity',
+ frontmatterFields: ['license', 'compatibility', 'metadata', 'allowed-tools'],
+ },
};
diff --git a/scripts/lib/utils.js b/scripts/lib/utils.js
index 9d98ccfa3..32aa72328 100644
--- a/scripts/lib/utils.js
+++ b/scripts/lib/utils.js
@@ -627,11 +627,18 @@ export const PROVIDER_PLACEHOLDERS = {
config_file: 'AGENTS.md',
ask_instruction: 'ask the user directly to clarify what you cannot infer.',
command_prefix: '/'
+ },
+ 'antigravity': {
+ model: 'Gemini',
+ config_file: 'AGENTS.md',
+ ask_instruction: 'ask the user directly to clarify what you cannot infer.',
+ command_prefix: '/'
}
};
export const PROVIDER_BLOCK_TAGS = new Set([
'agents',
+ 'antigravity',
'claude',
'claude-code',
'codex',
diff --git a/skill/scripts/pin.mjs b/skill/scripts/pin.mjs
index 320d98ce1..018ed6e40 100644
--- a/skill/scripts/pin.mjs
+++ b/skill/scripts/pin.mjs
@@ -21,7 +21,7 @@ const __dirname = dirname(fileURLToPath(import.meta.url));
// All known harness directories
const HARNESS_DIRS = [
- '.claude', '.cursor', '.gemini', '.codex', '.agents',
+ '.claude', '.cursor', '.gemini', '.codex', '.agents', '.agent',
'.trae', '.trae-cn', '.pi', '.opencode', '.kiro', '.rovodev',
];
From 47322cbcab8ef70262f16849457def4062bb547c Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Pawe=C5=82=20Adamczak?=
Date: Sat, 20 Jun 2026 12:46:47 +0200
Subject: [PATCH 2/3] Run `build:skills:release` and add `.agent/`
---
.agent/skills/impeccable/SKILL.md | 166 +
.agent/skills/impeccable/reference/adapt.md | 311 +
.agent/skills/impeccable/reference/animate.md | 201 +
.agent/skills/impeccable/reference/audit.md | 133 +
.agent/skills/impeccable/reference/bolder.md | 113 +
.agent/skills/impeccable/reference/brand.md | 108 +
.agent/skills/impeccable/reference/clarify.md | 288 +
.agent/skills/impeccable/reference/codex.md | 105 +
.../skills/impeccable/reference/colorize.md | 257 +
.agent/skills/impeccable/reference/craft.md | 123 +
.../skills/impeccable/reference/critique.md | 767 ++
.agent/skills/impeccable/reference/delight.md | 302 +
.agent/skills/impeccable/reference/distill.md | 111 +
.../skills/impeccable/reference/document.md | 429 +
.agent/skills/impeccable/reference/extract.md | 69 +
.agent/skills/impeccable/reference/harden.md | 347 +
.agent/skills/impeccable/reference/hooks.md | 90 +
.agent/skills/impeccable/reference/init.md | 172 +
.../reference/interaction-design.md | 189 +
.agent/skills/impeccable/reference/layout.md | 161 +
.agent/skills/impeccable/reference/live.md | 718 +
.agent/skills/impeccable/reference/onboard.md | 234 +
.../skills/impeccable/reference/optimize.md | 258 +
.../skills/impeccable/reference/overdrive.md | 130 +
.agent/skills/impeccable/reference/polish.md | 241 +
.agent/skills/impeccable/reference/product.md | 60 +
.agent/skills/impeccable/reference/quieter.md | 99 +
.agent/skills/impeccable/reference/shape.md | 165 +
.agent/skills/impeccable/reference/typeset.md | 279 +
.../impeccable/scripts/command-metadata.json | 94 +
.../impeccable/scripts/context-signals.mjs | 225 +
.agent/skills/impeccable/scripts/context.mjs | 280 +
.../impeccable/scripts/critique-storage.mjs | 242 +
.../skills/impeccable/scripts/detect-csp.mjs | 198 +
.agent/skills/impeccable/scripts/detect.mjs | 21 +
.../detector/browser/injected/index.mjs | 1937 +++
.../impeccable/scripts/detector/cli/main.mjs | 275 +
.../scripts/detector/design-system.mjs | 750 ++
.../detector/detect-antipatterns-browser.js | 5138 +++++++
.../scripts/detector/detect-antipatterns.mjs | 50 +
.../detector/engines/browser/detect-url.mjs | 277 +
.../detector/engines/regex/detect-text.mjs | 564 +
.../engines/static-html/css-cascade.mjs | 1015 ++
.../engines/static-html/detect-html.mjs | 229 +
.../engines/visual/screenshot-contrast.mjs | 189 +
.../impeccable/scripts/detector/findings.mjs | 12 +
.../scripts/detector/node/file-system.mjs | 198 +
.../scripts/detector/profile/profiler.mjs | 166 +
.../detector/registry/antipatterns.mjs | 448 +
.../scripts/detector/rules/checks.mjs | 2671 ++++
.../scripts/detector/shared/color.mjs | 124 +
.../scripts/detector/shared/constants.mjs | 101 +
.../scripts/detector/shared/page.mjs | 7 +
.../skills/impeccable/scripts/hook-admin.mjs | 636 +
.../impeccable/scripts/hook-before-edit.mjs | 476 +
.agent/skills/impeccable/scripts/hook-lib.mjs | 1526 +++
.agent/skills/impeccable/scripts/hook.mjs | 61 +
.../impeccable/scripts/lib/design-parser.mjs | 842 ++
.../scripts/lib/impeccable-config.mjs | 638 +
.../scripts/lib/impeccable-paths.mjs | 126 +
.../impeccable/scripts/lib/is-generated.mjs | 69 +
.../skills/impeccable/scripts/live-accept.mjs | 812 ++
.../impeccable/scripts/live-browser-dom.js | 146 +
.../scripts/live-browser-session.js | 123 +
.../skills/impeccable/scripts/live-browser.js | 11173 ++++++++++++++++
.../scripts/live-commit-manual-edits.mjs | 1241 ++
.../impeccable/scripts/live-complete.mjs | 75 +
.../scripts/live-copy-edit-agent.mjs | 683 +
.../scripts/live-discard-manual-edits.mjs | 51 +
.../skills/impeccable/scripts/live-inject.mjs | 583 +
.../skills/impeccable/scripts/live-insert.mjs | 272 +
.../scripts/live-manual-edit-evidence.mjs | 363 +
.../skills/impeccable/scripts/live-poll.mjs | 384 +
.../skills/impeccable/scripts/live-resume.mjs | 94 +
.../skills/impeccable/scripts/live-server.mjs | 1134 ++
.../skills/impeccable/scripts/live-status.mjs | 61 +
.../skills/impeccable/scripts/live-wrap.mjs | 894 ++
.agent/skills/impeccable/scripts/live.mjs | 246 +
.../scripts/live/browser-script-parts.mjs | 49 +
.../impeccable/scripts/live/completion.mjs | 19 +
.../scripts/live/event-validation.mjs | 137 +
.../impeccable/scripts/live/insert-ui.mjs | 458 +
.../impeccable/scripts/live/manual-apply.mjs | 939 ++
.../scripts/live/manual-edit-routes.mjs | 357 +
.../scripts/live/manual-edits-buffer.mjs | 152 +
.../impeccable/scripts/live/session-store.mjs | 289 +
.../scripts/live/svelte-component.mjs | 826 ++
.../scripts/live/sveltekit-adapter.mjs | 274 +
.../impeccable/scripts/live/ui-core.mjs | 180 +
.../impeccable/scripts/live/vocabulary.mjs | 36 +
.../scripts/modern-screenshot.umd.js | 14 +
.agent/skills/impeccable/scripts/palette.mjs | 633 +
.agent/skills/impeccable/scripts/pin.mjs | 214 +
93 files changed, 49123 insertions(+)
create mode 100644 .agent/skills/impeccable/SKILL.md
create mode 100644 .agent/skills/impeccable/reference/adapt.md
create mode 100644 .agent/skills/impeccable/reference/animate.md
create mode 100644 .agent/skills/impeccable/reference/audit.md
create mode 100644 .agent/skills/impeccable/reference/bolder.md
create mode 100644 .agent/skills/impeccable/reference/brand.md
create mode 100644 .agent/skills/impeccable/reference/clarify.md
create mode 100644 .agent/skills/impeccable/reference/codex.md
create mode 100644 .agent/skills/impeccable/reference/colorize.md
create mode 100644 .agent/skills/impeccable/reference/craft.md
create mode 100644 .agent/skills/impeccable/reference/critique.md
create mode 100644 .agent/skills/impeccable/reference/delight.md
create mode 100644 .agent/skills/impeccable/reference/distill.md
create mode 100644 .agent/skills/impeccable/reference/document.md
create mode 100644 .agent/skills/impeccable/reference/extract.md
create mode 100644 .agent/skills/impeccable/reference/harden.md
create mode 100644 .agent/skills/impeccable/reference/hooks.md
create mode 100644 .agent/skills/impeccable/reference/init.md
create mode 100644 .agent/skills/impeccable/reference/interaction-design.md
create mode 100644 .agent/skills/impeccable/reference/layout.md
create mode 100644 .agent/skills/impeccable/reference/live.md
create mode 100644 .agent/skills/impeccable/reference/onboard.md
create mode 100644 .agent/skills/impeccable/reference/optimize.md
create mode 100644 .agent/skills/impeccable/reference/overdrive.md
create mode 100644 .agent/skills/impeccable/reference/polish.md
create mode 100644 .agent/skills/impeccable/reference/product.md
create mode 100644 .agent/skills/impeccable/reference/quieter.md
create mode 100644 .agent/skills/impeccable/reference/shape.md
create mode 100644 .agent/skills/impeccable/reference/typeset.md
create mode 100644 .agent/skills/impeccable/scripts/command-metadata.json
create mode 100644 .agent/skills/impeccable/scripts/context-signals.mjs
create mode 100644 .agent/skills/impeccable/scripts/context.mjs
create mode 100644 .agent/skills/impeccable/scripts/critique-storage.mjs
create mode 100644 .agent/skills/impeccable/scripts/detect-csp.mjs
create mode 100644 .agent/skills/impeccable/scripts/detect.mjs
create mode 100644 .agent/skills/impeccable/scripts/detector/browser/injected/index.mjs
create mode 100644 .agent/skills/impeccable/scripts/detector/cli/main.mjs
create mode 100644 .agent/skills/impeccable/scripts/detector/design-system.mjs
create mode 100644 .agent/skills/impeccable/scripts/detector/detect-antipatterns-browser.js
create mode 100644 .agent/skills/impeccable/scripts/detector/detect-antipatterns.mjs
create mode 100644 .agent/skills/impeccable/scripts/detector/engines/browser/detect-url.mjs
create mode 100644 .agent/skills/impeccable/scripts/detector/engines/regex/detect-text.mjs
create mode 100644 .agent/skills/impeccable/scripts/detector/engines/static-html/css-cascade.mjs
create mode 100644 .agent/skills/impeccable/scripts/detector/engines/static-html/detect-html.mjs
create mode 100644 .agent/skills/impeccable/scripts/detector/engines/visual/screenshot-contrast.mjs
create mode 100644 .agent/skills/impeccable/scripts/detector/findings.mjs
create mode 100644 .agent/skills/impeccable/scripts/detector/node/file-system.mjs
create mode 100644 .agent/skills/impeccable/scripts/detector/profile/profiler.mjs
create mode 100644 .agent/skills/impeccable/scripts/detector/registry/antipatterns.mjs
create mode 100644 .agent/skills/impeccable/scripts/detector/rules/checks.mjs
create mode 100644 .agent/skills/impeccable/scripts/detector/shared/color.mjs
create mode 100644 .agent/skills/impeccable/scripts/detector/shared/constants.mjs
create mode 100644 .agent/skills/impeccable/scripts/detector/shared/page.mjs
create mode 100644 .agent/skills/impeccable/scripts/hook-admin.mjs
create mode 100644 .agent/skills/impeccable/scripts/hook-before-edit.mjs
create mode 100644 .agent/skills/impeccable/scripts/hook-lib.mjs
create mode 100644 .agent/skills/impeccable/scripts/hook.mjs
create mode 100644 .agent/skills/impeccable/scripts/lib/design-parser.mjs
create mode 100644 .agent/skills/impeccable/scripts/lib/impeccable-config.mjs
create mode 100644 .agent/skills/impeccable/scripts/lib/impeccable-paths.mjs
create mode 100644 .agent/skills/impeccable/scripts/lib/is-generated.mjs
create mode 100644 .agent/skills/impeccable/scripts/live-accept.mjs
create mode 100644 .agent/skills/impeccable/scripts/live-browser-dom.js
create mode 100644 .agent/skills/impeccable/scripts/live-browser-session.js
create mode 100644 .agent/skills/impeccable/scripts/live-browser.js
create mode 100644 .agent/skills/impeccable/scripts/live-commit-manual-edits.mjs
create mode 100644 .agent/skills/impeccable/scripts/live-complete.mjs
create mode 100644 .agent/skills/impeccable/scripts/live-copy-edit-agent.mjs
create mode 100644 .agent/skills/impeccable/scripts/live-discard-manual-edits.mjs
create mode 100644 .agent/skills/impeccable/scripts/live-inject.mjs
create mode 100644 .agent/skills/impeccable/scripts/live-insert.mjs
create mode 100644 .agent/skills/impeccable/scripts/live-manual-edit-evidence.mjs
create mode 100644 .agent/skills/impeccable/scripts/live-poll.mjs
create mode 100644 .agent/skills/impeccable/scripts/live-resume.mjs
create mode 100644 .agent/skills/impeccable/scripts/live-server.mjs
create mode 100644 .agent/skills/impeccable/scripts/live-status.mjs
create mode 100644 .agent/skills/impeccable/scripts/live-wrap.mjs
create mode 100644 .agent/skills/impeccable/scripts/live.mjs
create mode 100644 .agent/skills/impeccable/scripts/live/browser-script-parts.mjs
create mode 100644 .agent/skills/impeccable/scripts/live/completion.mjs
create mode 100644 .agent/skills/impeccable/scripts/live/event-validation.mjs
create mode 100644 .agent/skills/impeccable/scripts/live/insert-ui.mjs
create mode 100644 .agent/skills/impeccable/scripts/live/manual-apply.mjs
create mode 100644 .agent/skills/impeccable/scripts/live/manual-edit-routes.mjs
create mode 100644 .agent/skills/impeccable/scripts/live/manual-edits-buffer.mjs
create mode 100644 .agent/skills/impeccable/scripts/live/session-store.mjs
create mode 100644 .agent/skills/impeccable/scripts/live/svelte-component.mjs
create mode 100644 .agent/skills/impeccable/scripts/live/sveltekit-adapter.mjs
create mode 100644 .agent/skills/impeccable/scripts/live/ui-core.mjs
create mode 100644 .agent/skills/impeccable/scripts/live/vocabulary.mjs
create mode 100644 .agent/skills/impeccable/scripts/modern-screenshot.umd.js
create mode 100644 .agent/skills/impeccable/scripts/palette.mjs
create mode 100644 .agent/skills/impeccable/scripts/pin.mjs
diff --git a/.agent/skills/impeccable/SKILL.md b/.agent/skills/impeccable/SKILL.md
new file mode 100644
index 000000000..9e4322005
--- /dev/null
+++ b/.agent/skills/impeccable/SKILL.md
@@ -0,0 +1,166 @@
+---
+name: impeccable
+description: Use when the user wants to design, redesign, shape, critique, audit, polish, clarify, distill, harden, optimize, adapt, animate, colorize, extract, or otherwise improve a frontend interface. Covers websites, landing pages, dashboards, product UI, app shells, components, forms, settings, onboarding, and empty states. Handles UX review, visual hierarchy, information architecture, cognitive load, accessibility, performance, responsive behavior, theming, anti-patterns, typography, fonts, spacing, layout, alignment, color, motion, micro-interactions, UX copy, error states, edge cases, i18n, and reusable design systems or tokens. Also use for bland designs that need to become bolder or more delightful, loud designs that should become quieter, live browser iteration on UI elements, or ambitious visual effects that should feel technically extraordinary. Not for backend-only or non-UI tasks.
+version: 3.7.1
+license: Apache 2.0
+allowed-tools:
+ - Bash(npx impeccable *)
+---
+
+Designs and iterates production-grade frontend interfaces. Real working code, committed design choices, exceptional craft.
+
+## Setup
+
+You MUST do these steps before proceeding:
+
+1. Run `node .agent/skills/impeccable/scripts/context.mjs` once per session. If you've already seen its output in this conversation, do not re-run it. The script either prints the project's PRODUCT.md (and DESIGN.md when present) as a markdown block, or tells you it's missing. Follow whatever it prints. **If it reports `NO_PRODUCT_MD`, stop and follow `reference/init.md` before doing anything else.** If the output ends with an `UPDATE_AVAILABLE` directive, follow it (ask the user once about updating, then continue). It never blocks the current task.
+2. If the user invoked a sub-command (`craft`, `shape`, `audit`, `polish`, ...), you MUST read `reference/.md` next. Non-optional. The reference defines the command's flow; without it you will skip steps the user expects.
+3. Familiarize yourself with any existing design system, conventions, and components in the code. Read at least one project file (CSS / tokens / theme / a representative component or page). **Required even when you've loaded a sub-command reference in step 2.** Don't reinvent the wheel; use what's there when it works, branch out when the UX wins.
+4. Read the matching register reference. **This is non-optional; skipping it produces generic output.** If the project is marketing, a landing page, a campaign, long-form content, or a portfolio (design IS the product), read `reference/brand.md`. If it is app UI, admin, a dashboard, or a tool (design SERVES the product), read `reference/product.md`. Pick by first match: (1) task cue ("landing page" vs "dashboard"); (2) surface in focus (the page, file, or route being worked on); (3) `register` field in PRODUCT.md.
+5. **If the project is brand-new (no existing CSS tokens / theme / committed brand colors found in step 3)**, run `node .agent/skills/impeccable/scripts/palette.mjs` to receive a brand seed color and composition guidance. This is the anchor for your primary brand color. Compose the rest of the palette (bg, surface, ink, accent, muted) around it per the script's instructions. Use OKLCH throughout. **Skip this step only if step 3 found committed brand colors in existing tokens; in that case identity-preservation wins.**
+
+## Design guidance
+
+Produce ready-to-ship, production-grade code, not prototypes or starting points. Take no shortcuts unless the user asks for them (when in doubt, ask). Don't stop until arriving at a complete implementation (beautiful, responsive, fast, precise, bug-free, on brand). You take attention to detail seriously: every page, section or component crafted is battle tested using the tools available to you (browser screenshotting, computer use, etc). Gemini is capable of extraordinary work. Don't hold back.
+
+### General rules
+
+#### Color
+
+- **Verify contrast.** Body text must hit ≥4.5:1 against its background; large text (≥18px or bold ≥14px) needs ≥3:1. Placeholder text needs the same 4.5:1, not the muted-gray default. The most common failure: muted gray body text on a tinted near-white. If the contrast is even close, bump the body color toward the ink end of the ramp; light gray "for elegance" is the single biggest reason AI designs feel hard to read.
+- Gray text on a colored background looks washed out. Use a darker shade of the background's own hue, or a transparency of the text color.
+
+#### Typography
+
+- Cap body line length at 65–75ch.
+- Don't pair fonts that are similar but not identical (two geometric sans-serifs, two humanist sans-serifs). Pair on a contrast axis (serif + sans, geometric + humanist) or use one family in multiple weights.
+- Hero / display heading ceiling: clamp() max ≤ 6rem (~96px). Above that the page is shouting, not designing.
+- Display heading letter-spacing floor: ≥ -0.04em. Anything tighter and letters touch; cramped, not "designed".
+- Use `text-wrap: balance` on h1–h3 for even line lengths; `text-wrap: pretty` on long prose to reduce orphans.
+
+#### Layout
+
+- Vary spacing for rhythm.
+- Cards are the lazy answer. Use them only when they're truly the best affordance. Nested cards are always wrong.
+- Flexbox for 1D, Grid for 2D. Don't default to Grid when `flex-wrap` would be simpler.
+- For responsive grids without breakpoints: `repeat(auto-fit, minmax(280px, 1fr))`.
+- Build a semantic z-index scale (dropdown → sticky → modal-backdrop → modal → toast → tooltip). Never arbitrary values like 999 or 9999.
+
+#### Motion
+- Motion should be intentional, and not be an afterthought. consider it as part of the build.
+- Don't animate CSS layout properties unless truly needed.
+- Ease out with exponential curves (ease-out-quart / quint / expo). No bounce, no elastic.
+- Use libraries for more advanced motion needs (e.g. motion, gsap, anime.js, lenis etc)
+- Reduced motion is not optional. Every animation needs a `@media (prefers-reduced-motion: reduce)` alternative: typically a crossfade or instant transition.
+- Staggering the items within one list is legitimate. The tell is the uniform reflex (one identical entrance applied to every section), not motion itself; each reveal should fit what it reveals. Suppressing the reflex is never a reason to ship a page with no motion at all.
+- Reveal animations must enhance an already-visible default. Don't gate content visibility on a class-triggered transition; transitions pause on hidden tabs and headless renderers, so the reveal never fires and the section ships blank.
+- Premium motion materials are not just transform/opacity. Blur, backdrop-filter, clip-path, mask, and shadow/glow are part of the palette when they materially improve the effect and stay smooth.
+
+#### Interaction
+
+- Dropdowns rendered with `position: absolute` inside an `overflow: hidden` or `overflow: auto` container will be clipped. Use the native `
` open near the top of the document.
+ const idx = content.indexOf(config.insertAfter);
+ if (idx === -1) return content;
+ const after = idx + config.insertAfter.length;
+ // Preserve an existing trailing newline if the anchor already has one.
+ // Slice the remainder from the original anchor offset, not prefix.length:
+ // in the no-newline case prefix is one char longer than the anchor (the
+ // appended '\n'), so slicing by prefix.length would drop the first real
+ // character after the anchor (#227).
+ const existingNewline = readLineEndingAt(content, after);
+ const prefix = content.slice(0, after) + (existingNewline || lineEnding);
+ const rest = content.slice(after + existingNewline.length);
+ return prefix + block + rest;
+}
+
+/**
+ * Remove the live script block. Matches either HTML or JSX comment markers
+ * regardless of config (so stale tags from a wrong config can still be cleaned).
+ *
+ * Indent-preserving: captures any whitespace immediately preceding the opener
+ * marker and re-emits it in place of the removed block. `insertTag` inserted
+ * the block *after* the original line's indent and *before* the anchor (e.g.
+ * `
` naturally
+ // belong at the end, and the same literal can appear earlier in code blocks
+ // within rendered documentation pages.
+ if (config.insertBefore) {
+ const idx = content.lastIndexOf(config.insertBefore);
+ if (idx === -1) return content;
+ return content.slice(0, idx) + block + content.slice(idx);
+ }
+ // insertAfter: match the FIRST occurrence — typical anchors like `
` or
+ // `
`), which moved the indent onto the opener line and left the anchor
+ * unindented. Replacing the whole block (plus its trailing newline) with just
+ * the captured indent hands the indent back to the anchor that follows.
+ */
+function removeTag(content, _syntax) {
+ const patterns = [
+ /([ \t]*)[\s\S]*?([ \t]*(?:\r\n|\n|\r|$)?)/,
+ /([ \t]*)\{\/\*\s*impeccable-live-start\s*\*\/\}[\s\S]*?\{\/\*\s*impeccable-live-end\s*\*\/\}([ \t]*(?:\r\n|\n|\r|$)?)/,
+ ];
+ for (const pat of patterns) {
+ let changed = false;
+ let next = content;
+ do {
+ content = next;
+ next = content.replace(pat, (_match, leadingIndent, trailing = '') => {
+ if (/[\r\n]/.test(trailing)) return leadingIndent;
+ return leadingIndent || trailing || '';
+ });
+ if (next !== content) changed = true;
+ } while (next !== content);
+ if (changed) return next;
+ }
+ return content;
+}
+
+// ---------------------------------------------------------------------------
+// Content-Security-Policy meta-tag patcher
+//
+// When the user's HTML carries ``,
+// the cross-origin load of /live.js (and the SSE/POST connection back to
+// localhost:PORT) is blocked unless the CSP explicitly allows that origin.
+//
+// On insert: append `http://localhost:PORT` to `script-src` and `connect-src`,
+// and stash the original `content` value in a `data-impeccable-csp-original`
+// attribute (base64) so revert is exact.
+//
+// On remove: detect the marker attribute, decode it, restore the original
+// content value verbatim, drop the marker.
+//
+// Header-based CSP (Next.js headers, Nuxt routeRules, SvelteKit kit.csp,
+// shared helpers) is NOT patched here — those need framework-specific config
+// edits and are handled via the existing detect-csp.mjs reference output.
+// Only the in-source meta-tag form gets the auto-patch.
+// ---------------------------------------------------------------------------
+
+const CSP_MARKER_ATTR = 'data-impeccable-csp-original';
+
+function findCspMetaTags(content) {
+ const out = [];
+ const tagRe = /]*?)\/?>/gis;
+ let m;
+ while ((m = tagRe.exec(content)) !== null) {
+ const attrs = m[1];
+ if (!/(http-equiv|httpEquiv)\s*=\s*(['"])Content-Security-Policy\2/i.test(attrs)) continue;
+ out.push({ start: m.index, end: m.index + m[0].length, full: m[0], attrs });
+ }
+ return out;
+}
+
+function getAttr(attrs, name) {
+ const re = new RegExp(`\\b${name}\\s*=\\s*(['"])([\\s\\S]*?)\\1`, 'i');
+ const m = attrs.match(re);
+ return m ? { quote: m[1], value: m[2], full: m[0] } : null;
+}
+
+function appendOriginToDirective(csp, directive, origin) {
+ const re = new RegExp(`(^|;)(\\s*)(${directive})\\s+([^;]*)`, 'i');
+ const m = csp.match(re);
+ if (m) {
+ const tokens = m[4].trim().split(/\s+/);
+ if (tokens.includes(origin)) return csp;
+ return csp.replace(re, `${m[1]}${m[2]}${m[3]} ${[...tokens, origin].join(' ')}`);
+ }
+ // Directive missing — add it. Use 'self' + origin so we don't inadvertently
+ // narrow the policy compared to the default-src fallback (most users with
+ // an explicit CSP have 'self' there).
+ return csp.trim().replace(/;?\s*$/, '') + `; ${directive} 'self' ${origin}`;
+}
+
+export function patchCspMeta(content, port) {
+ const tags = findCspMetaTags(content);
+ if (tags.length === 0) return content;
+ const origin = `http://localhost:${port}`;
+
+ // Walk last-to-first so prior splices don't invalidate later indices.
+ let result = content;
+ for (let i = tags.length - 1; i >= 0; i--) {
+ const tag = tags[i];
+ const attrs = tag.attrs;
+ if (getAttr(attrs, CSP_MARKER_ATTR)) continue; // already patched
+ const contentAttr = getAttr(attrs, 'content');
+ if (!contentAttr) continue;
+
+ const original = contentAttr.value;
+ let patched = original;
+ patched = appendOriginToDirective(patched, 'script-src', origin);
+ patched = appendOriginToDirective(patched, 'connect-src', origin);
+ // The shader overlay during 'generating' creates a screenshot via
+ // URL.createObjectURL, producing a `blob:` URL — img-src 'self' rejects
+ // those. Add `blob:` so the overlay doesn't throw a CSP violation.
+ patched = appendOriginToDirective(patched, 'img-src', 'blob:');
+ if (patched === original) continue;
+
+ const newContentAttr = `content=${contentAttr.quote}${patched}${contentAttr.quote}`;
+ const marker = `${CSP_MARKER_ATTR}="${Buffer.from(original, 'utf-8').toString('base64')}"`;
+ // The tagRe captures any whitespace between the last attribute and the
+ // closing `/>` as part of `attrs`. Naively appending ` ${marker}` after
+ // a replace would land it BEFORE that trailing space, leaving a double
+ // space inside attrs and clobbering the space before `/>`. Split off
+ // the trailing whitespace, splice the marker into the attribute body,
+ // and re-append the original trailing whitespace so a self-closing
+ // `` round-trips byte-for-byte.
+ const trailingWs = (attrs.match(/[ \t]*$/) || [''])[0];
+ const attrsBody = attrs.slice(0, attrs.length - trailingWs.length);
+ const newAttrs = attrsBody.replace(contentAttr.full, newContentAttr) + ' ' + marker + trailingWs;
+ const newTag = tag.full.replace(attrs, newAttrs);
+
+ result = result.slice(0, tag.start) + newTag + result.slice(tag.end);
+ }
+ return result;
+}
+
+export function revertCspMeta(content) {
+ const tags = findCspMetaTags(content);
+ if (tags.length === 0) return content;
+
+ let result = content;
+ for (let i = tags.length - 1; i >= 0; i--) {
+ const tag = tags[i];
+ const origAttr = getAttr(tag.attrs, CSP_MARKER_ATTR);
+ if (!origAttr) continue;
+ const contentAttr = getAttr(tag.attrs, 'content');
+ if (!contentAttr) continue;
+
+ let originalValue;
+ try { originalValue = Buffer.from(origAttr.value, 'base64').toString('utf-8'); }
+ catch { continue; }
+
+ const newContentAttr = `content=${contentAttr.quote}${originalValue}${contentAttr.quote}`;
+ let newAttrs = tag.attrs.replace(contentAttr.full, newContentAttr);
+ // Drop the marker attribute and any single space immediately preceding it.
+ newAttrs = newAttrs.replace(new RegExp(`\\s*${origAttr.full}`), '');
+ const newTag = tag.full.replace(tag.attrs, newAttrs);
+
+ result = result.slice(0, tag.start) + newTag + result.slice(tag.end);
+ }
+ return result;
+}
+
+// ---------------------------------------------------------------------------
+// Auto-execute
+// ---------------------------------------------------------------------------
+
+const _running = process.argv[1];
+if (_running?.endsWith('live-inject.mjs') || _running?.endsWith('live-inject.mjs/')) {
+ injectCli();
+}
+
+export { insertTag, removeTag, validateConfig, buildTagBlock };
+// patchCspMeta + revertCspMeta are exported above where they're defined.
diff --git a/.agent/skills/impeccable/scripts/live-insert.mjs b/.agent/skills/impeccable/scripts/live-insert.mjs
new file mode 100644
index 000000000..0ed3cafea
--- /dev/null
+++ b/.agent/skills/impeccable/scripts/live-insert.mjs
@@ -0,0 +1,272 @@
+/**
+ * CLI helper: find an anchor element in source and splice an insert-variant
+ * wrapper before or after it (no original variant — net-new content).
+ *
+ * Usage:
+ * node live-insert.mjs --id SESSION_ID --count N --position after \
+ * --classes "hero" --tag section [--file path]
+ */
+
+import fs from 'node:fs';
+import path from 'node:path';
+import { isGeneratedFile } from './lib/is-generated.mjs';
+import {
+ buildSearchQueries,
+ findElement,
+ findAllElements,
+ filterByText,
+ findFileWithQuery,
+ detectCommentSyntax,
+ detectStyleMode,
+ buildCssAuthoring,
+ buildCssSelectorPrefixExamples,
+} from './live-wrap.mjs';
+import {
+ buildSvelteComponentCssAuthoring,
+ scaffoldSvelteComponentInsertSession,
+ shouldUseSvelteComponentInjection,
+} from './live/svelte-component.mjs';
+
+const INSERT_POSITIONS = new Set(['before', 'after']);
+
+export function isInsertPosition(value) {
+ return INSERT_POSITIONS.has(value);
+}
+
+export function computeInsertLine(startLine, endLine, position) {
+ return position === 'before' ? startLine : endLine + 1;
+}
+
+export function buildInsertWrapperLines({ id, count, indent, commentSyntax, isJsx }) {
+ const styleContents = isJsx ? 'style={{ display: "contents" }}' : 'style="display: contents"';
+ const attrs =
+ 'data-impeccable-variants="' + id + '" ' +
+ 'data-impeccable-mode="insert" ' +
+ 'data-impeccable-variant-count="' + count + '" ' +
+ styleContents;
+
+ if (isJsx) {
+ return [
+ indent + '
',
+ indent + commentSyntax.open + ' impeccable-variants-end ' + id + ' ' + commentSyntax.close,
+ ];
+}
+
+function argVal(args, flag) {
+ const idx = args.indexOf(flag);
+ return idx !== -1 && idx + 1 < args.length ? args[idx + 1] : null;
+}
+
+function resolveElementMatch({ lines, queries, tag, text }) {
+ if (text) {
+ const candidates = [];
+ for (const q of queries) {
+ const all = findAllElements(lines, q, tag);
+ for (const c of all) {
+ if (!candidates.some((x) => x.startLine === c.startLine)) candidates.push(c);
+ }
+ if (candidates.length === 1) break;
+ }
+ if (candidates.length === 0) return { error: 'element_not_found' };
+ if (candidates.length === 1) return { match: candidates[0] };
+ const filtered = filterByText(candidates, lines, text);
+ if (filtered.length === 1) return { match: filtered[0] };
+ if (filtered.length === 0) return { match: candidates[0] };
+ return { error: 'element_ambiguous', candidates: filtered };
+ }
+
+ for (const q of queries) {
+ const match = findElement(lines, q, tag);
+ if (match) return { match };
+ }
+ return { error: 'element_not_found' };
+}
+
+export async function insertCli() {
+ const args = process.argv.slice(2);
+
+ if (args.includes('--help') || args.includes('-h')) {
+ console.log(`Usage: node live-insert.mjs [options]
+
+Find an anchor element in source and splice an insert-variant wrapper.
+
+Required:
+ --id ID Session ID for the variant wrapper
+ --count N Number of expected variants (1-8)
+ --position POS before | after (relative to the anchor element)
+
+Element identification (at least one required):
+ --element-id ID HTML id attribute of the anchor 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)
+ --text TEXT Anchor textContent for disambiguation (~80 chars)
+
+Output (JSON):
+ { mode: "insert", file, position, insertLine, commentSyntax, styleMode, styleTag, cssAuthoring }`);
+ process.exit(0);
+ }
+
+ const id = argVal(args, '--id');
+ const count = parseInt(argVal(args, '--count') || '3', 10);
+ const position = argVal(args, '--position');
+ 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');
+ const text = argVal(args, '--text');
+
+ if (!id) { console.error('Missing --id'); process.exit(1); }
+ if (!position) { console.error('Missing --position (before | after)'); process.exit(1); }
+ if (!isInsertPosition(position)) { console.error('Invalid --position: ' + position); process.exit(1); }
+ if (!elementId && !classes && !query) {
+ console.error('Need at least one of: --element-id, --classes, --query');
+ process.exit(1);
+ }
+
+ const queries = buildSearchQueries(elementId, classes, tag, query);
+ const genOpts = { cwd: process.cwd() };
+
+ let targetFile = filePath;
+ if (!targetFile) {
+ for (const q of queries) {
+ targetFile = findFileWithQuery(q, process.cwd(), genOpts);
+ if (targetFile) break;
+ }
+ if (!targetFile) {
+ let generatedHit = null;
+ for (const q of queries) {
+ generatedHit = findFileWithQuery(q, process.cwd(), { ...genOpts, includeGenerated: true });
+ if (generatedHit) break;
+ }
+ console.error(JSON.stringify({
+ error: generatedHit ? 'element_not_in_source' : 'element_not_found',
+ fallback: 'agent-driven',
+ hint: 'See "Handle fallback" in live.md.',
+ }));
+ process.exit(1);
+ }
+ } else if (isGeneratedFile(targetFile, genOpts)) {
+ console.error(JSON.stringify({
+ error: 'file_is_generated',
+ fallback: 'agent-driven',
+ file: path.relative(process.cwd(), path.resolve(process.cwd(), targetFile)),
+ }));
+ process.exit(1);
+ }
+
+ const content = fs.readFileSync(targetFile, 'utf-8');
+ const lines = content.split('\n');
+ const resolved = resolveElementMatch({ lines, queries, tag, text });
+
+ if (resolved.error === 'element_ambiguous') {
+ console.error(JSON.stringify({
+ error: 'element_ambiguous',
+ fallback: 'agent-driven',
+ file: path.relative(process.cwd(), targetFile),
+ candidates: resolved.candidates.map((c) => ({
+ startLine: c.startLine + 1,
+ endLine: c.endLine + 1,
+ })),
+ }));
+ process.exit(1);
+ }
+ if (!resolved.match) {
+ console.error(JSON.stringify({ error: 'element_not_found', fallback: 'agent-driven' }));
+ process.exit(1);
+ }
+
+ const { startLine, endLine } = resolved.match;
+ const commentSyntax = detectCommentSyntax(targetFile);
+ const styleMode = detectStyleMode(targetFile);
+ const isJsx = commentSyntax.open === '{/*';
+ const spliceIndex = computeInsertLine(startLine, endLine, position);
+ const relTargetFile = path.relative(process.cwd(), targetFile).split(path.sep).join('/');
+
+ if (shouldUseSvelteComponentInjection(targetFile)) {
+ const session = scaffoldSvelteComponentInsertSession({
+ id,
+ count,
+ sourceFile: relTargetFile,
+ insertLine: spliceIndex + 1,
+ position,
+ anchorStartLine: startLine + 1,
+ anchorEndLine: endLine + 1,
+ anchorLines: lines.slice(startLine, endLine + 1),
+ cwd: process.cwd(),
+ });
+ console.log(JSON.stringify({
+ mode: 'insert',
+ position,
+ file: session.manifestFile,
+ sourceFile: relTargetFile,
+ previewMode: 'svelte-component',
+ componentDir: session.componentDir,
+ propContract: session.propContract,
+ insertLine: 1,
+ sourceInsertLine: spliceIndex + 1,
+ anchorStartLine: startLine + 1,
+ anchorEndLine: endLine + 1,
+ commentSyntax,
+ styleMode: 'svelte-component',
+ styleTag: null,
+ cssSelectorPrefixExamples: [],
+ cssAuthoring: buildSvelteComponentCssAuthoring(count),
+ }));
+ return;
+ }
+
+ const indent = lines[spliceIndex]?.match(/^(\s*)/)?.[1]
+ ?? lines[startLine]?.match(/^(\s*)/)?.[1]
+ ?? '';
+
+ const wrapperLines = buildInsertWrapperLines({
+ id,
+ count,
+ indent,
+ commentSyntax,
+ isJsx,
+ });
+
+ const newLines = [
+ ...lines.slice(0, spliceIndex),
+ ...wrapperLines,
+ ...lines.slice(spliceIndex),
+ ];
+ fs.writeFileSync(targetFile, newLines.join('\n'), 'utf-8');
+
+ const insertLine = spliceIndex + 3;
+
+ console.log(JSON.stringify({
+ mode: 'insert',
+ position,
+ file: relTargetFile,
+ insertLine: insertLine + 1,
+ commentSyntax,
+ styleMode: styleMode.mode,
+ styleTag: styleMode.styleTag,
+ cssSelectorPrefixExamples: buildCssSelectorPrefixExamples(styleMode.mode, count),
+ cssAuthoring: buildCssAuthoring(styleMode, count),
+ }));
+}
+
+const _running = process.argv[1];
+if (_running?.endsWith('live-insert.mjs') || _running?.endsWith('live-insert.mjs/')) {
+ insertCli();
+}
diff --git a/.agent/skills/impeccable/scripts/live-manual-edit-evidence.mjs b/.agent/skills/impeccable/scripts/live-manual-edit-evidence.mjs
new file mode 100644
index 000000000..dd10e96dc
--- /dev/null
+++ b/.agent/skills/impeccable/scripts/live-manual-edit-evidence.mjs
@@ -0,0 +1,363 @@
+#!/usr/bin/env node
+/**
+ * Collect evidence for pending live copy edits.
+ *
+ * This module intentionally does not edit source files and does not choose a
+ * winner. It gathers staged browser edits, rendered context, framework source
+ * hints, and likely source candidates so the AI copy-edit batch runner can make
+ * source changes with full repo context.
+ */
+
+import fs from 'node:fs';
+import path from 'node:path';
+import { isGeneratedFile } from './lib/is-generated.mjs';
+import { readBuffer, getBufferPath } from './live/manual-edits-buffer.mjs';
+
+const EVIDENCE_VERSION = 1;
+const TEXT_EXTENSIONS = new Set(['.html', '.jsx', '.tsx', '.vue', '.svelte', '.astro', '.js', '.mjs', '.ts']);
+const SEARCH_DIRS = ['src', 'app', 'pages', 'components', 'public', 'views', 'templates', 'site', 'lib', 'data'];
+const STRONG_LITERAL_MATCH_LIMIT = 8;
+const WEAK_LITERAL_MATCH_LIMIT = 4;
+const OBJECT_KEY_MATCH_LIMIT = 8;
+const LOCATOR_MATCH_LIMIT = 4;
+const CONTEXT_MATCH_LIMIT = 8;
+const CONTEXT_MATCH_PER_HINT = 2;
+const SKIP_DIRS = new Set([
+ 'node_modules',
+ '.git',
+ '.impeccable',
+ '.astro',
+ '.next',
+ '.nuxt',
+ '.svelte-kit',
+ 'dist',
+ 'build',
+ 'out',
+ 'coverage',
+]);
+
+export function buildManualEditEvidence({ cwd = process.cwd(), pageUrl = null } = {}) {
+ const buffer = readBuffer(cwd);
+ const entries = pageUrl
+ ? buffer.entries.filter((entry) => entry.pageUrl === pageUrl)
+ : buffer.entries;
+ const opCount = countOps(entries);
+
+ if (opCount === 0) {
+ return {
+ pageUrl,
+ count: 0,
+ entries: [],
+ ops: [],
+ candidates: [],
+ };
+ }
+
+ const searchFiles = collectSearchFiles(cwd);
+ const ops = flattenOps(entries);
+ const candidates = ops.map((op) => buildCandidatesForOp(op, cwd, searchFiles));
+ return {
+ version: EVIDENCE_VERSION,
+ pageUrl: pageUrl || null,
+ count: opCount,
+ entries,
+ ops,
+ context: {
+ cwd,
+ bufferPath: path.relative(cwd, getBufferPath(cwd)),
+ totalEntries: entries.length,
+ totalOps: opCount,
+ },
+ candidates,
+ };
+}
+
+function countOps(entries) {
+ let count = 0;
+ for (const entry of entries) count += Array.isArray(entry.ops) ? entry.ops.length : 0;
+ return count;
+}
+
+function flattenOps(entries) {
+ const out = [];
+ for (const entry of entries) {
+ const contextHintsByRef = buildContextHintsByRef(entry);
+ for (const op of entry.ops || []) {
+ out.push({
+ entryId: entry.id,
+ pageUrl: entry.pageUrl,
+ ref: op.ref,
+ contextRef: op.contextRef || null,
+ tag: op.tag,
+ elementId: op.elementId || null,
+ classes: Array.isArray(op.classes) ? op.classes : [],
+ originalText: op.originalText,
+ newText: op.newText,
+ deleted: op.deleted === true,
+ sourceHint: op.sourceHint || null,
+ leaf: op.leaf || null,
+ nearbyEditableTexts: Array.isArray(op.nearbyEditableTexts) ? op.nearbyEditableTexts : [],
+ container: op.container || null,
+ contextHints: contextHintsByRef.get(op.ref) || [],
+ });
+ }
+ }
+ return out;
+}
+
+function buildContextHintsByRef(entry) {
+ const map = new Map();
+ for (const op of entry.ops || []) {
+ const hints = new Set();
+ const add = (value) => {
+ const text = normalizeText(decodeBasicHtml(String(value || '')));
+ if (text.length < 3 || text.length > 160) return;
+ if (text === normalizeText(op.originalText) || text === normalizeText(op.newText)) return;
+ hints.add(text);
+ };
+
+ for (const item of op.nearbyEditableTexts || []) {
+ add(typeof item === 'string' ? item : item?.text);
+ }
+ const outer = typeof entry.element?.outerHTML === 'string' ? entry.element.outerHTML : '';
+ for (const match of outer.matchAll(/data-impeccable-original-text="([^"]*)"/g)) add(match[1]);
+ if (typeof entry.element?.textContent === 'string') {
+ for (const chunk of entry.element.textContent.split(/\s{2,}|\n|\t/)) add(chunk);
+ }
+ map.set(op.ref, [...hints].slice(0, 16));
+ }
+ return map;
+}
+
+function buildCandidatesForOp(op, cwd, searchFiles) {
+ const originalText = String(op.originalText || '');
+ const contextNeedles = op.contextHints || [];
+ return {
+ entryId: op.entryId,
+ ref: op.ref,
+ originalText,
+ sourceHint: analyzeSourceHint(op, cwd),
+ textMatches: originalText ? findLiteralMatches(searchFiles, originalText, { max: literalMatchLimit(originalText) }) : [],
+ objectKeyMatches: originalText ? findObjectKeyMatches(searchFiles, originalText, { max: OBJECT_KEY_MATCH_LIMIT }) : [],
+ locatorMatches: findLocatorMatches(searchFiles, op, { max: LOCATOR_MATCH_LIMIT }),
+ contextTextMatches: findContextMatches(searchFiles, contextNeedles, { maxPerHint: CONTEXT_MATCH_PER_HINT, max: CONTEXT_MATCH_LIMIT }),
+ };
+}
+
+function literalMatchLimit(text) {
+ return isWeakSourceNeedle(text) ? WEAK_LITERAL_MATCH_LIMIT : STRONG_LITERAL_MATCH_LIMIT;
+}
+
+function isWeakSourceNeedle(text) {
+ const normalized = normalizeText(text);
+ return normalized.length < 4 || /^[\d.,+\-%\s]+$/.test(normalized);
+}
+
+function analyzeSourceHint(op, cwd) {
+ const hint = normalizeSourceHint(op.sourceHint);
+ if (!hint.file) return null;
+ const file = path.resolve(cwd, hint.file);
+ const relativeFile = path.relative(cwd, file);
+ if (!isPathInsideOrEqual(cwd, file)) {
+ return { ...hint, status: 'outside_cwd', relativeFile: hint.file };
+ }
+ if (!fs.existsSync(file)) {
+ return { ...hint, status: 'file_missing', relativeFile };
+ }
+ if (isGeneratedFile(file, { cwd })) {
+ return { ...hint, status: 'generated', relativeFile };
+ }
+
+ const content = fs.readFileSync(file, 'utf-8');
+ const lines = content.split('\n');
+ const line = hint.line || 1;
+ const start = Math.max(0, line - 4);
+ const end = Math.min(lines.length, line + 3);
+ const windowText = lines.slice(start, end).join('\n');
+ const containsOriginalText = typeof op.originalText === 'string' && windowText.includes(op.originalText);
+ return {
+ ...hint,
+ status: containsOriginalText ? 'ok' : 'text_not_found_near_hint',
+ relativeFile,
+ excerpt: lines.slice(start, end).map((text, index) => ({
+ line: start + index + 1,
+ text: text.slice(0, 240),
+ })),
+ };
+}
+
+function normalizeSourceHint(hint) {
+ if (!hint || typeof hint !== 'object') return {};
+ let line = Number.isFinite(Number(hint.line)) ? Number(hint.line) : null;
+ let column = Number.isFinite(Number(hint.column)) ? Number(hint.column) : null;
+ if ((!line || !column) && typeof hint.loc === 'string') {
+ const match = hint.loc.match(/^(\d+)(?::(\d+))?/);
+ if (match) {
+ line = Number(match[1]);
+ if (match[2]) column = Number(match[2]);
+ }
+ }
+ return {
+ file: typeof hint.file === 'string' ? hint.file : '',
+ loc: typeof hint.loc === 'string' ? hint.loc : '',
+ line,
+ column,
+ };
+}
+
+function collectSearchFiles(cwd) {
+ const out = [];
+ const seenDirs = new Set();
+ const seenFiles = new Set();
+ for (const dir of SEARCH_DIRS) {
+ scanDir(path.join(cwd, dir), cwd, seenDirs, seenFiles, out, 0);
+ }
+ scanRootFiles(cwd, seenFiles, out);
+ return out;
+}
+
+function scanDir(dir, cwd, seenDirs, seenFiles, out, depth) {
+ if (depth > 7 || !fs.existsSync(dir)) return;
+ let realDir;
+ try { realDir = fs.realpathSync(dir); } catch { return; }
+ if (seenDirs.has(realDir)) return;
+ seenDirs.add(realDir);
+
+ let entries;
+ try { entries = fs.readdirSync(dir, { withFileTypes: true }); } catch { return; }
+ for (const entry of entries) {
+ const fullPath = path.join(dir, entry.name);
+ if (entry.isDirectory()) {
+ if (SKIP_DIRS.has(entry.name)) continue;
+ scanDir(fullPath, cwd, seenDirs, seenFiles, out, depth + 1);
+ continue;
+ }
+ if (!entry.isFile() || !TEXT_EXTENSIONS.has(path.extname(entry.name).toLowerCase())) continue;
+ maybeAddSearchFile(fullPath, cwd, seenFiles, out);
+ }
+}
+
+function scanRootFiles(cwd, seenFiles, out) {
+ let entries;
+ try { entries = fs.readdirSync(cwd, { withFileTypes: true }); } catch { return; }
+ for (const entry of entries) {
+ if (!entry.isFile() || !TEXT_EXTENSIONS.has(path.extname(entry.name).toLowerCase())) continue;
+ maybeAddSearchFile(path.join(cwd, entry.name), cwd, seenFiles, out);
+ }
+}
+
+function maybeAddSearchFile(file, cwd, seenFiles, out) {
+ let realFile;
+ try { realFile = fs.realpathSync(file); } catch { return; }
+ if (seenFiles.has(realFile)) return;
+ seenFiles.add(realFile);
+ if (isGeneratedFile(file, { cwd })) return;
+ let content;
+ try { content = fs.readFileSync(file, 'utf-8'); } catch { return; }
+ out.push({ file, relativeFile: path.relative(cwd, file), content, lines: content.split('\n') });
+}
+
+function findLiteralMatches(searchFiles, needle, { max }) {
+ return findMatches(searchFiles, needle, { kind: 'text', max });
+}
+
+function findObjectKeyMatches(searchFiles, text, { max }) {
+ const re = new RegExp('(["\\\'`])' + escapeRegExp(text) + '\\1(?=\\s*:)', 'g');
+ const out = [];
+ for (const file of searchFiles) {
+ for (const match of file.content.matchAll(re)) {
+ out.push(matchForIndex(file, match.index, 'object_key', text));
+ if (out.length >= max) return out;
+ }
+ }
+ return out;
+}
+
+function findLocatorMatches(searchFiles, op, { max }) {
+ const needles = [];
+ if (op.elementId) needles.push({ kind: 'id', needle: op.elementId });
+ for (const cls of op.classes || []) {
+ if (cls) needles.push({ kind: 'class', needle: cls });
+ }
+ if (op.tag) needles.push({ kind: 'tag', needle: '<' + op.tag });
+
+ const out = [];
+ const seen = new Set();
+ for (const { kind, needle } of needles) {
+ for (const match of findMatches(searchFiles, needle, { kind, max })) {
+ const key = match.file + ':' + match.line + ':' + kind + ':' + needle;
+ if (seen.has(key)) continue;
+ seen.add(key);
+ out.push({ ...match, needle });
+ if (out.length >= max) return out;
+ }
+ }
+ return out;
+}
+
+function findContextMatches(searchFiles, hints, { maxPerHint, max }) {
+ const out = [];
+ const seen = new Set();
+ for (const hint of hints || []) {
+ for (const match of findMatches(searchFiles, hint, { kind: 'context', max: maxPerHint })) {
+ const key = match.file + ':' + match.line + ':' + hint;
+ if (seen.has(key)) continue;
+ seen.add(key);
+ out.push({ ...match, needle: hint });
+ if (out.length >= max) return out;
+ }
+ }
+ return out;
+}
+
+function findMatches(searchFiles, needle, { kind, max }) {
+ const text = String(needle || '');
+ if (!text) return [];
+ const out = [];
+ for (const file of searchFiles) {
+ let index = 0;
+ while (out.length < max) {
+ index = file.content.indexOf(text, index);
+ if (index === -1) break;
+ out.push(matchForIndex(file, index, kind, text));
+ index += Math.max(1, text.length);
+ }
+ if (out.length >= max) break;
+ }
+ return out;
+}
+
+function matchForIndex(file, index, kind, needle) {
+ const line = file.content.slice(0, index).split('\n').length;
+ const lineText = file.lines[line - 1] || '';
+ return {
+ kind,
+ file: file.relativeFile,
+ line,
+ needle,
+ excerpt: lineText.trim().slice(0, 240),
+ };
+}
+
+function isPathInsideOrEqual(cwd, file) {
+ const rel = path.relative(path.resolve(cwd), path.resolve(file));
+ return rel === '' || (!rel.startsWith('..') && !path.isAbsolute(rel));
+}
+
+function normalizeText(value) {
+ return String(value || '').replace(/\s+/g, ' ').trim();
+}
+
+function decodeBasicHtml(value) {
+ return value
+ .replace(/"/g, '"')
+ .replace(/'/g, "'")
+ .replace(/'/g, "'")
+ .replace(/&/g, '&')
+ .replace(/</g, '<')
+ .replace(/>/g, '>');
+}
+
+function escapeRegExp(value) {
+ return String(value).replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
+}
diff --git a/.agent/skills/impeccable/scripts/live-poll.mjs b/.agent/skills/impeccable/scripts/live-poll.mjs
new file mode 100644
index 000000000..740161e10
--- /dev/null
+++ b/.agent/skills/impeccable/scripts/live-poll.mjs
@@ -0,0 +1,384 @@
+/**
+ * CLI client for the live variant mode poll/reply protocol.
+ *
+ * Usage:
+ * node /live-poll.mjs # Block until browser event, print JSON
+ * node /live-poll.mjs --stream # Experimental: keep polling; one JSON line per event
+ * node /live-poll.mjs --timeout=600000 # Custom timeout (ms); default is long-poll friendly
+ * node /live-poll.mjs --reply done # Reply "done" to event
+ * node /live-poll.mjs --reply error "msg" # Reply with error
+ */
+
+import { execFileSync } from 'node:child_process';
+import path from 'node:path';
+import { fileURLToPath } from 'node:url';
+import { completionAckForAcceptResult, completionTypeForAcceptResult } from './live/completion.mjs';
+import { readLiveServerInfo } from './lib/impeccable-paths.mjs';
+
+// Absolute path to a sibling script in this skill's scripts dir, so runtime
+// error hints print a directly-runnable command instead of a placeholder.
+const SELF_DIR = path.dirname(fileURLToPath(import.meta.url));
+const scriptCmd = (name) => `node "${path.join(SELF_DIR, name)}"`;
+
+// Node's built-in fetch (undici under the hood) enforces a 300s headers
+// timeout that can't be lowered per-request. We cap each request below
+// that ceiling and loop in `pollOnce` to synthesize a long poll without
+// depending on the standalone undici package.
+export const PER_REQUEST_TIMEOUT_MS = 270_000;
+export const DEFAULT_EVENT_LEASE_MS = 600_000;
+
+const EVENT_TYPES_NEEDING_AGENT_REPLY = new Set(['generate', 'steer', 'manual_edit_apply']);
+
+function readServerInfo() {
+ const record = readLiveServerInfo(process.cwd());
+ if (!record) {
+ console.error(`No running live server found. Start one with: ${scriptCmd('live.mjs')}`);
+ process.exit(1);
+ }
+ return record.info;
+}
+
+export function buildPollReplyPayload(token, { id, type, message, file, data }) {
+ return { token, id, type, message, file, data };
+}
+
+export function manualApplyPollBanner(event = {}) {
+ const id = event.id || 'EVENT_ID';
+ return [
+ `Manual Apply action required: edit source, then reply with \`live-poll.mjs --reply ${id} done --data ''\`.`,
+ 'The JSON data must include status, appliedEntryIds, failed, files, and notes; summary counters are only a recovery fallback.',
+ 'Do not run live-commit-manual-edits.mjs for this leased event.',
+ 'Do not poll again before replying.',
+ ].join('\n') + '\n';
+}
+
+/**
+ * Parse `--reply [--file path] [--data ''] [message]` argv
+ * into a reply object. Returns null when `--reply` is absent. Throws (code
+ * INVALID_REPLY_ARGS) when the reply shape is missing its event id/status and
+ * INVALID_DATA_JSON when `--data` is present but not valid JSON.
+ */
+export function parseReplyArgs(args) {
+ const replyIdx = args.indexOf('--reply');
+ if (replyIdx === -1) return null;
+ const id = args[replyIdx + 1];
+ const status = args[replyIdx + 2];
+ validateReplyArgs({ id, status });
+ const fileIdx = args.indexOf('--file');
+ const file = fileIdx !== -1 && fileIdx + 1 < args.length ? args[fileIdx + 1] : undefined;
+ const dataIdx = args.indexOf('--data');
+ let data;
+ if (dataIdx !== -1 && dataIdx + 1 < args.length) {
+ try {
+ data = JSON.parse(args[dataIdx + 1]);
+ } catch (err) {
+ const wrapped = new Error('--data must be valid JSON: ' + err.message);
+ wrapped.code = 'INVALID_DATA_JSON';
+ throw wrapped;
+ }
+ }
+ const message = args.find((a, i) =>
+ i > replyIdx + 2
+ && !a.startsWith('--')
+ && i !== fileIdx + 1
+ && i !== dataIdx + 1
+ ) || undefined;
+ return { id, type: status, message, file, data };
+}
+
+function validateReplyArgs({ id, status }) {
+ const usage = `Usage: ${scriptCmd('live-poll.mjs')} --reply [--file path] [--data ''] [message]`;
+ if (!id || id.startsWith('--')) {
+ const err = new Error(`${usage}\nMissing event id after --reply.`);
+ err.code = 'INVALID_REPLY_ARGS';
+ throw err;
+ }
+ if (['done', 'error', 'complete', 'discard', 'discarded'].includes(id)) {
+ const err = new Error(`${usage}\nThe value after --reply must be the event id, not the status ${JSON.stringify(id)}. Use --reply EVENT_ID ${id}.`);
+ err.code = 'INVALID_REPLY_ARGS';
+ throw err;
+ }
+ if (!status || status.startsWith('--')) {
+ const err = new Error(`${usage}\nMissing reply status after event id ${JSON.stringify(id)}.`);
+ err.code = 'INVALID_REPLY_ARGS';
+ throw err;
+ }
+}
+
+export function requiresAgentReply(event) {
+ return EVENT_TYPES_NEEDING_AGENT_REPLY.has(event?.type);
+}
+
+export async function postReply(base, token, reply) {
+ const res = await fetch(`${base}/poll`, {
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json' },
+ body: JSON.stringify(buildPollReplyPayload(token, reply)),
+ });
+ if (!res.ok) {
+ const body = await res.json().catch(() => ({}));
+ const parts = [body.error || res.statusText, body.reason, body.hint].filter(Boolean);
+ throw new Error(parts.join(': '));
+ }
+}
+
+export async function fetchServerStatus(base, token) {
+ const res = await fetch(`${base}/status?token=${token}`);
+ if (res.status === 401) {
+ const err = new Error('Authentication failed. The server token may have changed.');
+ err.code = 'AUTH_FAILED';
+ throw err;
+ }
+ if (!res.ok) {
+ throw new Error(`Status failed: ${res.status} ${res.statusText}`);
+ }
+ return res.json();
+}
+
+export function isEventPending(status, eventId) {
+ return (status.pendingEvents || []).some((entry) => entry.id === eventId);
+}
+
+export async function waitForEventAck(base, token, eventId, {
+ pollIntervalMs = 400,
+ maxWaitMs = 600_000,
+} = {}) {
+ const deadline = Date.now() + maxWaitMs;
+ while (Date.now() < deadline) {
+ const status = await fetchServerStatus(base, token);
+ if (!isEventPending(status, eventId)) return true;
+ await new Promise((resolve) => setTimeout(resolve, pollIntervalMs));
+ }
+ return false;
+}
+
+export async function fetchNextEvent(base, token, { totalDeadline } = {}) {
+ while (true) {
+ if (totalDeadline && Date.now() >= totalDeadline) {
+ return { type: 'timeout' };
+ }
+
+ const remaining = totalDeadline
+ ? totalDeadline - Date.now()
+ : PER_REQUEST_TIMEOUT_MS;
+ const slice = Math.min(Math.max(remaining, 1000), PER_REQUEST_TIMEOUT_MS);
+ const res = await fetch(`${base}/poll?token=${token}&timeout=${slice}&leaseMs=${DEFAULT_EVENT_LEASE_MS}`);
+
+ if (res.status === 401) {
+ const err = new Error('Authentication failed. The server token may have changed.');
+ err.code = 'AUTH_FAILED';
+ throw err;
+ }
+
+ if (!res.ok) {
+ throw new Error(`Poll failed: ${res.status} ${res.statusText}`);
+ }
+
+ const next = await res.json();
+ if (next?.type === 'timeout') {
+ if (totalDeadline && Date.now() < totalDeadline) continue;
+ if (!totalDeadline) continue;
+ return next;
+ }
+ return next;
+ }
+}
+
+export async function augmentEventWithAcceptHandling(event, base, token) {
+ if (event.type !== 'accept' && event.type !== 'discard') return event;
+
+ const __dirname = path.dirname(fileURLToPath(import.meta.url));
+ const acceptScript = path.join(__dirname, 'live-accept.mjs');
+ const scriptArgs = buildAcceptScriptArgs(event);
+
+ try {
+ const out = execFileSync(
+ 'node',
+ [acceptScript, ...scriptArgs],
+ { encoding: 'utf-8', cwd: process.cwd(), timeout: 30_000 },
+ );
+ event._acceptResult = JSON.parse(out.trim());
+ } catch (err) {
+ event._acceptResult = { handled: false, mode: 'error', error: err.message };
+ }
+
+ const completionType = completionTypeForAcceptResult(event.type, event._acceptResult);
+ try {
+ await postReply(base, token, {
+ id: event.id,
+ type: completionType,
+ message: event._acceptResult?.error,
+ file: event._acceptResult?.file,
+ data: event._acceptResult?.carbonize === true ? { carbonize: true } : undefined,
+ });
+ } catch (err) {
+ event._completionAck = { ok: false, error: err.message };
+ }
+ if (!event._completionAck) {
+ event._completionAck = completionAckForAcceptResult(event.id, completionType, event._acceptResult);
+ }
+
+ return event;
+}
+
+export function buildAcceptScriptArgs(event) {
+ const scriptArgs = event.type === 'discard'
+ ? ['--id', String(event.id), '--discard']
+ : ['--id', String(event.id), '--variant', String(event.variantId)];
+ if (event.pageUrl) scriptArgs.push('--page-url', String(event.pageUrl));
+ if (event.type === 'accept' && event.paramValues && Object.keys(event.paramValues).length > 0) {
+ scriptArgs.push('--param-values', JSON.stringify(event.paramValues));
+ }
+ return scriptArgs;
+}
+
+export function writeCarbonizeBanner(event) {
+ if (event.type === 'manual_edit_apply') {
+ process.stderr.write('\n' + manualApplyPollBanner(event) + '\n');
+ }
+ if (event._acceptResult?.carbonize === true) {
+ process.stderr.write('\n⚠ Carbonize cleanup REQUIRED before next poll. After cleanup, run live-complete.mjs --id ' + event.id + '. See reference/live.md "Required after accept".\n\n');
+ }
+}
+
+export function printPollEvent(event) {
+ console.log(JSON.stringify(event));
+}
+
+export async function runPollOnce(base, token, { totalTimeout = 600_000 } = {}) {
+ const deadline = Date.now() + totalTimeout;
+ const event = await fetchNextEvent(base, token, { totalDeadline: deadline });
+ await augmentEventWithAcceptHandling(event, base, token);
+ writeCarbonizeBanner(event);
+ printPollEvent(event);
+ return event;
+}
+
+export async function runPollStream(base, token, {
+ ackTimeoutMs = 600_000,
+ ackPollIntervalMs = 400,
+ shouldContinue = () => true,
+} = {}) {
+ process.stderr.write('[impeccable-poll] stream mode: one JSON object per line on stdout; use --reply while this process stays running\n');
+
+ while (shouldContinue()) {
+ const event = await fetchNextEvent(base, token);
+ await augmentEventWithAcceptHandling(event, base, token);
+ writeCarbonizeBanner(event);
+ printPollEvent(event);
+
+ if (event.type === 'exit') return event;
+
+ if (requiresAgentReply(event)) {
+ const acked = await waitForEventAck(base, token, event.id, {
+ pollIntervalMs: ackPollIntervalMs,
+ maxWaitMs: ackTimeoutMs,
+ });
+ if (!acked) {
+ const err = new Error(`Timed out waiting for --reply on event ${event.id}`);
+ err.code = 'ACK_TIMEOUT';
+ throw err;
+ }
+ }
+ }
+
+ return null;
+}
+
+function handlePollError(err) {
+ if (err.code === 'AUTH_FAILED') {
+ console.error(err.message);
+ console.error(`Try restarting: ${scriptCmd('live-server.mjs')} stop && ${scriptCmd('live.mjs')}`);
+ process.exit(1);
+ }
+ if (err.cause?.code === 'ECONNREFUSED') {
+ console.error(`Live server not running. Start one with: ${scriptCmd('live.mjs')}`);
+ process.exit(1);
+ }
+ if (err.code === 'ACK_TIMEOUT') {
+ console.error(err.message);
+ process.exit(1);
+ }
+ console.error('Poll failed:', err.message);
+ 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, exit
+ poll --stream Keep polling; print one JSON line per event (see live.md)
+ poll --reply done Reply "done" to event (replace or insert generate)
+ poll --reply steer_done Reply after handling a steer event (unlocks Steer bar)
+ poll --reply error "msg" Reply with an error message
+ poll --reply done --data ''
+ Reply with a structured JSON result (manual_edit_apply)
+
+Options:
+ --timeout=MS One-shot poll timeout in ms (default: 600000). Ignored in --stream mode
+ --ack-timeout=MS Stream mode: max wait for --reply after generate/steer (default: 600000)
+ --file PATH Attach a source file path to the reply (generate/steer flow)
+ --data JSON Attach a JSON result object to the reply (manual_edit_apply flow). Must be valid JSON
+ --help Show this help message
+
+Harness note:
+ Default one-shot mode is the portable contract for Claude Code, Codex, and Cursor.
+ --stream is experimental for harnesses with fast incremental stdout; do not use on Cursor.`);
+ process.exit(0);
+ }
+
+ const info = readServerInfo();
+ const base = `http://localhost:${info.port}`;
+
+ // Reply mode: node /live-poll.mjs --reply [--file path] [--data ''] [message]
+ if (args.includes('--reply')) {
+ let reply;
+ try {
+ reply = parseReplyArgs(args);
+ } catch (err) {
+ console.error(err.message);
+ process.exit(1);
+ }
+
+ try {
+ await postReply(base, info.token, reply);
+ } catch (err) {
+ if (err.cause?.code === 'ECONNREFUSED') {
+ console.error(`Live server not running. Start one with: ${scriptCmd('live.mjs')}`);
+ } else {
+ console.error('Reply failed:', err.message);
+ }
+ process.exit(1);
+ }
+ return;
+ }
+
+ const streamMode = args.includes('--stream');
+ const ackTimeoutArg = args.find((a) => a.startsWith('--ack-timeout='));
+ const ackTimeoutMs = ackTimeoutArg ? parseInt(ackTimeoutArg.split('=')[1], 10) : 600_000;
+
+ try {
+ if (streamMode) {
+ await runPollStream(base, info.token, { ackTimeoutMs });
+ return;
+ }
+
+ const timeoutArg = args.find((a) => a.startsWith('--timeout='));
+ const totalTimeout = timeoutArg ? parseInt(timeoutArg.split('=')[1], 10) : 600_000;
+ await runPollOnce(base, info.token, { totalTimeout });
+ } catch (err) {
+ handlePollError(err);
+ }
+}
+
+// Auto-execute when run directly
+const _running = process.argv[1];
+if (_running?.endsWith('live-poll.mjs') || _running?.endsWith('live-poll.mjs/')) {
+ pollCli();
+}
diff --git a/.agent/skills/impeccable/scripts/live-resume.mjs b/.agent/skills/impeccable/scripts/live-resume.mjs
new file mode 100644
index 000000000..74284d48a
--- /dev/null
+++ b/.agent/skills/impeccable/scripts/live-resume.mjs
@@ -0,0 +1,94 @@
+#!/usr/bin/env node
+/**
+ * Recover the next agent action from the durable live-session journal.
+ */
+
+import { createLiveSessionStore } from './live/session-store.mjs';
+
+function manualApplyReplyCommand(eventOrId = 'EVENT_ID') {
+ const id = typeof eventOrId === 'string' ? eventOrId : eventOrId?.id || 'EVENT_ID';
+ return `live-poll.mjs --reply ${id} done --data ''`;
+}
+
+export function manualApplyResumeHint(event = {}) {
+ const summary = event.manualApplySummary || summarizeManualApplyEvent(event);
+ const parts = [];
+ if (summary.pageUrl) parts.push(`page ${summary.pageUrl}`);
+ if (summary.chunk) parts.push(`chunk ${summary.chunk.index}/${summary.chunk.total}`);
+ if (Number.isFinite(summary.opCount)) parts.push(`${summary.opCount} op(s)`);
+ if (Number.isFinite(summary.entryCount)) parts.push(`${summary.entryCount} entr${summary.entryCount === 1 ? 'y' : 'ies'}`);
+ if (summary.files?.length) parts.push(`likely files: ${summary.files.join(', ')}`);
+ const scope = parts.length ? ` (${parts.join(', ')})` : '';
+ return `Manual Apply pending${scope}. If you have not already leased it, run live-poll.mjs. Apply the source edits from the manual_edit_apply batch, then reply with ${manualApplyReplyCommand(event.id)}. Polling only leases this work item; it does not commit source edits. Do not run live-commit-manual-edits.mjs for this leased event. Do not poll again before replying.`;
+}
+
+function summarizeManualApplyEvent(event = {}) {
+ const entries = Array.isArray(event.batch?.entries) ? event.batch.entries : [];
+ const opCount = entries.reduce((sum, entry) => sum + (Array.isArray(entry.ops) ? entry.ops.length : 0), 0);
+ return {
+ pageUrl: event.pageUrl || null,
+ chunk: event.chunk || null,
+ entryCount: entries.length,
+ opCount,
+ files: collectManualApplyFiles(event.batch),
+ };
+}
+
+function collectManualApplyFiles(batch) {
+ const files = [];
+ for (const entry of batch?.entries || []) {
+ for (const op of entry.ops || []) files.push(op.sourceHint?.file);
+ }
+ for (const candidate of batch?.candidates || []) {
+ files.push(candidate.sourceHint?.relativeFile, candidate.sourceHint?.file);
+ for (const item of candidate.textMatches || []) files.push(item.file);
+ for (const item of candidate.objectKeyMatches || []) files.push(item.file);
+ for (const item of candidate.locatorMatches || []) files.push(item.file);
+ for (const item of candidate.contextTextMatches || []) files.push(item.file);
+ }
+ return [...new Set(files.filter((file) => typeof file === 'string' && file.length > 0))].sort();
+}
+
+function parseArgs(argv) {
+ const out = { id: null };
+ for (let i = 0; i < argv.length; i++) {
+ const arg = argv[i];
+ if (arg === '--id') out.id = argv[++i];
+ else if (arg.startsWith('--id=')) out.id = arg.slice('--id='.length);
+ else if (arg === '--help' || arg === '-h') out.help = true;
+ }
+ return out;
+}
+
+export async function resumeCli() {
+ const args = parseArgs(process.argv.slice(2));
+ if (args.help) {
+ console.log(`Usage: node live-resume.mjs [--id SESSION_ID]\n\nPrint the active durable session checkpoint and the next safe agent action.`);
+ return;
+ }
+
+ const store = createLiveSessionStore({ cwd: process.cwd(), sessionId: args.id || undefined });
+ const snapshot = args.id ? store.getSnapshot(args.id) : store.listActiveSessions()[0] || null;
+ if (!snapshot) {
+ console.log(JSON.stringify({ active: false, nextAction: 'No active durable live session found.' }, null, 2));
+ return;
+ }
+
+ const pending = snapshot.pendingEvent || null;
+ const nextAction = pending
+ ? pending.type === 'manual_edit_apply'
+ ? manualApplyResumeHint(pending)
+ : `Run live-poll.mjs, handle ${pending.type} ${pending.id}, then acknowledge with live-poll.mjs --reply ${pending.id} done.`
+ : snapshot.phase === 'carbonize_required'
+ ? `Finish carbonize cleanup${snapshot.sourceFile ? ` in ${snapshot.sourceFile}` : ''}, then run live-complete.mjs --id ${snapshot.id}.`
+ : snapshot.phase === 'accept_requested'
+ ? `Run live-complete.mjs --id ${snapshot.id} after verifying the accepted variant is written.`
+ : `Inspect ${snapshot.id}; no pending agent event is currently queued.`;
+
+ console.log(JSON.stringify({ active: true, snapshot, pendingEvent: pending, nextAction }, null, 2));
+}
+
+const _running = process.argv[1];
+if (_running?.endsWith('live-resume.mjs') || _running?.endsWith('live-resume.mjs/')) {
+ resumeCli();
+}
diff --git a/.agent/skills/impeccable/scripts/live-server.mjs b/.agent/skills/impeccable/scripts/live-server.mjs
new file mode 100644
index 000000000..0fc4d61ba
--- /dev/null
+++ b/.agent/skills/impeccable/scripts/live-server.mjs
@@ -0,0 +1,1134 @@
+#!/usr/bin/env node
+/**
+ * Live variant mode server (self-contained, zero dependencies).
+ *
+ * Serves the browser script (/live.js), the detection overlay (/detect.js),
+ * uses Server-Sent Events (SSE) for server→browser push, and HTTP POST for
+ * browser→server events. Agent communicates via HTTP long-poll (/poll).
+ *
+ * Usage:
+ * node /live-server.mjs # start
+ * node /live-server.mjs stop # stop + remove injected live.js tag
+ * node /live-server.mjs stop --keep-inject # stop only
+ * node /live-server.mjs --help
+ */
+
+import http from 'node:http';
+import { randomUUID } from 'node:crypto';
+import { spawn, execFileSync } from 'node:child_process';
+import fs from 'node:fs';
+import path from 'node:path';
+import net from 'node:net';
+import { fileURLToPath } from 'node:url';
+import { parseDesignMd } from './lib/design-parser.mjs';
+import { resolveContextDir } from './context.mjs';
+import {
+ assembleLiveBrowserScript,
+ assertLiveBrowserScriptParts,
+ readLiveBrowserScriptParts,
+ resolveLiveBrowserScriptParts,
+} from './live/browser-script-parts.mjs';
+import { createLiveSessionStore } from './live/session-store.mjs';
+import { validateEvent } from './live/event-validation.mjs';
+import { createManualEditRoutes } from './live/manual-edit-routes.mjs';
+import { LIVE_COMMANDS } from './live/vocabulary.mjs';
+import {
+ getDesignSidecarPath,
+ getLiveDir,
+ getLiveAnnotationsDir,
+ readLiveServerInfo,
+ removeLiveServerInfo,
+ resolveDesignSidecarPath,
+ writeLiveServerInfo,
+} from './lib/impeccable-paths.mjs';
+import { countByPage as countPendingByPage } from './live/manual-edits-buffer.mjs';
+import {
+ createManualApplyController,
+ summarizeManualApplyFailures,
+} from './live/manual-apply.mjs';
+import {
+ applyDeferredSvelteComponentAccepts,
+ removeAllSvelteComponentSessions,
+} from './live/svelte-component.mjs';
+
+const __dirname = path.dirname(fileURLToPath(import.meta.url));
+// PRODUCT.md / DESIGN.md live wherever context.mjs resolves. The generated
+// DESIGN sidecar is project-local at .impeccable/design.json, with legacy
+// DESIGN.json fallback for existing projects.
+const CONTEXT_DIR = resolveContextDir(process.cwd());
+const DEFAULT_POLL_TIMEOUT = 600_000; // 10 min — agent re-polls on timeout anyway
+const SSE_HEARTBEAT_INTERVAL = 30_000; // keepalive ping every 30s
+
+// ---------------------------------------------------------------------------
+// Port detection
+// ---------------------------------------------------------------------------
+
+async function findOpenPort(start = 8400) {
+ return new Promise((resolve) => {
+ const srv = net.createServer();
+ srv.listen(start, '127.0.0.1', () => {
+ const port = srv.address().port;
+ srv.close(() => resolve(port));
+ });
+ srv.on('error', () => resolve(findOpenPort(start + 1)));
+ });
+}
+
+// ---------------------------------------------------------------------------
+// Session state
+// ---------------------------------------------------------------------------
+
+const state = {
+ token: null,
+ port: null,
+ sseClients: new Set(), // SSE response objects (server→browser push)
+ pendingEvents: [], // browser events waiting for agent ack ({ event, leaseUntil })
+ pendingPolls: [], // agent poll callbacks waiting for browser events
+ nextEventSeq: 1,
+ lastAgentPollingBroadcast: null,
+ exitTimer: null,
+ sessionDir: null, // per-session tmp dir for annotation screenshots
+ sessionStore: null,
+ leaseTimer: null,
+ manualEditActivity: null,
+ nextManualEditSeq: 1,
+ // Deferreds for in-flight chat-routed Apply events. Keyed by event id; each
+ // entry is resolved when the chat agent POSTs an ack carrying the batch
+ // result, or rejected when the hard timeout fires.
+ pendingApplyDeferreds: new Map(),
+ // Updated whenever a /poll long-poll request arrives or is resolved with an
+ // event. Used to detect "a chat agent is likely attached" without requiring
+ // a poll to be parked at the exact moment we dispatch.
+ lastPollAt: 0,
+ timedOutApplyIds: new Map(),
+};
+
+const CHAT_POLL_FRESHNESS_MS = 60_000;
+const POLL_LEASE_EXPIRY_TIMER_GRACE_MS = 2;
+const DEBUG_MANUAL_EDIT_EVENTS = /^(1|true|yes)$/i.test(process.env.IMPECCABLE_LIVE_DEBUG_EVENTS || '');
+
+const manualApply = createManualApplyController({
+ pendingEvents: state.pendingEvents,
+ pendingApplyDeferreds: state.pendingApplyDeferreds,
+ timedOutApplyIds: state.timedOutApplyIds,
+ enqueueEvent,
+ acknowledgePendingEvent,
+ flushPendingPolls,
+ recordManualEditActivity,
+ cwd: () => process.cwd(),
+});
+
+const manualEditRoutes = createManualEditRoutes({
+ getToken: () => state.token,
+ manualApply,
+ recordManualEditActivity,
+ getManualEditStatus,
+ chatAgentLikelyActive,
+ cwd: () => process.cwd(),
+ env: () => process.env,
+});
+
+function chatAgentLikelyActive() {
+ if (state.pendingPolls.length > 0) return true;
+ if (!state.lastPollAt) return false;
+ return Date.now() - state.lastPollAt < CHAT_POLL_FRESHNESS_MS;
+}
+
+// Cap per-annotation upload size. A full 1920×1080 PNG is typically <1 MB;
+// cap at 10 MB to guard against runaway writes from a misbehaving client.
+const MAX_ANNOTATION_BYTES = 10 * 1024 * 1024;
+
+function enqueueEvent(event) {
+ if (!event || (event.id && state.pendingEvents.some((entry) => entry.event?.id === event.id && entry.event?.type === event.type))) return;
+ state.pendingEvents.push({ event, leaseUntil: 0, seq: state.nextEventSeq++ });
+ flushPendingPolls();
+}
+
+function restorePendingEventsFromStore() {
+ if (!state.sessionStore) return;
+ for (const snapshot of state.sessionStore.listActiveSessions()) {
+ if (snapshot.pendingEvent) enqueueEvent(snapshot.pendingEvent);
+ }
+}
+
+function findAvailablePendingEvent(now = Date.now()) {
+ for (const entry of state.pendingEvents) {
+ if (entry.leaseUntil && entry.leaseUntil > now) continue;
+ return entry;
+ }
+ return null;
+}
+
+function leaseEvent(entry, leaseMs) {
+ if (!entry.event?.id) {
+ const idx = state.pendingEvents.indexOf(entry);
+ if (idx !== -1) state.pendingEvents.splice(idx, 1);
+ return entry.event;
+ }
+ entry.leaseUntil = Date.now() + leaseMs;
+ scheduleLeaseFlush();
+ broadcastAgentPollingIfChanged();
+ return entry.event;
+}
+
+function acknowledgePendingEvent(id) {
+ if (!id) return false;
+ const idx = state.pendingEvents.findIndex((entry) => entry.event?.id === id);
+ if (idx === -1) return false;
+ const acknowledged = state.pendingEvents[idx].event;
+ state.pendingEvents.splice(idx, 1);
+ scheduleLeaseFlush();
+ broadcastAgentPollingIfChanged();
+ return acknowledged;
+}
+
+function findPendingEventById(id) {
+ if (!id) return null;
+ const entry = state.pendingEvents.find((item) => item.event?.id === id);
+ return entry?.event || null;
+}
+
+function summarizePendingEventForStatus(entry) {
+ const event = entry.event || {};
+ const summary = {
+ id: event.id,
+ type: event.type,
+ leased: !!(entry.leaseUntil && entry.leaseUntil > Date.now()),
+ leaseUntil: entry.leaseUntil || null,
+ };
+ if (event.type === 'manual_edit_apply') {
+ summary.pageUrl = event.pageUrl || null;
+ summary.chunk = event.chunk || null;
+ summary.repair = event.repair || null;
+ summary.evidencePath = event.evidencePath || null;
+ summary.agentAction = event.agentAction || manualApply.buildAgentAction(event);
+ summary.manualApplySummary = manualApply.summarizeEvent(event, manualApply.getDeferred(event.id)?.batch || event.batch);
+ }
+ return summary;
+}
+
+function summarizeActiveSessionForClient(snapshot = {}) {
+ return {
+ id: snapshot.id,
+ phase: snapshot.phase,
+ pageUrl: snapshot.pageUrl ?? null,
+ sourceFile: snapshot.sourceFile ?? null,
+ previewFile: snapshot.previewFile ?? null,
+ previewMode: snapshot.previewMode ?? null,
+ expectedVariants: snapshot.expectedVariants ?? 0,
+ arrivedVariants: snapshot.arrivedVariants ?? 0,
+ visibleVariant: snapshot.visibleVariant ?? null,
+ checkpointRevision: snapshot.checkpointRevision ?? 0,
+ paramValues: snapshot.paramValues || {},
+ };
+}
+
+function activeSessionSummaries() {
+ if (!state.sessionStore) return [];
+ return state.sessionStore.listActiveSessions().map((snapshot) => summarizeActiveSessionForClient(snapshot));
+}
+
+function cancelQueuedAnonymousExitEvents() {
+ let removed = 0;
+ for (let i = state.pendingEvents.length - 1; i >= 0; i -= 1) {
+ const event = state.pendingEvents[i]?.event;
+ if (event?.type !== 'exit' || event.id) continue;
+ state.pendingEvents.splice(i, 1);
+ removed += 1;
+ }
+ if (removed > 0) {
+ scheduleLeaseFlush();
+ broadcastAgentPollingIfChanged();
+ }
+ return removed;
+}
+
+function scheduleLeaseFlush() {
+ if (state.leaseTimer) {
+ clearTimeout(state.leaseTimer);
+ state.leaseTimer = null;
+ }
+ const now = Date.now();
+ const nextLeaseUntil = state.pendingEvents
+ .map((entry) => entry.leaseUntil || 0)
+ .filter((leaseUntil) => leaseUntil > now)
+ .sort((a, b) => a - b)[0];
+ if (!nextLeaseUntil) return;
+ state.leaseTimer = setTimeout(() => {
+ state.leaseTimer = null;
+ flushPendingPolls();
+ broadcastAgentPollingIfChanged();
+ }, Math.max(0, nextLeaseUntil - now + POLL_LEASE_EXPIRY_TIMER_GRACE_MS));
+}
+
+function flushPendingPolls() {
+ let changed = false;
+ while (state.pendingPolls.length > 0) {
+ const entry = findAvailablePendingEvent();
+ if (!entry) {
+ scheduleLeaseFlush();
+ broadcastAgentPollingIfChanged();
+ return;
+ }
+ const poll = state.pendingPolls.shift();
+ poll.resolve(leaseEvent(entry, poll.leaseMs));
+ changed = true;
+ }
+ scheduleLeaseFlush();
+ if (changed) broadcastAgentPollingIfChanged();
+}
+
+function agentPollingConnected() {
+ const now = Date.now();
+ return state.pendingPolls.length > 0
+ || state.pendingEvents.some((entry) => entry.leaseUntil && entry.leaseUntil > now);
+}
+
+function broadcastAgentPollingIfChanged() {
+ const connected = agentPollingConnected();
+ if (state.lastAgentPollingBroadcast === connected) return;
+ state.lastAgentPollingBroadcast = connected;
+ broadcast({ type: 'agent_polling', connected });
+}
+
+/** Push a message to all connected SSE clients. */
+function broadcast(msg) {
+ const data = 'data: ' + JSON.stringify(msg) + '\n\n';
+ for (const res of state.sseClients) {
+ try { res.write(data); } catch { /* client gone */ }
+ }
+}
+
+function recordManualEditActivity(type, details = {}) {
+ const entry = {
+ seq: state.nextManualEditSeq++,
+ type,
+ ts: new Date().toISOString(),
+ ...details,
+ };
+ state.manualEditActivity = entry;
+ if (DEBUG_MANUAL_EDIT_EVENTS) {
+ try {
+ const filePath = path.join(getLiveDir(process.cwd()), 'manual-edit-events.jsonl');
+ fs.mkdirSync(path.dirname(filePath), { recursive: true });
+ fs.appendFileSync(filePath, JSON.stringify(entry) + '\n');
+ } catch {
+ /* diagnostics are best-effort; never block live mode on observability */
+ }
+ }
+ broadcast(entry);
+ return entry;
+}
+
+function getManualEditStatus() {
+ try {
+ const { totalCount, perPage } = countPendingByPage(process.cwd());
+ return { totalCount, perPage, lastActivity: state.manualEditActivity };
+ } catch (err) {
+ return {
+ totalCount: null,
+ perPage: {},
+ lastActivity: state.manualEditActivity,
+ error: err.message,
+ };
+ }
+}
+
+// ---------------------------------------------------------------------------
+// Load scripts
+// ---------------------------------------------------------------------------
+
+function loadBrowserScripts() {
+ // Detection script: prefer the skill-bundled detector, then fall back to
+ // source/npm package locations for local development and older installs.
+ // This one IS cached — detect.js rarely changes during a session.
+ const detectPaths = [
+ path.join(__dirname, 'detector', 'detect-antipatterns-browser.js'),
+ path.join(__dirname, '..', '..', 'cli', 'engine', 'detect-antipatterns-browser.js'),
+ path.join(__dirname, '..', '..', '..', '..', 'cli', 'engine', 'detect-antipatterns-browser.js'),
+ path.join(process.cwd(), 'node_modules', 'impeccable', 'cli', 'engine', 'detect-antipatterns-browser.js'),
+ ];
+ let detectScript = '';
+ for (const p of detectPaths) {
+ try { detectScript = fs.readFileSync(p, 'utf-8'); break; } catch { /* try next */ }
+ }
+
+ // Browser script parts: DO NOT cache. Return paths so the /live.js handler
+ // can re-read every part on each request. Editing browser code during
+ // iteration should land on the next tab reload, not require a server restart.
+ const liveScriptParts = resolveLiveBrowserScriptParts(__dirname);
+ try {
+ assertLiveBrowserScriptParts(liveScriptParts);
+ } catch (err) {
+ process.stderr.write('Error: ' + err.message + '\n');
+ process.exit(1);
+ }
+
+ return { detectScript, liveScriptParts };
+}
+
+function hasProjectContext() {
+ // PRODUCT.md carries brand voice / anti-references — that's what determines
+ // whether variants are brand-aware. DESIGN.md (visual tokens) is a separate
+ // concern, surfaced by the design panel's own empty state.
+ try {
+ fs.accessSync(path.join(CONTEXT_DIR, 'PRODUCT.md'), fs.constants.R_OK);
+ return true;
+ } catch { return false; }
+}
+
+function statOrNull(filePath) {
+ try { return fs.statSync(filePath); } catch { return null; }
+}
+
+// HTTP request handler
+// ---------------------------------------------------------------------------
+
+function createRequestHandler({ detectScript, liveScriptParts }) {
+ return (req, res) => {
+ const url = new URL(req.url, `http://localhost:${state.port}`);
+ res.setHeader('Access-Control-Allow-Origin', '*');
+ res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS');
+ res.setHeader('Access-Control-Allow-Headers', 'Content-Type');
+ if (req.method === 'OPTIONS') { res.writeHead(204); res.end(); return; }
+
+ const p = url.pathname;
+
+ // --- Scripts ---
+ if (p === '/live.js') {
+ // Re-read from disk each request so edits to live-browser.js land on
+ // the next tab reload. No-store headers prevent browser caching across
+ // sessions — during iteration, a cached old script silently breaks
+ // every subsequent session.
+ let parts;
+ try {
+ parts = readLiveBrowserScriptParts(liveScriptParts);
+ } catch (err) {
+ res.writeHead(500, { 'Content-Type': 'text/plain' });
+ res.end('Error reading live browser scripts: ' + err.message);
+ return;
+ }
+ const body = assembleLiveBrowserScript({
+ token: state.token,
+ port: state.port,
+ vocabulary: LIVE_COMMANDS,
+ parts,
+ });
+ res.writeHead(200, {
+ 'Content-Type': 'application/javascript',
+ 'Cache-Control': 'no-store, no-cache, must-revalidate, max-age=0',
+ 'Pragma': 'no-cache',
+ });
+ res.end(body);
+ return;
+ }
+ if (p === '/detect.js' || p === '/') {
+ if (!detectScript) { res.writeHead(404); res.end('Not available'); return; }
+ res.writeHead(200, { 'Content-Type': 'application/javascript' });
+ res.end(detectScript);
+ return;
+ }
+
+ // --- Vendored modern-screenshot (UMD build) ---
+ // Lazy-loaded by live.js when the user clicks Go; exposes
+ // window.modernScreenshot.domToBlob(...) for capture.
+ if (p === '/modern-screenshot.js') {
+ const vendorPath = path.join(__dirname, 'modern-screenshot.umd.js');
+ try {
+ res.writeHead(200, {
+ 'Content-Type': 'application/javascript',
+ 'Cache-Control': 'public, max-age=31536000, immutable',
+ });
+ res.end(fs.readFileSync(vendorPath));
+ } catch {
+ res.writeHead(404); res.end('Vendor script not found');
+ }
+ return;
+ }
+
+ // --- Annotation upload (browser → server, raw PNG body) ---
+ // Client generates the eventId, POSTs the PNG, then POSTs the generate
+ // event with screenshotPath already set. Keeps bytes out of the SSE/poll
+ // bridge and preserves the "one shot from the user's POV" UX.
+ if (p === '/annotation' && req.method === 'POST') {
+ const token = url.searchParams.get('token');
+ if (token !== state.token) { res.writeHead(401); res.end('Unauthorized'); return; }
+ const eventId = url.searchParams.get('eventId');
+ if (!eventId || !/^[A-Za-z0-9_-]{1,64}$/.test(eventId)) {
+ res.writeHead(400, { 'Content-Type': 'application/json' });
+ res.end(JSON.stringify({ error: 'Invalid eventId' }));
+ return;
+ }
+ if ((req.headers['content-type'] || '').toLowerCase() !== 'image/png') {
+ res.writeHead(415, { 'Content-Type': 'application/json' });
+ res.end(JSON.stringify({ error: 'Content-Type must be image/png' }));
+ return;
+ }
+ if (!state.sessionDir) {
+ res.writeHead(500, { 'Content-Type': 'application/json' });
+ res.end(JSON.stringify({ error: 'Session dir unavailable' }));
+ return;
+ }
+ const chunks = [];
+ let total = 0;
+ let aborted = false;
+ req.on('data', (c) => {
+ if (aborted) return;
+ total += c.length;
+ if (total > MAX_ANNOTATION_BYTES) {
+ aborted = true;
+ res.writeHead(413, { 'Content-Type': 'application/json' });
+ res.end(JSON.stringify({ error: 'Payload too large' }));
+ req.destroy();
+ return;
+ }
+ chunks.push(c);
+ });
+ req.on('end', () => {
+ if (aborted) return;
+ const absPath = path.join(state.sessionDir, eventId + '.png');
+ try {
+ fs.writeFileSync(absPath, Buffer.concat(chunks));
+ } catch (err) {
+ res.writeHead(500, { 'Content-Type': 'application/json' });
+ res.end(JSON.stringify({ error: 'Write failed: ' + err.message }));
+ return;
+ }
+ res.writeHead(200, { 'Content-Type': 'application/json' });
+ res.end(JSON.stringify({ ok: true, path: absPath }));
+ });
+ req.on('error', () => {
+ if (!aborted) {
+ res.writeHead(500, { 'Content-Type': 'application/json' });
+ res.end(JSON.stringify({ error: 'Upload failed' }));
+ }
+ });
+ return;
+ }
+
+ // --- Health ---
+ if (p === '/status') {
+ const token = url.searchParams.get('token');
+ if (token !== state.token) { res.writeHead(401, { 'Content-Type': 'application/json' }); res.end(JSON.stringify({ error: 'Unauthorized' })); return; }
+ const sessions = activeSessionSummaries();
+ res.writeHead(200, { 'Content-Type': 'application/json' });
+ res.end(JSON.stringify({
+ status: 'ok',
+ port: state.port,
+ connectedClients: state.sseClients.size,
+ pendingEvents: state.pendingEvents.map((entry) => summarizePendingEventForStatus(entry)),
+ agentPolling: agentPollingConnected(),
+ activeSessions: sessions,
+ manualEdits: getManualEditStatus(),
+ }));
+ return;
+ }
+
+ if (p === '/health') {
+ res.writeHead(200, { 'Content-Type': 'application/json' });
+ res.end(JSON.stringify({
+ status: 'ok', port: state.port, mode: 'variant',
+ hasProjectContext: hasProjectContext(),
+ connectedClients: state.sseClients.size,
+ }));
+ return;
+ }
+
+ // --- Design system (unified v2 response) + raw ---
+ // /design-system.json returns both parsed DESIGN.md and .impeccable/design.json
+ // sidecar when present. Panel merges them:
+ // { present, parsed, sidecar, hasMd, hasSidecar,
+ // mdNewerThanJson, parseError?, sidecarError? }
+ // - parsed: output of parseDesignMd (frontmatter
+ // + six canonical sections) when DESIGN.md exists.
+ // - sidecar: .impeccable/design.json contents when present.
+ // Expected shape: schemaVersion 2, carrying
+ // extensions + components + narrative.
+ // /design-system/raw returns DESIGN.md markdown verbatim
+ if (p === '/design-system.json' || p === '/design-system/raw') {
+ const token = url.searchParams.get('token');
+ if (token !== state.token) { res.writeHead(401); res.end('Unauthorized'); return; }
+
+ const mdPath = path.join(CONTEXT_DIR, 'DESIGN.md');
+ const jsonPath = resolveDesignSidecarPath(process.cwd(), CONTEXT_DIR) || getDesignSidecarPath(process.cwd());
+ const mdStat = statOrNull(mdPath);
+ const jsonStat = statOrNull(jsonPath);
+
+ if (p === '/design-system/raw') {
+ if (!mdStat) { res.writeHead(404); res.end('Not found'); return; }
+ res.writeHead(200, { 'Content-Type': 'text/markdown; charset=utf-8' });
+ res.end(fs.readFileSync(mdPath, 'utf-8'));
+ return;
+ }
+
+ if (!mdStat && !jsonStat) {
+ res.writeHead(404, { 'Content-Type': 'application/json' });
+ res.end(JSON.stringify({ present: false }));
+ return;
+ }
+
+ const response = {
+ present: true,
+ hasMd: !!mdStat,
+ hasSidecar: !!jsonStat,
+ mdNewerThanJson: !!(mdStat && jsonStat && mdStat.mtimeMs > jsonStat.mtimeMs + 1000),
+ };
+
+ if (mdStat) {
+ try {
+ response.parsed = parseDesignMd(fs.readFileSync(mdPath, 'utf-8'));
+ } catch (err) {
+ response.parseError = err.message;
+ }
+ }
+
+ if (jsonStat) {
+ try {
+ response.sidecar = JSON.parse(fs.readFileSync(jsonPath, 'utf-8'));
+ } catch (err) {
+ response.sidecarError = 'Failed to parse .impeccable/design.json: ' + err.message;
+ }
+ }
+
+ res.writeHead(200, { 'Content-Type': 'application/json' });
+ res.end(JSON.stringify(response));
+ return;
+ }
+
+ // --- Source file (no-HMR fallback) ---
+ if (p === '/source') {
+ const token = url.searchParams.get('token');
+ if (token !== state.token) { res.writeHead(401); res.end('Unauthorized'); return; }
+ const filePath = url.searchParams.get('path');
+ if (!filePath || filePath.includes('..')) { res.writeHead(400); res.end('Bad path'); return; }
+ const absPath = path.resolve(process.cwd(), filePath);
+ if (!absPath.startsWith(process.cwd())) { res.writeHead(403); res.end('Forbidden'); return; }
+ let content;
+ try { content = fs.readFileSync(absPath, 'utf-8'); }
+ catch { res.writeHead(404); res.end('File not found'); return; }
+ res.writeHead(200, { 'Content-Type': 'text/html; charset=utf-8' });
+ res.end(content);
+ return;
+ }
+
+ // --- SSE: server→browser push (replaces WebSocket) ---
+ if (p === '/events' && req.method === 'GET') {
+ const token = url.searchParams.get('token');
+ if (token !== state.token) { res.writeHead(401); res.end('Unauthorized'); return; }
+ clearTimeout(state.exitTimer);
+ state.exitTimer = null;
+ cancelQueuedAnonymousExitEvents();
+ res.writeHead(200, {
+ 'Content-Type': 'text/event-stream',
+ 'Cache-Control': 'no-cache',
+ 'Connection': 'keep-alive',
+ });
+ res.write('data: ' + JSON.stringify({
+ type: 'connected',
+ hasProjectContext: hasProjectContext(),
+ agentPolling: agentPollingConnected(),
+ activeSessions: activeSessionSummaries(),
+ }) + '\n\n');
+
+ state.sseClients.add(res);
+
+ // Keepalive: SSE comment every 30s prevents silent connection drops.
+ const heartbeat = setInterval(() => {
+ try { res.write(': keepalive\n\n'); } catch { clearInterval(heartbeat); }
+ }, SSE_HEARTBEAT_INTERVAL);
+
+ req.on('close', () => {
+ clearInterval(heartbeat);
+ state.sseClients.delete(res);
+ if (state.sseClients.size === 0) {
+ clearTimeout(state.exitTimer);
+ state.exitTimer = setTimeout(() => {
+ if (state.sseClients.size === 0) enqueueEvent({ type: 'exit' });
+ }, 8000);
+ }
+ });
+ return;
+ }
+
+ if (manualEditRoutes(req, res, url)) return;
+
+ // --- Browser→server events (replaces WebSocket messages) ---
+ if (p === '/events' && req.method === 'POST') {
+ let body = '';
+ req.on('data', (c) => { body += c; });
+ req.on('end', () => {
+ let msg;
+ try { msg = JSON.parse(body); } catch {
+ res.writeHead(400, { 'Content-Type': 'application/json' });
+ res.end(JSON.stringify({ error: 'Invalid JSON' }));
+ return;
+ }
+ if (msg.token !== state.token) {
+ res.writeHead(401, { 'Content-Type': 'application/json' });
+ res.end(JSON.stringify({ error: 'Unauthorized' }));
+ return;
+ }
+ // Defense in depth: manual copy edits must use the staged stash/apply
+ // endpoints. The direct Save event path is disabled in the browser.
+ if (msg.type === 'manual_edits') {
+ res.writeHead(400, { 'Content-Type': 'application/json' });
+ res.end(JSON.stringify({ error: 'manual_edits must POST to /manual-edit-stash, not /events' }));
+ return;
+ }
+ if (msg.type === 'manual_edit_apply') {
+ res.writeHead(400, { 'Content-Type': 'application/json' });
+ res.end(JSON.stringify({ error: 'manual_edit_apply is disabled; use /manual-edit-stash then /manual-edit-commit' }));
+ return;
+ }
+ const error = validateEvent(msg);
+ if (error) {
+ res.writeHead(400, { 'Content-Type': 'application/json' });
+ res.end(JSON.stringify({ error }));
+ return;
+ }
+ if (state.sessionStore && msg.id) {
+ try {
+ state.sessionStore.appendEvent(msg);
+ } catch (err) {
+ res.writeHead(500, { 'Content-Type': 'application/json' });
+ res.end(JSON.stringify({ error: 'session_store_append_failed', message: err.message }));
+ return;
+ }
+ }
+ if (msg.type === 'exit') {
+ cleanupSvelteComponentSessionsBeforeExit();
+ }
+ if (msg.type !== 'checkpoint') {
+ enqueueEvent(msg);
+ }
+ res.writeHead(200, { 'Content-Type': 'application/json' });
+ res.end(JSON.stringify({ ok: true }));
+ });
+ return;
+ }
+
+ // --- Stop ---
+ if (p === '/stop') {
+ const token = url.searchParams.get('token');
+ if (token !== state.token) { res.writeHead(401); res.end('Unauthorized'); return; }
+ res.writeHead(200, { 'Content-Type': 'text/plain' });
+ res.end('stopping');
+ shutdown();
+ return;
+ }
+
+ // --- Agent poll ---
+ if (p === '/poll' && req.method === 'GET') {
+ handlePollGet(req, res, url);
+ return;
+ }
+ if (p === '/poll' && req.method === 'POST') {
+ handlePollPost(req, res);
+ return;
+ }
+
+ res.writeHead(404); res.end('Not found');
+ };
+}
+
+// ---------------------------------------------------------------------------
+// Agent poll endpoints (unchanged from WS version)
+// ---------------------------------------------------------------------------
+
+function handlePollGet(req, res, url) {
+ const token = url.searchParams.get('token');
+ if (token !== state.token) {
+ res.writeHead(401, { 'Content-Type': 'application/json' });
+ res.end(JSON.stringify({ error: 'Unauthorized' }));
+ return;
+ }
+ state.lastPollAt = Date.now();
+ const timeout = parseInt(url.searchParams.get('timeout') || DEFAULT_POLL_TIMEOUT, 10);
+ const leaseMs = parseInt(url.searchParams.get('leaseMs') || '30000', 10);
+ const available = findAvailablePendingEvent();
+ if (available) {
+ res.writeHead(200, { 'Content-Type': 'application/json' });
+ res.end(JSON.stringify(leaseEvent(available, leaseMs)));
+ return;
+ }
+ const poll = { resolve, leaseMs };
+ const timer = setTimeout(() => {
+ const idx = state.pendingPolls.indexOf(poll);
+ if (idx !== -1) state.pendingPolls.splice(idx, 1);
+ broadcastAgentPollingIfChanged();
+ res.writeHead(200, { 'Content-Type': 'application/json' });
+ res.end(JSON.stringify({ type: 'timeout' }));
+ }, timeout);
+ function resolve(event) {
+ clearTimeout(timer);
+ state.lastPollAt = Date.now();
+ res.writeHead(200, { 'Content-Type': 'application/json' });
+ res.end(JSON.stringify(event));
+ }
+ state.pendingPolls.push(poll);
+ broadcastAgentPollingIfChanged();
+ scheduleLeaseFlush();
+ req.on('close', () => {
+ clearTimeout(timer);
+ const idx = state.pendingPolls.indexOf(poll);
+ if (idx !== -1) state.pendingPolls.splice(idx, 1);
+ broadcastAgentPollingIfChanged();
+ });
+}
+
+function sessionFileMetadataFromPollReply(file) {
+ if (!file || typeof file !== 'string') return { file };
+ const normalized = file.split(path.sep).join('/');
+ const base = { file: normalized };
+ if (!normalized.endsWith('/manifest.json') && normalized !== 'manifest.json') return base;
+ if (!normalized.includes('node_modules/.impeccable-live/') && !normalized.includes('src/lib/impeccable/')) return base;
+
+ let full;
+ try {
+ full = path.resolve(process.cwd(), normalized);
+ const rel = path.relative(process.cwd(), full);
+ if (!rel || rel.startsWith('..') || path.isAbsolute(rel)) return base;
+ } catch {
+ return base;
+ }
+
+ try {
+ const manifest = JSON.parse(fs.readFileSync(full, 'utf-8'));
+ if (manifest?.previewMode !== 'svelte-component' || !manifest.sourceFile) return base;
+ return {
+ file: String(manifest.sourceFile).split(path.sep).join('/'),
+ sourceFile: String(manifest.sourceFile).split(path.sep).join('/'),
+ previewFile: normalized,
+ previewMode: 'svelte-component',
+ };
+ } catch {
+ return base;
+ }
+}
+
+function handlePollPost(req, res) {
+ let body = '';
+ req.on('data', (c) => { body += c; });
+ req.on('end', () => {
+ let msg;
+ try { msg = JSON.parse(body); } catch {
+ res.writeHead(400, { 'Content-Type': 'application/json' });
+ res.end(JSON.stringify({ error: 'Invalid JSON' }));
+ return;
+ }
+ if (msg.token !== state.token) {
+ res.writeHead(401, { 'Content-Type': 'application/json' });
+ res.end(JSON.stringify({ error: 'Unauthorized' }));
+ return;
+ }
+ const pendingApplyDeferred = manualApply.getDeferred(msg.id);
+ if (pendingApplyDeferred) {
+ const validation = manualApply.validateResultMessage(msg, pendingApplyDeferred);
+ if (!validation.ok) {
+ recordManualEditActivity('manual_edit_apply_reply_invalid', {
+ id: msg.id,
+ pageUrl: pendingApplyDeferred.pageUrl,
+ chunk: pendingApplyDeferred.event?.chunk || null,
+ repair: pendingApplyDeferred.event?.repair || null,
+ reason: validation.body?.reason || validation.body?.error || 'invalid_manual_apply_result',
+ status: msg.data?.status || null,
+ });
+ res.writeHead(400, { 'Content-Type': 'application/json' });
+ res.end(JSON.stringify(validation.body));
+ return;
+ }
+ recordManualEditActivity('manual_edit_apply_reply_received', {
+ id: msg.id,
+ pageUrl: pendingApplyDeferred.pageUrl,
+ chunk: pendingApplyDeferred.event?.chunk || null,
+ repair: pendingApplyDeferred.event?.repair || null,
+ status: validation.result.status,
+ appliedCount: validation.result.appliedEntryIds.length,
+ failed: summarizeManualApplyFailures(validation.result.failed),
+ fileCount: validation.result.files.length,
+ noteCount: validation.result.notes.length,
+ });
+ manualApply.resolveDeferred(msg.id, validation.result);
+ acknowledgePendingEvent(msg.id);
+ flushPendingPolls();
+ res.writeHead(200, { 'Content-Type': 'application/json' });
+ res.end(JSON.stringify({ ok: true }));
+ return;
+ }
+ if (manualApply.hasTimedOutId(msg.id)) {
+ const rollback = manualApply.rollbackTimedOutReply(msg);
+ recordManualEditActivity('manual_edit_apply_stale_reply_rejected', {
+ id: msg.id,
+ rolledBackFileCount: rollback.rolledBackFiles?.length || 0,
+ rollbackFailureCount: rollback.rollbackFailures?.length || 0,
+ });
+ res.writeHead(409, { 'Content-Type': 'application/json' });
+ res.end(JSON.stringify({ error: 'stale_manual_edit_apply_reply', ...rollback }));
+ return;
+ }
+ const pendingEventBeforeAck = findPendingEventById(msg.id);
+ if (pendingEventBeforeAck?.type === 'steer' && msg.type === 'steer_done'
+ && !msg.file && !(typeof msg.message === 'string' && msg.message.trim())) {
+ res.writeHead(400, { 'Content-Type': 'application/json' });
+ res.end(JSON.stringify({
+ error: 'steer_done_requires_file_or_message',
+ hint: 'Reply with --file after writing source, or include a message explaining an intentional no-op.',
+ }));
+ return;
+ }
+ const acknowledgedEvent = acknowledgePendingEvent(msg.id);
+ let skipJournalReply = false;
+ let existingSession = null;
+ if (!acknowledgedEvent && state.sessionStore && msg.id) {
+ try {
+ existingSession = state.sessionStore.getSnapshot(msg.id, { includeCompleted: true });
+ if (!existingSession?.updatedAt) existingSession = null;
+ skipJournalReply = existingSession?.phase === 'completed' || existingSession?.phase === 'discarded';
+ } catch { /* fall through and record the reply normally */ }
+ }
+ if (!acknowledgedEvent && !existingSession) {
+ recordManualEditActivity('manual_edit_poll_reply_unknown', {
+ id: msg.id || null,
+ type: msg.type || null,
+ });
+ res.writeHead(msg.id ? 404 : 400, { 'Content-Type': 'application/json' });
+ res.end(JSON.stringify({
+ error: msg.id ? 'unknown_poll_reply_id' : 'missing_poll_reply_id',
+ id: msg.id,
+ }));
+ return;
+ }
+ const replyFileMeta = sessionFileMetadataFromPollReply(msg.file);
+ if (state.sessionStore && msg.id && !skipJournalReply) {
+ try {
+ const eventType = msg.type === 'steer_done'
+ ? 'steer_done'
+ : msg.type === 'discard' || msg.type === 'discarded'
+ ? 'discarded'
+ : msg.type === 'complete'
+ ? 'complete'
+ : msg.type === 'error'
+ ? 'agent_error'
+ : 'agent_done';
+ state.sessionStore.appendEvent({
+ type: eventType,
+ id: msg.id,
+ file: replyFileMeta.file,
+ sourceFile: replyFileMeta.sourceFile,
+ previewFile: replyFileMeta.previewFile,
+ previewMode: replyFileMeta.previewMode,
+ message: msg.message,
+ sourceEventType: acknowledgedEvent?.type,
+ carbonize: msg.data?.carbonize === true,
+ });
+ } catch { /* keep reply path best-effort; browser still needs SSE */ }
+ }
+ flushPendingPolls();
+ // Forward the reply to the browser via SSE
+ broadcast({
+ type: msg.type || 'done',
+ id: msg.id,
+ message: msg.message,
+ file: msg.file,
+ sourceFile: replyFileMeta.sourceFile,
+ previewFile: replyFileMeta.previewFile,
+ previewMode: replyFileMeta.previewMode,
+ data: msg.data,
+ });
+ res.writeHead(200, { 'Content-Type': 'application/json' });
+ res.end(JSON.stringify({ ok: true }));
+ });
+}
+
+// ---------------------------------------------------------------------------
+// Lifecycle
+// ---------------------------------------------------------------------------
+
+let httpServer = null;
+
+function shutdown() {
+ cleanupSvelteComponentSessionsBeforeExit();
+ removeLiveServerInfo(process.cwd());
+ if (state.leaseTimer) clearTimeout(state.leaseTimer);
+ state.leaseTimer = null;
+ if (state.sessionDir) {
+ try { fs.rmSync(state.sessionDir, { recursive: true, force: true }); } catch {}
+ }
+ for (const res of state.sseClients) { try { res.end(); } catch {} }
+ state.sseClients.clear();
+ for (const poll of state.pendingPolls) poll.resolve({ type: 'exit' });
+ state.pendingPolls.length = 0;
+ if (httpServer) httpServer.close();
+ process.exit(0);
+}
+
+function cleanupSvelteComponentSessionsBeforeExit() {
+ try {
+ removeAllSvelteComponentSessions(process.cwd());
+ } catch (err) {
+ console.warn('[impeccable] Svelte component session cleanup failed:', err.message);
+ }
+}
+
+function applyLegacyDeferredAcceptsOnStartup() {
+ try {
+ const result = applyDeferredSvelteComponentAccepts(process.cwd());
+ if (result.applied > 0 || result.failed > 0) {
+ console.log('[impeccable] applied legacy deferred Svelte component accepts:', JSON.stringify(result));
+ }
+ } catch (err) {
+ console.warn('[impeccable] legacy deferred Svelte component accept apply failed:', err.message);
+ }
+}
+
+// ---------------------------------------------------------------------------
+// Main
+// ---------------------------------------------------------------------------
+
+const args = process.argv.slice(2);
+
+if (args.includes('--help') || args.includes('-h')) {
+ console.log(`Usage: node live-server.mjs [options]
+
+Start the live variant mode server (zero dependencies).
+
+Commands:
+ (default) Start the server (foreground)
+ stop Stop the server and remove the injected live.js script tag
+ stop --keep-inject Stop the server only (leave the script tag in the HTML entry)
+
+Options:
+ --background Start detached, print connection JSON to stdout, then exit
+ --port=PORT Use a specific port (default: auto-detect starting at 8400)
+ --keep-inject Only with stop: skip live-inject.mjs --remove
+ --help Show this help
+
+Endpoints:
+ /live.js Browser script (element picker + variant cycling)
+ /detect.js Detection overlay (backwards compatible)
+ /modern-screenshot.js Vendored modern-screenshot UMD build (lazy-loaded by live.js)
+ /annotation POST raw image/png to stage a variant screenshot
+ /events SSE stream (server→browser) + POST (browser→server)
+ /poll Long-poll for agent CLI
+ /manual-edit-stash Stage browser copy edits
+ /manual-edit-commit Apply staged browser copy edits
+ /manual-edit-discard Discard staged browser copy edits
+ /source Raw source file reader (no-HMR fallback)
+ /status Durable recovery status (token-protected)
+ /health Health check`);
+ process.exit(0);
+}
+
+if (args.includes('stop')) {
+ const keepInject = args.includes('--keep-inject');
+ try {
+ const { info } = readLiveServerInfo(process.cwd()) || {};
+ const res = await fetch(`http://localhost:${info.port}/stop?token=${info.token}`);
+ if (res.ok) console.log(`Stopped live server on port ${info.port}.`);
+ } catch {
+ console.log('No running live server found.');
+ }
+ if (!keepInject) {
+ const injectPath = path.join(__dirname, 'live-inject.mjs');
+ try {
+ const out = execFileSync(process.execPath, [injectPath, '--remove'], {
+ encoding: 'utf-8',
+ cwd: process.cwd(),
+ });
+ const line = out.trim().split('\n').filter(Boolean).pop();
+ if (line) {
+ try {
+ const j = JSON.parse(line);
+ if (j.removed === true) {
+ console.log(`Removed live script tag from ${j.file}.`);
+ }
+ } catch {
+ /* ignore non-JSON lines */
+ }
+ }
+ } catch (err) {
+ const detail = err.stderr?.toString?.().trim?.()
+ || err.stdout?.toString?.().trim?.()
+ || err.message
+ || String(err);
+ console.warn(`Note: could not remove live script tag (${detail.split('\n')[0]})`);
+ }
+ }
+ process.exit(0);
+}
+
+// --background: spawn a detached child server, wait for it to be ready,
+// print the connection JSON, then exit. This keeps the startup command
+// simple (no shell backgrounding or chained commands).
+if (args.includes('--background')) {
+ const childArgs = args.filter(a => a !== '--background');
+ const child = spawn(process.execPath, [fileURLToPath(import.meta.url), ...childArgs], {
+ detached: true,
+ stdio: 'ignore',
+ cwd: process.cwd(),
+ });
+ child.unref();
+
+ // Poll for the PID file (the child writes it once the HTTP server is listening).
+ const deadline = Date.now() + 10_000;
+ while (Date.now() < deadline) {
+ try {
+ const { info } = readLiveServerInfo(process.cwd()) || {};
+ if (info.pid !== process.pid) {
+ // Output JSON so the agent can read port + token from stdout.
+ console.log(JSON.stringify(info));
+ process.exit(0);
+ }
+ } catch { /* not ready yet */ }
+ await new Promise(r => setTimeout(r, 200));
+ }
+ console.error('Timed out waiting for live server to start.');
+ process.exit(1);
+}
+
+// Check for existing session
+const existingRecord = readLiveServerInfo(process.cwd());
+if (existingRecord?.info) {
+ const existing = existingRecord.info;
+ try {
+ process.kill(existing.pid, 0);
+ console.error(`Live server already running on port ${existing.port} (pid ${existing.pid}).`);
+ console.error('Stop it first with: node ' + path.basename(fileURLToPath(import.meta.url)) + ' stop');
+ process.exit(1);
+ } catch {
+ try { fs.unlinkSync(existingRecord.path); } catch {}
+ }
+}
+
+state.token = randomUUID();
+state.sessionStore = createLiveSessionStore({ cwd: process.cwd() });
+manualApply.rollbackTransaction({
+ reason: 'manual_edit_server_start_recovered_abandoned_transaction',
+});
+applyLegacyDeferredAcceptsOnStartup();
+restorePendingEventsFromStore();
+manualApply.pruneStaleEvidence();
+const portArg = args.find(a => a.startsWith('--port='));
+state.port = portArg ? parseInt(portArg.split('=')[1], 10) : await findOpenPort();
+// Annotation screenshots live in the project root so the agent's Read tool
+// doesn't trip a per-file permission prompt. Sessioned by token so concurrent
+// projects (or quick restarts) don't collide.
+const annotRoot = getLiveAnnotationsDir(process.cwd());
+fs.mkdirSync(annotRoot, { recursive: true });
+state.sessionDir = fs.mkdtempSync(path.join(annotRoot, 'session-'));
+
+const { detectScript, liveScriptParts } = loadBrowserScripts();
+httpServer = http.createServer(createRequestHandler({ detectScript, liveScriptParts }));
+
+httpServer.listen(state.port, '127.0.0.1', () => {
+ writeLiveServerInfo(process.cwd(), { pid: process.pid, port: state.port, token: state.token });
+ const url = `http://localhost:${state.port}`;
+ console.log(`\nImpeccable live server running on ${url}`);
+ console.log(`Token: ${state.token}\n`);
+ console.log(`Script: ${url}/live.js`);
+ console.log('Inject: managed by live-inject.mjs; Astro source tags use is:inline automatically.');
+ console.log(`Stop: node ${path.basename(fileURLToPath(import.meta.url))} stop`);
+});
+
+process.on('SIGINT', shutdown);
+process.on('SIGTERM', shutdown);
diff --git a/.agent/skills/impeccable/scripts/live-status.mjs b/.agent/skills/impeccable/scripts/live-status.mjs
new file mode 100644
index 000000000..f7e464999
--- /dev/null
+++ b/.agent/skills/impeccable/scripts/live-status.mjs
@@ -0,0 +1,61 @@
+#!/usr/bin/env node
+/**
+ * Print durable recovery status for Impeccable live sessions.
+ */
+
+import { createLiveSessionStore } from './live/session-store.mjs';
+import { readLiveServerInfo } from './lib/impeccable-paths.mjs';
+import { manualApplyResumeHint } from './live-resume.mjs';
+
+function readServerInfo() {
+ return readLiveServerInfo(process.cwd())?.info || null;
+}
+
+async function fetchServerStatus(info) {
+ if (!info) return null;
+ try {
+ const res = await fetch(`http://localhost:${info.port}/status?token=${info.token}`);
+ if (!res.ok) return null;
+ return await res.json();
+ } catch {
+ return null;
+ }
+}
+
+export async function statusCli() {
+ const info = readServerInfo();
+ const server = await fetchServerStatus(info);
+ const store = createLiveSessionStore({ cwd: process.cwd() });
+ const activeSessions = store.listActiveSessions();
+ const manualApply = findPendingManualApply(server, activeSessions);
+ const payload = {
+ liveServer: server ? {
+ status: server.status,
+ port: server.port,
+ connectedClients: server.connectedClients,
+ agentPolling: server.agentPolling,
+ pendingEvents: server.pendingEvents,
+ } : null,
+ activeSessions: server?.activeSessions || activeSessions,
+ recoveryHint: manualApply
+ ? manualApplyResumeHint(manualApply)
+ : server
+ ? 'Run live-poll.mjs to continue pending work, or live-complete.mjs --id after manual cleanup.'
+ : 'Start live-server.mjs to requeue pending durable events, then run live-poll.mjs.',
+ };
+ console.log(JSON.stringify(payload, null, 2));
+}
+
+function findPendingManualApply(server, activeSessions) {
+ const fromServer = server?.pendingEvents?.find((event) => event?.type === 'manual_edit_apply');
+ if (fromServer) return fromServer;
+ const fromSession = activeSessions
+ ?.map((session) => session.pendingEvent)
+ .find((event) => event?.type === 'manual_edit_apply');
+ return fromSession || null;
+}
+
+const _running = process.argv[1];
+if (_running?.endsWith('live-status.mjs') || _running?.endsWith('live-status.mjs/')) {
+ statusCli();
+}
diff --git a/.agent/skills/impeccable/scripts/live-wrap.mjs b/.agent/skills/impeccable/scripts/live-wrap.mjs
new file mode 100644
index 000000000..438c01b68
--- /dev/null
+++ b/.agent/skills/impeccable/scripts/live-wrap.mjs
@@ -0,0 +1,894 @@
+/**
+ * CLI helper: find an element in source and wrap it in a variant container.
+ *
+ * Usage:
+ * node /live-wrap.mjs --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';
+import { isGeneratedFile } from './lib/is-generated.mjs';
+import { readBuffer as readManualEditsBuffer } from './live/manual-edits-buffer.mjs';
+import {
+ buildSvelteComponentCssAuthoring,
+ scaffoldSvelteComponentSession,
+ shouldUseSvelteComponentInjection,
+} from './live/svelte-component.mjs';
+
+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- or space-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)
+ --text TEXT Picked element's textContent. Used to disambiguate when
+ classes/tag match multiple sibling elements (e.g. a list
+ of s with the same className). Pass the first ~80
+ chars of event.element.textContent.
+ --page-url URL Current page URL. Required when pending manual edits may
+ affect the picked source block. Pending edits are filtered
+ to this page so an edit on /a doesn't bleed into /b.
+ --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');
+ const text = argVal(args, '--text');
+ const pageUrl = argVal(args, '--page-url');
+
+ 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);
+
+ const genOpts = { cwd: process.cwd() };
+
+ // Find the source file. Generated files are excluded from auto-search so we
+ // don't silently write variants into a file the next build will wipe.
+ let targetFile = filePath;
+ let matchedQuery = null;
+ if (!targetFile) {
+ for (const q of queries) {
+ targetFile = findFileWithQuery(q, process.cwd(), genOpts);
+ if (targetFile) { matchedQuery = q; break; }
+ }
+ if (!targetFile) {
+ // Nothing in source. Did the element show up in a generated file? That
+ // tells the agent "fall back to the agent-driven flow" vs "element just
+ // doesn't exist in this project."
+ let generatedHit = null;
+ for (const q of queries) {
+ generatedHit = findFileWithQuery(q, process.cwd(), { ...genOpts, includeGenerated: true });
+ if (generatedHit) break;
+ }
+ if (generatedHit) {
+ console.error(JSON.stringify({
+ error: 'element_not_in_source',
+ fallback: 'agent-driven',
+ generatedMatch: path.relative(process.cwd(), generatedHit),
+ hint: 'Element found only in a generated file. See "Handle fallback" in live.md.',
+ }));
+ } else {
+ console.error(JSON.stringify({
+ error: 'element_not_found',
+ fallback: 'agent-driven',
+ hint: 'Element not found in any project file. It may be runtime-injected (JS component, etc.). See "Handle fallback" in live.md.',
+ }));
+ }
+ process.exit(1);
+ }
+ } else {
+ if (isGeneratedFile(targetFile, genOpts)) {
+ console.error(JSON.stringify({
+ error: 'file_is_generated',
+ fallback: 'agent-driven',
+ file: path.relative(process.cwd(), path.resolve(process.cwd(), targetFile)),
+ hint: 'Explicit --file points at a generated file. Writing here gets wiped by the next build. See "Handle fallback" in live.md.',
+ }));
+ process.exit(1);
+ }
+ matchedQuery = queries[0];
+ }
+
+ const content = fs.readFileSync(targetFile, 'utf-8');
+ const lines = content.split('\n');
+
+ // Find the element, trying each query in priority order. When `--text` is
+ // supplied, collect every candidate the queries surface and disambiguate
+ // by the picked element's textContent. Without `--text`, fall back to the
+ // legacy first-match behavior so unmodified callers keep working.
+ let match = null;
+ if (text) {
+ const candidates = [];
+ for (const q of queries) {
+ const all = findAllElements(lines, q, tag);
+ for (const c of all) {
+ if (!candidates.some((x) => x.startLine === c.startLine)) {
+ candidates.push(c);
+ }
+ }
+ // Once a more-specific query (ID, full className combo) yielded a unique
+ // result, stop — falling through to the loose tag+single-class query
+ // would readmit the siblings we just disambiguated past.
+ if (candidates.length === 1) break;
+ }
+ if (candidates.length === 0) {
+ console.error(JSON.stringify({ error: 'Found file but could not locate element in ' + targetFile + '. Searched for: ' + queries.join(', ') }));
+ process.exit(1);
+ }
+ if (candidates.length === 1) {
+ match = candidates[0];
+ } else {
+ const filtered = filterByText(candidates, lines, text);
+ if (filtered.length === 1) {
+ match = filtered[0];
+ } else if (filtered.length === 0) {
+ // Source uses dynamic content (`
{title}
` etc.) so the
+ // browser-side textContent doesn't appear literally in source. Fall
+ // back to first-match rather than refusing — this is the same
+ // behavior unmodified callers see, just preserved.
+ match = candidates[0];
+ } else {
+ // Multiple candidates ALSO match the text. Truly ambiguous — refuse
+ // rather than pick wrong, and hand the agent the candidate locations
+ // so it can disambiguate by reading the file.
+ console.error(JSON.stringify({
+ error: 'element_ambiguous',
+ fallback: 'agent-driven',
+ file: path.relative(process.cwd(), targetFile),
+ candidates: filtered.map((c) => ({
+ startLine: c.startLine + 1,
+ endLine: c.endLine + 1,
+ })),
+ hint: 'Multiple source elements match both classes/tag and textContent. Pass --element-id, a more specific --text, or write the wrapper manually. See "Handle fallback" in live.md.',
+ }));
+ process.exit(1);
+ }
+ }
+ } else {
+ for (const q of queries) {
+ match = findElement(lines, q, tag);
+ 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 styleMode = detectStyleMode(targetFile);
+ const isJsx = commentSyntax.open === '{/*';
+ const indent = lines[startLine].match(/^(\s*)/)[1];
+
+ // Extract the original element. Reindent under the wrapper while preserving
+ // the relative depth between lines — `l.trimStart()` would strip ALL leading
+ // whitespace and collapse e.g. `` (6/8/6 spaces)
+ // to a single uniform indent, so on accept/discard the round-trip restores
+ // the inner element at its parent's depth instead of nested inside it.
+ // Strip only the COMMON minimum leading whitespace across the picked lines;
+ // `deindentContent` on the accept side already mirrors this convention.
+ let originalLines = lines.slice(startLine, endLine + 1);
+
+ // Buffer-aware "original" content: if the user has pending manual edits for
+ // this page whose originalText appears in the picked source range, apply
+ // them so the wrap block's "original" variant reflects what the user was
+ // looking at (their edited DOM), not the raw source. Source itself stays
+ // untouched here — only the wrap block's embedded "original" copy is
+ // adjusted. The pending edits remain in the buffer until committed.
+ //
+ // Apply buffered edits only when the browser provided the current page URL.
+ // Without it, fail if pending edits plausibly touch this exact source range;
+ // otherwise skip buffer awareness so unrelated staged edits on another page
+ // do not block normal wrap work.
+ let pendingBuffer = { entries: [] };
+ try { pendingBuffer = readManualEditsBuffer(process.cwd()); } catch {}
+ const pendingEntriesForTarget = pageUrl
+ ? []
+ : pendingEntriesThatMayAffectWrap(pendingBuffer.entries, targetFile, originalLines, startLine, process.cwd());
+ if (pendingEntriesForTarget.length > 0) {
+ console.error(JSON.stringify({
+ error: 'missing_page_url_with_pending_edits',
+ pendingEntries: pendingEntriesForTarget.length,
+ hint: 'Pending manual edits may affect the selected source block. Pass --page-url=$event.pageUrl so the wrap block reflects the user\'s staged DOM.',
+ }));
+ process.exit(1);
+ }
+ if (pageUrl) {
+ const failedBufferedOps = [];
+ for (const entry of pendingBuffer.entries || []) {
+ if (entry.pageUrl !== pageUrl) continue;
+ for (const op of entry.ops || []) {
+ const mayAffectWrap = manualEditMayAffectWrap(op, targetFile, originalLines, startLine, process.cwd());
+ const result = applyBufferedManualEditToLines(originalLines, startLine, op);
+ if (result.changed) {
+ originalLines = result.lines;
+ continue;
+ }
+ if (!mayAffectWrap) continue;
+ failedBufferedOps.push({
+ entryId: entry.id,
+ ref: op?.ref || null,
+ originalText: op?.originalText || null,
+ reason: 'ambiguous_or_unmatched_pending_edit',
+ });
+ }
+ }
+ if (failedBufferedOps.length > 0) {
+ console.error(JSON.stringify({
+ error: 'manual_edit_buffer_apply_failed',
+ pendingOps: failedBufferedOps,
+ hint: 'A staged copy edit appears to affect the selected source block, but could not be applied unambiguously to the wrap original. Apply or discard copy edits first, or write the wrapper manually.',
+ }));
+ process.exit(1);
+ }
+ }
+
+ const originalBaseIndent = minLeadingSpaces(originalLines);
+ const reindentOriginal = (extra) => originalLines
+ .map((l) => (l.trim() === '' ? '' : indent + extra + l.slice(originalBaseIndent)))
+ .join('\n');
+ const originalIndented = reindentOriginal(' ');
+ const relTargetFile = path.relative(process.cwd(), targetFile).split(path.sep).join('/');
+ const useSvelteComponent = shouldUseSvelteComponentInjection(targetFile);
+
+ // Wrapper attributes differ by syntax. HTML allows plain string attrs;
+ // JSX requires object-literal style and parses string attrs as HTML (which
+ // either type-errors or renders a literal CSS string).
+ const styleContents = isJsx ? 'style={{ display: "contents" }}' : 'style="display: contents"';
+
+ // JSX/TSX guard: the picked element occupies a single JSX child slot
+ // (inside `return (...)`, an array `.map(...)`, an `asChild` branch, or
+ // any other expression position). Replacing it with `comment +
+
+ // comment` yields three adjacent siblings — invalid JSX. We can't use a
+ // Fragment `<>>` either: parents that clone children (Radix `asChild`,
+ // Headless UI, etc.) hit "Invalid prop supplied to React.Fragment" when
+ // they try to pass an `id` through.
+ //
+ // Solution: keep the wrapper `
` as the single JSX-slot child and
+ // tuck both marker comments INSIDE it. accept/discard then expands its
+ // replacement range to include the wrapper's `
` open / close lines
+ // so the entire scaffold gets removed cleanly.
+ const wrapperLines = isJsx ? [
+ indent + '