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 `` / popover API, `position: fixed`, or a portal to escape the stacking context. + +### New projects only (when no prior work exists) + +#### Color & Theme + +- Use OKLCH. +- **The cream / sand / beige body bg is the saturated AI default of 2026.** The whole warm-neutral band (OKLCH L 0.84-0.97, C < 0.06, hue 40-100) reads as cream/sand/paper/parchment regardless of what you call it. Token names like `--paper`, `--cream`, `--sand`, `--bone`, `--flour`, `--linen`, `--parchment`, `--wheat`, `--biscuit`, `--ivory` are tells in themselves. If the brief is "warm, traditional, family-coastal-Italian" or "magazine-warm" or "editorial-restraint", DO NOT translate that into a near-white warm-tinted bg; that's the AI move. Pick: (a) a saturated brand color as the body (terracotta, oxblood, deep ochre, near-black), (b) a true off-white at chroma 0 (or chroma toward the brand's own hue, not toward warmth-by-default), or (c) a darker mid-tone tinted neutral that's clearly the brand's own. "Warmth" in the brand is carried by accent + typography + imagery, not by body bg. +- Tinted neutrals: add 0.005–0.015 chroma toward the brand's hue. Don't default-tint toward warm or cool "because the brand feels that way"; that's the cross-project monoculture move. +- When picking a theme: Dark vs. light is never a default. Not dark "because tools look cool dark." Not light "to be safe.".Before choosing, write one sentence of physical scene: who uses this, where, under what ambient light, in what mood. If the sentence doesn't force the answer, it's not concrete enough. Add detail until it does. +- Pick a **color strategy** before picking colors. Four steps on the commitment axis: + - **Restrained**: tinted neutrals + one accent ≤10%. Product default; brand minimalism. + - **Committed**: one saturated color carries 30–60% of the surface. Brand default for identity-driven pages. + - **Full palette**: 3–4 named roles, each used deliberately. Brand campaigns; product data viz. + - **Drenched**: the surface IS the color. Brand heroes, campaign pages. + +### Absolute bans + +Match-and-refuse. If you're about to write any of these, rewrite the element with different structure. + +- **Side-stripe borders.** `border-left` or `border-right` greater than 1px as a colored accent on cards, list items, callouts, or alerts. Never intentional. Rewrite with full borders, background tints, leading numbers/icons, or nothing. +- **Gradient text.** `background-clip: text` combined with a gradient background. Decorative, never meaningful. Use a single solid color. Emphasis via weight or size. +- **Glassmorphism as default.** Blurs and glass cards used decoratively. Rare and purposeful, or nothing. +- **The hero-metric template.** Big number, small label, supporting stats, gradient accent. SaaS cliché. +- **Identical card grids.** Same-sized cards with icon + heading + text, repeated endlessly. +- **Tiny uppercase tracked eyebrow above every section.** The 2023-era kicker (small all-caps text with wide tracking, "ABOUT" "PROCESS" "PRICING" above each heading) is now the saturated AI scaffold; it appears on 55-95% of generations regardless of brief, which is the definition of a tell. One named kicker as a deliberate brand system is voice; an eyebrow on every section is AI grammar. Choose a different cadence. +- **Numbered section markers as default scaffolding (01 / 02 / 03).** Putting `01 · About / 02 · Process / 03 · Pricing` above every section is the eyebrow trope one tier deeper: reach for it because "landing pages do this" and you're scaffolding by reflex. Numbers earn their place when the section actually IS a sequence (a real 3-step process, an ordered flow, a typed timeline) and the order carries information the reader needs. One deliberate numbered sequence on one page is voice; numbered eyebrows on every section across the site is AI grammar. +- **Text that overflows its container.** Long heading words plus large clamp scales plus narrow grids cause headline overflow on tablet/mobile. Test the heading copy at every breakpoint; if it overflows, reduce the clamp max or rewrite the copy. The viewport is part of the design. + +### The AI slop test + +If someone could look at this interface and say "AI made that" without doubt, it's failed. Cross-register failures are the absolute bans above. Register-specific failures live in each reference. + +**Category-reflex check.** Run at two altitudes; the second one catches what the first one misses. + +- **First-order:** if someone could guess the theme + palette from the category alone, it's the first training-data reflex. Rework the scene sentence and color strategy until the answer isn't obvious from the domain. +- **Second-order:** if someone could guess the aesthetic family from category-plus-anti-references ("AI workflow tool that's not SaaS-cream → editorial-typographic", "fintech that's not navy-and-gold → terminal-native dark mode"), it's the trap one tier deeper. The first reflex was avoided; the second wasn't. Rework until both answers are not obvious. The brand register's [reflex-reject aesthetic lanes](reference/brand.md) list catches the currently-saturated families. + +## Commands + +| Command | Category | Description | Reference | +|---|---|---|---| +| `craft [feature]` | Build | Shape, then build a feature end-to-end | [reference/craft.md](reference/craft.md) | +| `shape [feature]` | Build | Plan UX/UI before writing code | [reference/shape.md](reference/shape.md) | +| `init` | Build | Set up project context: PRODUCT.md, DESIGN.md, live config, next steps | [reference/init.md](reference/init.md) | +| `document` | Build | Generate DESIGN.md from existing project code | [reference/document.md](reference/document.md) | +| `extract [target]` | Build | Pull reusable tokens and components into design system | [reference/extract.md](reference/extract.md) | +| `critique [target]` | Evaluate | UX design review with heuristic scoring | [reference/critique.md](reference/critique.md) | +| `audit [target]` | Evaluate | Technical quality checks (a11y, perf, responsive) | [reference/audit.md](reference/audit.md) | +| `polish [target]` | Refine | Final quality pass before shipping | [reference/polish.md](reference/polish.md) | +| `bolder [target]` | Refine | Amplify safe or bland designs | [reference/bolder.md](reference/bolder.md) | +| `quieter [target]` | Refine | Tone down aggressive or overstimulating designs | [reference/quieter.md](reference/quieter.md) | +| `distill [target]` | Refine | Strip to essence, remove complexity | [reference/distill.md](reference/distill.md) | +| `harden [target]` | Refine | Production-ready: errors, i18n, edge cases | [reference/harden.md](reference/harden.md) | +| `onboard [target]` | Refine | Design first-run flows, empty states, activation | [reference/onboard.md](reference/onboard.md) | +| `animate [target]` | Enhance | Add purposeful animations and motion | [reference/animate.md](reference/animate.md) | +| `colorize [target]` | Enhance | Add strategic color to monochromatic UIs | [reference/colorize.md](reference/colorize.md) | +| `typeset [target]` | Enhance | Improve typography hierarchy and fonts | [reference/typeset.md](reference/typeset.md) | +| `layout [target]` | Enhance | Fix spacing, rhythm, and visual hierarchy | [reference/layout.md](reference/layout.md) | +| `delight [target]` | Enhance | Add personality and memorable touches | [reference/delight.md](reference/delight.md) | +| `overdrive [target]` | Enhance | Push past conventional limits | [reference/overdrive.md](reference/overdrive.md) | +| `clarify [target]` | Fix | Improve UX copy, labels, and error messages | [reference/clarify.md](reference/clarify.md) | +| `adapt [target]` | Fix | Adapt for different devices and screen sizes | [reference/adapt.md](reference/adapt.md) | +| `optimize [target]` | Fix | Diagnose and fix UI performance | [reference/optimize.md](reference/optimize.md) | +| `live` | Iterate | Visual variant mode: pick elements in the browser, generate alternatives | [reference/live.md](reference/live.md) | + +Plus three management commands: `pin `, `unpin `, and `hooks `, detailed below. + +### Routing rules + +1. **No argument**: the user is asking "what should I do?" Make the menu context-aware instead of static. Setup has already run `context.mjs`; if that reported `NO_PRODUCT_MD` you are already in init (setup), so finish that and skip this. Otherwise run `node .agent/skills/impeccable/scripts/context-signals.mjs` once and read its JSON, then lead with the **2-3 highest-value next commands**, each with a one-line reason pulled from the signals, followed by the full menu (the table above, grouped by category). **Never auto-run a command; the recommendation is a suggestion the user confirms.** + + Reason over the signals; there is no score to obey: + - `setup.hasDesign` false while `setup.hasCode` true → `document` (capture the visual system). + - `critique.latest` is `null` → the project has never been critiqued; for a set-up project with a real surface, offering `/impeccable critique ` is a strong default. + - `critique.latest` with a low `score` or non-zero `p0` / `p1` → `polish` (it reads that snapshot as its backlog), or re-run `critique` if the snapshot looks stale. + - `git.changedFiles` pointing at one surface → scope `audit` or `polish` to those files specifically, naming them. + - `devServer.running` true → `live` is available for in-browser iteration; if false, don't lead with `live`. + - Otherwise group by intent exactly as init's "Recommend starting points" step does (build new / improve what's there / iterate visually), tailored to `setup.register`. + + **If `scan.targets` is non-empty, run `node .agent/skills/impeccable/scripts/detect.mjs --json ` once** (the bundled detector over local files: no network, no npx). `scan.via` tells you what they are: `git-changes` (the markup/style files in your dirty tree, the most relevant set), `source-dir` (e.g. `src`, `app`), `html`, or `root`. Fold the hits into your picks: many quality / contrast hits → `audit` or `polish`; a specific slop family → the matching command (gradient text or eyebrows → `quieter` / `typeset`, flat or gray palette → `colorize`, and so on). It's a real, current signal that beats guessing. If detect errors or the tree is large and slow, skip it and recommend the user run `audit` themselves; never block the suggestion on it. + + Keep it to 2-3 pointed picks with the exact command to type. The menu stays the fallback; the recommendation is the lede. +2. **First word matches a command** (table above OR `pin` / `unpin` / `hooks`): load its reference file and follow its instructions. Everything after the command name is the target. +3. **First word doesn't match, but the intent clearly maps to one command** (e.g. "fix the spacing" → `layout`, "rewrite this error message" → `clarify`, "the colors feel flat" → `colorize`): load that command's reference and proceed as if invoked. If two commands could fit, ask once which. +4. **No clear command match**: general design invocation. Apply the setup steps, the General rules, and the loaded register reference, using the full argument as context. + +Setup (context gathering, register) is already loaded by then; sub-commands don't re-invoke `/impeccable`. + +If the first word is `craft`, setup still runs first, but [reference/craft.md](reference/craft.md) owns the rest of the flow. If setup invokes `init` as a blocker, finish init, refresh context, then resume the original command and target. + +`teach` is a deprecated alias for `init`: if the user types it, load [reference/init.md](reference/init.md) and proceed as if they ran `init`. + +## Pin / Unpin + +**Pin** creates a standalone shortcut so `/` invokes `/impeccable ` directly. **Unpin** removes it. The script writes to every harness directory present in the project. + +```bash +node .agent/skills/impeccable/scripts/pin.mjs +``` + +Valid `` is any command from the table above. Report the script's result concisely. Confirm the new shortcut on success, relay stderr verbatim on error. + +## Hooks + +`/impeccable hooks ` manages the design detector hook for this project. The hook auto-runs the detector after direct UI file edits and surfaces findings as system reminders. Full flow is in [reference/hooks.md](reference/hooks.md); load it when the user invokes `/impeccable hooks` with any argument. \ No newline at end of file diff --git a/.agent/skills/impeccable/reference/adapt.md b/.agent/skills/impeccable/reference/adapt.md new file mode 100644 index 000000000..5af7606cb --- /dev/null +++ b/.agent/skills/impeccable/reference/adapt.md @@ -0,0 +1,311 @@ +> **Additional context needed**: target platforms/devices and usage contexts. + +Adapt an existing design to a different context: another screen size, device, platform, or use case. The trap is treating adaptation as scaling. The job is rethinking the experience for the new context. + + +--- + +## Assess Adaptation Challenge + +Understand what needs adaptation and why: + +1. **Identify the source context**: + - What was it designed for originally? (Desktop web? Mobile app?) + - What assumptions were made? (Large screen? Mouse input? Fast connection?) + - What works well in current context? + +2. **Understand target context**: + - **Device**: Mobile, tablet, desktop, TV, watch, print? + - **Input method**: Touch, mouse, keyboard, voice, gamepad? + - **Screen constraints**: Size, resolution, orientation? + - **Connection**: Fast wifi, slow 3G, offline? + - **Usage context**: On-the-go vs desk, quick glance vs focused reading? + - **User expectations**: What do users expect on this platform? + +3. **Identify adaptation challenges**: + - What won't fit? (Content, navigation, features) + - What won't work? (Hover states on touch, tiny touch targets) + - What's inappropriate? (Desktop patterns on mobile, mobile patterns on desktop) + +**CRITICAL**: Adaptation is rethinking the experience for the new context, not scaling pixels. + +## Plan Adaptation Strategy + +Create context-appropriate strategy: + +### Mobile Adaptation (Desktop → Mobile) + +**Layout Strategy**: +- Single column instead of multi-column +- Vertical stacking instead of side-by-side +- Full-width components instead of fixed widths +- Bottom navigation instead of top/side navigation + +**Interaction Strategy**: +- Touch targets 44x44px minimum (not hover-dependent) +- Swipe gestures where appropriate (lists, carousels) +- Bottom sheets instead of dropdowns +- Thumbs-first design (controls within thumb reach) +- Larger tap areas with more spacing + +**Content Strategy**: +- Progressive disclosure (don't show everything at once) +- Prioritize primary content (secondary content in tabs/accordions) +- Shorter text (more concise) +- Larger text (16px minimum) + +**Navigation Strategy**: +- Hamburger menu or bottom navigation +- Reduce navigation complexity +- Sticky headers for context +- Back button in navigation flow + +### Tablet Adaptation (Hybrid Approach) + +**Layout Strategy**: +- Two-column layouts (not single or three-column) +- Side panels for secondary content +- Master-detail views (list + detail) +- Adaptive based on orientation (portrait vs landscape) + +**Interaction Strategy**: +- Support both touch and pointer +- Touch targets 44x44px but allow denser layouts than phone +- Side navigation drawers +- Multi-column forms where appropriate + +### Desktop Adaptation (Mobile → Desktop) + +**Layout Strategy**: +- Multi-column layouts (use horizontal space) +- Side navigation always visible +- Multiple information panels simultaneously +- Fixed widths with max-width constraints (don't stretch to 4K) + +**Interaction Strategy**: +- Hover states for additional information +- Keyboard shortcuts +- Right-click context menus +- Drag and drop where helpful +- Multi-select with Shift/Cmd + +**Content Strategy**: +- Show more information upfront (less progressive disclosure) +- Data tables with many columns +- Richer visualizations +- More detailed descriptions + +### Print Adaptation (Screen → Print) + +**Layout Strategy**: +- Page breaks at logical points +- Remove navigation, footer, interactive elements +- Black and white (or limited color) +- Proper margins for binding + +**Content Strategy**: +- Expand shortened content (show full URLs, hidden sections) +- Add page numbers, headers, footers +- Include metadata (print date, page title) +- Convert charts to print-friendly versions + +### Email Adaptation (Web → Email) + +**Layout Strategy**: +- Narrow width (600px max) +- Single column only +- Inline CSS (no external stylesheets) +- Table-based layouts (for email client compatibility) + +**Interaction Strategy**: +- Large, obvious CTAs (buttons not text links) +- No hover states (not reliable) +- Deep links to web app for complex interactions + +## Implement Adaptations + +Apply changes systematically: + +### Responsive Breakpoints + +Choose appropriate breakpoints: +- Mobile: 320px-767px +- Tablet: 768px-1023px +- Desktop: 1024px+ +- Or content-driven breakpoints (where design breaks) + +### Layout Adaptation Techniques + +- **CSS Grid/Flexbox**: Reflow layouts automatically +- **Container Queries**: Adapt based on container, not viewport +- **`clamp()`**: Fluid sizing between min and max +- **Media queries**: Different styles for different contexts +- **Display properties**: Show/hide elements per context + +### Touch Adaptation + +- Increase touch target sizes (44x44px minimum) +- Add more spacing between interactive elements +- Remove hover-dependent interactions +- Add touch feedback (ripples, highlights) +- Consider thumb zones (easier to reach bottom than top) + +### Content Adaptation + +- Use `display: none` sparingly (still downloads) +- Progressive enhancement (core content first, enhancements on larger screens) +- Lazy loading for off-screen content +- Responsive images (`srcset`, `picture` element) + +### Navigation Adaptation + +- Transform complex nav to hamburger/drawer on mobile +- Bottom nav bar for mobile apps +- Persistent side navigation on desktop +- Breadcrumbs on smaller screens for context + +**IMPORTANT**: Test on real devices. Device emulation in DevTools is helpful but not perfect. + +**NEVER**: +- Hide core functionality on mobile (if it matters, make it work) +- Assume desktop = powerful device (consider accessibility, older machines) +- Use different information architecture across contexts (confusing) +- Break user expectations for platform (mobile users expect mobile patterns) +- Forget landscape orientation on mobile/tablet +- Use generic breakpoints blindly (use content-driven breakpoints) +- Ignore touch on desktop (many desktop devices have touch) + +## Verify Adaptations + +Test thoroughly across contexts: + +- **Real devices**: Test on actual phones, tablets, desktops +- **Different orientations**: Portrait and landscape +- **Different browsers**: Safari, Chrome, Firefox, Edge +- **Different OS**: iOS, Android, Windows, macOS +- **Different input methods**: Touch, mouse, keyboard +- **Edge cases**: Very small screens (320px), very large screens (4K) +- **Slow connections**: Test on throttled network + +When the adaptation feels native to each context, hand off to `/impeccable polish` for the final pass. + +--- + +## Reference Material + +The sections below were previously `responsive-design.md` and live inline now so the adapt flow has its deep responsive reference in one place. + +### Responsive Design + +#### Mobile-First: Write It Right + +Start with base styles for mobile, use `min-width` queries to layer complexity. Desktop-first (`max-width`) means mobile loads unnecessary styles first. + +#### Breakpoints: Content-Driven + +Don't chase device sizes; let content tell you where to break. Start narrow, stretch until design breaks, add breakpoint there. Three breakpoints usually suffice (640, 768, 1024px). Use `clamp()` for fluid values without breakpoints. + +#### Detect Input Method, Not Just Screen Size + +**Screen size doesn't tell you input method.** A laptop with touchscreen, a tablet with keyboard. Use pointer and hover queries: + +```css +/* Fine pointer (mouse, trackpad) */ +@media (pointer: fine) { + .button { padding: 8px 16px; } +} + +/* Coarse pointer (touch, stylus) */ +@media (pointer: coarse) { + .button { padding: 12px 20px; } /* Larger touch target */ +} + +/* Device supports hover */ +@media (hover: hover) { + .card:hover { transform: translateY(-2px); } +} + +/* Device doesn't support hover (touch) */ +@media (hover: none) { + .card { /* No hover state - use active instead */ } +} +``` + +**Critical**: Don't rely on hover for functionality. Touch users can't hover. + +#### Safe Areas: Handle the Notch + +Modern phones have notches, rounded corners, and home indicators. Use `env()`: + +```css +body { + padding-top: env(safe-area-inset-top); + padding-bottom: env(safe-area-inset-bottom); + padding-left: env(safe-area-inset-left); + padding-right: env(safe-area-inset-right); +} + +/* With fallback */ +.footer { + padding-bottom: max(1rem, env(safe-area-inset-bottom)); +} +``` + +**Enable viewport-fit** in your meta tag: +```html + +``` + +#### Responsive Images: Get It Right + +##### srcset with Width Descriptors + +```html +Hero image +``` + +**How it works**: +- `srcset` lists available images with their actual widths (`w` descriptors) +- `sizes` tells the browser how wide the image will display +- Browser picks the best file based on viewport width AND device pixel ratio + +##### Picture Element for Art Direction + +When you need different crops/compositions (not just resolutions): + +```html + + + + ... + +``` + +#### Layout Adaptation Patterns + +**Navigation**: Three stages: hamburger + drawer on mobile, horizontal compact on tablet, full with labels on desktop. **Tables**: Transform to cards on mobile using `display: block` and `data-label` attributes. **Progressive disclosure**: Use `
/` for content that can collapse on mobile. + +#### Testing: Don't Trust DevTools Alone + +DevTools device emulation is useful for layout but misses: + +- Actual touch interactions +- Real CPU/memory constraints +- Network latency patterns +- Font rendering differences +- Browser chrome/keyboard appearances + +**Test on at least**: One real iPhone, one real Android, a tablet if relevant. Cheap Android phones reveal performance issues you'll never see on simulators. + +--- + +**Avoid**: Desktop-first design. Device detection instead of feature detection. Separate mobile/desktop codebases. Ignoring tablet and landscape. Assuming all mobile devices are powerful. diff --git a/.agent/skills/impeccable/reference/animate.md b/.agent/skills/impeccable/reference/animate.md new file mode 100644 index 000000000..15d9f9080 --- /dev/null +++ b/.agent/skills/impeccable/reference/animate.md @@ -0,0 +1,201 @@ +> **Additional context needed**: performance constraints. + +Add motion that conveys state, gives feedback, and clarifies hierarchy. Cut motion that exists only for decoration. Animation fatigue is a real cost; spend the budget on the moments that need it. + +--- + +## Register + +Brand: motion is part of the voice; one well-rehearsed entrance beats scattered micro-interactions. The saturated AI default is fade-and-rise reveals on every scrolled section; that's a tell, not a choreography. Reserve scroll-triggered motion for moments that earn it. + +Product: 150–250 ms on most transitions. Motion conveys state: feedback, reveal, loading, transitions between views. No page-load choreography; users are in a task and won't wait for it. + +--- + +## Assess Animation Opportunities + +Analyze where motion would improve the experience: + +1. **Identify static areas**: + - **Missing feedback**: Actions without visual acknowledgment (button clicks, form submission, etc.) + - **Jarring transitions**: Instant state changes that feel abrupt (show/hide, page loads, route changes) + - **Unclear relationships**: Spatial or hierarchical relationships that aren't obvious + - **Lack of delight**: Functional but joyless interactions + - **Missed guidance**: Opportunities to direct attention or explain behavior + +2. **Understand the context**: + - What's the personality? (Playful vs serious, energetic vs calm) + - What's the performance budget? (Mobile-first? Complex page?) + - Who's the audience? (Motion-sensitive users? Power users who want speed?) + - What matters most? (One hero animation vs many micro-interactions?) + +If any of these are unclear from the codebase, ask the user directly to clarify what you cannot infer. + +**CRITICAL**: Respect `prefers-reduced-motion`. Always provide non-animated alternatives for users who need them. + +## Plan Animation Strategy + +Create a purposeful animation plan: + +- **Hero moment**: What's the ONE signature animation? (Page load? Hero section? Key interaction?) +- **Feedback layer**: Which interactions need acknowledgment? +- **Transition layer**: Which state changes need smoothing? +- **Delight layer**: Where can we surprise and delight? + +**IMPORTANT**: One well-orchestrated experience beats scattered animations everywhere. Focus on high-impact moments. + +## Implement Animations + +Add motion systematically across these categories: + +### Entrance Animations +- **Hero section**: Dramatic entrance for primary content (scale, parallax, or creative effects) +- **Modal/drawer entry**: Smooth slide + fade, backdrop fade, focus management +- **List rhythm**: Sibling stagger is legitimate for cards-in-a-grid or list-items-appearing. Whole-section fade-on-scroll is not a list and is not legitimate. Cap total stagger time: 10 items at 50ms each = 500ms total. For more items, reduce per-item delay or cap the staggered count. + + Use CSS custom properties for clean stagger: `animation-delay: calc(var(--i, 0) * 50ms)` with `style="--i: 0"`, `style="--i: 1"`, etc. on each item. + +### Micro-interactions +- **Button feedback**: + - Hover: Subtle scale (1.02-1.05), color shift, shadow increase + - Click: Quick scale down then up (0.95 → 1), ripple effect + - Loading: Spinner or pulse state +- **Form interactions**: + - Input focus: Border color transition, slight scale or glow + - Validation: Shake on error, check mark on success, smooth color transitions +- **Toggle switches**: Smooth slide + color transition (200-300ms) +- **Checkboxes/radio**: Check mark animation, ripple effect +- **Like/favorite**: Scale + rotation, particle effects, color transition + +### State Transitions +- **Show/hide**: Fade + slide (not instant), appropriate timing (200-300ms) +- **Expand/collapse**: Height transition with overflow handling, icon rotation +- **Loading states**: Skeleton screen fades, spinner animations, progress bars +- **Success/error**: Color transitions, icon animations, gentle scale pulse +- **Enable/disable**: Opacity transitions, cursor changes + +### Navigation & Flow +- **Page transitions**: Crossfade between routes, shared element transitions +- **Tab switching**: Slide indicator, content fade/slide +- **Carousel/slider**: Smooth transforms, snap points, momentum +- **Scroll effects**: Parallax layers, sticky headers with state changes, scroll progress indicators + +### Feedback & Guidance +- **Hover hints**: Tooltip fade-ins, cursor changes, element highlights +- **Drag & drop**: Lift effect (shadow + scale), drop zone highlights, smooth repositioning +- **Copy/paste**: Brief highlight flash on paste, "copied" confirmation +- **Focus flow**: Highlight path through form or workflow + +### Delight Moments +- **Empty states**: Subtle floating animations on illustrations +- **Completed actions**: Confetti, check mark flourish, success celebrations +- **Easter eggs**: Hidden interactions for discovery +- **Contextual animation**: Weather effects, time-of-day themes, seasonal touches + +## Technical Implementation + +Use appropriate techniques for each animation: + +### Timing & Easing + +**Duration: the 100/300/500 rule.** Timing matters more than easing for "feels right": + +| Duration | Use Case | Examples | +|----------|----------|----------| +| **100–150ms** | Instant feedback | Button press, toggle, color change | +| **200–300ms** | State changes | Menu open, tooltip, hover state | +| **300–500ms** | Layout changes | Accordion, modal, drawer | +| **500–800ms** | Entrance animations | Page load, hero reveal | + +**Easing curves (use these, not CSS defaults):** +```css +/* Recommended: natural deceleration */ +--ease-out-quart: cubic-bezier(0.25, 1, 0.5, 1); /* Smooth */ +--ease-out-quint: cubic-bezier(0.22, 1, 0.36, 1); /* Slightly snappier */ +--ease-out-expo: cubic-bezier(0.16, 1, 0.3, 1); /* Confident, decisive */ + +/* AVOID: feel dated and tacky */ +/* bounce: cubic-bezier(0.34, 1.56, 0.64, 1); */ +/* elastic: cubic-bezier(0.68, -0.6, 0.32, 1.6); */ +``` + +**Exit animations are faster than entrances.** Use ~75% of enter duration. + +### CSS Animations +```css +/* Prefer for simple, declarative animations */ +- transitions for state changes +- @keyframes for complex sequences +- transform and opacity for reliable movement +- blur, filters, masks, clip paths, shadows, and color shifts for premium atmospheric effects when verified smooth +``` + +### JavaScript Animation +```javascript +/* Use for complex, interactive animations */ +- Web Animations API for programmatic control +- Framer Motion for React +- GSAP for complex sequences +``` + +### Motion Materials + +Transform and opacity are reliable defaults, not the whole palette. Premium interfaces often need atmospheric properties. Match material to effect: + +- **Transform / opacity**: movement, press feedback, simple reveals, list choreography +- **Blur / filter / backdrop-filter**: focus pulls, depth, glass or lens effects, softened entrances +- **Clip-path / masks**: wipes, reveals, editorial cropping, product-like transitions +- **Shadow / glow / color filters**: energy, affordance, focus, warmth, active state +- **Grid-template-rows or FLIP-style transforms**: expanding and reflowing layout without animating `height` directly + +The hard rule isn't "transform and opacity only." It's: avoid animating layout-driving properties casually (`width`, `height`, `top`, `left`, margins), keep expensive effects bounded to small or isolated areas, and verify smoothness in-browser on target viewports. + +### Performance +- **Layout safety**: Avoid casual animation of layout-driving properties (`width`, `height`, `top`, `left`, margins) +- **will-change**: Add sparingly for known expensive animations only (e.g. on `:hover` or an `.animating` class), never preemptively across the whole page +- **Scroll triggers**: Use Intersection Observer instead of scroll event listeners; unobserve after the animation fires once +- **Bound expensive effects**: Keep blur/filter/shadow areas small or isolated, use `contain` where appropriate +- **Monitor FPS**: Ensure 60fps on target devices + +### Perceived Performance + +Nobody cares how fast your site *is*, only how fast it feels. The 80ms threshold: anything under ~80ms feels instant because our brains buffer sensory input for that long to synchronize perception. Target this for micro-interactions. + +- **Preemptive start**: Begin transitions immediately while loading (iOS app zoom, skeleton UI). Users perceive work happening. +- **Early completion**: Show content progressively, don't wait for everything (progressive images, streaming HTML, skeleton fade-ins). +- **Optimistic UI**: Update the interface immediately, handle failures gracefully. Use for low-stakes actions (likes, follows). Avoid for payments or destructive operations. +- **Easing affects perceived duration**: Ease-in (accelerating toward completion) makes tasks feel shorter because the peak-end effect weights final moments heavily. Ease-out feels satisfying for entrances. +- **Caution**: Too-fast responses can decrease perceived value for complex operations (search, analysis). Sometimes a brief delay signals "real work" is happening. + +### Accessibility +```css +@media (prefers-reduced-motion: reduce) { + * { + animation-duration: 0.01ms !important; + animation-iteration-count: 1 !important; + transition-duration: 0.01ms !important; + } +} +``` + +**NEVER**: +- Use bounce or elastic easing curves; they feel dated and draw attention to the animation itself +- Animate layout properties casually (`width`, `height`, `top`, `left`, margins) when transform, FLIP, or grid-based techniques would work +- Use durations over 500ms for feedback (it feels laggy) +- Animate without purpose (every animation needs a reason) +- Ignore `prefers-reduced-motion` (this is an accessibility violation) +- Animate everything (animation fatigue makes interfaces feel exhausting) +- Block interaction during animations unless intentional + +## Verify Quality + +Test animations thoroughly: + +- **Smooth at 60fps**: No jank on target devices +- **Feels natural**: Easing curves feel organic, not robotic +- **Appropriate timing**: Not too fast (jarring) or too slow (laggy) +- **Reduced motion works**: Animations disabled or simplified appropriately +- **Doesn't block**: Users can interact during/after animations +- **Adds value**: Makes interface clearer or more delightful + +When the motion clarifies state instead of decorating it, hand off to `/impeccable polish` for the final pass. diff --git a/.agent/skills/impeccable/reference/audit.md b/.agent/skills/impeccable/reference/audit.md new file mode 100644 index 000000000..51ab59c06 --- /dev/null +++ b/.agent/skills/impeccable/reference/audit.md @@ -0,0 +1,133 @@ +Run systematic **technical** quality checks and generate a comprehensive report. Don't fix issues; document them for other commands to address. + +This is a code-level audit, not a design critique. Check what's measurable and verifiable in the implementation. + +## Diagnostic Scan + +Run comprehensive checks across 5 dimensions. Score each dimension 0-4 using the criteria below. + +### 1. Accessibility (A11y) + +**Check for**: +- **Contrast issues**: Text contrast ratios < 4.5:1 (or 7:1 for AAA) +- **Missing ARIA**: Interactive elements without proper roles, labels, or states +- **Keyboard navigation**: Missing focus indicators, illogical tab order, keyboard traps +- **Semantic HTML**: Improper heading hierarchy, missing landmarks, divs instead of buttons +- **Alt text**: Missing or poor image descriptions +- **Form issues**: Inputs without labels, poor error messaging, missing required indicators + +**Score 0-4**: 0=Inaccessible (fails WCAG A), 1=Major gaps (few ARIA labels, no keyboard nav), 2=Partial (some a11y effort, significant gaps), 3=Good (WCAG AA mostly met, minor gaps), 4=Excellent (WCAG AA fully met, approaches AAA) + +### 2. Performance + +**Check for**: +- **Layout thrashing**: Reading/writing layout properties in loops +- **Expensive animations**: Casual layout-property animation, unbounded blur/filter/shadow effects, or effects that visibly drop frames +- **Missing optimization**: Images without lazy loading, unoptimized assets, missing will-change +- **Bundle size**: Unnecessary imports, unused dependencies +- **Render performance**: Unnecessary re-renders, missing memoization + +**Score 0-4**: 0=Severe issues (layout thrash, unoptimized everything), 1=Major problems (no lazy loading, expensive animations), 2=Partial (some optimization, gaps remain), 3=Good (mostly optimized, minor improvements possible), 4=Excellent (fast, lean, well-optimized) + +### 3. Theming + +**Check for**: +- **Hard-coded colors**: Colors not using design tokens +- **Broken dark mode**: Missing dark mode variants, poor contrast in dark theme +- **Inconsistent tokens**: Using wrong tokens, mixing token types +- **Theme switching issues**: Values that don't update on theme change + +**Score 0-4**: 0=No theming (hard-coded everything), 1=Minimal tokens (mostly hard-coded), 2=Partial (tokens exist but inconsistently used), 3=Good (tokens used, minor hard-coded values), 4=Excellent (full token system, dark mode works perfectly) + +### 4. Responsive Design + +**Check for**: +- **Fixed widths**: Hard-coded widths that break on mobile +- **Touch targets**: Interactive elements < 44x44px +- **Horizontal scroll**: Content overflow on narrow viewports +- **Text scaling**: Layouts that break when text size increases +- **Missing breakpoints**: No mobile/tablet variants + +**Score 0-4**: 0=Desktop-only (breaks on mobile), 1=Major issues (some breakpoints, many failures), 2=Partial (works on mobile, rough edges), 3=Good (responsive, minor touch target or overflow issues), 4=Excellent (fluid, all viewports, proper touch targets) + +### 5. Anti-Patterns (CRITICAL) + +Check against ALL the **DON'T** guidelines from the parent impeccable skill (already loaded in this context). Look for AI slop tells (AI color palette, gradient text, glassmorphism, hero metrics, card grids, generic fonts) and general design anti-patterns (gray on color, nested cards, bounce easing, redundant copy). + +**Score 0-4**: 0=AI slop gallery (5+ tells), 1=Heavy AI aesthetic (3-4 tells), 2=Some tells (1-2 noticeable), 3=Mostly clean (subtle issues only), 4=No AI tells (distinctive, intentional design) + +## Generate Report + +### Audit Health Score + +| # | Dimension | Score | Key Finding | +|---|-----------|-------|-------------| +| 1 | Accessibility | ? | [most critical a11y issue or "--"] | +| 2 | Performance | ? | | +| 3 | Responsive Design | ? | | +| 4 | Theming | ? | | +| 5 | Anti-Patterns | ? | | +| **Total** | | **??/20** | **[Rating band]** | + +**Rating bands**: 18-20 Excellent (minor polish), 14-17 Good (address weak dimensions), 10-13 Acceptable (significant work needed), 6-9 Poor (major overhaul), 0-5 Critical (fundamental issues) + +### Anti-Patterns Verdict +**Start here.** Pass/fail: Does this look AI-generated? List specific tells. Be brutally honest. + +### Executive Summary +- Audit Health Score: **??/20** ([rating band]) +- Total issues found (count by severity: P0/P1/P2/P3) +- Top 3-5 critical issues +- Recommended next steps + +### Detailed Findings by Severity + +Tag every issue with **P0-P3 severity**: +- **P0 Blocking**: Prevents task completion. Fix immediately +- **P1 Major**: Significant difficulty or WCAG AA violation. Fix before release +- **P2 Minor**: Annoyance, workaround exists. Fix in next pass +- **P3 Polish**: Nice-to-fix, no real user impact. Fix if time permits + +For each issue, document: +- **[P?] Issue name** +- **Location**: Component, file, line +- **Category**: Accessibility / Performance / Theming / Responsive / Anti-Pattern +- **Impact**: How it affects users +- **WCAG/Standard**: Which standard it violates (if applicable) +- **Recommendation**: How to fix it +- **Suggested command**: Which command to use (prefer: /impeccable adapt, /impeccable animate, /impeccable audit, /impeccable bolder, /impeccable clarify, /impeccable colorize, /impeccable critique, /impeccable delight, /impeccable distill, /impeccable document, /impeccable harden, /impeccable layout, /impeccable onboard, /impeccable optimize, /impeccable overdrive, /impeccable polish, /impeccable quieter, /impeccable shape, /impeccable typeset) + +### Patterns & Systemic Issues + +Identify recurring problems that indicate systemic gaps rather than one-off mistakes: +- "Hard-coded colors appear in 15+ components, should use design tokens" +- "Touch targets consistently too small (<44px) throughout mobile experience" + +### Positive Findings + +Note what's working well: good practices to maintain and replicate. + +## Recommended Actions + +List recommended commands in priority order (P0 first, then P1, then P2): + +1. **[P?] `/command-name`**: Brief description (specific context from audit findings) +2. **[P?] `/command-name`**: Brief description (specific context) + +**Rules**: Only recommend commands from: /impeccable adapt, /impeccable animate, /impeccable audit, /impeccable bolder, /impeccable clarify, /impeccable colorize, /impeccable critique, /impeccable delight, /impeccable distill, /impeccable document, /impeccable harden, /impeccable layout, /impeccable onboard, /impeccable optimize, /impeccable overdrive, /impeccable polish, /impeccable quieter, /impeccable shape, /impeccable typeset. Map findings to the most appropriate command. End with `/impeccable polish` as the final step if any fixes were recommended. + +After presenting the summary, tell the user: + +> You can ask me to run these one at a time, all at once, or in any order you prefer. +> +> Re-run `/impeccable audit` after fixes to see your score improve. + +**IMPORTANT**: Be thorough but actionable. Too many P3 issues creates noise. Focus on what actually matters. + +**NEVER**: +- Report issues without explaining impact (why does this matter?) +- Provide generic recommendations (be specific and actionable) +- Skip positive findings (celebrate what works) +- Forget to prioritize (everything can't be P0) +- Report false positives without verification + diff --git a/.agent/skills/impeccable/reference/bolder.md b/.agent/skills/impeccable/reference/bolder.md new file mode 100644 index 000000000..30d4e852c --- /dev/null +++ b/.agent/skills/impeccable/reference/bolder.md @@ -0,0 +1,113 @@ +When asked for "bolder," AI defaults to the same tired tricks: cyan/purple gradients, glassmorphism, neon accents on dark backgrounds, gradient text on metrics. These are the opposite of bold. Reject them first, then increase visual impact and personality through stronger hierarchy, committed scale, and decisive type. + +--- + +## Register + +Brand: "bolder" means distinctive. Extreme scale, unexpected color, typographic risk, committed POV. + +Product: "bolder" rarely means theatrics; those undermine trust. It means stronger hierarchy, clearer weight contrast, one sharper accent, more committed density. The amplification is in clarity, not drama. + +--- + +## Assess Current State + +Analyze what makes the design feel too safe or boring: + +1. **Identify weakness sources**: + - **Generic choices**: System fonts, basic colors, standard layouts + - **Timid scale**: Everything is medium-sized with no drama + - **Low contrast**: Everything has similar visual weight + - **Static**: No motion, no energy, no life + - **Predictable**: Standard patterns with no surprises + - **Flat hierarchy**: Nothing stands out or commands attention + +2. **Understand the context**: + - What's the brand personality? (How far can we push?) + - What's the purpose? (Marketing can be bolder than financial dashboards) + - Who's the audience? (What will resonate?) + - What are the constraints? (Brand guidelines, accessibility, performance) + +If any of these are unclear from the codebase, ask the user directly to clarify what you cannot infer. + +**CRITICAL**: "Bolder" doesn't mean chaotic or garish. It means distinctive, memorable, and confident. Think intentional drama, not random chaos. + +**WARNING - AI SLOP TRAP**: Review ALL the DON'T guidelines from the parent impeccable skill (already loaded in this context) before proceeding. Bold means distinctive, not "more effects." + +## Plan Amplification + +Create a strategy to increase impact while maintaining coherence: + +- **Focal point**: What should be the hero moment? (Pick ONE, make it amazing) +- **Personality direction**: Maximalist chaos? Elegant drama? Playful energy? Dark moody? Choose a lane. +- **Risk budget**: How experimental can we be? Push boundaries within constraints. +- **Hierarchy amplification**: Make big things BIGGER, small things smaller (increase contrast) + +**IMPORTANT**: Bold design must still be usable. Impact without function is just decoration. + +## Amplify the Design + +Systematically increase impact across these dimensions: + +### Typography Amplification +- **Replace generic fonts**: Swap system fonts for distinctive choices (see the parent skill's typography guidelines and the [Reference Material section of typeset.md](typeset.md#reference-material) for inspiration) +- **Extreme scale**: Create dramatic size jumps (3x-5x differences, not 1.5x) +- **Weight contrast**: Pair 900 weights with 200 weights, not 600 with 400 +- **Unexpected choices**: Variable fonts, display fonts for headlines, condensed/extended widths, monospace as intentional accent (not as lazy "dev tool" default) + +### Color Intensification +- **Increase saturation**: Shift to more vibrant, energetic colors (but not neon) +- **Bold palette**: Introduce unexpected color combinations. Avoid the purple-blue gradient AI slop +- **Dominant color strategy**: Let one bold color own 60% of the design +- **Sharp accents**: High-contrast accent colors that pop +- **Tinted neutrals**: Replace pure grays with tinted grays that harmonize with your palette +- **Rich gradients**: Intentional multi-stop gradients (not generic purple-to-blue) + +### Spatial Drama +- **Extreme scale jumps**: Make important elements 3-5x larger than surroundings +- **Break the grid**: Let hero elements escape containers and cross boundaries +- **Asymmetric layouts**: Replace centered, balanced layouts with tension-filled asymmetry +- **Generous space**: Use white space dramatically (100-200px gaps, not 20-40px) +- **Overlap**: Layer elements intentionally for depth + +### Visual Effects +- **Dramatic shadows**: Large, soft shadows for elevation (but not generic drop shadows on rounded rectangles) +- **Background treatments**: Mesh patterns, noise textures, geometric patterns, intentional gradients (not purple-to-blue) +- **Texture & depth**: Grain, halftone, duotone, layered elements. NOT glassmorphism (it's overused AI slop) +- **Borders & frames**: Thick borders, decorative frames, custom shapes (not rounded rectangles with colored border on one side) +- **Custom elements**: Illustrative elements, custom icons, decorative details that reinforce brand + +### Motion & Animation +- **Hero moment**: One signature entrance, once. Not on every visit and not on every section. +- **Micro-interactions**: Satisfying hover effects, click feedback, state changes. +- **Transitions**: Smooth, noticeable transitions using ease-out-quart/quint/expo (not bounce or elastic, which cheapen the effect). +- **Bolder ≠ scroll-fade-rise on every section.** That's the saturated AI default, the opposite of bold. + +### Composition Boldness +- **Hero moments**: Create clear focal points with dramatic treatment +- **Diagonal flows**: Escape horizontal/vertical rigidity with diagonal arrangements +- **Full-bleed elements**: Use full viewport width/height for impact +- **Unexpected proportions**: Golden ratio? Throw it out. Try 70/30, 80/20 splits + +**NEVER**: +- Add effects randomly without purpose (chaos ≠ bold) +- Sacrifice readability for aesthetics (body text must be readable) +- Make everything bold (then nothing is bold; you need contrast) +- Ignore accessibility (bold design must still meet WCAG standards) +- Overwhelm with motion (animation fatigue is real) +- Copy trendy aesthetics blindly (bold means distinctive, not derivative) + +## Verify Quality + +Ensure amplification maintains usability and coherence: + +- **NOT AI slop**: Does this look like every other AI-generated "bold" design? If yes, start over. +- **Still functional**: Can users accomplish tasks without distraction? +- **Coherent**: Does everything feel intentional and unified? +- **Memorable**: Will users remember this experience? +- **Performant**: Do all these effects run smoothly? +- **Accessible**: Does it still meet accessibility standards? + +**The test**: If you showed this to someone and said "AI made this bolder," would they believe you immediately? If yes, you've failed. Bold means distinctive, not "more AI effects." + +When the result feels right, hand off to `/impeccable polish` for the final pass. diff --git a/.agent/skills/impeccable/reference/brand.md b/.agent/skills/impeccable/reference/brand.md new file mode 100644 index 000000000..a461c5484 --- /dev/null +++ b/.agent/skills/impeccable/reference/brand.md @@ -0,0 +1,108 @@ +# Brand register + +When design IS the product: brand sites, landing pages, marketing surfaces, campaign pages, portfolios, long-form content, about pages. The deliverable is the design itself; a visitor's impression is the thing being made. + +The register spans every genre. A tech brand (Stripe, Linear, Vercel). A luxury brand (a hotel, a fashion house). A consumer product (a restaurant, a travel site, a CPG packaging page). A creative studio, an agency portfolio, a band's album page. They all share the stance (*communicate, not transact*) and diverge wildly in aesthetic. Don't collapse them into a single look. + +## The brand slop test + +If someone could look at this and say "AI made that" without hesitation, it's failed. The bar is distinctiveness; a visitor should ask "how was this made?", not "which AI made this?" + +Brand isn't a neutral register. AI-generated landing pages have flooded the internet, and average is no longer findable. Restraint without intent now reads as mediocre, not refined. Brand surfaces need a POV, a specific audience, a willingness to risk strangeness. Go big or go home. + +**The second slop test: aesthetic lane.** Before committing to moves, name the reference. A Klim-style specimen page is one lane; Stripe-minimal is another; Liquid-Death-acid-maximalism is another. Don't drift into editorial-magazine aesthetics on a brief that isn't editorial. A hiking brand with Cormorant italic drop caps has the wrong register within the register. + +Then the inverse test: in one sentence, describe what you're about to build the way a competitor would describe theirs. If that sentence fits the modal landing page in the category, restart. + +## Typography + +### Font selection procedure + +Every project. Never skip. + +1. Read the brief. Write three concrete brand-voice words. Not "modern" or "elegant," but "warm and mechanical and opinionated" or "calm and clinical and careful." Physical-object words. +2. List the three fonts you'd reach for by reflex. If any appear in the reflex-reject list below, reject them; they are training-data defaults and they create monoculture. +3. Browse a real catalog (Google Fonts, Pangram Pangram, Future Fonts, Adobe Fonts, ABC Dinamo, Klim, Velvetyne) with the three words in mind. Find the font for the brand as a *physical object*: a museum caption, a 1970s terminal manual, a fabric label, a cheap-newsprint children's book, a concert poster, a receipt from a mid-century diner. Reject the first thing that "looks designy." +4. Cross-check. "Elegant" is not necessarily serif. "Technical" is not necessarily sans. "Warm" is not Fraunces. If the final pick lines up with the original reflex, start over. + +### Reflex-reject list + +Training-data defaults. Ban list. Look further: + +Fraunces · Newsreader · Lora · Crimson · Crimson Pro · Crimson Text · Playfair Display · Cormorant · Cormorant Garamond · Syne · IBM Plex Mono · IBM Plex Sans · IBM Plex Serif · Space Mono · Space Grotesk · Inter · DM Sans · DM Serif Display · DM Serif Text · Outfit · Plus Jakarta Sans · Instrument Sans · Instrument Serif + +### Reflex-reject aesthetic lanes + +Parallel to the font list. Currently saturated aesthetic families that have flooded brand surfaces. If a brief lands in one of these lanes without a register reason that *requires* it (a literal magazine, a literal terminal, a literal industrial signage system), it's the second-order training reflex: the trap one tier deeper than picking a Fraunces font. Look further. + +- **Editorial-typographic.** Display serif (often italic) + small mono labels + ruled separators + monochromatic restraint. Klim-influenced, magazine-cover affectation. By 2026, every Stripe-adjacent and Notion-adjacent brand has landed here. The fingerprint: three rule-separated columns, an italic Fraunces / Recoleta / Newsreader headline, lowercase track-spaced metadata, no imagery. + +(More entries land here on the same cadence the font list updates. Brutalist-utility and acid-maximalism may join when they saturate. Removing entries when they fall back below saturation is also fine.) + +The reflex-reject lists apply to **new design choices**. When the existing brand has already committed to a font or a lane as part of its identity, identity-preservation wins; variants on an existing surface don't second-guess what's already shipping. The reflex-reject lists are for greenfield decisions and for departure-mode variants in [live.md](live.md). + +### Pairing and voice + +Distinctive + refined is the goal. The specific shape depends on the brand, not on the brand's category. A category ("restaurant", "dev tool", "magazine", "fintech") is not a recipe; treating it as one is the first-order reflex SKILL.md warns against. + +Two families minimum is the rule *only* when the voice needs it. A single well-chosen family with committed weight/size contrast is stronger than a timid display+body pair. + +### Scale + +Modular scale, fluid `clamp()` for headings, ≥1.25 ratio between steps. Flat scales (1.1× apart) read as uncommitted. + +Light text on dark backgrounds: add 0.05–0.1 to line-height. Light type reads as lighter weight and needs more breathing room. + +## Color + +Brand surfaces have permission for Committed, Full palette, and Drenched strategies. Use them. A single saturated color spread across a hero is not excess; it's voice. A beige-and-muted-slate landing page ignores the register. + +- Name a real reference before picking a strategy. "Klim Type Foundry #ff4500 orange drench", "Stripe purple-on-white restraint", "Liquid Death acid-green full palette", "Mailchimp yellow full palette", "Condé Nast Traveler muted navy restraint", "Vercel pure black monochrome". Unnamed ambition becomes beige. +- Palette IS voice. A calm brand and a restless brand should not share palette mechanics. +- When the strategy is Committed or Drenched, color carries the brand. Don't hedge with neutrals around the edges. Commit. +- Don't converge across projects. Each brand surface differentiates from the last. +- When a cultural-symbol palette is the obvious pull, reach past it. Let the cultural reading come from typography, imagery, and copy, not the palette. + +## Layout + +- Asymmetric compositions are one option. Break the grid intentionally for emphasis. +- Fluid spacing with `clamp()` that breathes on larger viewports. Vary for rhythm: generous separations, tight groupings. +- For image-led briefs (hotels, restaurants, magazines, photography), full-bleed hero imagery with overlaid menu and centered headline is a canonical move; let the photograph be the design. +- When cards ARE the right affordance, use `grid-template-columns: repeat(auto-fit, minmax(280px, 1fr))` for breakpoint-free responsiveness. + +## Imagery + +Brand surfaces lean on imagery. A restaurant, hotel, magazine, or product landing page without any imagery reads as incomplete, not as restrained. A solid-color rectangle where a hero image should go is worse than a representative stock photo. + +**When the brief implies imagery, you must ship imagery.** Zero images is a bug, not a design choice. "Restraint" is not an excuse. If the approved comp or brief is image-led, ship real project assets, generated raster assets, or a credible canvas/SVG/WebGL scene. Do not replace photographic, architectural, product, or place imagery with generic CSS panels, decorative diagrams, cards, bullets, or copy. + +- **For greenfield work without local assets, use stock imagery.** Unsplash is the default. The URL shape is `https://images.unsplash.com/photo-{id}?auto=format&fit=crop&w=1600&q=80`. **Verify the URLs before referencing them.** If you have an image-search MCP, web-fetch tool, or browser access, use it to find real photo IDs and confirm they resolve. Guessed IDs (even ones that look real) often 404 and ship as broken-image placeholders. Without a verification path, pick fewer photos you're confident exist over more that you guessed; never substitute colored `
` placeholders. +- **Search for the brand's physical object**, not the generic category: "handmade pasta on a scratched wooden table" beats "Italian food"; "cypress trees above a limestone hotel facade at dusk" beats "luxury hotel". +- **One decisive photo beats five mediocre ones.** Hero imagery should commit to a mood; padding with more stock doesn't rescue an indecisive one. +- **Alt text is part of the voice.** "Coastal fettuccine, hand-cut, served on the terrace" beats "pasta dish". + +"Imagery" here is broader than stock photography: product screenshots, custom data visualizations, generated SVG, and canvas/WebGL scenes are all imagery. Text-only pages where typography alone carries the entire visual weight are the failure mode. + +## Motion + +- One well-orchestrated page-load beats scattered micro-interactions, when the brand invites it. Some brands skip entrance motion entirely; the restraint is the voice. + +## Brand bans (on top of the shared absolute bans) + +- Monospace as lazy shorthand for "technical / developer." If the brand isn't technical, mono reads as costume. +- Large rounded-corner icons above every heading. Screams template. +- Single-family pages that picked the family by reflex, not voice. (A single family chosen deliberately is fine.) +- All-caps body copy. Reserve caps for short labels and headings. +- Timid palettes and average layouts. Safe = invisible. +- Zero imagery on a brief that implies imagery (restaurant, hotel, food, travel, fashion, photography, hobbyist). Colored blocks where a hero photo belongs. +- Defaulting to editorial-magazine aesthetics (display serif + italic + drop caps + broadsheet grid) on briefs that aren't magazine-shaped. Editorial is ONE aesthetic lane, not the default brand aesthetic. +- Repeated tiny uppercase tracked labels above every section heading. A single strong kicker can be voice; repeating it as section grammar is AI scaffolding unless it's a deliberate, named brand system. + +## Brand permissions + +Brand can afford things product can't. Take them. + +- Ambitious first-load motion. Reveals and typographic choreography that earn their place; not fade-on-scroll for every section. +- Single-purpose viewports. One dominant idea per fold, long scroll, deliberate pacing. +- Unexpected color strategies. Palette IS voice; a calm brand and a restless brand should not share palette mechanics. +- Art direction per section. Different sections can have different visual worlds if the narrative demands it. Consistency of voice beats consistency of treatment. diff --git a/.agent/skills/impeccable/reference/clarify.md b/.agent/skills/impeccable/reference/clarify.md new file mode 100644 index 000000000..00ee978c3 --- /dev/null +++ b/.agent/skills/impeccable/reference/clarify.md @@ -0,0 +1,288 @@ +> **Additional context needed**: audience technical level and users' mental state in context. + +Find the unclear, confusing, or poorly written interface text and rewrite it. Vague copy creates support tickets and abandonment; specific copy gets users through the task. + + +--- + +## Assess Current Copy + +Identify what makes the text unclear or ineffective: + +1. **Find clarity problems**: + - **Jargon**: Technical terms users won't understand + - **Ambiguity**: Multiple interpretations possible + - **Passive voice**: "Your file has been uploaded" vs "We uploaded your file" + - **Length**: Too wordy or too terse + - **Assumptions**: Assuming user knowledge they don't have + - **Missing context**: Users don't know what to do or why + - **Tone mismatch**: Too formal, too casual, or inappropriate for situation + +2. **Understand the context**: + - Who's the audience? (Technical? General? First-time users?) + - What's the user's mental state? (Stressed during error? Confident during success?) + - What's the action? (What do we want users to do?) + - What's the constraint? (Character limits? Space limitations?) + +**CRITICAL**: Clear copy helps users succeed. Unclear copy creates frustration, errors, and support tickets. + +## Plan Copy Improvements + +Create a strategy for clearer communication: + +- **Primary message**: What's the ONE thing users need to know? +- **Action needed**: What should users do next (if anything)? +- **Tone**: How should this feel? (Helpful? Apologetic? Encouraging?) +- **Constraints**: Length limits, brand voice, localization considerations + +**IMPORTANT**: Good UX writing is invisible. Users should understand immediately without noticing the words. + +## Improve Copy Systematically + +Refine text across these common areas: + +### Error Messages +**Bad**: "Error 403: Forbidden" +**Good**: "You don't have permission to view this page. Contact your admin for access." + +**Bad**: "Invalid input" +**Good**: "Email addresses need an @ symbol. Try: name@example.com" + +**Principles**: +- Explain what went wrong in plain language +- Suggest how to fix it +- Don't blame the user +- Include examples when helpful +- Link to help/support if applicable + +### Form Labels & Instructions +**Bad**: "DOB (MM/DD/YYYY)" +**Good**: "Date of birth" (with placeholder showing format) + +**Bad**: "Enter value here" +**Good**: "Your email address" or "Company name" + +**Principles**: +- Use clear, specific labels (not generic placeholders) +- Show format expectations with examples +- Explain why you're asking (when not obvious) +- Put instructions before the field, not after +- Keep required field indicators clear + +### Button & CTA Text +**Bad**: "Click here" | "Submit" | "OK" +**Good**: "Create account" | "Save changes" | "Got it, thanks" + +**Principles**: +- Describe the action specifically +- Use active voice (verb + noun) +- Match user's mental model +- Be specific ("Save" is better than "OK") + +### Help Text & Tooltips +**Bad**: "This is the username field" +**Good**: "Choose a username. You can change this later in Settings." + +**Principles**: +- Add value (don't just repeat the label) +- Answer the implicit question ("What is this?" or "Why do you need this?") +- Keep it brief but complete +- Link to detailed docs if needed + +### Empty States +**Bad**: "No items" +**Good**: "No projects yet. Create your first project to get started." + +**Principles**: +- Explain why it's empty (if not obvious) +- Show next action clearly +- Make it welcoming, not dead-end + +### Success Messages +**Bad**: "Success" +**Good**: "Settings saved! Your changes will take effect immediately." + +**Principles**: +- Confirm what happened +- Explain what happens next (if relevant) +- Be brief but complete +- Match the user's emotional moment (celebrate big wins) + +### Loading States +**Bad**: "Loading..." (for 30+ seconds) +**Good**: "Analyzing your data... this usually takes 30-60 seconds" + +**Principles**: +- Set expectations (how long?) +- Explain what's happening (when it's not obvious) +- Show progress when possible +- Offer escape hatch if appropriate ("Cancel") + +### Confirmation Dialogs +**Bad**: "Are you sure?" +**Good**: "Delete 'Project Alpha'? This can't be undone." + +**Principles**: +- State the specific action +- Explain consequences (especially for destructive actions) +- Use clear button labels ("Delete project" not "Yes") +- Don't overuse confirmations (only for risky actions) + +### Navigation & Wayfinding +**Bad**: Generic labels like "Items" | "Things" | "Stuff" +**Good**: Specific labels like "Your projects" | "Team members" | "Settings" + +**Principles**: +- Be specific and descriptive +- Use language users understand (not internal jargon) +- Make hierarchy clear +- Consider information scent (breadcrumbs, current location) + +## Apply Clarity Principles + +Every piece of copy should follow these rules: + +1. **Be specific**: "Enter email" not "Enter value" +2. **Be concise**: Cut unnecessary words (but don't sacrifice clarity) +3. **Be active**: "Save changes" not "Changes will be saved" +4. **Be human**: "Oops, something went wrong" not "System error encountered" +5. **Tell users what to do**, not just what happened +6. **Be consistent**: Use same terms throughout (don't vary for variety) + +**NEVER**: +- Use jargon without explanation +- Blame users ("You made an error" → "This field is required") +- Be vague ("Something went wrong" without explanation) +- Use passive voice unnecessarily +- Write overly long explanations (be concise) +- Use humor for errors (be empathetic instead) +- Assume technical knowledge +- Vary terminology (pick one term and stick with it) +- Repeat information (headers restating intros, redundant explanations) +- Use placeholders as the only labels (they disappear when users type) + +## Verify Improvements + +Test that copy improvements work: + +- **Comprehension**: Can users understand without context? +- **Actionability**: Do users know what to do next? +- **Brevity**: Is it as short as possible while remaining clear? +- **Consistency**: Does it match terminology elsewhere? +- **Tone**: Is it appropriate for the situation? + +When the copy reads cleanly, hand off to `/impeccable polish` for the final pass. + +--- + +## Reference Material + +The sections below were previously `ux-writing.md` and live inline now so the clarify flow has its deep UX-writing reference in one place. + +### UX Writing + +#### The Button Label Problem + +**Never use "OK", "Submit", or "Yes/No".** These are lazy and ambiguous. Use specific verb + object patterns: + +| Bad | Good | Why | +|-----|------|-----| +| OK | Save changes | Says what will happen | +| Submit | Create account | Outcome-focused | +| Yes | Delete message | Confirms the action | +| Cancel | Keep editing | Clarifies what "cancel" means | +| Click here | Download PDF | Describes the destination | + +**For destructive actions**, name the destruction: +- "Delete" not "Remove" (delete is permanent, remove implies recoverable) +- "Delete 5 items" not "Delete selected" (show the count) + +#### Error Messages: The Formula + +Every error message should answer: (1) What happened? (2) Why? (3) How to fix it? Example: "Email address isn't valid. Please include an @ symbol." not "Invalid input". + +##### Error Message Templates + +| Situation | Template | +|-----------|----------| +| **Format error** | "[Field] needs to be [format]. Example: [example]" | +| **Missing required** | "Please enter [what's missing]" | +| **Permission denied** | "You don't have access to [thing]. [What to do instead]" | +| **Network error** | "We couldn't reach [thing]. Check your connection and [action]." | +| **Server error** | "Something went wrong on our end. We're looking into it. [Alternative action]" | + +##### Don't Blame the User + +Reframe errors: "Please enter a date in MM/DD/YYYY format" not "You entered an invalid date". + +#### Empty States Are Opportunities + +Empty states are onboarding moments: (1) Acknowledge briefly, (2) Explain the value of filling it, (3) Provide a clear action. "No projects yet. Create your first one to get started." not just "No items". + +#### Voice vs Tone + +**Voice** is your brand's personality, consistent everywhere. +**Tone** adapts to the moment. + +| Moment | Tone Shift | +|--------|------------| +| Success | Celebratory, brief: "Done! Your changes are live." | +| Error | Empathetic, helpful: "That didn't work. Here's what to try..." | +| Loading | Reassuring: "Saving your work..." | +| Destructive confirm | Serious, clear: "Delete this project? This can't be undone." | + +**Never use humor for errors.** Users are already frustrated. Be helpful, not cute. + +#### Writing for Accessibility + +**Link text** must have standalone meaning: "View pricing plans" not "Click here". **Alt text** describes information, not the image: "Revenue increased 40% in Q4" not "Chart". Use `alt=""` for decorative images. **Icon buttons** need `aria-label` for screen reader context. + +#### Writing for Translation + +##### Plan for Expansion + +German text is ~30% longer than English. Allocate space: + +| Language | Expansion | +|----------|-----------| +| German | +30% | +| French | +20% | +| Finnish | +30-40% | +| Chinese | -30% (fewer chars, but same width) | + +##### Translation-Friendly Patterns + +Keep numbers separate ("New messages: 3" not "You have 3 new messages"). Use full sentences as single strings (word order varies by language). Avoid abbreviations ("5 minutes ago" not "5 mins ago"). Give translators context about where strings appear. + +#### Consistency: The Terminology Problem + +Pick one term and stick with it: + +| Inconsistent | Consistent | +|--------------|------------| +| Delete / Remove / Trash | Delete | +| Settings / Preferences / Options | Settings | +| Sign in / Log in / Enter | Sign in | +| Create / Add / New | Create | + +Build a terminology glossary and enforce it. Variety creates confusion. + +#### Avoid Redundant Copy + +If the heading explains it, the intro is redundant. If the button is clear, don't explain it again. Say it once, say it well. + +#### Loading States + +Be specific: "Saving your draft..." not "Loading...". For long waits, set expectations ("This usually takes 30 seconds") or show progress. + +#### Confirmation Dialogs: Use Sparingly + +Most confirmation dialogs are design failures; consider undo instead. When you must confirm: name the action, explain consequences, use specific button labels ("Delete project" / "Keep project", not "Yes" / "No"). + +#### Form Instructions + +Show format with placeholders, not instructions. For non-obvious fields, explain why you're asking. + +--- + +**Avoid**: Jargon without explanation. Blaming users ("You made an error" → "This field is required"). Vague errors ("Something went wrong"). Varying terminology for variety. Humor for errors. diff --git a/.agent/skills/impeccable/reference/codex.md b/.agent/skills/impeccable/reference/codex.md new file mode 100644 index 000000000..d563af95b --- /dev/null +++ b/.agent/skills/impeccable/reference/codex.md @@ -0,0 +1,105 @@ +# Codex: Visual Direction & Asset Production + +This file is loaded by `/impeccable craft` when the harness has native image generation (currently Codex via `image_gen`). Other harnesses skip it. It covers the two craft steps that depend on real image generation: landing the visual direction, and producing the raster assets the implementation will compose. + +Read this *before* generating any images. The order matters, and the per-step user pauses are what keep generated imagery from drifting away from the brief. + +### Four stop points before code + +Steps A through D each end with the user. Do not advance past any of them on your own read of the situation. + +1. **STOP after Step A questions.** Wait for answers. +2. **STOP after Step B palette generation.** Wait for "confirm palette." +3. **STOP after Step C mocks.** Wait for direction approval or delegation. +4. **Only after Step D approves a direction** do you return to craft.md Step 4 and write code. + +Prior shape approval does **not** satisfy any of these. Shape's "confirm or override" advances you into Step A; it is not a substitute for it. + +## Step A: Explore Directions with the User + +Before generating anything, run a brief direction conversation grounded in the shape brief. + +**Step A is required even when shape just produced a confirmed brief.** The shape questions and Step A questions cover different ground: shape pins purpose, content, scope; Step A pins palette, atmosphere, and named visual references for the comps you're about to generate. The only time you can skip Step A is when the user has already answered these exact palette/atmosphere/reference questions in the same session. + +Ask **2-3 targeted questions** about visual lane, color strategy, atmosphere, and named anchor references. Don't enumerate generic menus; tie each question to the shape brief's answers. Example shape-grounded questions: + +- "Brief says 'specimen-page restraint.' Are we closer to a quiet typographic page or a wider editorial spread with hero imagery?" +- "Palette strategy from shape was 'Committed.' Which one color carries the surface (a brand-driven pick rather than a default warm-or-cool framing)? (And no, the answer isn't a cream/sand body bg; that's the saturated AI default.)" + +**STOP and wait for answers.** These pin the palette before any pixel gets generated. Do not proceed to Step B until the user has responded. + +## Step B: Generate the Brand Palette First + +Generate **one** palette artifact before any mocks. This is a small, focused image: typography pairing on the chosen background, primary + accent color swatches, one signature ornament or motif. Single image, single pass. + +Why palette first: mocks generated against a vague color sense produce noise that drowns out the structural decisions. A confirmed palette is the first concrete contract for everything downstream. + +Show the palette to the user. Ask one question: "This is the palette I'm locking in for the mocks. Confirm, or call out what to shift?" + +**STOP and wait for confirmation.** Do not generate mocks against an unconfirmed palette. "Probably good enough" is the wrong call here; the palette is the contract for everything downstream. + +## Step C: Generate 1-3 Visual Mocks Against the Palette + +Once the palette is confirmed, generate **1 to 3** high-fidelity north-star comps. Each mock must use the confirmed palette and typography. Mocks differ in *structural* direction (hierarchy, topology, density, composition), not in color or motif. + +- Brand work: push visual identity, composition, mood, and signature motifs. +- Product work: push hierarchy, topology, density, tone, grounded in realistic product structure. +- Landing pages and long-form brand surfaces: show enough of the second fold to establish the system beyond the hero. + +Use the `image_gen` tool directly (or via the imagegen skill when available). Don't ask the user to install anything. + +## Step D: Approval Loop + +Show the comps. Ask what carries forward. Iterate until **one direction is approved** or the user explicitly delegates. + +**STOP and wait for the approval or the delegation.** Do not begin Step E or return to craft.md Step 4 until a single direction is named. If the user delegates, pick the strongest direction and explain it from the brief, not personal taste. + +Before moving to assets, summarize what to carry into code and what *not* to literalize from the mock. This is the handoff between visual exploration and semantic implementation. + +## Step E: Mock Fidelity Inventory + +Inventory the approved mock's major visible ingredients. For each, decide implementation: semantic HTML/CSS/SVG, generated raster, sourced raster, icon library, canvas/WebGL, or accepted omission. + +Common ingredients to inventory: + +- Hero silhouette and dominant composition +- Signature motifs (planets, devices, portraits, charts, route lines, insets, badges, etc.) +- Nav and primary CTA treatment +- Section sequence, especially the second fold +- Image-native content the concept depends on +- Typography, density, color/material treatment, motion cues + +Treat the mock as a north star, not a screenshot to trace. Don't rasterize core UI text. But if the live result lacks the mock's major ingredients, the implementation is wrong. + +If a photographic, architectural, product, or place-led mock becomes generic CSS scenery, decorative diagrams, bullets, or copy, stop and fix it. That's a broken implementation, not a harmless interpretation. + +Don't substitute a different hero composition or visual driver post-approval without user sign-off. + +## Step F: Asset Slicing via the Asset Producer + +Raster ingredients identified in Step E need clean production assets. Use the bundled `impeccable_asset_producer` subagent rather than producing inline. + +Spawn it as a scoped subagent. If you do not have explicit permission to use agents, stop and ask: + +```text +Asset production will work better as a scoped subagent job. Should I spawn the Impeccable asset producer subagent for this step? +``` + +Pass to the agent: + +- Approved mock path or screenshot reference +- Crop paths or a contact sheet with crop ids +- Output directory +- Required dimensions, format, transparency needs +- Avoid list +- Notes on what should remain semantic HTML/CSS/SVG instead of raster + +Attach image generation capability to the spawned agent when the harness supports it. Do **not** load image-generation reference material into the parent thread. + +Inline asset production is allowed only if the user declines subagents, the harness cannot spawn the authorized agent, or the user explicitly asks for single-thread mode. + +Prefer HTML/CSS/SVG/canvas when they can credibly reproduce an ingredient; reach for real, generated, or stock imagery when the mock or subject matter calls for actual visual content. + +## After This File + +Once Steps A through F are complete, return to `craft.md` Step 5 (Build to Production Quality). The implementation builds against the confirmed palette, approved mock, and the assets the producer wrote. diff --git a/.agent/skills/impeccable/reference/colorize.md b/.agent/skills/impeccable/reference/colorize.md new file mode 100644 index 000000000..2457f608c --- /dev/null +++ b/.agent/skills/impeccable/reference/colorize.md @@ -0,0 +1,257 @@ +> **Additional context needed**: existing brand colors. + +Replace timid grayscale or single-accent designs with a strategic palette: pick a color strategy, choose a hue family that fits the brand, then apply color with intent. More color ≠ better. Strategic color beats rainbow vomit. + +--- + +## Register + +Brand: palette IS voice. Pick a color strategy first per SKILL.md (Restrained / Committed / Full palette / Drenched) and follow its dosage. Committed, Full palette, and Drenched deliberately exceed the ≤10% rule; that rule is Restrained only. Unexpected combinations are allowed; a dominant color can own the page when the chosen strategy calls for it. + +Product: semantic-first and almost always Restrained. Accent color is reserved for primary action, current selection, and state indicators. Not decoration. Every color has a consistent meaning across every screen. + +--- + +## Assess Color Opportunity + +Analyze the current state and identify opportunities: + +1. **Understand current state**: + - **Color absence**: Pure grayscale? Limited neutrals? One timid accent? + - **Missed opportunities**: Where could color add meaning, hierarchy, or delight? + - **Context**: What's appropriate for this domain and audience? + - **Brand**: Are there existing brand colors we should use? + +2. **Identify where color adds value**: + - **Semantic meaning**: Success (green), error (red), warning (yellow/orange), info (blue) + - **Hierarchy**: Drawing attention to important elements + - **Categorization**: Different sections, types, or states + - **Emotional tone**: Warmth, energy, trust, creativity + - **Wayfinding**: Helping users navigate and understand structure + - **Delight**: Moments of visual interest and personality + +If any of these are unclear from the codebase, ask the user directly to clarify what you cannot infer. + +**CRITICAL**: More color ≠ better. Strategic color beats rainbow vomit every time. Every color should have a purpose. + +## Plan Color Strategy + +Create a purposeful color introduction plan: + +- **Color palette**: What colors match the brand/context? (Choose 2-4 colors max beyond neutrals) +- **Dominant color**: Which color owns 60% of colored elements? +- **Accent colors**: Which colors provide contrast and highlights? (30% and 10%) +- **Application strategy**: Where does each color appear and why? + +**IMPORTANT**: Color should enhance hierarchy and meaning, not create chaos. Less is more when it matters more. + +## Introduce Color Strategically + +Add color systematically across these dimensions: + +### Semantic Color +- **State indicators**: + - Success: Green tones (emerald, forest, mint) + - Error: Red/pink tones (rose, crimson, coral) + - Warning: Orange/amber tones + - Info: Blue tones (sky, ocean, indigo) + - Neutral: Gray/slate for inactive states + +- **Status badges**: Colored backgrounds or borders for states (active, pending, completed, etc.) +- **Progress indicators**: Colored bars, rings, or charts showing completion or health + +### Accent Color Application +- **Primary actions**: Color the most important buttons/CTAs +- **Links**: Add color to clickable text (maintain accessibility) +- **Icons**: Colorize key icons for recognition and personality +- **Headers/titles**: Add color to section headers or key labels +- **Hover states**: Introduce color on interaction + +### Background & Surfaces +- **Tinted backgrounds**: If you replace pure gray, tint toward the brand hue, not toward a generic-warm-or-cool pair. The default-warm-tint (`oklch(97% 0.01 60)` and its neighbors) is now the AI cream/sand giveaway. Be specific to the brand or stay neutral. +- **Colored sections**: Use subtle background colors to separate areas +- **Gradient backgrounds**: Add depth with subtle, intentional gradients (not generic purple-blue) +- **Cards & surfaces**: Tint cards or surfaces toward the brand, not "for warmth" by reflex + +**Use OKLCH for color**: It's perceptually uniform, meaning equal steps in lightness *look* equal. Great for generating harmonious scales. + +### Data Visualization +- **Charts & graphs**: Use color to encode categories or values +- **Heatmaps**: Color intensity shows density or importance +- **Comparison**: Color coding for different datasets or timeframes + +### Borders & Accents +- **Hairline borders**: 1px colored borders on full perimeter (not side-stripes; see the absolute ban on `border-left/right > 1px`) +- **Underlines**: Color underlines for emphasis or active states +- **Dividers**: Subtle colored dividers instead of gray lines +- **Focus rings**: Colored focus indicators matching brand +- **Surface tints**: A 4-8% background wash of the accent color instead of a stripe + +**NEVER**: `border-left` or `border-right` greater than 1px as a colored accent stripe. This is one of the three absolute bans in the parent skill. If you want to mark a card as "active" or "warning", use a full hairline border, a background tint, a leading glyph, or a numbered prefix. Not a side stripe. + +### Typography Color +- **Colored headings**: Use brand colors for section headings (maintain contrast) +- **Highlight text**: Color for emphasis or categories +- **Labels & tags**: Small colored labels for metadata or categories + +### Decorative Elements +- **Illustrations**: Add colored illustrations or icons +- **Shapes**: Geometric shapes in brand colors as background elements +- **Gradients**: Colorful gradient overlays or mesh backgrounds +- **Blobs/organic shapes**: Soft colored shapes for visual interest + +## Balance & Refinement + +Ensure color addition improves rather than overwhelms: + +### Maintain Hierarchy +- **Dominant color** (60%): Primary brand color or most used accent +- **Secondary color** (30%): Supporting color for variety +- **Accent color** (10%): High contrast for key moments +- **Neutrals** (remaining): Gray/black/white for structure + +### Accessibility +- **Contrast ratios**: Ensure WCAG compliance (4.5:1 for text, 3:1 for UI components) +- **Don't rely on color alone**: Use icons, labels, or patterns alongside color +- **Test for color blindness**: Verify red/green combinations work for all users + +### Cohesion +- **Consistent palette**: Use colors from defined palette, not arbitrary choices +- **Systematic application**: Same color meanings throughout (green always = success) +- **Temperature consistency**: Warm palette stays warm, cool stays cool + +**NEVER**: +- Use every color in the rainbow (choose 2-4 colors beyond neutrals) +- Apply color randomly without semantic meaning +- Put gray text on colored backgrounds. It looks washed out; use a darker shade of the background color or transparency instead +- Violate WCAG contrast requirements +- Use color as the only indicator (accessibility issue) +- Make everything colorful (defeats the purpose) +- Default to purple-blue gradients (AI slop aesthetic) + +## Verify Color Addition + +Test that colorization improves the experience: + +- **Better hierarchy**: Does color guide attention appropriately? +- **Clearer meaning**: Does color help users understand states/categories? +- **More engaging**: Does the interface feel warmer and more inviting? +- **Still accessible**: Do all color combinations meet WCAG standards? +- **Not overwhelming**: Is color balanced and purposeful? + +When the palette earns its place, hand off to `/impeccable polish` for the final pass. + +## Live-mode signature params + +When invoked from live mode, each variant MUST declare a `color-amount` param so the user can dial between a restrained accent and a drenched surface without regeneration. Author the variant's CSS against `var(--p-color-amount, 0.5)`, typically as the alpha multiplier on backgrounds, or as a scaling factor on the chroma axis in an OKLCH expression. 0 = neutral/monochrome, 1 = full saturation / dominant coverage. + +```json +{"id":"color-amount","kind":"range","min":0,"max":1,"step":0.05,"default":0.5,"label":"Color amount"} +``` + +Layer 1-2 variant-specific params on top: palette selection (`steps` with named options), temperature warmth, or tint vs. true color. See `reference/live.md` for the full params contract. + +--- + +## Reference Material + +The sections below were previously `color-and-contrast.md` and live inline now so the colorize flow has its deep color reference in one place. + +### Color & Contrast + +#### Color Spaces: Use OKLCH + +**Stop using HSL.** Use OKLCH (or LCH) instead. It's perceptually uniform, meaning equal steps in lightness *look* equal, unlike HSL where 50% lightness in yellow looks bright while 50% in blue looks dark. + +The OKLCH function takes three components: `oklch(lightness chroma hue)` where lightness is 0-100%, chroma is roughly 0-0.4, and hue is 0-360. To build a primary color and its lighter / darker variants, hold the chroma+hue roughly constant and vary the lightness, but **reduce chroma as you approach white or black**, because high chroma at extreme lightness looks garish. + +The hue you pick is a brand decision and should not come from a default. Do not reach for blue (hue 250) or warm orange (hue 60) by reflex; those are the dominant AI-design defaults, not the right answer for any specific brand. + +#### Building Functional Palettes + +##### Tinted Neutrals + +**Pure gray is dead.** A neutral with zero chroma feels lifeless next to a colored brand. Add a tiny chroma value (0.005-0.015) to all your neutrals, hued toward whatever your brand color is. The chroma is small enough not to read as "tinted" consciously, but it creates subconscious cohesion between brand color and UI surfaces. + +The hue you tint toward should come from THIS project's brand, not from a "warm = friendly, cool = tech" formula. If your brand color is teal, your neutrals lean toward teal. If your brand color is amber, they lean toward amber. The point is cohesion with the SPECIFIC brand, not a stock palette. + +**Avoid** the trap of always tinting toward warm orange or always tinting toward cool blue. Those are the two laziest defaults and they create their own monoculture across projects. + +##### Palette Structure + +A complete system needs: + +| Role | Purpose | Example | +|------|---------|---------| +| **Primary** | Brand, CTAs, key actions | 1 color, 3-5 shades | +| **Neutral** | Text, backgrounds, borders | 9-11 shade scale | +| **Semantic** | Success, error, warning, info | 4 colors, 2-3 shades each | +| **Surface** | Cards, modals, overlays | 2-3 elevation levels | + +**Skip secondary/tertiary unless you need them.** Most apps work fine with one accent color. Adding more creates decision fatigue and visual noise. + +##### The 60-30-10 Rule (Applied Correctly) + +This rule is about **visual weight**, not pixel count: + +- **60%**: Neutral backgrounds, white space, base surfaces +- **30%**: Secondary colors: text, borders, inactive states +- **10%**: Accent: CTAs, highlights, focus states + +The common mistake: using the accent color everywhere because it's "the brand color." Accent colors work *because* they're rare. Overuse kills their power. + +#### Contrast & Accessibility + +##### WCAG Requirements + +| Content Type | AA Minimum | AAA Target | +|--------------|------------|------------| +| Body text | 4.5:1 | 7:1 | +| Large text (18px+ or 14px bold) | 3:1 | 4.5:1 | +| UI components, icons | 3:1 | 4.5:1 | +| Non-essential decorations | None | None | + +##### Dangerous Color Combinations + +These commonly fail contrast or cause readability issues: + +- Light gray text on white (the #1 accessibility fail) +- Red text on green background (or vice versa): 8% of men can't distinguish these +- Blue text on red background (vibrates visually) +- Yellow text on white (almost always fails) +- Thin light text on images (unpredictable contrast) + +##### Testing + +Don't trust your eyes. Use tools: + +- [WebAIM Contrast Checker](https://webaim.org/resources/contrastchecker/) +- Browser DevTools → Rendering → Emulate vision deficiencies +- [Polypane](https://polypane.app/) for real-time testing + +#### Theming: Light & Dark Mode + +##### Dark Mode Is Not Inverted Light Mode + +You can't just swap colors. Dark mode requires different design decisions: + +| Light Mode | Dark Mode | +|------------|-----------| +| Shadows for depth | Lighter surfaces for depth (no shadows) | +| Dark text on light | Light text on dark (reduce font weight) | +| Vibrant accents | Desaturate accents slightly | +| White backgrounds | Either pure black or a deep surface that fits the brand (a brand-tinted near-black at oklch 12-18% works too) | + +In dark mode, depth comes from surface lightness, not shadow. Build a 3-step surface scale where higher elevations are lighter (e.g. 15% / 20% / 25% lightness). Use the SAME hue and chroma as your brand color (whatever it is for THIS project; do not reach for blue) and only vary the lightness. Reduce body text weight slightly (e.g. 350 instead of 400) because light text on dark reads as heavier than dark text on light. + +##### Token Hierarchy + +Use two layers: primitive tokens (`--blue-500`) and semantic tokens (`--color-primary: var(--blue-500)`). For dark mode, only redefine the semantic layer; primitives stay the same. + +#### Alpha Is A Design Smell + +Heavy use of transparency (rgba, hsla) usually means an incomplete palette. Alpha creates unpredictable contrast, performance overhead, and inconsistency. Define explicit overlay colors for each context instead. Exception: focus rings and interactive states where see-through is needed. + +--- + +**Avoid**: Relying on color alone to convey information. Creating palettes without clear roles for each color. Skipping color blindness testing (8% of men affected). diff --git a/.agent/skills/impeccable/reference/craft.md b/.agent/skills/impeccable/reference/craft.md new file mode 100644 index 000000000..2c7bd99b1 --- /dev/null +++ b/.agent/skills/impeccable/reference/craft.md @@ -0,0 +1,123 @@ +# Craft Flow + +Build a feature with impeccable UX and UI quality: shape the design, land the visual direction, build real production code, inspect and improve in-browser until it meets a high-end studio bar. + +Before writing code, you need: PRODUCT.md loaded, register identified and the matching reference loaded, and a confirmed design direction for this task (either from `shape` or supplied by the user). PRODUCT.md is project context, not a task-specific brief. + +Treat any approved visual direction (generated mock or stated reference) as a concrete contract for composition, hierarchy, density, atmosphere, signature motifs, and distinctive visual moves. Don't let mocks replace structure, copy, accessibility, or state design. But if the live result lacks the approved direction's major ingredients, the implementation is wrong. + +### Gates: do not compress + +Craft has **multiple user gates**, not one. When the harness has native image generation (Codex via `image_gen`), the gate sequence before code is: + +1. **Shape brief confirmed** (Step 1) +2. **Direction questions answered** (codex.md Step A) +3. **Palette confirmed** (codex.md Step B) +4. **One mock direction approved or delegated** (codex.md Step D) + +You must stop at every gate. **Shape confirmation alone is NOT a green light to start coding.** It is the green light to begin codex.md Step A. Compressing gates 2 through 4 because the shape brief felt complete is the dominant failure mode of this flow. + +When the harness lacks native image generation, gates 2-4 collapse into the brief itself, and shape confirmation does advance straight to code. + +## Step 0: Project Foundation + +Before shape, before code: figure out what kind of project you're working in. + +Look at the working directory. Run `ls`. Check for: + +- An existing framework: `astro.config.mjs/ts`, `next.config.js/ts`, `nuxt.config.ts`, `svelte.config.js`, `vite.config.js/ts`, `package.json` with framework deps, `Cargo.toml` + Leptos/Yew, `Gemfile` + Rails. **If found, use it.** Do not start a parallel build, do not introduce a second framework, do not write to `dist/` or `build/` directly. Whatever pipeline the project has, respect it. +- An existing component library or design system: `src/components/`, `app/components/`, a `tokens.css` / `theme.ts`, an `astro.config` `integrations`. Read what's there before adding to it. +- An existing icon set: `lucide-react`, `@phosphor-icons/react`, `@iconify/*`, hand-rolled SVG sprites in `assets/icons/`. **Use what's already in the project**; don't introduce a second set. + +If the directory is empty (greenfield), don't pick a framework silently. Ask the user via the AskUserQuestion tool, with sensible defaults framed by the brief: + +```text +What should this be built on? + - Astro (default for content-led brand sites, landing pages, marketing surfaces) + - SvelteKit / Next.js / Nuxt (when the brief implies an app surface or significant interactivity) + - Single index.html (one-shot demo, prototype, or a deliberately framework-free experiment) +``` + +Default: Astro for brand briefs, the project's existing framework for product briefs. Ask once; don't re-ask mid-task. + +## Step 1: Shape the Design + +Run /impeccable shape, passing along whatever feature description the user provided. Shape is **required** for craft; it is what produces a confirmed direction. + +Present the shape output and stop. Wait for the user to confirm, override, or course-correct before writing code. + +If the user already supplied a confirmed brief or ran shape separately, use it and skip this step. + +When the original prompt + PRODUCT.md already answer scope, content, and visual direction with no real ambiguity, the shape output can be **compact** (3-5 bullets stating what you're building and the visual lane, ending with one or two specific questions or "confirm or override"). The full 10-section structured brief is reserved for genuinely ambiguous, multi-screen, or stakeholder-heavy tasks. Don't pad a clear brief into a long one to look thorough; equally, don't skip the pause to look efficient. + +If the harness has native image generation (Codex), a compact shape's "confirm or override" advances to **Step 3 and the codex.md flow**, not to Step 4. Phrase the closing line accordingly: "Confirm or override; once we lock direction, I'll run a couple of palette and reference questions before generating any mocks." This stops the model from reading shape confirmation as code-green. + +## Step 2: Load References + +Based on the design brief's "Recommended References" section, consult the relevant impeccable reference files. At minimum, always consult: + +- [layout.md](layout.md) for layout, spacing, grid, container queries, optical adjustments +- [typeset.md](typeset.md) for type hierarchy, font selection, web font loading, OpenType features (Reference Material section) + +Then add references based on the brief's needs: +- Complex interactions or forms? Consult [interaction-design.md](interaction-design.md) +- Animation or transitions? Consult [animate.md](animate.md) (Reference Material covers motion materials, durations, easing, perceived performance) +- Color-heavy or themed? Consult [colorize.md](colorize.md) (Reference Material covers OKLCH, palette structure, dark mode, contrast) +- Responsive requirements? Consult [adapt.md](adapt.md) (Reference Material covers breakpoints, input methods, safe areas, responsive images) +- Heavy on copy, labels, or errors? Consult [clarify.md](clarify.md) (Reference Material covers button labels, error formula, voice/tone, translation) + +## Step 3: Visual Direction & Assets (Harness-Gated) + +If the harness has **native image generation** (currently Codex via `image_gen`), this step is mandatory. **Stop and load [codex.md](codex.md)**. It covers palette generation, mock exploration, the approval loop, mock-fidelity inventory, and asset slicing via the `impeccable_asset_producer` subagent. Follow Steps A-F in that file, then return here for Step 4. + +If the harness lacks native image generation, **state in one line that the visual-direction-by-generation step is being skipped because the harness lacks native image generation, then proceed**. The one-line announcement is required; it forces a conscious decision instead of letting the step quietly evaporate. The brief is your only visual reference. Implement directly from it, treating any named anchor references and the brief's "Design Direction" as the contract. + +Whether you generated mocks or not: don't replace required imagery with generic cards, bullets, emoji, fake metrics, decorative CSS panels, or filler copy. Image-led briefs (restaurants, hotels, magazines, photography, hobbyist communities, food, travel, fashion, product) need real or sourced imagery in the build, not CSS scenery. + +## Step 4: Build to Production Quality + +**Precondition.** If Step 3 routed you to codex.md (native image generation available), Steps A through D in that file must be complete before any code: questions answered, palette confirmed, mocks generated, one direction approved or delegated. **Do not mention implementation, file paths, or patch plans until that's done.** A confirmed shape brief is not enough; the model that compressed those gates is the model that already failed this flow. + +Implement the feature following the design brief. Build in passes so structure, visual system, states, motion/media, and responsive behavior each get deliberate attention. The list below is the definition of done, not inspiration. + +### Production bar + +- **Real content.** No placeholder copy, placeholder images, dead links, fake controls, or unused scaffold at presentation time. +- **Preserve the approved mock's major ingredients.** Missing hero objects, world/product imagery, section structure, CTA/nav treatment, or distinctive motifs are blocking defects unless the user accepted the change. +- **Semantic first.** Real headings, landmarks, labels, form associations, button/link semantics, accessible names, state announcements where needed. +- **Deliberate spacing and alignment.** No default gaps, arbitrary margins, unbalanced whitespace, or accidental optical misalignment. +- **Intentional typography.** Chosen loading strategy, clear hierarchy, readable measure, stable line breaks, no overflow at any width. +- **Realistic state coverage.** Default, hover, focus-visible, active, disabled, loading, error, success, empty, overflow, long/short text, first-run. +- **Finished interaction quality.** Keyboard paths, touch targets, feedback timing, scroll behavior, state transitions, no hover-only functionality. +- **Coherent icon set.** Use the project's established set; otherwise pick one library or use accessible text. Don't mix. +- **Respect the build pipeline.** Edit source files and run the project's build (`npm run build` or equivalent). Don't write to `build/` / `dist/` / `.next/` with `cat`, heredoc, or Bash redirects; that skips asset hashing, image optimization, code splitting, and CSS extraction, and produces output the dev server won't serve. +- **Verify image URLs before referencing them.** Use image-search MCP or web-fetch when available; guessed photo IDs ship as broken-image placeholders. Without verification, prefer fewer images you're confident about. +- **Optimized imagery and media.** Correct dimensions, useful alt text, lazy loading below the fold, modern formats when practical, responsive `srcset`/`picture` for raster, no project-referenced asset left outside the workspace. +- **Premium motion.** Use atmospheric blur, filter, mask, shadow, reveal when they improve the experience. Avoid casual layout-property animation, bound expensive effects, verify smoothness in-browser, respect reduced motion, and avoid choreography that blocks task completion. +- **Maintainable.** Reusable local patterns, clear component boundaries, project conventions. No rasterized UI text or one-off hacks when a local pattern exists. +- **Technically clean.** Production build passes, no console errors, no avoidable layout shift, no needless dependencies, no broken asset paths. +- **Ask when uncertain.** If a discovery materially changes the brief or approved direction, stop and ask. Don't guess. + +## Step 5: Iterate Visually + +Look at what you built like a designer would. Your eyes are whatever the harness gives you: a connected browser, a screenshotting tool, Playwright, or asking the user. Use them for responsive testing (mobile, tablet, desktop minimum) and general visual validation. + +If your tool returns a file path, read the PNG back into the conversation. A screenshot you didn't read doesn't count. + +For long-form brand surfaces, inspect major sections individually. Thumbnails hide spacing, clipping, and cascade defects. + +After the first pass, write an honest critique against the brief, the approved mock's major ingredients (hero silhouette, motifs, imagery, nav/CTA, density), and impeccable's DON'Ts. Patch material defects and re-inspect. **Don't invent defects to demonstrate iteration.** A confident "first pass clean, shipping" beats a fake fix. + +Actively check: responsive behavior (composes, not shrinks), every state (empty / error / loading / edge), craft details (spacing, alignment, hierarchy, contrast, motion timing, focus), performance basics. The exit bar: defensible in a high-end studio review. + +Detector or QA output is defect evidence only; never proof the work is finished. + +## Step 6: Present + +Present the result to the user: +- Show the feature in its primary state +- Summarize the browser/viewports checked and the most important fixes made after inspection +- Walk through the key states (empty, error, responsive) +- Explain design decisions that connect back to the design brief and, when used, the chosen north-star mock. Include any accepted deviations from the mock; do not hide unimplemented mock ingredients. +- Note any remaining limitations or follow-up risks honestly +- Ask: "What's working? What isn't?" diff --git a/.agent/skills/impeccable/reference/critique.md b/.agent/skills/impeccable/reference/critique.md new file mode 100644 index 000000000..aa8e008ae --- /dev/null +++ b/.agent/skills/impeccable/reference/critique.md @@ -0,0 +1,767 @@ +### Purpose + +Resolve one stable target, run two independent assessments, synthesize a design critique, persist a snapshot, and ask the user what to improve next. The chat response is the primary deliverable; the snapshot is an archive/backlog for future commands. + +### Hard Invariants + +- Assessment A (design review) and Assessment B (detector/browser evidence) are both required. +- Assessment A must finish before detector findings enter the parent synthesis context. Detector output is deterministic, but it still anchors judgment. +- If sub-agents are unavailable, fall back sequentially: finish and record Assessment A first, then run Assessment B, then synthesize. +- A skipped detector is a failed critique run unless `detect.mjs` is missing or crashes after a real attempt. +- Viewable targets require browser inspection when available. +- Any local server started only for critique visualization must run in the background, have a recorded stop method, and be stopped before final reporting unless the user asks to keep it. +- Do not claim a user-visible overlay exists unless script injection succeeded and the detector ran in the page. + +### Setup + +1. **Resolve the target** to a concrete file path or URL. Prefer a source path over a dev-server URL when both identify the same surface; ports drift, paths do not. + - "the homepage" -> `site/pages/index.astro` or `index.html` + - "the settings modal" -> the primary component file + - "this page" -> the current URL or source file +2. **Compute the slug**: + ```bash + node .agent/skills/impeccable/scripts/critique-storage.mjs slug "" + ``` + Keep it. If the command exits non-zero, skip persistence and trend for this run, but continue the critique. +3. **Read `.impeccable/critique/ignore.md`** if it exists. Drop matching findings silently; it is the only prior-run input critique consumes. + +### Assessment Orchestration + +Delegate Assessment A and Assessment B to separate sub-agents when possible. They must not see each other's output. Do not show findings to the user until synthesis. + +If browser automation is available, each assessment creates its own new tab. Never reuse an existing tab, even if it is already at the right URL. + +### Assessment A: Design Review + +Read relevant source files and visually inspect the live page when browser automation is available. Think like a design director. + +Evaluate: +- **AI slop**: Would someone believe "AI made this" immediately? Check all DON'T guidance from the parent Impeccable skill. +- **Holistic design**: hierarchy, IA, emotional fit, discoverability, composition, typography, color, accessibility, states, copy, and edge cases. +- **Cognitive load**: consult the [Cognitive Load Assessment](#cognitive-load-assessment) section below; report checklist failures and decision points with >4 visible options. +- **Emotional journey**: peak-end rule, emotional valleys, reassurance at high-stakes moments. +- **Nielsen heuristics**: consult the [Heuristics Scoring Guide](#heuristics-scoring-guide) section below; score all 10 heuristics 0-4. + +Return: AI slop verdict, heuristic scores, cognitive load, emotional journey, 2-3 strengths, 3-5 priority issues, persona red flags, minor observations, and provocative questions. + +### Assessment B: Detector + Browser Evidence + +Run the bundled detector and browser visualization evidence. Assessment B is mandatory and must remain isolated from Assessment A until both are complete. + +CLI scan: +```bash +node .agent/skills/impeccable/scripts/detect.mjs --json [target] +``` + +- Pass markup files/directories as `[target]`; do not pass CSS-only files. +- For URLs, skip CLI scan and use browser visualization. +- For very large trees (500+ scannable files), narrow scope or ask. +- Exit code 0 = clean; 2 = findings. +- If the detector entrypoint is missing or fails to load, report deterministic scan unavailable and continue with browser/manual review. + +Browser visualization is required for a viewable target when browser automation is available. Use a localhost dev/static URL for local files; avoid `file://` unless the available browser explicitly supports this workflow. Overlay flow: + +1. Create a fresh tab and navigate. +2. Preflight mutable injection by setting `document.title` and appending a `\n' + + open + ' ' + MARKER_CLOSE_TEXT + ' ' + close + '\n' + ); +} + +function detectLineEnding(content) { + if (content.includes('\r\n')) return '\r\n'; + if (content.includes('\r')) return '\r'; + return '\n'; +} + +function normalizeLineEndings(content, lineEnding) { + return lineEnding === '\n' ? content : content.replace(/\n/g, lineEnding); +} + +function readLineEndingAt(content, index) { + if (content[index] === '\r' && content[index + 1] === '\n') return '\r\n'; + if (content[index] === '\n') return '\n'; + if (content[index] === '\r') return '\r'; + return ''; +} + +function insertTag(content, config, port, filePath) { + const lineEnding = detectLineEnding(content); + const block = normalizeLineEndings(buildTagBlock(config.commentSyntax, port, filePath), lineEnding); + // insertBefore: match the LAST occurrence. Anchors like `` 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 + // `` 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. + * ``), 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-start ' + id + ' ' + commentSyntax.close, + indent + ' ' + commentSyntax.open + ' Variants: insert below this line ' + commentSyntax.close, + indent + ' ' + commentSyntax.open + ' impeccable-variants-end ' + id + ' ' + commentSyntax.close, + indent + '
', + ]; + } + + return [ + indent + commentSyntax.open + ' impeccable-variants-start ' + id + ' ' + commentSyntax.close, + indent + '
', + indent + ' ' + commentSyntax.open + ' Variants: insert below this line ' + commentSyntax.close, + 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 + '
', + indent + ' ' + commentSyntax.open + ' impeccable-variants-start ' + id + ' ' + commentSyntax.close, + indent + ' ' + commentSyntax.open + ' Original ' + commentSyntax.close, + indent + '
', + reindentOriginal(' '), + indent + '
', + indent + ' ' + commentSyntax.open + ' Variants: insert below this line ' + commentSyntax.close, + indent + ' ' + commentSyntax.open + ' impeccable-variants-end ' + id + ' ' + commentSyntax.close, + indent + '
', + ] : [ + indent + commentSyntax.open + ' impeccable-variants-start ' + id + ' ' + commentSyntax.close, + indent + '
', + indent + ' ' + commentSyntax.open + ' Original ' + commentSyntax.close, + indent + '
', + originalIndented, + indent + '
', + indent + ' ' + commentSyntax.open + ' Variants: insert below this line ' + commentSyntax.close, + indent + '
', + indent + commentSyntax.open + ' impeccable-variants-end ' + id + ' ' + commentSyntax.close, + ]; + + let outputFile = targetFile; + let outputLines; + let outputStartLine = startLine + 1; + let outputEndLine = startLine + wrapperLines.length + (originalLines.length - 1); + let insertLine; + let svelteSession = null; + + if (useSvelteComponent) { + // Svelte/SvelteKit resets component-local state on markup HMR updates. + // Keep generation source-neutral: agents write real variant components + // under the generated componentDir, the browser mounts them into the live + // DOM, and live-accept.mjs inlines the accepted variant back into the route. + svelteSession = scaffoldSvelteComponentSession({ + id, + count, + sourceFile: relTargetFile, + sourceStartLine: startLine + 1, + sourceEndLine: endLine + 1, + originalLines, + cwd: process.cwd(), + }); + outputFile = path.resolve(process.cwd(), svelteSession.manifestFile); + outputStartLine = 1; + outputEndLine = 1; + insertLine = 1; + } else { + // Replace the original element with the wrapper + const newLines = [ + ...lines.slice(0, startLine), + ...wrapperLines, + ...lines.slice(endLine + 1), + ]; + fs.writeFileSync(targetFile, newLines.join('\n'), 'utf-8'); + + // Calculate insert line (the "insert below this line" comment). + // 0-indexed file position. Both HTML and JSX wrappers have 6 lines above + // the insert marker (HTML: start-comment + outer-div + Original-comment + + // original-div + content + close-original-div; JSX: outer-div + + // start-comment + Original-comment + original-div + content + + // close-original-div). Multi-line originals push the marker by their + // extra line count. + insertLine = startLine + 6 + (originalLines.length - 1) + 1; + } + + const outputRelFile = path.relative(process.cwd(), outputFile).split(path.sep).join('/'); + + const svelteComponentAuthoring = useSvelteComponent ? buildSvelteComponentCssAuthoring(count) : null; + + console.log(JSON.stringify({ + file: outputRelFile, + sourceFile: useSvelteComponent ? relTargetFile : undefined, + previewMode: useSvelteComponent ? 'svelte-component' : undefined, + componentDir: svelteSession?.componentDir, + propContract: svelteSession?.propContract, + sourceStartLine: useSvelteComponent ? startLine + 1 : undefined, + sourceEndLine: useSvelteComponent ? endLine + 1 : undefined, + startLine: outputStartLine, // 1-indexed for the agent + // wrapperLines is an array but one element (the original-content slot) + // is a `\n`-joined multi-line string, so the actual file-row count is + // wrapperLines.length + (originalLines.length - 1). Without the offset, + // endLine pointed inside the wrapper for any picked element that + // spanned more than one source line. + endLine: outputEndLine, // 1-indexed + insertLine, // 1-indexed: where variants go + commentSyntax: commentSyntax, + styleMode: useSvelteComponent ? 'svelte-component' : styleMode.mode, + styleTag: useSvelteComponent ? null : styleMode.styleTag, + cssSelectorPrefixExamples: useSvelteComponent ? [] : buildCssSelectorPrefixExamples(styleMode.mode, count), + cssAuthoring: useSvelteComponent ? svelteComponentAuthoring : buildCssAuthoring(styleMode, count), + originalLineCount: originalLines.length, + })); +} + +// --------------------------------------------------------------------------- +// Helpers +// --------------------------------------------------------------------------- + +function argVal(args, flag) { + const prefix = flag + '='; + for (const arg of args) { + if (arg.startsWith(prefix)) return arg.slice(prefix.length); + } + const idx = args.indexOf(flag); + return idx !== -1 && idx + 1 < args.length ? args[idx + 1] : null; +} + +function pendingEntriesThatMayAffectWrap(entries, targetFile, originalLines, selectionStartLine, cwd) { + const targetAbs = path.resolve(cwd, targetFile); + return (entries || []).filter((entry) => { + return (entry.ops || []).some((op) => { + return manualEditMayAffectWrap(op, targetAbs, originalLines, selectionStartLine, cwd); + }); + }); +} + +function manualEditMayAffectWrap(op, targetFile, originalLines, selectionStartLine, cwd) { + const targetAbs = path.resolve(cwd, targetFile); + if (manualEditHintFallsInsideSelection(op, targetAbs, originalLines, selectionStartLine, cwd)) return true; + if (manualEditLocatorMatchesSelection(op, originalLines)) return true; + if (typeof op?.originalText === 'string' && op.originalText.length > 0) { + return originalLines.join('\n').includes(op.originalText); + } + return false; +} + +function manualEditHintFallsInsideSelection(op, targetAbs, originalLines, selectionStartLine, cwd) { + const hintFile = op?.sourceHint?.file; + const hintedLine = Number(op?.sourceHint?.line); + if (!hintFile || !Number.isFinite(hintedLine)) return false; + const hintAbs = path.isAbsolute(hintFile) ? hintFile : path.resolve(cwd, hintFile); + if (path.resolve(hintAbs) !== targetAbs) return false; + const hintedIndex = hintedLine - 1 - selectionStartLine; + return hintedIndex >= 0 + && hintedIndex < originalLines.length + && typeof op?.originalText === 'string' + && originalLines[hintedIndex].includes(op.originalText); +} + +function manualEditLocatorMatchesSelection(op, originalLines) { + if (!op || typeof op.originalText !== 'string' || op.originalText.length === 0) return false; + return originalLines.some((line) => ( + line.includes(op.originalText) && lineMatchesManualEditLocator(line, op) + )); +} + +function applyBufferedManualEditToLines(originalLines, selectionStartLine, op) { + if ( + !op + || typeof op.originalText !== 'string' + || op.originalText.length === 0 + || typeof op.newText !== 'string' + ) { + return { lines: originalLines, changed: false }; + } + + const replaceLine = (lineIndex) => ({ + lines: originalLines.map((line, index) => ( + index === lineIndex ? replaceOnce(line, op.originalText, op.newText) : line + )), + changed: true, + }); + + const hintedLine = Number(op.sourceHint?.line); + if (Number.isFinite(hintedLine)) { + const hintedIndex = hintedLine - 1 - selectionStartLine; + if (hintedIndex >= 0 && hintedIndex < originalLines.length && originalLines[hintedIndex].includes(op.originalText)) { + return replaceLine(hintedIndex); + } + } + + const locatorMatches = []; + for (let index = 0; index < originalLines.length; index += 1) { + const line = originalLines[index]; + if (!line.includes(op.originalText)) continue; + if (!lineMatchesManualEditLocator(line, op)) continue; + locatorMatches.push(index); + } + if (locatorMatches.length === 1) return replaceLine(locatorMatches[0]); + + const originalBlock = originalLines.join('\n'); + if (countOccurrences(originalBlock, op.originalText) === 1) { + return { + lines: replaceOnce(originalBlock, op.originalText, op.newText).split('\n'), + changed: true, + }; + } + + return { lines: originalLines, changed: false }; +} + +function lineMatchesManualEditLocator(line, op) { + if (op.tag) { + const tagRe = new RegExp('<\\s*' + escapeRegExp(op.tag) + '(?=[\\s>/]|$)', 'i'); + if (!tagRe.test(line)) return false; + } + + if (op.elementId) { + const id = escapeRegExp(op.elementId); + const idRe = new RegExp('\\bid\\s*=\\s*["\']' + id + '["\']'); + if (!idRe.test(line)) return false; + } + + const classes = Array.isArray(op.classes) ? op.classes.filter(Boolean) : []; + for (const className of classes) { + if (!line.includes(className)) return false; + } + + return true; +} + +function replaceOnce(value, needle, replacement) { + const index = value.indexOf(needle); + if (index === -1) return value; + return value.slice(0, index) + replacement + value.slice(index + needle.length); +} + +function countOccurrences(value, needle) { + if (!needle) return 0; + let count = 0; + let index = 0; + while (true) { + index = value.indexOf(needle, index); + if (index === -1) return count; + count += 1; + index += needle.length; + } +} + +function escapeRegExp(value) { + return String(value).replace(/[.*+?^${}()|[\]\\]/g, '\\$&'); +} + +/** + * Build search query strings in priority order (most specific first). + * ID is most reliable, then specific class combos, then single classes, then raw query. + */ +function buildSearchQueries(elementId, classes, tag, query) { + const queries = []; + + // 1. ID is the most specific + if (elementId) { + queries.push('id="' + elementId + '"'); + } + + // 2. Full class attribute match (for elements with distinctive multi-class combos). + // Emit both class="..." (HTML) and className="..." (React/JSX) so whichever + // convention the file uses will match. + if (classes) { + const classList = splitClassList(classes); + if (classList.length > 1) { + const joined = classList.join(' '); + const sorted = [...classList].sort((a, b) => b.length - a.length); + queries.push('class="' + joined + '"'); + queries.push('className="' + joined + '"'); + for (const className of sorted) { + queries.push(className); + } + } else if (classList.length === 1) { + queries.push(classList[0]); + } + } + + // 3. Tag + class combo (e.g.,
). + // Same dual-emit for JSX compatibility. + if (tag && classes) { + const firstClass = splitClassList(classes)[0]; + queries.push('<' + tag + ' class="' + firstClass); + queries.push('<' + tag + ' className="' + firstClass); + } + + // 4. Raw fallback query + if (query) { + queries.push(query); + } + + return queries; +} + +function splitClassList(classes) { + return String(classes).split(/[,\s]+/).map(c => c.trim()).filter(Boolean); +} + +function attrEscapeDouble(str) { + return String(str) + .replace(/&/g, '&') + .replace(/"/g, '"') + .replace(//g, '>'); +} + +function detectCommentSyntax(filePath) { + const ext = path.extname(filePath).toLowerCase(); + if (ext === '.jsx' || ext === '.tsx') { + return { open: '{/*', close: '*/}' }; + } + // HTML, Vue, Svelte, Astro all use HTML comments + return { open: '' }; +} + +function detectStyleMode(filePath) { + const ext = path.extname(filePath).toLowerCase(); + if (ext === '.astro') { + return { + mode: 'astro-global-prefixed', + styleTag: ' close.', + 'Prefix every preview selector with the matching [data-impeccable-variant="N"] selector.', + 'Keep selectors anchored to the generated variant wrapper; do not rely on component CSS scoping for preview rules.', + ], + forbidden: [ + 'Do not use @scope for this styleMode.', + 'Do not wrap style content in a JSX/TSX template literal ({` ... `}); that syntax is for .tsx/.jsx only.', + 'Do not put { immediately after the style opening tag; Astro parses { as expression syntax.', + ], + }; + } + return { + mode: styleMode.mode, + styleTag: styleMode.styleTag, + strategy: 'scope-rule', + rulePattern: '@scope ([data-impeccable-variant="N"]) { :scope > .variant-class { ... } }', + selectorExamples: variantNumbers.map((n) => `@scope ([data-impeccable-variant="${n}"]) { :scope > .variant-class { ... } }`), + requirements: [ + 'Use @scope blocks keyed to each [data-impeccable-variant="N"] wrapper.', + 'Inside each @scope block, make :scope rules step into the replacement element with a descendant combinator.', + 'Use the styleTag exactly; do not add framework-specific style attributes unless this object says to.', + ], + forbidden: [ + 'Do not use global [data-impeccable-variant="N"] selector prefixes for this styleMode.', + 'Do not add is:inline to the style tag for this styleMode.', + ], + }; +} + +/** + * Search project files for the query string (class name, ID, etc.) + * Returns the first matching file path, or null. + */ +function findFileWithQuery(query, cwd, genOpts = {}) { + const searchDirs = ['src', 'app', 'pages', 'components', 'public', 'views', 'templates', '.']; + const seen = new Set(); + + for (const dir of searchDirs) { + const absDir = path.join(cwd, dir); + if (!fs.existsSync(absDir)) continue; + const result = searchDir(absDir, query, seen, 0, genOpts); + if (result) return result; + } + return null; +} + +function searchDir(dir, query, seen, depth, genOpts) { + if (depth > 5) return null; // don't go too deep + const realDir = fs.realpathSync(dir); + if (seen.has(realDir)) return null; + seen.add(realDir); + + let entries; + try { entries = fs.readdirSync(dir, { withFileTypes: true }); } + catch { return null; } + + // Check files first + for (const entry of entries) { + if (!entry.isFile()) continue; + const ext = path.extname(entry.name).toLowerCase(); + if (!EXTENSIONS.includes(ext)) continue; + + const filePath = path.join(dir, entry.name); + if (!genOpts.includeGenerated && isGeneratedFile(filePath, genOpts)) continue; + try { + const content = fs.readFileSync(filePath, 'utf-8'); + if (content.includes(query)) return filePath; + } catch { /* skip unreadable files */ } + } + + // Then recurse into directories. Always skip node_modules and .git (never + // project content). dist/build/out are left to the isGeneratedFile guard so + // the includeGenerated second-pass can still find the element there and + // report `generatedMatch`. + for (const entry of entries) { + if (!entry.isDirectory()) continue; + if (entry.name === 'node_modules' || entry.name === '.git') continue; + const result = searchDir(path.join(dir, entry.name), query, seen, depth + 1, genOpts); + if (result) return result; + } + + return null; +} + +/** + * Regex that matches a tag opener on a line. Allows the tag name to be + * followed by whitespace, `>`, `/`, or end-of-line so that multi-line JSX + * openers (e.g. ``) are recognised. + */ +const OPENER_RE = /<([A-Za-z][A-Za-z0-9]*)(?=[\s/>]|$)/; + +/** + * Find the element's start and end line in the file. + * + * `query` is a class name, attribute fragment (`class="..."`, `className="..."`, + * `id="..."`), or a raw text snippet. Because a query can appear on a + * continuation line of a multi-line tag (e.g. the `className="..."` row of a + * `` JSX tag), we walk backward from the match + * line to find the actual tag opener. When `tag` is provided, opener candidates + * must match that tag name. + */ +/** + * Return the smallest leading-whitespace count across a set of lines, + * ignoring blank lines (whose indent isn't load-bearing). Used to compute + * the common base indent of a multi-line picked element so reindenting + * under the wrapper preserves the relative depth between lines. + */ +function minLeadingSpaces(lines) { + let min = Infinity; + for (const l of lines) { + if (l.trim() === '') continue; + const m = l.match(/^(\s*)/); + if (m && m[1].length < min) min = m[1].length; + } + return min === Infinity ? 0 : min; +} + +function findElement(lines, query, tag = null) { + // Iterate all matches — the first substring hit isn't always the right one. + for (let i = 0; i < lines.length; i++) { + if (!lines[i].includes(query)) continue; + + const stripped = lines[i].trim(); + if (stripped.startsWith('). + */ +export function extractMustacheExpressions(text) { + const expressions = []; + const seen = new Set(); + const lines = String(text || '').split('\n'); + for (const line of lines) { + const trimmed = line.trim(); + if (trimmed.startsWith('\n` + : ''; + return `${buildPropsScript(contract)}${propsComment}${originalWithProps.trim()}\n\n\n`; +} + +function buildInsertVariantStub(variantNum) { + return `${buildPropsScript([])}
Insert variant ${variantNum}
\n\n\n`; +} + +export function scaffoldSvelteComponentSession({ + id, + count, + sourceFile, + sourceStartLine, + sourceEndLine, + originalLines, + cwd = process.cwd(), +}) { + ensureRuntimeHelper(cwd); + const dir = componentSessionDir(id, cwd); + fs.mkdirSync(dir, { recursive: true }); + + const originalMarkup = originalLines.join('\n'); + const contract = buildPropContract(extractMustacheExpressions(originalMarkup)); + const originalWithProps = substituteExprsWithProps(originalMarkup, contract); + + const manifest = { + id, + previewMode: 'svelte-component', + sourceFile: sourceFile.split(path.sep).join('/'), + sourceStartLine, + sourceEndLine, + count, + propContract: contract, + originalMarkup, + componentDir: path.relative(cwd, dir).split(path.sep).join('/'), + runtimeModule: `/${SVELTE_RUNTIME_FILE}`, + }; + + fs.writeFileSync(path.join(dir, 'manifest.json'), JSON.stringify(manifest, null, 2) + '\n', 'utf-8'); + + for (let n = 1; n <= count; n++) { + const variantFile = path.join(dir, `v${n}.svelte`); + if (!fs.existsSync(variantFile)) { + fs.writeFileSync(variantFile, buildVariantStub(n, originalWithProps, contract), 'utf-8'); + } + } + + return { + manifest, + manifestFile: path.relative(cwd, path.join(dir, 'manifest.json')).split(path.sep).join('/'), + componentDir: manifest.componentDir, + propContract: contract, + }; +} + +export function scaffoldSvelteComponentInsertSession({ + id, + count, + sourceFile, + insertLine, + position, + anchorStartLine, + anchorEndLine, + anchorLines, + cwd = process.cwd(), +}) { + ensureRuntimeHelper(cwd); + const dir = componentSessionDir(id, cwd); + fs.mkdirSync(dir, { recursive: true }); + + const anchorMarkup = (anchorLines || []).join('\n'); + const manifest = { + id, + mode: 'insert', + previewMode: 'svelte-component', + sourceFile: sourceFile.split(path.sep).join('/'), + insertLine, + position, + anchorStartLine, + anchorEndLine, + originalMarkup: anchorMarkup, + anchorMarkup, + count, + propContract: [], + componentDir: path.relative(cwd, dir).split(path.sep).join('/'), + runtimeModule: `/${SVELTE_RUNTIME_FILE}`, + }; + + fs.writeFileSync(path.join(dir, 'manifest.json'), JSON.stringify(manifest, null, 2) + '\n', 'utf-8'); + + for (let n = 1; n <= count; n++) { + const variantFile = path.join(dir, `v${n}.svelte`); + if (!fs.existsSync(variantFile)) { + fs.writeFileSync(variantFile, buildInsertVariantStub(n), 'utf-8'); + } + } + + return { + manifest, + manifestFile: path.relative(cwd, path.join(dir, 'manifest.json')).split(path.sep).join('/'), + componentDir: manifest.componentDir, + propContract: [], + }; +} + +export function findSvelteComponentManifest(id, cwd = process.cwd()) { + const direct = manifestPathForSession(id, cwd); + if (fs.existsSync(direct)) { + return readManifest(direct); + } + const root = path.join(cwd, SVELTE_COMPONENT_ROOT); + if (!fs.existsSync(root)) return null; + for (const entry of fs.readdirSync(root, { withFileTypes: true })) { + if (!entry.isDirectory()) continue; + const candidate = path.join(root, entry.name, 'manifest.json'); + if (!fs.existsSync(candidate)) continue; + try { + const manifest = readManifest(candidate); + if (manifest?.id === id) return { ...manifest, manifestPath: candidate }; + } catch { /* skip */ } + } + return null; +} + +export function readManifest(manifestPath) { + const data = JSON.parse(fs.readFileSync(manifestPath, 'utf-8')); + return { + ...data, + manifestPath, + }; +} + +export function resolveSourceFile(sourceFile, cwd = process.cwd()) { + if (!sourceFile || path.isAbsolute(sourceFile)) { + throw new Error('Invalid svelte-component source file'); + } + const full = path.resolve(cwd, sourceFile); + const rel = path.relative(cwd, full); + if (!rel || rel.startsWith('..') || path.isAbsolute(rel)) { + throw new Error('Svelte-component source file escapes project root'); + } + if (!fs.existsSync(full)) { + throw new Error('Svelte-component source file not found: ' + sourceFile); + } + return full; +} + +function appendCssToSvelteStyle(lines, cssLines) { + const closeIdx = findLastStyleCloseLine(lines); + const prepared = ['', ...cssLines.map((line) => (line.trim() === '' ? '' : ' ' + line.trimStart()))]; + if (closeIdx === -1) { + return [...lines, '', '']; + } + return [ + ...lines.slice(0, closeIdx), + ...prepared, + ...lines.slice(closeIdx), + ]; +} + +function findLastStyleCloseLine(lines) { + for (let i = lines.length - 1; i >= 0; i--) { + if (/<\/style\s*>/.test(lines[i])) return i; + } + return -1; +} + +function bakeParamValuesInCss(cssLines, paramValues) { + if (!paramValues || Object.keys(paramValues).length === 0) return cssLines; + return cssLines.map((line) => { + let out = line; + for (const [key, value] of Object.entries(paramValues)) { + const varName = `--p-${key}`; + out = out.replace(new RegExp(`var\\(${escapeRegExp(varName)}(?:,\\s*[^)]+)?\\)`, 'g'), String(value)); + } + return out; + }); +} + +function sanitizeAcceptedSvelteCss(cssLines, variantNum, paramValues = null, rootTag = 'div') { + const css = String((cssLines || []).join('\n')); + if (!/data-impeccable-variant|impeccable-variant-ready/.test(css)) return cssLines; + + const rules = parseCssRules(css); + const output = []; + for (const rule of rules) { + appendSanitizedCssRule(output, rule, variantNum, paramValues, rootTag); + } + return output.join('\n') + .split('\n') + .map((line) => line.trimEnd()) + .filter((line) => line.trim() !== ''); +} + +function appendSanitizedCssRule(output, rule, variantNum, paramValues, rootTag) { + const prelude = rule.prelude.trim(); + const body = rule.body.trim(); + if (!prelude || !body || /--impeccable-variant-ready\s*:/.test(body)) return; + + if (/^@scope\b/i.test(prelude)) { + if (/data-impeccable-variant/.test(prelude) && !selectorHasVariant(prelude, variantNum)) return; + const inner = parseCssRules(body); + for (const innerRule of inner) { + const rewrittenPrelude = rewriteAcceptedSvelteSelector(innerRule.prelude, variantNum, paramValues, rootTag, true); + if (!rewrittenPrelude || /--impeccable-variant-ready\s*:/.test(innerRule.body)) continue; + output.push(formatCssRule(rewrittenPrelude, innerRule.body.trim())); + } + return; + } + + const rewrittenPrelude = rewriteAcceptedSvelteSelector(prelude, variantNum, paramValues, rootTag, false); + if (!rewrittenPrelude) return; + output.push(formatCssRule(rewrittenPrelude, body)); +} + +function parseCssRules(css) { + const rules = []; + const text = String(css || ''); + let i = 0; + while (i < text.length) { + while (i < text.length && /\s/.test(text[i])) i++; + const preludeStart = i; + while (i < text.length && text[i] !== '{') i++; + if (i >= text.length) break; + const prelude = text.slice(preludeStart, i).trim(); + i++; + const bodyStart = i; + let depth = 1; + let quote = null; + let comment = false; + while (i < text.length && depth > 0) { + const ch = text[i]; + const next = text[i + 1]; + if (comment) { + if (ch === '*' && next === '/') { + comment = false; + i += 2; + continue; + } + i++; + continue; + } + if (quote) { + if (ch === '\\') { + i += 2; + continue; + } + if (ch === quote) quote = null; + i++; + continue; + } + if (ch === '/' && next === '*') { + comment = true; + i += 2; + continue; + } + if (ch === '"' || ch === "'") { + quote = ch; + i++; + continue; + } + if (ch === '{') depth++; + else if (ch === '}') depth--; + i++; + } + const body = text.slice(bodyStart, Math.max(bodyStart, i - 1)); + if (prelude) rules.push({ prelude, body }); + } + return rules; +} + +function rewriteAcceptedSvelteSelector(prelude, variantNum, paramValues, rootTag, fromScope) { + const selectors = splitSelectorList(prelude); + const rewritten = []; + for (const selector of selectors) { + const next = rewriteAcceptedSvelteSelectorPart(selector, variantNum, paramValues, rootTag, fromScope); + if (next) rewritten.push(next); + } + return rewritten.join(', '); +} + +function rewriteAcceptedSvelteSelectorPart(selector, variantNum, paramValues, rootTag, fromScope) { + let out = selector.trim(); + const hasVariant = /data-impeccable-variant/.test(out); + if (hasVariant && !selectorHasVariant(out, variantNum)) return ''; + if (hasVariant) { + out = out.replace(variantSelectorRegex(variantNum), ''); + out = out.replace(/\[data-impeccable-variant=(["']).*?\1\]/g, ''); + } + + const paramResult = rewriteParamSelectors(out, paramValues); + if (!paramResult.keep) return ''; + out = paramResult.selector; + + out = out + .replace(/:scope(?:\[[^\]]+\])?\s*>\s*/g, '') + .replace(/:scope(?:\[[^\]]+\])?/g, rootTag || '') + .replace(/\s+/g, ' ') + .trim(); + + out = out.replace(/^[>+~]\s*/, '').trim(); + if (!out && (hasVariant || fromScope)) return rootTag || ':global(*)'; + return out; +} + +function rewriteParamSelectors(selector, paramValues) { + let keep = true; + const next = selector.replace(/\[data-p-([A-Za-z0-9_-]+)(?:=(["'])(.*?)\2)?\]/g, (_match, key, _quote, expected) => { + if (!paramValues || !Object.prototype.hasOwnProperty.call(paramValues, key)) return ''; + const actual = paramValues[key]; + if (expected != null && String(actual) !== String(expected)) { + keep = false; + return ''; + } + if (expected == null && (actual === false || actual == null || actual === 'false' || actual === 'off' || actual === '0')) { + keep = false; + return ''; + } + return ''; + }); + return { keep, selector: next }; +} + +function splitSelectorList(prelude) { + const selectors = []; + let start = 0; + let bracket = 0; + let paren = 0; + let quote = null; + for (let i = 0; i < prelude.length; i++) { + const ch = prelude[i]; + if (quote) { + if (ch === '\\') i++; + else if (ch === quote) quote = null; + continue; + } + if (ch === '"' || ch === "'") { + quote = ch; + continue; + } + if (ch === '[') bracket++; + else if (ch === ']') bracket = Math.max(0, bracket - 1); + else if (ch === '(') paren++; + else if (ch === ')') paren = Math.max(0, paren - 1); + else if (ch === ',' && bracket === 0 && paren === 0) { + selectors.push(prelude.slice(start, i)); + start = i + 1; + } + } + selectors.push(prelude.slice(start)); + return selectors; +} + +function selectorHasVariant(selector, variantNum) { + return variantSelectorRegex(variantNum).test(selector); +} + +function variantSelectorRegex(variantNum) { + return new RegExp(`\\[data-impeccable-variant=(["'])${escapeRegExp(String(variantNum))}\\1\\]`, 'g'); +} + +function formatCssRule(selector, body) { + return `${selector} { ${body.trim()} }`; +} + +function escapeRegExp(value) { + return String(value).replace(/[.*+?^${}()|[\]\\]/g, '\\$&'); +} + +export function inlineSvelteComponentAccept(manifest, variantNum, paramValues = null, cwd = process.cwd()) { + const sourceFile = resolveSourceFile(manifest.sourceFile, cwd); + const variantPath = path.join(cwd, manifest.componentDir, `v${variantNum}.svelte`); + const resultBase = { + file: manifest.sourceFile, + sourceFile: manifest.sourceFile, + previewMode: 'svelte-component', + componentDir: manifest.componentDir, + carbonize: false, + }; + if (!fs.existsSync(variantPath)) { + return { handled: false, error: `Variant ${variantNum} not found`, ...resultBase }; + } + + const { markup, cssLines } = parseSvelteComponentFile(fs.readFileSync(variantPath, 'utf-8')); + if (manifest.mode === 'insert') { + return inlineSvelteComponentInsertAccept({ + manifest, + markup, + cssLines, + variantNum, + paramValues, + sourceFile, + resultBase, + cwd, + }); + } + + const rootTag = matchOpeningTag(markup)?.tag || 'div'; + const contract = manifest.propContract || []; + const mergedMarkup = mergeOriginalTopLevelAttrs(markup, manifest.originalMarkup || ''); + const restoredMarkup = substitutePropsWithExprs(mergedMarkup, contract) + .split('\n') + .map((line) => line.trimEnd()); + + const sourceContent = fs.readFileSync(sourceFile, 'utf-8'); + const sourceLines = sourceContent.split('\n'); + const start = Number(manifest.sourceStartLine) - 1; + const end = Number(manifest.sourceEndLine) - 1; + if (!Number.isInteger(start) || !Number.isInteger(end) || start < 0 || end < start || end >= sourceLines.length) { + return { handled: false, error: 'Invalid source line range for ' + manifest.sourceFile, ...resultBase }; + } + + const indent = sourceLines[start].match(/^(\s*)/)?.[1] || ''; + const indentedMarkup = restoredMarkup.map((line) => { + if (line.trim() === '') return ''; + return indent + line.trimStart(); + }); + + let newLines = [ + ...sourceLines.slice(0, start), + ...indentedMarkup, + ...sourceLines.slice(end + 1), + ]; + + const sanitizedCss = sanitizeAcceptedSvelteCss(cssLines, variantNum, paramValues, rootTag); + const bakedCss = bakeParamValuesInCss(sanitizedCss, paramValues); + if (bakedCss.length > 0) { + newLines = appendCssToSvelteStyle(newLines, bakedCss); + } + + try { + fs.writeFileSync(sourceFile, newLines.join('\n'), 'utf-8'); + } catch (err) { + return { handled: false, error: 'Failed to write Svelte source: ' + err.message, ...resultBase }; + } + removeSvelteComponentSession(manifest.id, cwd); + + return { + handled: true, + ...resultBase, + }; +} + +function inlineSvelteComponentInsertAccept({ + manifest, + markup, + cssLines, + variantNum, + paramValues, + sourceFile, + resultBase, + cwd, +}) { + if (!svelteMarkupHasVisibleContent(markup)) { + return { handled: false, error: 'Accepted Svelte insert variant is empty', ...resultBase }; + } + if (/\bdata-impeccable-[\w-]*\s*=/.test(markup)) { + return { handled: false, error: 'Accepted Svelte insert variant contains preview-only data-impeccable attributes', ...resultBase }; + } + + const rootTag = matchOpeningTag(markup)?.tag || 'div'; + const restoredMarkup = String(markup || '') + .split('\n') + .map((line) => line.trimEnd()); + const sourceContent = fs.readFileSync(sourceFile, 'utf-8'); + const sourceLines = sourceContent.split('\n'); + const insertIndex = Number(manifest.insertLine) - 1; + if (!Number.isInteger(insertIndex) || insertIndex < 0 || insertIndex > sourceLines.length) { + return { handled: false, error: 'Invalid insert line for ' + manifest.sourceFile, ...resultBase }; + } + + const nearbyLine = sourceLines[insertIndex] ?? sourceLines[insertIndex - 1] ?? ''; + const indent = nearbyLine.match(/^(\s*)/)?.[1] || ''; + const indentedMarkup = restoredMarkup.map((line) => { + if (line.trim() === '') return ''; + return indent + line.trimStart(); + }); + + let newLines = [ + ...sourceLines.slice(0, insertIndex), + ...indentedMarkup, + ...sourceLines.slice(insertIndex), + ]; + + const sanitizedCss = sanitizeAcceptedSvelteCss(cssLines, variantNum, paramValues, rootTag); + const bakedCss = bakeParamValuesInCss(sanitizedCss, paramValues); + if (bakedCss.length > 0) { + newLines = appendCssToSvelteStyle(newLines, bakedCss); + } + + try { + fs.writeFileSync(sourceFile, newLines.join('\n'), 'utf-8'); + } catch (err) { + return { handled: false, error: 'Failed to write Svelte source: ' + err.message, ...resultBase }; + } + removeSvelteComponentSession(manifest.id, cwd); + + return { + handled: true, + ...resultBase, + }; +} + +function svelteMarkupHasVisibleContent(markup) { + const text = String(markup || '') + .replace(//gi, '') + .replace(//gi, '') + .replace(//g, '') + .replace(/<[^>]+>/g, ' ') + .replace(/\s+/g, ' ') + .trim(); + if (text.length > 0) return true; + return /<(img|svg|canvas|video|audio|picture|input|button|select|textarea)\b/i.test(markup || ''); +} + +function mergeOriginalTopLevelAttrs(markup, originalMarkup) { + const variantOpen = matchOpeningTag(markup); + const originalOpen = matchOpeningTag(originalMarkup); + if (!variantOpen || !originalOpen) return markup; + if (variantOpen.tag.toLowerCase() !== originalOpen.tag.toLowerCase()) return markup; + + const variantAttrs = parseAttrSegments(variantOpen.attrs); + const originalAttrs = parseAttrSegments(originalOpen.attrs); + const additions = []; + let attrs = variantOpen.attrs; + + const originalClass = originalAttrs.get('class'); + const variantClass = variantAttrs.get('class'); + if (originalClass && variantClass) { + const merged = mergeStaticClassAttr(originalClass, variantClass); + if (merged) { + attrs = attrs.slice(0, variantClass.start) + merged + attrs.slice(variantClass.end); + variantAttrs.set('class', { ...variantClass, raw: merged }); + } + } else if (originalClass && !variantClass) { + additions.push(originalClass.raw); + } + + for (const [name, attr] of originalAttrs) { + if (name === 'class') continue; + if (!variantAttrs.has(name)) additions.push(attr.raw); + } + + if (additions.length === 0 && attrs === variantOpen.attrs) return markup; + const nextOpen = variantOpen.prefix + + variantOpen.tag + + attrs + + additions.map((attr) => ' ' + attr.trim()).join('') + + variantOpen.close; + return markup.slice(0, variantOpen.index) + nextOpen + markup.slice(variantOpen.index + variantOpen.raw.length); +} + +function matchOpeningTag(markup) { + const match = String(markup || '').match(/^(\s*<)([A-Za-z][\w:-]*)([^>]*?)(\/?>)/); + if (!match) return null; + return { + raw: match[0], + prefix: match[1], + tag: match[2], + attrs: match[3] || '', + close: match[4], + index: match.index || 0, + }; +} + +function parseAttrSegments(attrs) { + const out = new Map(); + const re = /([A-Za-z_:][\w:.-]*)(?:\s*=\s*(?:"[^"]*"|'[^']*'|\{[^}]*\}|[^\s"'>=]+))?/g; + let match; + while ((match = re.exec(attrs))) { + const raw = match[0]; + const name = match[1]; + out.set(name, { + name, + raw, + start: match.index, + end: match.index + raw.length, + }); + } + return out; +} + +function mergeStaticClassAttr(originalClass, variantClass) { + const originalValue = originalClass.raw.match(/class\s*=\s*(["'])(.*?)\1/); + const variantValue = variantClass.raw.match(/class\s*=\s*(["'])(.*?)\1/); + if (!originalValue || !variantValue) return null; + const quote = variantValue[1]; + const classes = [ + ...variantValue[2].split(/\s+/), + ...originalValue[2].split(/\s+/), + ].filter(Boolean); + return `class=${quote}${[...new Set(classes)].join(' ')}${quote}`; +} + +export function removeSvelteComponentSession(id, cwd = process.cwd()) { + const dir = componentSessionDir(id, cwd); + try { + fs.rmSync(dir, { recursive: true, force: true }); + } catch { /* non-fatal */ } +} + +export function removeAllSvelteComponentSessions(cwd = process.cwd()) { + const root = path.join(cwd, SVELTE_COMPONENT_ROOT); + if (!fs.existsSync(root)) return; + for (const entry of fs.readdirSync(root, { withFileTypes: true })) { + if (!entry.isDirectory()) continue; + if (entry.name.startsWith('__')) continue; + try { + fs.rmSync(path.join(root, entry.name), { recursive: true, force: true }); + } catch { /* non-fatal */ } + } +} + +export function deferredAcceptsPath(cwd = process.cwd()) { + const key = createHash('sha1').update(path.resolve(cwd)).digest('hex').slice(0, 16); + return path.join(os.tmpdir(), 'impeccable-live', key, 'deferred-svelte-component-accepts.json'); +} + +export function readDeferredAccepts(cwd = process.cwd()) { + const file = deferredAcceptsPath(cwd); + try { + return JSON.parse(fs.readFileSync(file, 'utf-8')); + } catch { + return { accepts: [] }; + } +} + +export function writeDeferredAccept(entry, cwd = process.cwd()) { + const file = deferredAcceptsPath(cwd); + fs.mkdirSync(path.dirname(file), { recursive: true }); + const data = readDeferredAccepts(cwd); + data.accepts = (data.accepts || []).filter((item) => item.id !== entry.id); + data.accepts.push({ ...entry, createdAt: new Date().toISOString() }); + fs.writeFileSync(file, JSON.stringify(data, null, 2) + '\n', 'utf-8'); +} + +export function applyDeferredSvelteComponentAccepts(cwd = process.cwd()) { + const file = deferredAcceptsPath(cwd); + const data = readDeferredAccepts(cwd); + const pending = Array.isArray(data.accepts) ? data.accepts : []; + const results = []; + const remaining = []; + for (const entry of pending) { + try { + const manifest = findSvelteComponentManifest(entry.id, cwd); + if (!manifest) { + results.push({ id: entry.id, ok: false, error: 'manifest not found' }); + remaining.push(entry); + continue; + } + const result = inlineSvelteComponentAccept( + manifest, + entry.variantNum, + entry.paramValues || null, + cwd, + ); + results.push({ id: entry.id, ok: result.handled !== false, result }); + if (result.handled === false) remaining.push(entry); + } catch (err) { + results.push({ id: entry.id, ok: false, error: err.message }); + remaining.push(entry); + } + } + if (remaining.length > 0) { + fs.writeFileSync(file, JSON.stringify({ accepts: remaining }, null, 2) + '\n', 'utf-8'); + } else { + try { fs.rmSync(file, { force: true }); } catch {} + } + return { applied: results.filter((r) => r.ok).length, failed: results.filter((r) => !r.ok).length, results }; +} + +export function buildSvelteComponentCssAuthoring(count) { + const variantNumbers = Array.from({ length: count }, (_, i) => i + 1); + return { + mode: 'svelte-component', + styleTag: null, + strategy: 'component-style-block', + rulePattern: '.semantic-class { ... }', + selectorExamples: variantNumbers.map(() => '.expense-row { padding: 22px; }'), + requirements: [ + 'Write each variant as a real Svelte component file (v1.svelte, v2.svelte, ...).', + 'Keep the prop names from propContract; bind dynamic text with {propName}, not literal snapshot text.', + 'Put variant CSS in the component