* Improve Live polling responsiveness and reliability Restore foreground/background polling as the primary harness architecture, add progressive publication and framework-safe previews, and harden quality and regression coverage. The experimental app-server runtime is intentionally excluded.\n\nPrepared with AI assistance under maintainer direction. * Fix source-safety, detector, and lock defects in Live polling work Addresses the review findings on #371, plus several the bots did not catch. All fixes have regression coverage that fails on the prior code. Source corruption: - Vue accept dropped valueless root attrs (disabled, v-cloak) and, worse, rewrote @click="x" as a literal click="x" DOM attribute, because the attr parser was name-anchored and skipped the sigil. Tokenize the whole Vue attr grammar and normalize shorthands so accept round-trips directives. - --variant was interpolated unescaped into a RegExp, so --variant '.*' matched the original block first and reported a successful accept while silently restoring the original. Validate against the digits pattern the browser and the /events schema already enforce. - --id reached path.join unvalidated, so --id ../../../../etc/evil wrote and read receipts outside the project. Hoist the existing safeSessionId check into impeccable-paths and apply it at every id-to-path sink. Accept/lock correctness: - Plain HTML/JSX accept and discard did not catch SOURCE_LOCKED, so contention exited non-zero with empty stdout and the agent got no JSON to retry on. - Lock staleness was mtime-only and never read the pid it records: a holder whose critical section outran 60s had its live lock swept, admitting a second writer to the same file, while a crashed holder blocked accepts for a full 60s. Decide staleness by owner liveness, and release only our own lock. Detector: - isNeutralColor only parses computed color forms, so routing authored CSS through it reported inset 4px 0 0 #000 / black / #e5e7eb as chromatic side-tab stripes. Add an authored-color neutrality test covering hex and named neutrals; the fixture had no literal-color cases at all. - Rule line numbers were off by one for every rule after the first, and commented-out CSS was scanned as live rules. Server: - An error reply carries no sourceEventType, and inferSourceEventType returned undefined, which acknowledgePendingEvent treats as a wildcard: a stale generate worker's failure consumed the user's queued Accept, which then reached no agent and left the browser in SAVING forever. - The generate preflight spawned live-wrap.mjs synchronously inside the request handler, freezing the single-threaded server for the whole scaffold (~7.6s measured on this repo, 15s ceiling) and stalling Accept/Discard/SSE. Make it async, claiming the lease before the first await so no event double-delivers. - Every browser checkpoint was echoed back as variant_progress, so a Tune slider drag remounted the preview under the user's cursor and latched the *_reviewable phases from the wrong trigger. Gate on the reason. Cleanup: - Collapse four divergent benchmark argv parsers into scripts/lib/cli-args.mjs. Three silently misread flags: --iterations 20 benchmarked 5, --agent llm ran the fake agent, --median-target=0.4 used the default threshold. - Drop a snapshot cache this branch made write-only (it grew per session for the server's lifetime and was never read), a dead exported reconcile helper, and the unused deferReply branch. Prepared with AI assistance under maintainer direction. Co-Authored-By: Claude <noreply@anthropic.com> * Route the last two benchmark scripts through the shared argv parser Follow-up on review feedback. The previous commit consolidated four of the six Live benchmark parsers and left these two on their own hand-rolled `arg()`, which was the inconsistency the first pass was meant to remove. - benchmark-live-control.mjs and benchmark-live-init.mjs parsed --iterations with Number(), so a non-numeric value became NaN and `index < NaN` ran the benchmark zero times before failing on the metrics file. They also accepted only the space-separated form, so --iterations=20 silently measured the default. Both now use parseArgs + positiveIntFlag, which throws on a value that was clearly meant as a number. - benchmark-live-control.mjs read the metrics file with no handling for the case where the run produced nothing: a missing file surfaced as a raw ENOENT stack and a malformed line as a bare SyntaxError. Report both with a diagnostic naming the file and the env var that populates it. - summarize() now reports a `samples` count and nulls instead of letting percentile() read past an empty array, where the NaN serialized to null and a report of nothing measured looked like a real measurement. Prepared with AI assistance under maintainer direction. Co-Authored-By: Claude <noreply@anthropic.com> * Stop telling users a busy agent is disconnected The agent-poll indicator tracks whether a poll is parked, which is the right signal for "can steering reach the agent right now" and is why the flag itself is left alone. But it goes quiet for two different reasons, and both got the same copy: "Agent disconnected - run live-poll.mjs to connect". Under the one-shot foreground polling that live.md calls the primary contract, no poll is parked while the agent works, so the second reason is every normal generation. For its whole duration the bar told the user a healthy session was broken and advised them to start a poll loop that was already running. Pick the copy from the live state, which the browser already tracks: GENERATING and SAVING mean the agent holds work it was handed, so say it is working. Every other state with no parked poll keeps the original, actionable wording. The aria-label carries the same distinction, since the tooltip is mouse-only. The text is derived at read time rather than cached, because the live state moves between the 5s status polls and a finished generation would otherwise keep reading "Agent is working" until the next one landed. Deriving it also keeps the read out of setLiveState, which runs long before agentPollingConnected's declaration and would hit its temporal dead zone. Prepared with AI assistance under maintainer direction. Co-Authored-By: Claude <noreply@anthropic.com> * Scope design-system-font-size off the injected live overlay live-browser.js builds a self-contained UI that renders over arbitrary host pages, so its inline type scale is deliberately independent of DESIGN.md, which documents the impeccable website's ramp. The rule fired 32 times there and is the only rule that fires on that file. Suppress it as a file-scoped value wildcard rather than via ignoreFiles: an ignoreFiles glob would silence every rule for the file, and the overlay is real user-facing chrome where a future contrast or side-tab finding should still be heard. Scoped to this one file, so the rule keeps working everywhere else. Written by hand because hook-admin's ignore-value cannot emit the `files` array that detector.ignoreValues supports and existing entries already use. Prepared with AI assistance under maintainer direction. Co-Authored-By: Claude <noreply@anthropic.com> * Let hooks ignore-value scope a rule to files, and stop churning the config Fallout from suppressing the overlay's font-size findings: the narrowest exception detector.ignoreValues supports was unreachable from the path the hook tells the model to use, so the guidance steered to the blunt instrument instead. - hook-admin's ignore-value now takes --file / --files / --file= / --files=, matching `impeccable ignores add-value`, which already had them. Without it the only file-scoped option was ignore-file, which silences every rule for a path permanently, including rules not yet written. - A bare wildcard value is now refused with a message pointing at either --file or ignore-rule. Previously `ignore-value <rule> "*"` quietly wrote a project-wide suppression from a single file's finding. - ignore-value keyed entries on rule+value only, so a second scope for the same rule overwrote the first instead of coexisting. Key on the file scope too. - An unknown flag folded into the value: `ignore-value overused-font Inter --shard` stored "inter --shard", matched nothing, and reported success. Reject it, as the sibling command does. Config churn: normalizeIgnoreValueEntries runs on every write and emitted keys as rule, value, files, reason, createdAt while the config on disk uses createdAt before reason. Any edit therefore rewrote every untouched entry (35 churned lines for a one-line change). Pin the canonical order in both copies of the normalizer and in ignores.mjs, and add a test that the two copies cannot drift apart. Also point the hook's own footer and reference/hooks.md at the file-scoped form first, and say plainly what ignore-file costs. Prepared with AI assistance under maintainer direction. Co-Authored-By: Claude <noreply@anthropic.com> * Correct the prose-gate docs and write down the no-bump-in-a-PR rule CLAUDE.md said the prose validator "deliberately skips skill/", which is only half true and cost a build failure this week: validateProse skips it, but validateSkillProse then scans skill/**/*.md and fails the build on em dashes plus the phrases with no technical reading. Document both gates, which files each one reads, and the line that actually matters in practice: an em dash in skill/reference/*.md fails the build, one in a skill/scripts/*.mjs comment does not. Each claim was checked against a real `bun run build`. Also record that feature PRs do not bump manifest versions or add changelog entries. It was not written down anywhere: not CLAUDE.md, not AGENTS.md, not the PR template. CLAUDE.md's "Bump when: CLI code changes" reads as an instruction to bump inside the PR that touches cli/, so say plainly that it names which component a change belongs to rather than when to edit the manifest. Put the rule in AGENTS.md too. That is the guide the agents opening PRs here actually read, so a rule about PR hygiene living only in CLAUDE.md would not reach them. Prepared with AI assistance under maintainer direction. Co-Authored-By: Claude <noreply@anthropic.com> * Bring Live progressive delivery and the generator subagent to Claude Code Almost none of this branch's Live work was actually Codex-specific. The publisher, the fences, the source locks and the browser's partial-arrival UI are plain node and DOM with zero provider references, and the progressive E2E already passes on five frameworks driven by a non-Codex agent. The Codex-only part was policy prose and one frontmatter line, so Claude Code shipped the progressive browser UI it could never trigger. Progressive delivery, Codex and Claude Code: - Add a `live-progressive` capability tag and opt codex, agents, and claude-code in. A provider block takes one tag, so naming harnesses would have meant duplicating the recipe per tag; a capability reads better than a provider list anyway. Cursor and everyone else keep the atomic path until their poll loop is known not to stall on the extra publish calls. - Claude Code publishes variant 1 as soon as it validates rather than waiting to write the whole trio in one edit. Nothing about the arrival path needed changing: the publisher writes, framework HMR pushes, and the browser's MutationObserver counts variants. The parent conversation was never in that path, which is why Claude Code's lack of subagent progress streaming does not matter here. Generator subagent: - Drop `providers: codex` from impeccable-live-generator. The build already maps its frontmatter correctly for Claude Code, and impeccable-manual-edit-applier has shipped to .claude/agents/ this way all along. - The reason differs per harness, so the reference says so: Codex delegates to unblock a foreground poll, Claude Code delegates to keep a long session's screenshots and variant CSS out of the main context. Follows the existing manual-edit-applier convention: both agent names, and an inline fallback when native subagents are unavailable. Fixes found on the way: - The two publish commands hardcoded `.agents/skills/impeccable/scripts/` while the other thirteen commands in live.md use {{scripts_path}}. Correct only for the Codex repo-skills bundle; it would have pointed Claude Code at a directory its install never creates. The shipped .codex variant was already internally inconsistent. Now covered by a test. - `--agent=codex` resolved to the canned fake agent, because the flag parsed as `x === 'llm' ? 'llm' : 'fake'`. The private evals Live runner passes exactly that, so a real-harness run would have scored deterministic stub variants and reported them as Codex output. Unknown values for --agent, --scenario and --delivery now fail loudly. - live-reference tests now compile with each provider's real providerTags instead of hand-written lists, so a providers.js misconfiguration fails in tests rather than shipping. Verified: progressive E2E green on vite8-react-plain against a real Vite server and Chromium; every provider variant's publish and poll paths now agree; Cursor and Gemini still compile to atomic only. Prepared with AI assistance under maintainer direction. Co-Authored-By: Claude <noreply@anthropic.com> * Fix inset-order detection, the unlocked artifact discard, and stray boolean flags Three of the four open review findings. The fourth is declined below. - The inset-stripe scan only matched layers starting with `inset`, but the keyword is order-independent: `box-shadow: 4px 0 0 var(--brand-accent) inset` paints the same stripe and was silently missed. Strip the keyword wherever it sits, but only as a standalone token, so a color like var(--inset-accent) is not mangled into `var(-- -accent)` and quietly reclassified as neutral. The fixture now covers both orders plus that token, and a trailing-inset neutral still passes. - The source-artifact discard deleted the preview without the source lock, unlike every other discard path. Take the lock. Narrower than reported, though: the server journals `discard_requested` as a fenced phase before live-accept runs and the publisher checks it three times, so a publish could never land on a discarded session. What this actually prevents is deleting the artifact under a publisher mid-critical-section, turning a clean stale_generation_epoch into an ENOENT crash. - benchmark-live-providers.mjs still compared `--headed` and `--skip-cleanup-control` against a boolean sentinel, so the `=true` spelling silently did nothing. My gap: I introduced boolFlag and converted benchmark-live.mjs but not this one. skipCleanupControl is now read once rather than twice, so the two call sites cannot drift. Declined: tightening the selector guard that skips `active` / `current` / `selected` tokens. It does cause false negatives on names like `.selected-feature`, but the rule's contract makes selection and focus indicators its one exception, and `.active-tab` / `.current-step` / `.selected-row` are syntactically identical to `.selected-feature`. No regex separates them, so tightening the guard trades missed stripes for false positives on exactly the case the rule exempts. The conservative skip is the intended behavior. Prepared with AI assistance under maintainer direction. Co-Authored-By: Claude <noreply@anthropic.com> * Classify failed accepts as errors, and fix parallel lane race/all misuse Two of the three new findings, plus the bug that chasing them exposed in my own earlier fix. The third is mitigated rather than broken; details below. Failed accepts reported success: live/completion.mjs only classifies a result as `error` when it carries `mode: 'error'`. Everything else unhandled falls through to `agent_done` with an ok ack, which is deliberate for the documented fallback paths (two tests pin it) but wrong for a real failure. So `accept_receipt_conflict` reported success, and reference/live.md's `handled: false` without `mode` bullet told the agent to "read file, find markers, edit" — hand-applying a second accept on top of the one the receipt already recorded. The same hole swallowed `source_locked`, which is mine: the earlier commit made lock contention return clean JSON so the agent could retry, but the classifier turned that failure into agent_done/ok, so the accept was dequeued and silently lost. Mark genuine failures with `mode: 'error'` through one `operationFailure` helper, and give live.md a `mode: "error"` bullet with per-error guidance: retry the same command on `source_locked`, never hand-edit, and on a receipt conflict report what the session actually resolved to. The deliberate fallback and markers-not-found handoffs stay untouched. parallel-compact lane orchestration: `Promise.race` settles on the first *settlement*, so one lane failing fast rejected the whole first-variant step while two lanes were still on their way to succeeding. `Promise.any` now takes the first success and only a total wipeout is fatal, reporting every lane's reason. The tail step's `Promise.all` surfaced a raw lane error non-deterministically; `Promise.allSettled` now reports how many lanes failed and why. Added a `requestImpl` seam so lane orchestration is testable without a provider key. Not a defect: the browser releasing Accept before the source write. That is the intended optimistic design, and it is safe because poll-lanes ranks accept at priority 0 against generate at 2, so a queued accept is always leased before a generate the user queues afterwards, even if the generate arrived first. Its source write lands inside the poll script before the next generate preflights. That invariant is load-bearing and had no tests at all; poll-lanes.mjs now has a suite covering it plus lease and type filtering. Prepared with AI assistance under maintainer direction. Co-Authored-By: Claude <noreply@anthropic.com> * Finish the failed-accept classification my last commit only half did All three new findings are the same root cause, and it is my incomplete fix: operationFailure only covered results built from a *thrown* error. Two paths it missed: - Two catches wrote the failure result as a multi-line literal, so the single-line replace skipped them. The Vue accept catch was still bare, exactly as reported; the Svelte one too, though its failures happened to be caught by completion.mjs's Svelte-only special case. - The accept implementations also *return* `{handled: false, error}` for their own checks (variant missing, template empty, original text ambiguous). Those never throw, so no catch ran and no `mode` was set. Both layers now agree, because each is reachable on its own: - live-accept marks any unhandled preview-path result via markPreviewFailure, keyed on `previewMode` — a clean discriminator, since only the preview branches set it and a plain wrapper never does. This is what the agent reads: reference/live.md routes on `mode`, so without it the agent was told "read file, find markers, edit" for a preview that has no markers in source. - completion.mjs replaces its arbitrary svelte-component special case with the set of preview modes whose variants live outside the user's source. That case existed for precisely this reason; Vue and source-artifact were simply never added, so the identical failure on those paths acknowledged as success. The plain wrapper keeps its manual handoff, which is the one shape with editable markers in source. Both deliberate handoffs (mode: 'fallback' and markers not found) still classify as agent_done, now pinned by a test so the generalization cannot swallow them. Prepared with AI assistance under maintainer direction. Co-Authored-By: Claude <noreply@anthropic.com> * Stop the progressive benchmark agent inventing a second variant on count:1 `Math.max(1, event.count - 1)` floored the tail request at one variant, so a one-variant request fetched a second direction and assembled two. Ask for `count - 1` and return the first variant untouched when there is no tail. Latent rather than live: the only caller hardcodes `count: 3`. The reason it is worth fixing is the caller inconsistency it exposed. tests/live-e2e/agent.mjs gates its split-progressive path on `event.count > 1`; benchmark-live-providers.mjs had no such guard, so it would have run the tail for a one-variant request, and the parallel strategy would have assembled its three fixed lanes regardless of what was asked for. Guard the caller the same way. Prepared with AI assistance under maintainer direction. Co-Authored-By: Claude <noreply@anthropic.com> * Drop the live generator subagent; fix the artifact decoy that broke accept The first real Claude Code Live run failed, and the subagent was not the cause. Root cause: progressive publication stages each revision as `.impeccable/live/artifacts/<id>-r<n>.<source-ext>`, nothing ever deleted them, and findSessionFile's walker skipped only node_modules/.git/dist/build. It searches src, app, pages, ... then `.`; a project whose source is not under one of those (this repo's own site lives in site/pages/) falls through to the `.` walk, where dot-directories sort before letters. So accept found the artifact instead of the real file. Two outcomes, both reproduced: where isGeneratedFile returns true it declines with mode: 'fallback' (what the run hit, after which the agent hand-carbonized several hundred lines across three stylesheets, including unrequested drive-by edits); where it returns false, accept writes the variant into the throwaway artifact and reports handled: true while real source never changes. The E2E suite could not have caught this. Every fixture puts source under `src/`, which is searched before the `.` walk can reach `.impeccable`. Five framework fixtures and three progressive scenarios pass because of fixture layout, not because the path works. I read that as evidence and shouldn't have. - Never search `.impeccable`: it is Impeccable's own state, never project source. - Retire a session's staged artifacts on accept/discard, so they cannot outlive the session and become a decoy for anything else that walks the tree. - Regression tests use a site/pages layout with artifacts present. All three fail against the previous code. Generator subagent removed, on both harnesses: The parent must hand-compress the design system into the handoff, and compression is lossy. Measured on the real run: a 6,826-char handoff carrying exactly one token reference, after the parent had itself read kinpaku-tokens.css. The subagent then spent 3 of its first 9 turns hunting DESIGN.md, gave up, and emitted 0 var(--token) uses and 22 raw oklch literals — violating its own spec's "Never invent raw colors when tokens exist" — including a 1:1 gold-on-gold contrast bug. Isolation is not a benefit here; knowing the design system is the job. Generation stays in the main thread, which already holds the tokens and writes them from the first byte, so carbonize is a move rather than a translation. Copy edits keep their subagent: applying a known set of ops to a named file is self-contained, so an isolated context costs nothing. That is the line. Progressive delivery stays for Codex and Claude Code, main-thread driven. Claude Code keeps the full benefit because its poll is a background task. Codex's poll blocks the foreground, so with no subagent the user sees variant 1 early via HMR but cannot accept it until the trio finishes; that is the cost of the simplification and it is worth naming. Prepared with AI assistance under maintainer direction. Co-Authored-By: Claude <noreply@anthropic.com> * Rip out the dead isolated-preview mode and the private repo's job Comparing this branch's live against main's turned up two whole features that never made sense here. -2,466 lines. 1. The isolated source-artifact preview was never switched on. `scaffoldSourceArtifactSession` is only reachable via live-wrap's `--isolated`, and nothing passes it: not the server's preflight, not live.md, nothing. Proved it end-to-end — the default wrap writes markers straight into real source and creates no previews/ session. So the mode was wired through three modules, carried its own accept/discard branches, browser branches, server metadata resolution, preview-mode classifier entry, and test suites, and none of it could run. Worse, live.md documented it as the active path and told the agent "The true source is only the publisher's hash fence and must remain byte-identical until Accept." That is false: the wrapper lands in source at scaffold time and each revision rewrites it. An agent following that sentence believes source is protected when it isn't, and the leftover artifacts are what made accept resolve the wrong file in the first real run. live.md now describes what actually happens, including that markers are visible in source until Accept or Discard. Removed: source-artifact.mjs, --isolated, the preflight's isolated option, the accept/discard branches, four dead browser branches, the server's previews/ resolution, the classifier entry, and their tests. Kept the previews/ gitignore pattern: an ignore line for a directory that cannot exist is free, and a test pins it. 2. Quality judging belongs to the private evals repo, which says so. runner/live/README.md there is explicit: the public repo owns protocol correctness, framework coverage, timing, source commit, recovery, and a rubric-free evidence bundle; the private repo owns the task corpus, baselines, comparative judges, and release-quality decisions — "Do not add quality rubrics, competitor comparisons, or broad fixture corpora to the public Live benchmark." This branch added exactly those: an LLM judge scoring 1-10 on "off-brand, generic-AI" (live-rendered-quality.mjs, judge-live-rendered.mjs), a cross-provider comparison with a BRAND_CONTRACT rubric (live-provider-benchmark .mjs, benchmark-live-providers.mjs), and a brand-fidelity fixture corpus. All removed, with bench:live:providers and their suite entries. Also removed tests/framework-fixtures/README.md's "External quality-eval fixtures" section: it documented a bench:live workflow using --fixture-dir, --agent=codex, --action and --evidence-bundle, none of which benchmark-live.mjs implements, plus an evidenceCapture block nothing reads. Kept: timing benchmarks (the public repo's half of that boundary), progressive publication, the source lock, poll lanes, and Nuxt/Vue component previews. Coverage note: deleting the isolated suites took the only tests for `source_locked` classification with them, so the plain wrapper path — now the only non-component preview — gets equivalent accept and discard coverage. Both new tests fail if mode:'error' is removed. Prepared with AI assistance under maintainer direction. Co-Authored-By: Claude <noreply@anthropic.com> * Flag inset stripes written with the two-length box-shadow form box-shadow takes <length>{2,4}: only the two offsets are required, so `inset 4px 0 red` is valid and paints the same single-edge stripe as `inset 4px 0 0 red`. The scan demanded a third length, so the short form was silently missed. Blur and spread now default to 0 when omitted, which is exactly the stripe shape the rule looks for. The neutral-color and blur/spread exclusions still hold: `inset 4px 0 #000` and `inset 4px 0 5px var(--brand-accent)` both pass. Fixture covers both orders of the short form plus those two exclusions, and fails against the previous regex. Third false negative found in this rule (after trailing `inset` and literal neutral colors), all from the same cause: the scan was written against one spelling of the syntax rather than the grammar. Prepared with AI assistance under maintainer direction. Co-Authored-By: Claude <noreply@anthropic.com> * Live: polling rework, source locks, preflight scaffolding, Vue previews Carved out of #371, minus progressive publication. Everything here works against real project source the way main's Live already does: the agent writes variants into the file the browser loaded, HMR fires, Accept promotes and carbonizes. Nothing is staged anywhere. Poll lanes. Events now carry an explicit priority: accept/discard/exit ahead of manual_edit_apply/steer/carbonize_cleanup ahead of generate. A long generate can no longer sit in front of the Accept the user just clicked. leaseEvent claims its lease before awaiting, so a slow prepare cannot hand the same event to two pollers. Source locks. A per-file mutex around every accept and discard path, keyed on a digest of the absolute path. Staleness is decided by owner-pid liveness rather than mtime, so a wedged lock clears when its owner dies instead of after an arbitrary timeout, and a slow-but-live accept is never stolen from. Only the owning process can release a lock. Preflight scaffolding. The server runs live-wrap (or live-insert) before the poll returns and hands the result back as event.scaffold. That walk is measured at ~7.6s on a large repo; moving it off the agent's critical path removes a deterministic tool round trip without touching the generated design. Falls back cleanly to the agent running the helper itself. Vue previews. previewMode: "vue-component" for Nuxt/Vue targets, matching the existing Svelte component path: variants compile as real SFCs from a dev-only directory so the route is never rewritten during generation, and Vite mounts them without invalidating page state. Accept is the only route write. Includes a Vue attr tokenizer that normalizes shorthand bindings (@x, :x, #x) to their canonical forms. Accept hardening. Every thrown failure now returns mode: 'error' rather than an ambiguous unhandled result, so a real failure is never classified as a deliberate manual handoff and silently dropped. The marker search skips node_modules/.git/dist/build/.impeccable. Shared CLI arg parsing extracted to scripts/lib/cli-args.mjs. Assisted-by: Claude Code * Drop the progressive benchmark, remove dead wrap scaffolding Review fallout from removing progressive publication. The Live benchmark existed to compare atomic against progressive delivery: compareModelBackedReports measures goToFirstVariantMs improvement of one over the other. With progressive gone it measures nothing against nothing. Worse, benchmark-live.mjs still passed `progressive` to bootFixtureSession, which no longer accepts it, so `--delivery progressive` was silently ignored and would have emitted reports labeled progressive that actually ran atomic. Silent wrong data is worse than a crash. It was built for progressive, so it goes with progressive: benchmark-live.mjs, its lib, its test, and the bench:live script. If an atomic latency baseline is wanted later, that is a smaller thing built on purpose. live-wrap.mjs: sourceOriginalLines was assigned and never read. Both found by review bots on #381 (Copilot). Assisted-by: Claude Code * Drop the Vue preview mode; it never reached Svelte's accept path Cursor found that inlineVueComponentAccept never receives paramValues, while the Svelte equivalent uses them in 23 places: Accept on a tuned Vue variant silently persisted the default and threw the user's tuning away. Chasing that corrected something I had asserted the other way round. I said Vue's raw-CSS-append was inherited from the Svelte path. It is not. svelte-component.mjs calls sanitizeAcceptedSvelteCss before writing, which sanitizes the CSS and bakes tuned params into it. vue-component.mjs had no sanitize step at all — it appended the variant's <style scoped> body into whatever style block came last, so a variant could leak CSS site-wide when the last block was global, and brace CSS landed in a lang="sass" block. Both are the same defect: the Vue mode mirrored Svelte's preview path without its accept-side subsystem (bakeParamValuesInCss, sanitizeAcceptedSvelteCss, appendSanitizedCssRule, rewriteAcceptedSvelteSelector, rewriteParamSelectors — roughly 200 lines of CSS rewriting). Both were introduced here, not inherited. A shipped Vue session could leak styles and discard tuning without saying so. So it comes out. The poll lanes, source locks, preflight scaffolding, and accept hardening do not depend on it and are worth landing now. Vue returns when its accept path reaches parity. The nuxt-vite7 fixture goes back to main's plain-wrapper shape. Assisted-by: Claude Code * Stop the lease redelivery test racing the scheduler CI failed `does not drop polled events until the agent acknowledges them` on a commit whose content was byte-identical to one that passed, which is the signature of a flake rather than a regression. The test leased an event for 50ms, then asserted a second poll saw a timeout because the lease was still held. That gave the whole second HTTP round trip a 50ms real-time budget: cross it and the lease expires, the event is redelivered, and the assertion fails for a scheduling hiccup instead of a bookkeeping bug. Locally it passed 6/6; a loaded runner is where it bites. Hold the lease for 1000ms so a round trip cannot cross it, and wait LEASE_MS + 300 before asserting redelivery, so each half has headroom in the direction it asserts. Verified by injecting a 60ms stall before the second poll: the old test fails with exactly the CI message, the new one passes. Assisted-by: Claude Code * Recover live sessions that reload past the generation done broadcast The preflight scaffold write (new in this PR) triggers a framework full-reload — Astro reloads the page for any .astro edit. When the agent's variant write and its done SSE land while the browser is mid-reload, the resumed page misses both the second HMR reload and the done broadcast: it comes back up on the scaffold-only source and waits in GENERATING at 0/N forever, with the finished variants sitting in source. This is the astro-vite7 CI timeout; the failure artifacts show the full sequence (scaffold at 26.319s, done at 26.515s, the new page's browser_resumed checkpoint at 26.653s, DOM still scaffold-only). Three-part fix: - session-store: agent_done now stamps a monotone generationCompletedAt on the snapshot. Browser checkpoints legitimately regress phase and arrivedVariants (a resumed page reports what it sees), so completion needed a field checkpoints cannot un-set. - live-browser: on every SSE (re)connect, compare the session summary's generationCompletedAt against local progress; when behind while GENERATING, pull the finished variants from source (same settle delay as the done handler's HMR-first fallback). Covers both orderings of resumed-checkpoint vs agent_done. Also, the source-fallback empty- wrapper branch no longer tears the session down mid-generation — a scaffold-only wrapper is a legitimate in-flight state, so stay in GENERATING instead of destroying a session the agent is still filling. - live-server: a browser checkpoint reporting generating/behind for a session whose generation already completed re-broadcasts the stored done (idempotent for every other tab), and connected-payload summaries expose generationCompletedAt for the browser-side check. Coverage: live-server unit tests for redelivery, the no-redelivery guard, and marker durability across checkpoint regression; plus a deterministic live-e2e scenario on astro-vite7 that blocks the reloaded page's SSE stream and mocks its HMR websocket dead until after the agent finishes, forcing the missed-broadcast window every run. All new tests fail against the pre-fix code. The e2e harness additionally gains an IMPECCABLE_E2E_ATOMIC_DELAY_MS lever (widens the scaffold-to-write window) and env-gated console/nav tracing (IMPECCABLE_E2E_CONSOLE=1) used to diagnose this. The hypothesis that preflight opens a wrapper-with-no-variants window came from Copilot's review sketch in the follow-up WIP PR; the killing mechanism differs from that sketch (nothing calls recoverEmptyCycling in the CI trace — the session hangs precisely because no code path runs at all), but the window is real and the guard it suggested is folded into the source-fallback fix. Assisted-by: Claude Code Co-Authored-By: Claude Code <noreply@anthropic.com> * Retry a completion-driven source fallback that reads only the scaffold Greptile flagged a hole in the previous commit's empty-scaffold guard: when a `done` has already been delivered, the source fallback gets exactly one read. If that read returns the preflight-only scaffold (a stale source view, or an agent whose write lands in multiple steps), the guard's silent return left the tab in GENERATING with no further event ever coming — the same stuck state the previous commit fixed, reintroduced through a different door. Callers that know generation finished (the done handler's fallback and the SSE-reconnect self-heal) now pass generationCompleted, and an empty read on that path re-reads the source up to 3 times before surfacing recoverEmptyCycling instead of hanging. Mid-generation callers are unchanged and still wait indefinitely — a real agent can legitimately take minutes between scaffold and write, and tearing that down was the original #385 hazard. The missed-done e2e scenario now also serves a captured scaffold-only copy for the first post-reconnect /source read, forcing the retry path every run. Verified failing against the pre-retry code (tab stranded in GENERATING, test timeout) and passing with it. Assisted-by: Claude Code Co-Authored-By: Claude Code <noreply@anthropic.com> --------- Co-authored-by: Claude <noreply@anthropic.com>
60 KiB
Interactive live variant mode: select elements in the browser, pick a design action, and get AI-generated HTML+CSS variants hot-swapped via the dev server's HMR.
Prerequisites
A running dev server with hot module replacement (Vite, Next.js, Bun, etc.), OR a static HTML file open in the browser.
Codex: run live helper commands, the app dev server, and any dependency-installing setup with `sandbox_permissions: "require_escalated"` from the start; live mode depends on localhost and package-manager network access that the sandbox blocks.The contract (read once)
Execute in order. No step skipped, no step reordered.
live.mjs: boot. If the request names or implies a file, route, or app inside a monorepo, infer the concrete path and runnode {{scripts_path}}/live.mjs --target <path>instead; then run the rest of this live session from the returnedprojectRoot.- Open the app URL that serves
pageFile(infer frompackage.json, docs, terminal output, or an open tab). Never useserverPort; it's the helper, not the app. Cursor:browser_navigateto that URL before polling; do not skip. Other harnesses: use the available browser tool; if the URL is uncertain, ask the user once. - Poll loop with the default long timeout (600000 ms). Run
live-poll.mjsagain immediately after every event or--reply; Codex runs this one-shot poll in the foreground. Never pass a short--timeout=.
The global bar Impeccable mark dims and shows a pulsing amber dot when no agent is long-polling /poll. Hover the mark for the hint; restart live-poll.mjs to reconnect.
4. On generate: reuse event.scaffold when present; read the screenshot if present; load the action's reference; deliver variants using the delivery policy below; --reply done; poll again. Generate in this thread. You already hold the project's tokens, conventions, and file layout; that context is the job, not overhead.
5. On steer: read the message and pageUrl; do the work (page edits, navigation help, or a short reply in the --reply message); --reply steer_done; poll again. No pickup ack. The Steer bar unlocks when steer_done arrives over SSE.
6. On accept / discard: the poll script runs live-accept.mjs, acknowledges the delivered event, and prints _completionAck. Plain accepts/discards are terminal immediately. Carbonize accepts remain recoverable until the foreground task runs live-complete.mjs --id EVENT_ID; finish that cleanup before polling again.
7. If interrupted, run live-status.mjs or live-resume.mjs before guessing. The durable journal replays unacknowledged work after helper restart.
8. On exit: run the cleanup at the bottom.
Harness policy:
- Claude Code: run the poll as a background task (no short timeout). The harness notifies you when it completes, so the main conversation stays free while you generate and publish in it. Do not block the shell.
- Cursor: run one-shot poll in a background terminal with notify on
"type":"(steer|generate|accept|discard|exit)". After each event the poll exits; handle it,--reply, then startlive-poll.mjsagain. Do not use--streamon Cursor: incremental stdout notify is slower in practice than exit-based notify (~5s vs sub-second in testing). - Codex: run the default one-shot poll in a yielded foreground exec session. Do not suffix it with
&, use--stream, or leave Live without an active foreground poll. Handle every event in the main task; after each handler/reply, restart the foreground poll. - Other harnesses: one-shot foreground unless you know stdout reliably returns to this session when a shell exits.
Generation delivery policy:
- Default (Cursor and other harnesses): keep the established atomic single-edit delivery. Do not switch a harness to progressive until its poll loop is known not to block on the extra publish calls. This avoids trading model latency for extra tool-call latency on harnesses with different streaming behavior.
Chat is overhead. No recap, no tutorial output, no pasting PRODUCT / DESIGN bodies. Spend tokens on tools and edits; on failure, one or two short sentences.
Start
node {{scripts_path}}/live.mjs
Output JSON: { ok, serverPort, serverToken, pageFiles, hasProduct, product, productPath, hasDesign, design, designPath }. pageFiles is the list of HTML entries the live script was injected into. Keep PRODUCT.md and DESIGN.md in mind for variant generation; DESIGN.md wins on visual decisions; PRODUCT.md wins on strategic/voice decisions. When DESIGN.md is missing, identity is not absent; extract it from CSS variables, computed styles, and sibling components on the page (see Step 4 Phase A). Identity preservation is the default; departure from existing identity requires an explicit trigger from PRODUCT.md anti-references or the user's freeform prompt.
serverPort and serverToken belong to the small Impeccable live helper HTTP server (serves /live.js, SSE, and /poll). That port is not your dev server and is usually not the URL you open to view the app. The browser page is whatever origin serves one of the pageFiles entries (Vite / Next / Bun / tunnel / LAN hostname).
If output is { ok: false, error: "config_missing" | "config_invalid", path }, this project hasn't been configured for live mode (or its config is stale). See First-time setup at the bottom.
Poll loop
Default (portable, all harnesses):
LOOP:
node {{scripts_path}}/live-poll.mjs # default long timeout; no --timeout=
Read JSON; dispatch on "type"
"generate" → Handle Generate; reply done; LOOP
"steer" → Handle Steer; reply steer_done; LOOP
"accept" → Handle Accept; complete carbonize cleanup if required; LOOP
"discard" → Handle Discard; LOOP
"prefetch" → Handle Prefetch; LOOP
"manual_edit_apply" → Handle Manual Edit Apply; reply done|partial|error; LOOP
"timeout" → LOOP
"exit" → break → Cleanup
Stream mode (experimental, not for Cursor):
node {{scripts_path}}/live-poll.mjs --stream # stays running; one JSON line per event
Handle event; run --reply in a separate command
Repeat until "exit" line → Cleanup
Stream keeps one process alive and waits for --reply ack before polling again. Useful only when the harness reads incremental stdout reliably and quickly. Cursor is not one of those: background pattern notify on a long-running shell was ~5s to pick up events vs sub-second for one-shot exit notify. Default to one-shot everywhere unless you have measured otherwise.
Recovery commands
The live helper persists an append-only journal under .impeccable/live/sessions/. Browser checkpoints are advisory but durable; the journal is canonical. This is local durable recovery state, not project source.
Use these commands when the chat was interrupted, polling was missed, the helper restarted, or the browser reloaded:
node {{scripts_path}}/live-status.mjs
node {{scripts_path}}/live-resume.mjs --id SESSION_ID
node {{scripts_path}}/live-complete.mjs --id SESSION_ID
live-status.mjsprints connected helper state, active durable sessions, and queued pending events. It works even when the helper is down by reading the journal directly.live-resume.mjsprints the active snapshot, pending event, checkpoint phase, visible variant, parameter values, and the next safe agent action.live-complete.mjsis the canonical manual final acknowledgement. Use it after carbonize/manual cleanup is verified and no further poll acknowledgement will happen automatically.
Server restart rule: start live-server.mjs again, then poll. Startup requeues unacknowledged pending events from the journal, so do not ask the user to click Go again unless live-resume.mjs says no active session exists.
Handle generate
Replace mode (default): {id, action, freeformPrompt?, count, pageUrl, element, screenshotPath?, comments?, strokes?}.
Insert mode (event.mode === "insert"): {id, mode: "insert", count, pageUrl, insert: { position, anchor }, placeholder: { width, height }, freeformPrompt?, screenshotPath?, comments?, strokes?}. No action. Requires a non-empty freeformPrompt or annotations. Screenshot is sent only when annotations exist (same rule as replace). Use placeholder dimensions as a soft size hint for net-new content.
Speed matters; the user is watching the selected element. Reuse server preflight metadata when available, minimize discovery calls, and follow the harness-specific delivery policy above.
Insert mode branch
When event.mode === "insert":
- Read the screenshot if
event.screenshotPathis present (annotations only). - If
event.scaffoldis present, use it as the insert-helper result and do not run the helper again. Otherwise run the insert helper instead of wrap:
node {{scripts_path}}/live-insert.mjs --id EVENT_ID --count EVENT_COUNT --position after \
--element-id "ANCHOR_ID" --classes "class1,class2" --tag "section" --text "ANCHOR_TEXT"
--position←event.insert.position(before|after)- Anchor flags ←
event.insert.anchor(same mapping as wrap: id, classes, tag, text)
The scaffold has no data-impeccable-variant="original". Variants are net-new HTML+CSS inserted at insertLine. Load brand.md or product.md (freeform only, no action sub-command). Deliver using the harness policy, then --reply done.
For Svelte/SvelteKit targets, live-insert.mjs returns previewMode: "svelte-component" with mode: "insert", file pointing at a temporary node_modules/.impeccable-live/<id>/manifest.json, componentDir pointing at the variant component files, and sourceFile pointing at the real .svelte route. Write each inserted variant as a real Svelte component (v1.svelte, v2.svelte, …) under componentDir. Insert variants must be non-empty net-new content with a single top-level root, no data-impeccable-* attributes, and CSS in each component's <style> block. Do not edit the route source during generation; the browser mounts the temporary component before/after the live anchor while the user cycles variants. On Accept, live-accept.mjs inserts the selected component markup into sourceFile immediately and deletes the temp session after the source write succeeds.
For non-Svelte targets, on accept/discard, live-accept.mjs removes the wrapper block; the anchor element is untouched.
Replace mode (default)
1. Read the screenshot (if present)
event.screenshotPath is only sent when the user placed at least one comment or stroke before Go. When present, it's an absolute path to a PNG of the element as rendered with the annotations baked in. Read it before planning: annotations encode user intent not recoverable from element.outerHTML alone.
When screenshotPath is absent, don't ask for one and don't go looking for the current rendering. The omission is deliberate: without annotations, a screenshot would anchor the model on the existing design and fight the three-distinct-directions brief. Work from element.outerHTML, the computed styles in event.element, and the freeform prompt if present.
event.comments and event.strokes carry structured metadata alongside the visual. Treat the screenshot as primary; use the structured data for specifics worth quoting (e.g. the exact text of a comment).
Reading annotations precisely:
- Comment position carries meaning. Its
{x, y}is element-local CSS px (same coord space aselement.boundingRect). Find the child under that point and apply the comment text LOCALLY to that sub-element. A comment near the title is about the title, not a global description. - Comments and strokes are independent annotations unless clearly paired by overlap or tight proximity. Don't let the visual weight of a prominent stroke override the precise location of a textually-specific comment elsewhere.
- Strokes are gestures; read them by shape. Closed loop = "this thing" (emphasis / focus); arrow = direction (move / point to); cross or slash = delete; free scribble = emphasis or delete depending on context. A loop around region X means "pay attention to X," not "only change pixels inside X."
- When a stroke's intent is ambiguous (circle or arrow? emphasis or move?), state your reading in one sentence of rationale rather than silently guessing. If the uncertainty materially changes the brief, ask one short clarifying question before generating.
2. Wrap the element
When event.scaffold is present, the local helper already found and wrapped the source before the poll returned. Treat event.scaffold as the successful helper output and skip this command entirely. event.scaffoldAttempted with scaffoldError means local preflight could not finish; use the command/fallback path below. This optimization removes a deterministic tool round trip without changing the generated design.
node {{scripts_path}}/live-wrap.mjs --id EVENT_ID --count EVENT_COUNT --element-id "ELEMENT_ID" --classes "class1,class2" --tag "div" --text "TEXT_SNIPPET"
Flag mapping. Keep them separate, don't collapse into --query:
--element-id←event.element.id--classes←event.element.classesjoined with commas--tag←event.element.tagName--text← first ~80 chars ofevent.element.textContent(trim, single-line). Pass this every call. When the picked element shares classes + tag with sibling components (a list of<Card>s, repeating sections), this is what disambiguates which branch in source to wrap. Without it, wrap silently lands on the first match and may rewrite the wrong element.
The helper searches ID first, then classes, then tag + class combo. If event.pageUrl implies the file (e.g. / is usually index.html), pass --file PATH to skip the search. --query is a fallback for raw text search only; do not use it for normal element lookups.
If --text matches multiple candidates equally well, wrap exits with { error: "element_ambiguous", candidates: [...] } and fallback: "agent-driven": read the candidate line ranges, decide which one matches the picked element from page context, and write the wrapper manually per the fallback flow.
Output on success: { file, insertLine, commentSyntax, styleMode, styleTag, cssSelectorPrefixExamples, cssAuthoring }.
For Svelte/SvelteKit targets, live-wrap.mjs returns previewMode: "svelte-component" with file pointing at a temporary node_modules/.impeccable-live/<id>/manifest.json, componentDir pointing at the variant component files, and sourceFile pointing at the real .svelte route. Write each variant as a real Svelte component (v1.svelte, v2.svelte, …) under componentDir; use the propContract prop names for dynamic text ({propName}), not literal snapshot strings. Put variant CSS in each component's <style> block with semantic class selectors (no @scope, no data-impeccable-*). Reply with --file set to the manifest path; the browser dynamically imports and mounts the compiled components so Svelte HMR does not reset page state while the user cycles variants. On Accept, live-accept.mjs inlines the accepted component back into sourceFile immediately after source promotion succeeds.
Params on component-preview paths go in a sidecar, never as an attribute. Svelte parses { inside an attribute value as the start of an expression, and both Svelte/Vue previews mount without an HTML variant wrapper. Declare params in componentDir/params.json, keyed by variant number, using the exact param schema from section 7:
{
"1": [
{"id":"density","kind":"steps","default":"snug","label":"Density","options":[
{"value":"airy","label":"Airy"},{"value":"snug","label":"Snug"},{"value":"packed","label":"Packed"}
]}
],
"2": [
{"id":"accent","kind":"range","min":0,"max":1,"step":0.05,"default":0.5,"label":"Accent"}
]
}
Author the component <style> against var(--p-<id>, default) for range/toggle and [data-p-<id>="…"] for steps; wrap those selectors in :global(...) so the knob values the runtime sets on the mounted root reach your rules. The browser reads params.json, docks the panel, and drives --p-* / data-p-* on the mounted component exactly as it does for the HTML/JSX path.
styleMode controls how preview CSS must be authored. Treat it as a detected capability mode, not a framework guess:
scoped: use@scope ([data-impeccable-variant="N"])rules.astro-global-prefixed: use explicit[data-impeccable-variant="N"]selector prefixes and the exactstyleTagreturned by the tool.
Use cssAuthoring as the source of truth for the current file. It includes the exact styleTag, selector strategy, selector examples, requirements, and forbidden patterns. Do not apply a framework-specific exception unless the returned styleMode / cssAuthoring.mode says to.
Fallback errors. Wrap only writes into files it judges to be source (tracked by git, not marked GENERATED, not listed in config's generatedFiles). If it can't land on a source file, it errors without writing; accepting a variant into a generated file is silent data loss. Three shapes:
{ error: "file_is_generated", file, hint }: user-supplied--filepoints at a generated file.{ error: "element_not_in_source", generatedMatch, hint }: element exists only in a generated file (the next build would wipe any edits).{ error: "element_not_found", hint }: element isn't in any project file; likely runtime-injected (JS component, dynamic render from data).
All three carry fallback: "agent-driven". Follow Handle fallback below.
3. Load the action's reference
If event.action is impeccable (the default freeform action), use SKILL.md's shared laws plus the loaded register reference (brand.md or product.md). Do not load a sub-command reference. Freeform is not a pass to skip parameters: you still follow the composition budget and the freeform bias in §7 Parameters below. Sub-command files list MUST-have signature knobs; freeform has no such file, so sizing knobs from surface weight and primary axes is entirely on you.
Any other event.action (bolder, quieter, distill, polish, typeset, colorize, layout, adapt, animate, delight, overdrive): Read reference/<action>.md before planning. Each sub-command encodes a specific discipline; skipping its reference produces generic output. Those files may require specific params; layer them on top of the §7 budget, not instead of it.
4. Plan three variants: identity first, then mode, then axes
The wrong frame for live mode is "show three different design directions." Live runs on an existing surface; the brand has already been chosen. The job is variation within identity, not selection between identities. Failure mode: three editorial-typographic variants on a brief that wasn't editorial. Bigger failure mode: three off-brand variants the user can't accept because they don't look like their product.
Four phases. Do them in order.
Phase A: Extract the identity (non-skippable)
The existing surface has an identity already. Read it before planning anything. Sources, in priority order:
- DESIGN.md if loaded: read the visual system fields (palette, type pairing, motion, components). This is the authoritative answer.
- CSS custom properties in the page's stylesheets (
:root { --color-...; --font-...; ... }): these are de-facto tokens. - Computed styles on the picked element and its parent: colors, fonts, spacing scales, corner radii.
- Sibling components on the page: what visual rhetoric do existing components use? (Asymmetric or centered? Dense or airy? Bold or quiet?)
Write down what you see in one sentence. The sentence describes the surface that's actually on screen; it is not aspirational, not opinionated, not edited toward what the brand "should" be. Capture, in roughly this order:
- The dominant surface color and accent color, by hex or token name (use the actual values, not categories like "warm" or "neutral").
- The type pairing: the actual font names loaded, primary first.
- The layout topology: how the dominant elements are arranged (stacked / side-by-side / grid / asymmetric / overlay).
- The surface treatment: corners, borders, shadows, density of decoration.
- The voice tone you read off the copy itself, not off the aesthetic feel.
Be specific. "Modern" is not a color, "elegant" is not a type pairing, "clean" is not a layout. If you can't extract a real value for an axis, skip it rather than fabricate. The point is to record what is, not to describe what you wish it were.
Do not include adjectives that name an aesthetic family ("editorial-leaning", "terminal-flavored", "brutalist"); those are conclusions, not data. They belong to Phase C lane selection in departure mode, not to identity description. Letting them sneak into Phase A is how the identity-lock collapses into a self-fulfilling prophecy.
This sentence is the identity lock. Every variant must be readable as the same brand if rendered side by side. Skipping this phase is the primary cause of off-brand variants. Absence of DESIGN.md is never an excuse; extract from CSS and computed styles instead.
Phase B: Pick mode (default vs departure)
Default mode: the existing identity is preserved. Variants vary expression axes within it. This is the right mode for ~90% of live sessions. The user picked an element on a real product they're shipping; they expect variants of their hero, not three different brands' heroes.
Departure mode: the existing identity is rejected. Variants propose alternatives consistent with PRODUCT.md voice. Trigger only when at least one is true:
- PRODUCT.md anti-references explicitly call out the current surface ("the current
index.htmlis itself an example"; "diffuse away from this"; "the page on screen is the failure"). Generic anti-references that describe what to avoid in general do not trigger departure mode; only ones that point at this surface specifically. - The user's freeform prompt explicitly asks for departure ("rebuild this from scratch", "what if it weren't editorial at all", "show me something completely different").
If you're unsure, you're in default mode. The cost of being wrong about default is "three on-brand variants with similar feel": recoverable, the user picks none. The cost of being wrong about departure is "three off-brand variants": unrecoverable, the user is annoyed.
Phase C: Plan three variants
Default mode. Each variant commits to a different primary axis of difference, while preserving the identity sentence. The six axes:
- Hierarchy: which element commands the eye?
- Layout topology: stacked / side-by-side / grid / asymmetric / overlay
- Typographic system: pairing logic, scale ratio, case/weight strategy within the available faces
- Color strategy: which existing palette role carries the surface (Restrained / Committed / Full palette / Drenched). Use the brand's existing palette tokens, not new colors.
- Density: minimal / comfortable / dense
- Structural decomposition: merge, split, progressive disclosure
Three variants → three DIFFERENT axes. The trio reads as the same brand at three angles. Do not introduce new fonts, new palette hues, or new aesthetic-family signals; those belong to departure mode.
While planning each variant, also name its 2–3 parameter knobs (per the §7 budget table). Parameters are part of the design, not a decoration added afterward. If the variant explores density, expose a density knob. If it explores color commitment, expose a color-amount range. Deciding "what's tunable" during planning produces better knobs than retrofitting them onto finished HTML.
Departure mode. Each variant anchors to a different aesthetic direction, derived from the brand's stated voice and register in PRODUCT.md. Do NOT pick from a fixed catalog of lane categories. The right three directions for this brand are not the same as the right three for another brand, and picking from a list is itself the training-data reflex (the model selects "Swiss-grid, Terminal, Industrial-signage" every time because those are the furthest-from-editorial items in any enumerated list).
Instead, work from the brand:
- Read PRODUCT.md's Brand Personality words. What physical, spatial, or material experiences would embody those words if design were not involved? (A personality described as "specific, earned, unmistakable" evokes a hand-stamped letter, a numbered print, a watchmaker's loupe. A personality described as "restless, loud, unfiltered" evokes a concert poster, a spray-painted wall, a megaphone.)
- From those physical experiences, derive three visual directions that are genuinely different from each other AND from the current surface you're departing.
- Avoid the reflex-reject lanes in brand.md. Don't trade one monoculture for another. If you find yourself reaching for "Swiss-grid" or "Terminal" or "Industrial-signage" by reflex, you are pattern-matching a catalog in your training data, not reading the brand. Start over from the personality words.
- Each direction must be expressible in one concrete sentence that names a real-world referent ("a museum exhibition label system for a contemporary art gallery" not "clean and minimal"). If your sentence contains only adjectives, it's not concrete enough.
- While planning each direction, also name its 2–3 parameter knobs (per the §7 budget table). The same principle as default mode: decide "what's tunable" during planning, not after writing the HTML. A departure-mode hero with 0 parameters is not "bold creative vision," it's a missed opportunity for the user to fine-tune the direction they pick.
Phase D: Squint test
Default mode squint. Read each variant's identity sentence and compare to the locked identity from Phase A. If any variant has drifted to a different palette, type voice, or visual rhetoric, it has crossed into departure mode by accident; rework. Then check that each variant commits to a different primary axis. Three "tighter density" variants is failure.
Departure mode squint. Two passes, family before sentence:
- Family pass. Label each variant with one design-family word of your own choosing (any concrete noun: exhibition, storefront, cockpit, recipe-card, playbill, field-manual). If any two variants share a label, or if the label could apply to the other variants equally well, rework. Do not use a fixed vocabulary list for the labels. This pass is non-negotiable in departure mode and catches the monoculture failure that the sentence pass misses.
- Sentence pass. Write three one-sentence descriptions side by side. If two of them rhyme ("both feature big type" / "both are stacks of sections" / "both center the CTA"), rework the offender.
When the primary axis is color or theme, forbid the trio from sharing theme + dominant hue. Two dark-plus-one-dark is not distinct. Aim for three color worlds, not three shades of the same.
For action-specific invocations, each variant must vary along the dimension the action names:
bolder: amplify a different dimension per variant (scale / saturation / structural change). Not three "slightly bigger" variants.quieter: pull back a different dimension (color / ornament / spacing).distill: remove a different class of excess (visual noise / redundant content / nested structure).polish: target a different refinement axis (rhythm / hierarchy / micro-details like corner radii, focus states, optical kerning).typeset: different type pairing AND different scale ratio each. Not three riffs on one pairing.colorize: different hue family each (not shades of one hue). Vary chroma and contrast strategy.layout: different structural arrangement (stacked / side-by-side / grid / asymmetric). Not spacing tweaks.adapt: different target context per variant (mobile-first / tablet / desktop / print or low-data). Don't make three mobile layouts.animate: different motion vocabulary (cascade stagger / clip wipe / scale-and-focus / morph / parallax). Not three staggered fades.delight: different flavor of personality (unexpected micro-interaction / typographic surprise / illustrated accent / sonic-or-haptic moment / easter-egg interaction).overdrive: different convention broken (scale / structure / motion / input model / state transitions). Skipoverdrive.md's "propose and ask" step; live mode is non-interactive.
5. Apply the freeform prompt (if present)
event.freeformPrompt is the user's ceiling on direction (all variants must honor it), but still explore meaningfully different interpretations. The interpretations stay within whichever mode you picked in Phase B.
In default mode, the prompt narrows the axes you choose, not the identity. "Make it feel more confident" → variant 1 amplifies hierarchy (one element commands the eye), variant 2 commits the existing accent color (Committed strategy on the brand's hue), variant 3 tightens density and removes decorative slack. Three different axes, same brand.
In departure mode, the prompt narrows the lanes you draw from, not the families. "Make it feel like a newspaper front page" would itself be a departure-mode prompt; honor it but pick three meaningfully different newspaper-adjacent lanes (broadsheet vs. tabloid vs. trade journal), and run the family pass to confirm they don't collapse into one.
When the prompt and PRODUCT.md anti-references conflict (the prompt asks for X, the anti-references ban X), the anti-references win; they describe the brand's standing position, the prompt is one moment.
6. Deliver variants
Complete HTML replacement of the original element for each variant, not a CSS-only patch. Consider the element's context (computed styles, parent structure, CSS variables from event.element).
Colocate preview CSS as a <style> tag inside the variant wrapper; <style> works anywhere in modern browsers and keeps each delivered state internally complete (no FOUC).
Atomic default: write CSS + all variants + parameter manifests in one edit at insertLine, preserving the established behavior.
Use the cssAuthoring object returned by live-wrap.mjs to author the temporary preview CSS. The style opening tag shown below is the common case; replace it with cssAuthoring.styleTag when the tool returns a different one. The variant markup shape is otherwise stable:
<!-- Variants: insert below this line -->
<style data-impeccable-css="SESSION_ID">
/* rules matching cssAuthoring.rulePattern */
</style>
<div data-impeccable-variant="1">
<!-- variant 1: full element replacement (single top-level element) -->
</div>
<div data-impeccable-variant="2" style="display: none">
<!-- variant 2: full element replacement -->
</div>
<div data-impeccable-variant="3" style="display: none">
<!-- variant 3: full element replacement -->
</div>
Each variant div contains exactly one top-level element: the full replacement for the original. Use the same tag as the original (e.g. <section> if the user picked a <section>). Loose siblings (heading + paragraph + div as direct children of the variant div) break the outline tracking and the accept flow, which both assume one child.
The first variant has no display: none (visible by default). All others do. If variants use only inline styles and no preview CSS, omit the <style> tag entirely.
The browser's MutationObserver accepts either delivery shape. On the transactional progressive path it shows arrived variants and pending dots immediately; Accept and Discard are available as soon as one variant exists. Accepting an arrived variant fences the worker before the browser releases the picker, so later publications are rejected.
For styleMode: "scoped", author every :scope rule with a descendant combinator. The @scope boundary is the variant wrapper <div data-impeccable-variant="N">, not the element you're designing. A bare :scope { background: cream; } styles the wrapper, not the inner replacement, so the cream lands on a display: contents shell while the actual element keeps page defaults. Always step in: :scope > .card, :scope > section, :scope .hero-title, etc. The fake test agent's CSS in tests/live-e2e/agent.mjs is a faithful template; every scoped rule starts :scope > ....
JSX / TSX target files. Wrap <style> content in a template literal so the CSS { / } aren't parsed as JSX expressions, and use className= / style={{…}} on every variant element. Keep data-impeccable-* attributes as-is; they're plain strings:
<style data-impeccable-css="SESSION_ID">{`
@scope ([data-impeccable-variant="1"]) { ... }
@scope ([data-impeccable-variant="2"]) { ... }
`}</style>
<div data-impeccable-variant="1">
{/* variant 1 */}
</div>
<div data-impeccable-variant="2" style={{ display: 'none' }}>
{/* variant 2 */}
</div>
The wrap script already gives you a single-rooted JSX wrapper: a <div data-impeccable-variants="…"> outer element with the marker comments tucked inside. Drop the variants block above into the "Variants: insert below this line" comment and the source stays valid TSX.
7. Parameters (composition-sized, 0–4 per variant)
Each variant can expose coarse knobs alongside the full HTML/CSS replacement. The browser docks a small panel to the right of the outline with one control per parameter. The user drags/clicks and sees instant feedback: there is zero regeneration cost because the knob toggles a CSS variable or data attribute that the variant's scoped CSS is already authored against.
What “optional” does not mean. Parameters are not nice-to-have decoration on large work. The word meant “omit controls that are redundant or cosmetic,” not “default to zero because three variants were enough work.”
When to add. As soon as the variant’s scoped CSS has a meaningful continuous or stepped axis: density, color amount, type scale, motion intensity, column weight, and so on. If you can imagine the user muttering “a bit tighter” or “a touch more accent” without wanting a full regeneration, wire that axis. Not micro-margins or one-off nudges; those are not parameters.
Freeform (action is impeccable) bias. You did not load a sub-command reference, so you must choose signature axes yourself. Match the budget table: for a hero or large composition, that means 2–3 axes per variant, not 1. Prefer knobs that sit on the dimensions where your three variants actually differ (if density varies, expose it as a steps knob; if color commitment varies, expose it as a range). A hero that ships with 0 params is almost always a mistake, not a judgment call. A hero with exactly 1 param is underweight unless the design is genuinely a fixed-point comparison. Start from the budget table, not from zero.
Budget scales with the element's visual weight, not token budget. Knobs need real estate to read as tunable; three sliders on a single control are noise.
- Leaf / tiny: a single button, icon, input, bare heading, solitary paragraph: 0 params.
- Small composition: labeled input, simple card, short callout (≤ ~5 visual children): 0–1 params when one dominant axis is obvious; otherwise 0.
- Medium composition: section component, nav cluster, dense card, short feature block (6–15 visual children): target 2; 1 is acceptable if the block is simple; 0 only when variants are truly fixed points.
- Large composition: hero section, full page region, spread layout, strong internal structure (16+ visual children or multiple sub-sections): target 2–3; up to 4 when several independent axes (e.g. structure
steps+density+ one accent) are all authored in scoped CSS.
When in doubt, ask whether a dial exists before defaulting to zero. The user can always request more variants, but the point of live mode is instant tuning without another Go. Crowding the panel is bad; under-shipping knobs on a dense composition is the more common failure for freeform. Count by visual children, not DOM depth; a shallow-but-wide hero is still large.
Hard cap per variant: at most four parameters so the panel stays legible; rare fifth only if the reference explicitly allows it.
How to declare. Put a JSON manifest on the variant wrapper (HTML/JSX path). On the svelte-component path, do not use this attribute. Declare params in componentDir/params.json keyed by variant number instead (see the component-preview paragraphs in the wrap section). The param schema below is identical for every path.
<div data-impeccable-variant="1" data-impeccable-params='[
{"id":"color-amount","kind":"range","min":0,"max":1,"step":0.05,"default":0.5,"label":"Color amount"},
{"id":"density","kind":"steps","default":"snug","label":"Density","options":[
{"value":"airy","label":"Airy"},
{"value":"snug","label":"Snug"},
{"value":"packed","label":"Packed"}
]},
{"id":"serif","kind":"toggle","default":false,"label":"Serif display"}
]'>
...variant content...
</div>
Three kinds:
range: smooth slider. Drives a CSS custom property--p-<id>on the variant wrapper. Author CSS withvar(--p-color-amount, 0.5). Fields:min,max,step,default(number),label.steps: segmented radio. Drives a data attributedata-p-<id>on the variant wrapper. Author CSS with:scope[data-p-density="airy"] .grid { ... }. Fields:options(array of{value, label}),default(string),label.toggle: on/off switch. Drives BOTH a CSS var (--p-<id>: 0|1) and a data attribute (present when on, absent when off). Use whichever is more convenient. Fields:default(boolean),label.
Signature params per action. For named sub-commands, read that action’s reference/<action>.md for one or two MUST params (e.g. layout → density). Those are non-negotiable when the design can express them. Freeform has no file-level MUST; the Freeform (impeccable) bias in this section is the stand-in. If the user’s action is both stylized and sub-command (e.g. colorize), the sub-command’s MUST list takes precedence for its axes; still respect the Hard cap and add no redundant duplicate knobs.
Reset on variant switch. User dials density on v1, flips to v2, v2 starts at v2's declared defaults. Known limitation; preservation across variants may land later.
On accept, the browser sends the user's current values in the accept event. live-accept.mjs writes them as a sibling comment:
<!-- impeccable-param-values SESSION_ID: {"color-amount":0.7,"density":"packed"} -->
The carbonize cleanup step (see below) reads that comment and bakes the chosen values into the final CSS. For steps/toggle attribute selectors: keep only the branch matching the chosen value, drop the others, collapse :scope[data-p-density="packed"] .grid to a semantic class rule. For range vars: either substitute the literal or keep the var with the chosen value as its new default.
8. Signal done
node {{scripts_path}}/live-poll.mjs --reply EVENT_ID done --file RELATIVE_PATH
RELATIVE_PATH is relative to project root (public/index.html, src/App.tsx, etc.); the browser fetches source directly if the dev server lacks HMR.
Then run live-poll.mjs again immediately.
Aborting an in-flight session
If wrap or generation fails after the browser has flipped to GENERATING (e.g. wrap landed on the wrong source branch and you've already reverted it, or generation hit an unrecoverable error), tell the browser so its bar resets to PICKING:
node {{scripts_path}}/live-poll.mjs --reply EVENT_ID error "Short reason"
Don't run live-accept --discard for this; that's a pure file mutator, the browser doesn't see it, and the bar gets stuck on the GENERATING dots forever (the user has to refresh). --discard is only correct when the browser initiated the discard (user clicked ✕ during CYCLING) and the agent is just running source-side cleanup the browser already triggered.
Handle fallback
When wrap returns fallback: "agent-driven", the deterministic flow doesn't apply. Pick up here.
The goal is the same: give the user three variants to choose from AND persist the accepted one in a place the next build won't wipe. The difference is that you have to pick the right source file yourself.
Step 1: Identify where the element actually lives
Use the error payload:
element_not_in_sourcewithgeneratedMatch: "public/docs/foo.html": the served HTML is generated. Find the generator (grep for writers of that path, e.g.scripts/build-sub-pages.js, an Astro/Next template) and locate the template or partial that emits this element.element_not_found: the element is runtime-injected. Look for the component that renders it (React/Vue/Svelte), the JS that assembles it, or the data source that feeds it.file_is_generatedwithfile: "...": user pointed at a generated file explicitly. Same resolution aselement_not_in_source.
Read the candidate source until you're confident where a change to the element would belong. If the change is purely visual, that source might be a shared stylesheet, not the template.
Step 2: Show three variants in the DOM for preview
The browser bar is waiting for variants. Even without a wrapper in source, you still need to show something:
- Manually write the wrapper scaffold into the served file (the one the browser actually loaded). Use the same structure
live-wrap.mjsproduces;<!-- impeccable-variants-start ID --><div data-impeccable-variants="ID" data-impeccable-variant-count="3" style="display: contents">…</div><!-- end -->. - Insert your three variant divs inside it, same shape as the deterministic path.
- Signal done with
--reply EVENT_ID done --file <served file>. The browser's no-HMR fallback will fetch and inject.
This served-file edit is temporary: next regen wipes it, and that's fine. The real work happens on accept.
Step 3: On accept, write to true source
When the accept event arrives (_acceptResult.handled will usually be false here because accept also refuses to persist into generated files; see Handle accept for the carbonize branch), extract the accepted variant's content and write it into the source you identified in Step 1:
- Structural change → edit the template / component source.
- Visual-only change → add or update rules in the appropriate stylesheet; remove the inline
<style>scope. - Dynamic from data → update the data source or the render logic.
Then remove the temporary wrapper from the served file if it's still there.
Step 4: On discard, clean up the served file
Remove the wrapper you inserted in Step 2. Nothing else to do.
Handle accept
Event: {id, variantId, _acceptResult, _completionAck}. The poll script already ran live-accept.mjs to handle the file operation deterministically, then acknowledged event delivery to the helper. The browser DOM is already updated.
- The accept event includes
pageUrl; the poll script must forward it tolive-accept.mjs --page-url PAGE_URLso accept-time cleanup only scrubs staged copy edits for the current page. _completionAck.ok !== true: do not poll yet. Runlive-status.mjs/live-resume.mjs, complete the cleanup manually if needed, then runlive-complete.mjs --id EVENT_ID._acceptResult.handled: trueandcarbonize: false: nothing to do. Poll again._acceptResult.handled: trueandcarbonize: true: post-accept cleanup is required, but it must not stall Codex's control lane. See "Required after accept (carbonize)" below. Theevent._acceptResult.todofield,_completionAck.requiresComplete, and stderr banner all point at this required follow-up; none are decorative._acceptResult.handled: false, mode: "fallback": the session lived in a generated file and the script refused to persist there. You've already written the accepted variant into true source during Handle fallback Step 3; just clean up the temporary wrapper in the served file if any, and poll again._acceptResult.handled: false, mode: "error": the operation genuinely failed. Do not hand-edit the file; the source was not touched and editing it yourself would either double-apply or race whoever holds it.error: "source_locked": a generation publish holds the file. Run the samelive-accept.mjscommand again; it is idempotent and will succeed once the publisher releases. Do not poll past it.error: "accept_receipt_conflict": this session already resolved aspriorOperation(onpriorVariantIdfor an accept), so the request contradicts durable truth. Do not edit. Runlive-status.mjsand tell the user what the session actually resolved to.- anything else: report the error briefly and run
live-status.mjsbefore continuing.
_acceptResult.handled: falsewithoutmode: manual cleanup: read file, find markers, edit.
Required after accept (carbonize)
When _acceptResult.carbonize === true, the accepted variant was stitched into source with helper markers and inline CSS so the browser can render it immediately with no visual gap. That stitch-in is temporary. The agent must rewrite it into permanent form before doing anything else. Skipping this leaves dead @scope rules for unaccepted variants, a pointless data-impeccable-variant wrapper, and impeccable-carbonize-start/end comment noise in the source file; all of which accumulate across sessions.
Do these five steps synchronously before the next poll. The source lock, generation epoch, and expected-source hash remain the final safety gates against a generator finishing concurrently with Accept.
- Locate the carbonize block in the source file (
_acceptResult.file). It's bracketed by<!-- impeccable-carbonize-start SESSION_ID -->and<!-- impeccable-carbonize-end SESSION_ID -->and contains a<style data-impeccable-css="SESSION_ID">element. If the variant declared parameters, an<!-- impeccable-param-values SESSION_ID: {...} -->comment sits alongside the style tag with the user's chosen values; read it first; it drives steps 3 and 4 below. - Move the CSS rules into the project's real stylesheet. Which stylesheet depends on the project (e.g.
site/styles/workflow.cssfor an Astro project, or the component's co-located CSS file for a Vite/Next project; pick whichever already owns styling for the surrounding element). - Bake in parameter values while rewriting selectors. For
@scope ([data-impeccable-variant="N"])wrappers: retarget to real, semantic classes on the accepted HTML (.why-visual--v2 .v2-label { … }). For:scope[data-p-<id>="VALUE"]selectors: keep only the branch matching the chosen value from the param-values comment; drop the others (they're dead after accept). Forvar(--p-<id>, DEFAULT)in the CSS: either substitute the literal value, or if the param is still useful as a knob going forward, leave the var and update its initial declaration to the chosen value. - Unwrap the accepted content. Delete the inner
<div data-impeccable-variant="N" style="display: contents">that wraps it. On JSX/TSX, also delete the outer<div data-impeccable-carbonize="SESSION_ID" style={{ display: 'contents' }}>wrapper if present (accept adds it so ternary/returnslots keep a single root). Dropdata-impeccable-paramsand anydata-p-*attributes; those are live-mode plumbing, not source. - Delete the inline
<style>block, the<!-- impeccable-param-values -->comment if present, and both<!-- impeccable-carbonize-start/end -->markers. Also drop any@scoperules for variants other than the accepted one; those are dead code now.
After the file is clean, the cleanup owner runs live-complete.mjs --id SESSION_ID and verifies phase: "completed". Poll again only after that verification.
Handle discard
Event: {id, _acceptResult, _completionAck}. The poll script already restored the original, removed all variant markers, and acknowledged discarded durable completion. Nothing to do unless _completionAck.ok !== true; in that case run live-complete.mjs --id EVENT_ID --discarded, then poll again.
Handle steer
Event: {id, message, pageUrl}. The user typed or spoke into the global bar Steer control: page-level direction without picking an element or launching variant generation.
The mic button uses the browser Web Speech API (MVP): click to start, speak, stop automatically when the utterance ends, then the transcript submits as a steer event. Click again while listening to cancel without submitting.
This is lighter than generate: no screenshot, no element context, no variant cycling. Read message and inspect the live page or project files as needed, then either make edits or answer in prose.
When finished:
node {{scripts_path}}/live-poll.mjs --reply EVENT_ID steer_done ["Optional short note for a browser toast"]
On failure:
node {{scripts_path}}/live-poll.mjs --reply EVENT_ID error "Short reason"
Then poll again immediately. Do not send a separate "picked up" reply. The Steer bar stays locked until steer_done or error arrives over SSE.
Handle prefetch
Event: {pageUrl}. The browser fires this the first time the user selects an element on a given route, as a latency shortcut; it signals the user is likely about to Go on a page you haven't read yet.
Resolve pageUrl to the underlying file:
- Root
/→ thepageFilereturned bylive.mjs(usuallypublic/index.htmlor equivalent). - Sub-routes (e.g.
/docs,/docs/live) → the generated or source file for that route. Use your knowledge of the project layout (multi-page static sites often resolve/foo→public/foo/index.html; SPAs may map all routes to a single entry).
Read the file into context, then poll again. No --reply: this is speculative pre-work; Go will come later. If you can't confidently resolve the route to a file, skip and poll again.
Dedupe is the browser's job (one prefetch per unique pathname per session); trust it. If the same file shows up twice from different routes mapping to the same file, the second Read is cached anyway.
Handle manual_edit_apply
Event: {id, pageUrl, batch: {entries}, evidencePath?, chunk?, repair?, deadlineMs}.
The user already clicked Apply. Do not ask what to do, discard, or redirect to Go. The parent live thread keeps the foreground poll loop and sends the final /poll --reply --data.
When native subagents are available, delegate source edits to impeccable_manual_edit_applier / impeccable-manual-edit-applier. Pass cwd, scripts path, event id, page URL, chunk/deadline, batch, evidencePath, and the canonical JSON result schema. The subagent must not poll or reply. If unavailable, apply inline with the same contract.
If repair is present, the previous Apply changed source but final validation failed. Fix the current source and return the same canonical JSON result; do not roll files back yourself. The browser will ask the user before any rollback.
After source edits finish, reply exactly once with node {{scripts_path}}/live-poll.mjs --reply EVENT_ID done --data '{"status":"done","appliedEntryIds":["8hexid"],"failed":[],"files":["src/page.html"],"notes":[]}'. Use status:"partial" or status:"error" with failed[] when not every entry applied. Then poll again. Never reply without the event id; --reply done --file ... is invalid for manual Apply.
Exit
The user can stop live mode by:
- Saying "stop live mode" / "exit live" in chat
- Closing the browser tab (SSE drops, poll returns
exitafter 8s) - The browser's exit button
When the poll returns exit, proceed to cleanup. If the poll is still running as a background task, kill it first.
Cleanup
node {{scripts_path}}/live-server.mjs stop
Stops the HTTP server and runs live-inject.mjs --remove to strip localhost:…/live.js from the HTML entry. To stop the server but keep the inject tag (for a quick restart), use stop --keep-inject. .impeccable/live/config.json persists as project config for future sessions.
Then:
- Remove any leftover variant wrappers (search for
impeccable-variants-startmarkers). - Remove any leftover carbonize blocks (search for
impeccable-carbonize-startmarkers).
First-time setup (config missing or invalid)
If live.mjs outputs { ok: false, error: "config_missing" | "config_invalid", path }, write the live config at the reported path. By default this is .impeccable/live/config.json.
Schema:
{
"files": ["<path-or-glob>", "<path-or-glob>", ...],
"exclude": ["<optional-glob>", ...],
"insertBefore": "</body>",
"commentSyntax": "html",
"cspChecked": true
}
files is the inject target; the HTML files the browser actually loads, not necessarily source. Each entry is either a literal path ("public/index.html") or a glob pattern ("public/**/*.html"). Tracked or generated doesn't matter here; wrap has its own generated-file guard and routes accepts through the fallback flow.
exclude (optional) is a list of glob patterns matching files to skip, even if a files glob would have included them. Use for email templates, demo fixtures, or any HTML that isn't a live page.
cspChecked tracks whether the CSP detection step below has already run. Absent on first setup; set to true after CSP is checked (whether patched, declined, or not needed).
Hard-excluded paths (cannot be overridden). **/node_modules/** and **/.git/** are never matched regardless of what the user writes. These are vendor/metadata directories and injecting into them would silently instrument third-party code.
Glob syntax. ** matches any number of path segments (including zero), * matches any characters except /, ? matches a single character except /. Paths are always relative to the project root with forward slashes.
| Framework | files |
insertBefore |
commentSyntax |
|---|---|---|---|
| SPA with single shell (Vite / React / Plain HTML) | ["index.html"] |
</body> |
html |
| Next.js (App Router) | ["app/layout.tsx"] |
</body> |
jsx |
| Next.js (Pages) | ["pages/_document.tsx"] |
</body> |
jsx |
| Nuxt | ["app.vue"] |
</body> |
html |
| Svelte / SvelteKit | ["src/app.html"] |
</body> |
html |
| Astro | [" <root layout .astro>"] |
</body> |
html |
| Multi-page (separate HTML per route) | ["public/**/*.html"]: a glob covering the served directory |
</body> |
html |
Pick an anchor that exists in every file (</body> almost always works). Use insertAfter if the anchor should match after a specific line.
For multi-page sites, prefer a glob over a literal file list. New pages added later are picked up automatically on the next live-inject.mjs run; no config maintenance needed.
For multi-page sites whose pages are rebuilt by a generator (Astro, static-site generators, custom scripts like build-sub-pages.js), the inject survives only until the next regeneration. Re-run live.mjs after each build. Accept is unaffected; it writes to true source via the fallback flow.
Drift-heal warning
On every live.mjs boot, after inject, the project is scanned for HTML files under common page-source roots (public/, src/, app/, pages/). If any exist that aren't covered by the resolved files list, the output includes a configDrift field:
{
"ok": true,
"serverPort": 8400,
"pageFiles": [ "..." ],
"configDrift": {
"orphans": ["public/new-section/index.html", "public/docs/new-command.html"],
"orphanCount": 2,
"hint": "2 HTML file(s) exist but aren't in config.files. Consider adding them, or use a glob pattern like \"public/**/*.html\"."
}
}
When configDrift is present, surface it to the user once per session before entering the poll loop:
Noticed N HTML file(s) in the project that aren't in
config.files:
public/new-section/index.htmlpublic/docs/new-command.htmlAdd them, or switch
filesto a glob like["public/**/*.html"]and let it track new pages automatically?
Don't auto-update the config; let the user decide. configDrift is null when there's no drift.
CSP detection (first-time only)
If config.cspChecked === true, skip this entire section. You already asked this user once; the answer sticks.
Otherwise, run the detection helper:
node {{scripts_path}}/detect-csp.mjs
Output: { shape, signals } where shape is one of append-arrays, append-string, middleware, meta-tag, or null. The shape is named by patch mechanism, so one template covers many frameworks.
null: no CSP; skip to writing.impeccable/live/config.jsonwithcspChecked: true.append-arrays: CSP defined as structured directive arrays. Auto-patchable. See append-arrays below. Covers:- Monorepo helpers with
additionalScriptSrc/additionalConnectSrcoptions (Next.js + shared config package) - SvelteKit
kit.csp.directives - Nuxt
nuxt-securitymodule'scontentSecurityPolicy
- Monorepo helpers with
append-string: CSP written as a literal value string. Auto-patchable. See append-string below. Covers:- Inline
next.config.*headers()with a CSP literal - Nuxt
routeRules/nitro.routeRulesheaders
- Inline
middlewareormeta-tag: rarer. Detected but not auto-patched in v1. Show the user the detected files and ask them to addhttp://localhost:8400toscript-srcandconnect-srcmanually, then markcspChecked: trueand proceed.
Consent prompt template
Use this phrasing so the experience is consistent across agents:
CSP patch needed. I detected a Content Security Policy in your project that blocks
http://localhost:8400: the live picker won't load without an allowance. Here's the change I'd make:[file: <patchTarget>] [exact diff, 2–5 lines]It's guarded by
NODE_ENV === "development"so the extra entry only appears in dev and never reaches production. You can remove it any time by reverting this file. Apply? [y/n]
On "no": skip the patch, mention live won't work until the user adds the allowance manually, still write cspChecked: true (the question's been asked).
On "yes": apply the Shape-specific patch below, then write cspChecked: true.
append-arrays
CSP expressed as structured directive arrays. Patch mechanism: declare a dev-only array, spread it into the script-src and connect-src arrays.
Declare near the top of the file that holds the CSP arrays:
// Dev-only allowance so impeccable live mode can load. Guarded by NODE_ENV.
const __impeccableLiveDev =
process.env.NODE_ENV === "development" ? ["http://localhost:8400"] : [];
Append ...__impeccableLiveDev to the script-src and connect-src directive arrays. Per-framework specifics:
- Next.js + monorepo helper: edit the app's
next.config.*(not the shared helper), appending toadditionalScriptSrcandadditionalConnectSrcpassed intocreateBaseNextConfig(or equivalent). Keeps the shared package clean. - SvelteKit: edit
svelte.config.js, appending tokit.csp.directives['script-src']andkit.csp.directives['connect-src']. - Nuxt + nuxt-security: edit
nuxt.config.*, appending tosecurity.headers.contentSecurityPolicy['script-src']and['connect-src'].
Reference outputs:
tests/framework-fixtures/nextjs-turborepo/expected-after-patch.ts(Next.js)tests/framework-fixtures/sveltekit-csp/expected-after-patch.js(SvelteKit)
Idempotency: if __impeccableLiveDev already exists in the file, the patch is already applied; skip asking and just mark cspChecked: true.
append-string
CSP built as a literal value string. Two-point patch: declare a dev-only string near the top, interpolate it into the CSP at the script-src and connect-src directives.
// Dev-only allowance so impeccable live mode can load.
const __impeccableLiveDev =
process.env.NODE_ENV === "development" ? " http://localhost:8400" : "";
Then in the CSP value string:
script-src 'self' 'unsafe-inline'→`script-src 'self' 'unsafe-inline'${__impeccableLiveDev}`connect-src 'self'→`connect-src 'self'${__impeccableLiveDev}`
(Leading space on the dev string so it concatenates cleanly into the existing value. Convert the literal CSP directives into template strings as part of the edit if they aren't already.)
Per-framework specifics:
- Next.js inline
headers(): editnext.config.*, splicing the variable into the CSP value. - Nuxt
routeRules: editnuxt.config.*, splicing into the CSP inrouteRules['/**'].headers['Content-Security-Policy'].
Reference outputs:
tests/framework-fixtures/nextjs-inline-csp/expected-after-patch.js(Next.js)tests/framework-fixtures/nuxt-csp/expected-after-patch.ts(Nuxt)
Troubleshooting
If a user says "no" to the CSP patch at setup time and later complains that live doesn't work: their dev CSP blocks http://localhost:8400. Fix: delete cspChecked from .impeccable/live/config.json and re-run live.mjs: setup will ask again.
Then re-run live.mjs.