mirror of
https://github.com/pbakaus/impeccable.git
synced 2026-09-12 06:06:37 +03:00
* 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>
917 lines
36 KiB
JavaScript
917 lines
36 KiB
JavaScript
/**
|
|
* CLI helper: find an element in source and wrap it in a variant container.
|
|
*
|
|
* Usage:
|
|
* node <scripts_path>/live-wrap.mjs --id SESSION_ID --count N --query "hero-combined-left" [--file path]
|
|
*
|
|
* Searches project files for the element matching the query (class name, ID, or
|
|
* text snippet), wraps it with the variant scaffolding, and prints the file path
|
|
* + line range where the agent should insert variant HTML.
|
|
*
|
|
* This replaces 3-4 agent tool calls (grep + read + edit) with a single CLI call.
|
|
*/
|
|
|
|
import fs from 'node:fs';
|
|
import path from 'node:path';
|
|
import { isGeneratedFile } from './lib/is-generated.mjs';
|
|
import { readBuffer as readManualEditsBuffer } from './live/manual-edits-buffer.mjs';
|
|
import {
|
|
buildSvelteComponentCssAuthoring,
|
|
scaffoldSvelteComponentSession,
|
|
shouldUseSvelteComponentInjection,
|
|
} from './live/svelte-component.mjs';
|
|
|
|
const EXTENSIONS = ['.html', '.jsx', '.tsx', '.vue', '.svelte', '.astro'];
|
|
|
|
export async function wrapCli() {
|
|
const args = process.argv.slice(2);
|
|
|
|
if (args.includes('--help') || args.includes('-h')) {
|
|
console.log(`Usage: impeccable wrap [options]
|
|
|
|
Find an element in source and wrap it in a variant container.
|
|
|
|
Required:
|
|
--id ID Session ID for the variant wrapper
|
|
--count N Number of expected variants (1-8)
|
|
|
|
Element identification (at least one required):
|
|
--element-id ID HTML id attribute of the element
|
|
--classes A,B,C Comma- or space-separated CSS class names
|
|
--tag TAG Tag name (div, section, etc.)
|
|
--query TEXT Fallback: raw text to search for
|
|
|
|
Optional:
|
|
--file PATH Source file to search in (skips auto-detection)
|
|
--text TEXT Picked element's textContent. Used to disambiguate when
|
|
classes/tag match multiple sibling elements (e.g. a list
|
|
of <Card>s with the same className). Pass the first ~80
|
|
chars of event.element.textContent.
|
|
--page-url URL Current page URL. Required when pending manual edits may
|
|
affect the picked source block. Pending edits are filtered
|
|
to this page so an edit on /a doesn't bleed into /b.
|
|
--help Show this help message
|
|
|
|
Output (JSON):
|
|
{ file, startLine, endLine, insertLine, commentSyntax }
|
|
|
|
The agent should insert variant HTML at insertLine.`);
|
|
process.exit(0);
|
|
}
|
|
|
|
const id = argVal(args, '--id');
|
|
const count = parseInt(argVal(args, '--count') || '3');
|
|
const elementId = argVal(args, '--element-id');
|
|
const classes = argVal(args, '--classes');
|
|
const tag = argVal(args, '--tag');
|
|
const query = argVal(args, '--query');
|
|
const filePath = argVal(args, '--file');
|
|
const text = argVal(args, '--text');
|
|
const pageUrl = argVal(args, '--page-url');
|
|
|
|
if (!id) { console.error('Missing --id'); process.exit(1); }
|
|
if (!elementId && !classes && !query) {
|
|
console.error('Need at least one of: --element-id, --classes, --query');
|
|
process.exit(1);
|
|
}
|
|
|
|
// Build search queries in priority order (most specific first)
|
|
const queries = buildSearchQueries(elementId, classes, tag, query);
|
|
|
|
const genOpts = { cwd: process.cwd() };
|
|
|
|
// Find the source file. Generated files are excluded from auto-search so we
|
|
// don't silently write variants into a file the next build will wipe.
|
|
let targetFile = filePath;
|
|
let matchedQuery = null;
|
|
if (!targetFile) {
|
|
for (const q of queries) {
|
|
targetFile = findFileWithQuery(q, process.cwd(), genOpts);
|
|
if (targetFile) { matchedQuery = q; break; }
|
|
}
|
|
if (!targetFile) {
|
|
// Nothing in source. Did the element show up in a generated file? That
|
|
// tells the agent "fall back to the agent-driven flow" vs "element just
|
|
// doesn't exist in this project."
|
|
let generatedHit = null;
|
|
for (const q of queries) {
|
|
generatedHit = findFileWithQuery(q, process.cwd(), { ...genOpts, includeGenerated: true });
|
|
if (generatedHit) break;
|
|
}
|
|
if (generatedHit) {
|
|
console.error(JSON.stringify({
|
|
error: 'element_not_in_source',
|
|
fallback: 'agent-driven',
|
|
generatedMatch: path.relative(process.cwd(), generatedHit),
|
|
hint: 'Element found only in a generated file. See "Handle fallback" in live.md.',
|
|
}));
|
|
} else {
|
|
console.error(JSON.stringify({
|
|
error: 'element_not_found',
|
|
fallback: 'agent-driven',
|
|
hint: 'Element not found in any project file. It may be runtime-injected (JS component, etc.). See "Handle fallback" in live.md.',
|
|
}));
|
|
}
|
|
process.exit(1);
|
|
}
|
|
} else {
|
|
if (isGeneratedFile(targetFile, genOpts)) {
|
|
console.error(JSON.stringify({
|
|
error: 'file_is_generated',
|
|
fallback: 'agent-driven',
|
|
file: path.relative(process.cwd(), path.resolve(process.cwd(), targetFile)),
|
|
hint: 'Explicit --file points at a generated file. Writing here gets wiped by the next build. See "Handle fallback" in live.md.',
|
|
}));
|
|
process.exit(1);
|
|
}
|
|
matchedQuery = queries[0];
|
|
}
|
|
|
|
const content = fs.readFileSync(targetFile, 'utf-8');
|
|
const lines = content.split('\n');
|
|
|
|
// Find the element, trying each query in priority order. When `--text` is
|
|
// supplied, collect every candidate the queries surface and disambiguate
|
|
// by the picked element's textContent. Without `--text`, fall back to the
|
|
// legacy first-match behavior so unmodified callers keep working.
|
|
let match = null;
|
|
if (text) {
|
|
const candidates = [];
|
|
for (const q of queries) {
|
|
const all = findAllElements(lines, q, tag);
|
|
for (const c of all) {
|
|
if (!candidates.some((x) => x.startLine === c.startLine)) {
|
|
candidates.push(c);
|
|
}
|
|
}
|
|
// Once a more-specific query (ID, full className combo) yielded a unique
|
|
// result, stop — falling through to the loose tag+single-class query
|
|
// would readmit the siblings we just disambiguated past.
|
|
if (candidates.length === 1) break;
|
|
}
|
|
if (candidates.length === 0) {
|
|
console.error(JSON.stringify({ error: 'Found file but could not locate element in ' + targetFile + '. Searched for: ' + queries.join(', ') }));
|
|
process.exit(1);
|
|
}
|
|
if (candidates.length === 1) {
|
|
match = candidates[0];
|
|
} else {
|
|
const filtered = filterByText(candidates, lines, text);
|
|
if (filtered.length === 1) {
|
|
match = filtered[0];
|
|
} else if (filtered.length === 0) {
|
|
const normalizedText = String(text).replace(/\s+/g, ' ').trim();
|
|
if (normalizedText.length < 8) {
|
|
// Very short labels cannot disambiguate siblings reliably. Preserve
|
|
// the legacy behavior for these low-information picker events.
|
|
match = candidates[0];
|
|
} else {
|
|
// Rendered text that is absent from every candidate usually means
|
|
// the source uses expressions or component props. Picking the first
|
|
// same-class sibling silently edits the wrong instance (observed on
|
|
// Astro result cards), so stop and surface every candidate instead.
|
|
console.error(JSON.stringify({
|
|
error: 'element_ambiguous',
|
|
fallback: 'agent-driven',
|
|
reason: 'rendered_text_not_in_source',
|
|
file: path.relative(process.cwd(), targetFile),
|
|
candidates: candidates.map((c) => ({
|
|
startLine: c.startLine + 1,
|
|
endLine: c.endLine + 1,
|
|
})),
|
|
hint: 'Rendered text does not occur in any matching source branch. The element may use dynamic props or expressions; inspect the candidates and wrap the intended instance manually.',
|
|
}));
|
|
process.exit(1);
|
|
}
|
|
} else {
|
|
// Multiple candidates ALSO match the text. Truly ambiguous — refuse
|
|
// rather than pick wrong, and hand the agent the candidate locations
|
|
// so it can disambiguate by reading the file.
|
|
console.error(JSON.stringify({
|
|
error: 'element_ambiguous',
|
|
fallback: 'agent-driven',
|
|
file: path.relative(process.cwd(), targetFile),
|
|
candidates: filtered.map((c) => ({
|
|
startLine: c.startLine + 1,
|
|
endLine: c.endLine + 1,
|
|
})),
|
|
hint: 'Multiple source elements match both classes/tag and textContent. Pass --element-id, a more specific --text, or write the wrapper manually. See "Handle fallback" in live.md.',
|
|
}));
|
|
process.exit(1);
|
|
}
|
|
}
|
|
} else {
|
|
for (const q of queries) {
|
|
match = findElement(lines, q, tag);
|
|
if (match) break;
|
|
}
|
|
if (!match) {
|
|
console.error(JSON.stringify({ error: 'Found file but could not locate element in ' + targetFile + '. Searched for: ' + queries.join(', ') }));
|
|
process.exit(1);
|
|
}
|
|
}
|
|
|
|
const { startLine, endLine } = match;
|
|
const commentSyntax = detectCommentSyntax(targetFile);
|
|
const styleMode = detectStyleMode(targetFile);
|
|
const isJsx = commentSyntax.open === '{/*';
|
|
const indent = lines[startLine].match(/^(\s*)/)[1];
|
|
|
|
// Extract the original element. Reindent under the wrapper while preserving
|
|
// the relative depth between lines — `l.trimStart()` would strip ALL leading
|
|
// whitespace and collapse e.g. `<aside>`/` <h1>`/`</aside>` (6/8/6 spaces)
|
|
// to a single uniform indent, so on accept/discard the round-trip restores
|
|
// the inner element at its parent's depth instead of nested inside it.
|
|
// Strip only the COMMON minimum leading whitespace across the picked lines;
|
|
// `deindentContent` on the accept side already mirrors this convention.
|
|
let originalLines = lines.slice(startLine, endLine + 1);
|
|
|
|
// Buffer-aware "original" content: if the user has pending manual edits for
|
|
// this page whose originalText appears in the picked source range, apply
|
|
// them so the wrap block's "original" variant reflects what the user was
|
|
// looking at (their edited DOM), not the raw source. Source itself stays
|
|
// untouched here — only the wrap block's embedded "original" copy is
|
|
// adjusted. The pending edits remain in the buffer until committed.
|
|
//
|
|
// Apply buffered edits only when the browser provided the current page URL.
|
|
// Without it, fail if pending edits plausibly touch this exact source range;
|
|
// otherwise skip buffer awareness so unrelated staged edits on another page
|
|
// do not block normal wrap work.
|
|
let pendingBuffer = { entries: [] };
|
|
try { pendingBuffer = readManualEditsBuffer(process.cwd()); } catch {}
|
|
const pendingEntriesForTarget = pageUrl
|
|
? []
|
|
: pendingEntriesThatMayAffectWrap(pendingBuffer.entries, targetFile, originalLines, startLine, process.cwd());
|
|
if (pendingEntriesForTarget.length > 0) {
|
|
console.error(JSON.stringify({
|
|
error: 'missing_page_url_with_pending_edits',
|
|
pendingEntries: pendingEntriesForTarget.length,
|
|
hint: 'Pending manual edits may affect the selected source block. Pass --page-url=$event.pageUrl so the wrap block reflects the user\'s staged DOM.',
|
|
}));
|
|
process.exit(1);
|
|
}
|
|
if (pageUrl) {
|
|
const failedBufferedOps = [];
|
|
for (const entry of pendingBuffer.entries || []) {
|
|
if (entry.pageUrl !== pageUrl) continue;
|
|
for (const op of entry.ops || []) {
|
|
const mayAffectWrap = manualEditMayAffectWrap(op, targetFile, originalLines, startLine, process.cwd());
|
|
const result = applyBufferedManualEditToLines(originalLines, startLine, op);
|
|
if (result.changed) {
|
|
originalLines = result.lines;
|
|
continue;
|
|
}
|
|
if (!mayAffectWrap) continue;
|
|
failedBufferedOps.push({
|
|
entryId: entry.id,
|
|
ref: op?.ref || null,
|
|
originalText: op?.originalText || null,
|
|
reason: 'ambiguous_or_unmatched_pending_edit',
|
|
});
|
|
}
|
|
}
|
|
if (failedBufferedOps.length > 0) {
|
|
console.error(JSON.stringify({
|
|
error: 'manual_edit_buffer_apply_failed',
|
|
pendingOps: failedBufferedOps,
|
|
hint: 'A staged copy edit appears to affect the selected source block, but could not be applied unambiguously to the wrap original. Apply or discard copy edits first, or write the wrapper manually.',
|
|
}));
|
|
process.exit(1);
|
|
}
|
|
}
|
|
|
|
const originalBaseIndent = minLeadingSpaces(originalLines);
|
|
const reindentOriginal = (extra) => originalLines
|
|
.map((l) => (l.trim() === '' ? '' : indent + extra + l.slice(originalBaseIndent)))
|
|
.join('\n');
|
|
const originalIndented = reindentOriginal(' ');
|
|
const relTargetFile = path.relative(process.cwd(), targetFile).split(path.sep).join('/');
|
|
const useSvelteComponent = shouldUseSvelteComponentInjection(targetFile);
|
|
const useFrameworkComponent = useSvelteComponent;
|
|
|
|
// Wrapper attributes differ by syntax. HTML allows plain string attrs;
|
|
// JSX requires object-literal style and parses string attrs as HTML (which
|
|
// either type-errors or renders a literal CSS string).
|
|
const styleContents = isJsx ? 'style={{ display: "contents" }}' : 'style="display: contents"';
|
|
|
|
// JSX/TSX guard: the picked element occupies a single JSX child slot
|
|
// (inside `return (...)`, an array `.map(...)`, an `asChild` branch, or
|
|
// any other expression position). Replacing it with `comment + <div> +
|
|
// comment` yields three adjacent siblings — invalid JSX. We can't use a
|
|
// Fragment `<></>` either: parents that clone children (Radix `asChild`,
|
|
// Headless UI, etc.) hit "Invalid prop supplied to React.Fragment" when
|
|
// they try to pass an `id` through.
|
|
//
|
|
// Solution: keep the wrapper `<div>` as the single JSX-slot child and
|
|
// tuck both marker comments INSIDE it. accept/discard then expands its
|
|
// replacement range to include the wrapper's `<div>` open / close lines
|
|
// so the entire scaffold gets removed cleanly.
|
|
const wrapperLines = isJsx ? [
|
|
indent + '<div data-impeccable-variants="' + id + '" data-impeccable-variant-count="' + count + '"' + ' ' + styleContents + '>',
|
|
indent + ' ' + commentSyntax.open + ' impeccable-variants-start ' + id + ' ' + commentSyntax.close,
|
|
indent + ' ' + commentSyntax.open + ' Original ' + commentSyntax.close,
|
|
indent + ' <div data-impeccable-variant="original">',
|
|
reindentOriginal(' '),
|
|
indent + ' </div>',
|
|
indent + ' ' + commentSyntax.open + ' Variants: insert below this line ' + commentSyntax.close,
|
|
indent + ' ' + commentSyntax.open + ' impeccable-variants-end ' + id + ' ' + commentSyntax.close,
|
|
indent + '</div>',
|
|
] : [
|
|
indent + commentSyntax.open + ' impeccable-variants-start ' + id + ' ' + commentSyntax.close,
|
|
indent + '<div data-impeccable-variants="' + id + '" data-impeccable-variant-count="' + count + '"' + ' ' + styleContents + '>',
|
|
indent + ' ' + commentSyntax.open + ' Original ' + commentSyntax.close,
|
|
indent + ' <div data-impeccable-variant="original">',
|
|
originalIndented,
|
|
indent + ' </div>',
|
|
indent + ' ' + commentSyntax.open + ' Variants: insert below this line ' + commentSyntax.close,
|
|
indent + '</div>',
|
|
indent + commentSyntax.open + ' impeccable-variants-end ' + id + ' ' + commentSyntax.close,
|
|
];
|
|
|
|
let outputFile = targetFile;
|
|
let outputLines;
|
|
let outputStartLine = startLine + 1;
|
|
let outputEndLine = startLine + wrapperLines.length + (originalLines.length - 1);
|
|
let insertLine;
|
|
let svelteSession = null;
|
|
|
|
if (useSvelteComponent) {
|
|
// Svelte/SvelteKit resets component-local state on markup HMR updates.
|
|
// Keep generation source-neutral: agents write real variant components
|
|
// under the generated componentDir, the browser mounts them into the live
|
|
// DOM, and live-accept.mjs inlines the accepted variant back into the route.
|
|
svelteSession = scaffoldSvelteComponentSession({
|
|
id,
|
|
count,
|
|
sourceFile: relTargetFile,
|
|
sourceStartLine: startLine + 1,
|
|
sourceEndLine: endLine + 1,
|
|
originalLines,
|
|
cwd: process.cwd(),
|
|
});
|
|
outputFile = path.resolve(process.cwd(), svelteSession.manifestFile);
|
|
outputStartLine = 1;
|
|
outputEndLine = 1;
|
|
insertLine = 1;
|
|
} else {
|
|
// Replace the original element with the wrapper
|
|
const newLines = [
|
|
...lines.slice(0, startLine),
|
|
...wrapperLines,
|
|
...lines.slice(endLine + 1),
|
|
];
|
|
fs.writeFileSync(targetFile, newLines.join('\n'), 'utf-8');
|
|
|
|
// Calculate insert line (the "insert below this line" comment).
|
|
// 0-indexed file position. Both HTML and JSX wrappers have 6 lines above
|
|
// the insert marker (HTML: start-comment + outer-div + Original-comment +
|
|
// original-div + content + close-original-div; JSX: outer-div +
|
|
// start-comment + Original-comment + original-div + content +
|
|
// close-original-div). Multi-line originals push the marker by their
|
|
// extra line count.
|
|
insertLine = startLine + 6 + (originalLines.length - 1) + 1;
|
|
}
|
|
|
|
const outputRelFile = path.relative(process.cwd(), outputFile).split(path.sep).join('/');
|
|
|
|
const svelteComponentAuthoring = useSvelteComponent ? buildSvelteComponentCssAuthoring(count) : null;
|
|
const componentSession = svelteSession;
|
|
const componentPreviewMode = useSvelteComponent ? 'svelte-component' : undefined;
|
|
const previewMode = componentPreviewMode;
|
|
|
|
console.log(JSON.stringify({
|
|
file: outputRelFile,
|
|
sourceFile: useFrameworkComponent ? relTargetFile : undefined,
|
|
previewMode,
|
|
componentDir: componentSession?.componentDir,
|
|
propContract: componentSession?.propContract,
|
|
sourceStartLine: useFrameworkComponent ? startLine + 1 : undefined,
|
|
sourceEndLine: useFrameworkComponent ? endLine + 1 : undefined,
|
|
startLine: outputStartLine, // 1-indexed for the agent
|
|
// wrapperLines is an array but one element (the original-content slot)
|
|
// is a `\n`-joined multi-line string, so the actual file-row count is
|
|
// wrapperLines.length + (originalLines.length - 1). Without the offset,
|
|
// endLine pointed inside the wrapper for any picked element that
|
|
// spanned more than one source line.
|
|
endLine: outputEndLine, // 1-indexed
|
|
insertLine, // 1-indexed: where variants go
|
|
commentSyntax: commentSyntax,
|
|
styleMode: componentPreviewMode || styleMode.mode,
|
|
styleTag: useFrameworkComponent ? null : styleMode.styleTag,
|
|
cssSelectorPrefixExamples: useFrameworkComponent ? [] : buildCssSelectorPrefixExamples(styleMode.mode, count),
|
|
cssAuthoring: svelteComponentAuthoring || buildCssAuthoring(styleMode, count),
|
|
originalLineCount: originalLines.length,
|
|
}));
|
|
}
|
|
|
|
// ---------------------------------------------------------------------------
|
|
// Helpers
|
|
// ---------------------------------------------------------------------------
|
|
|
|
function argVal(args, flag) {
|
|
const prefix = flag + '=';
|
|
for (const arg of args) {
|
|
if (arg.startsWith(prefix)) return arg.slice(prefix.length);
|
|
}
|
|
const idx = args.indexOf(flag);
|
|
return idx !== -1 && idx + 1 < args.length ? args[idx + 1] : null;
|
|
}
|
|
|
|
function pendingEntriesThatMayAffectWrap(entries, targetFile, originalLines, selectionStartLine, cwd) {
|
|
const targetAbs = path.resolve(cwd, targetFile);
|
|
return (entries || []).filter((entry) => {
|
|
return (entry.ops || []).some((op) => {
|
|
return manualEditMayAffectWrap(op, targetAbs, originalLines, selectionStartLine, cwd);
|
|
});
|
|
});
|
|
}
|
|
|
|
function manualEditMayAffectWrap(op, targetFile, originalLines, selectionStartLine, cwd) {
|
|
const targetAbs = path.resolve(cwd, targetFile);
|
|
if (manualEditHintFallsInsideSelection(op, targetAbs, originalLines, selectionStartLine, cwd)) return true;
|
|
if (manualEditLocatorMatchesSelection(op, originalLines)) return true;
|
|
if (typeof op?.originalText === 'string' && op.originalText.length > 0) {
|
|
return originalLines.join('\n').includes(op.originalText);
|
|
}
|
|
return false;
|
|
}
|
|
|
|
function manualEditHintFallsInsideSelection(op, targetAbs, originalLines, selectionStartLine, cwd) {
|
|
const hintFile = op?.sourceHint?.file;
|
|
const hintedLine = Number(op?.sourceHint?.line);
|
|
if (!hintFile || !Number.isFinite(hintedLine)) return false;
|
|
const hintAbs = path.isAbsolute(hintFile) ? hintFile : path.resolve(cwd, hintFile);
|
|
if (path.resolve(hintAbs) !== targetAbs) return false;
|
|
const hintedIndex = hintedLine - 1 - selectionStartLine;
|
|
return hintedIndex >= 0
|
|
&& hintedIndex < originalLines.length
|
|
&& typeof op?.originalText === 'string'
|
|
&& originalLines[hintedIndex].includes(op.originalText);
|
|
}
|
|
|
|
function manualEditLocatorMatchesSelection(op, originalLines) {
|
|
if (!op || typeof op.originalText !== 'string' || op.originalText.length === 0) return false;
|
|
return originalLines.some((line) => (
|
|
line.includes(op.originalText) && lineMatchesManualEditLocator(line, op)
|
|
));
|
|
}
|
|
|
|
function applyBufferedManualEditToLines(originalLines, selectionStartLine, op) {
|
|
if (
|
|
!op
|
|
|| typeof op.originalText !== 'string'
|
|
|| op.originalText.length === 0
|
|
|| typeof op.newText !== 'string'
|
|
) {
|
|
return { lines: originalLines, changed: false };
|
|
}
|
|
|
|
const replaceLine = (lineIndex) => ({
|
|
lines: originalLines.map((line, index) => (
|
|
index === lineIndex ? replaceOnce(line, op.originalText, op.newText) : line
|
|
)),
|
|
changed: true,
|
|
});
|
|
|
|
const hintedLine = Number(op.sourceHint?.line);
|
|
if (Number.isFinite(hintedLine)) {
|
|
const hintedIndex = hintedLine - 1 - selectionStartLine;
|
|
if (hintedIndex >= 0 && hintedIndex < originalLines.length && originalLines[hintedIndex].includes(op.originalText)) {
|
|
return replaceLine(hintedIndex);
|
|
}
|
|
}
|
|
|
|
const locatorMatches = [];
|
|
for (let index = 0; index < originalLines.length; index += 1) {
|
|
const line = originalLines[index];
|
|
if (!line.includes(op.originalText)) continue;
|
|
if (!lineMatchesManualEditLocator(line, op)) continue;
|
|
locatorMatches.push(index);
|
|
}
|
|
if (locatorMatches.length === 1) return replaceLine(locatorMatches[0]);
|
|
|
|
const originalBlock = originalLines.join('\n');
|
|
if (countOccurrences(originalBlock, op.originalText) === 1) {
|
|
return {
|
|
lines: replaceOnce(originalBlock, op.originalText, op.newText).split('\n'),
|
|
changed: true,
|
|
};
|
|
}
|
|
|
|
return { lines: originalLines, changed: false };
|
|
}
|
|
|
|
function lineMatchesManualEditLocator(line, op) {
|
|
if (op.tag) {
|
|
const tagRe = new RegExp('<\\s*' + escapeRegExp(op.tag) + '(?=[\\s>/]|$)', 'i');
|
|
if (!tagRe.test(line)) return false;
|
|
}
|
|
|
|
if (op.elementId) {
|
|
const id = escapeRegExp(op.elementId);
|
|
const idRe = new RegExp('\\bid\\s*=\\s*["\']' + id + '["\']');
|
|
if (!idRe.test(line)) return false;
|
|
}
|
|
|
|
const classes = Array.isArray(op.classes) ? op.classes.filter(Boolean) : [];
|
|
for (const className of classes) {
|
|
if (!line.includes(className)) return false;
|
|
}
|
|
|
|
return true;
|
|
}
|
|
|
|
function replaceOnce(value, needle, replacement) {
|
|
const index = value.indexOf(needle);
|
|
if (index === -1) return value;
|
|
return value.slice(0, index) + replacement + value.slice(index + needle.length);
|
|
}
|
|
|
|
function countOccurrences(value, needle) {
|
|
if (!needle) return 0;
|
|
let count = 0;
|
|
let index = 0;
|
|
while (true) {
|
|
index = value.indexOf(needle, index);
|
|
if (index === -1) return count;
|
|
count += 1;
|
|
index += needle.length;
|
|
}
|
|
}
|
|
|
|
function escapeRegExp(value) {
|
|
return String(value).replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
|
|
}
|
|
|
|
/**
|
|
* Build search query strings in priority order (most specific first).
|
|
* ID is most reliable, then specific class combos, then single classes, then raw query.
|
|
*/
|
|
function buildSearchQueries(elementId, classes, tag, query) {
|
|
const queries = [];
|
|
|
|
// 1. ID is the most specific
|
|
if (elementId) {
|
|
queries.push('id="' + elementId + '"');
|
|
}
|
|
|
|
// 2. Full class attribute match (for elements with distinctive multi-class combos).
|
|
// Emit both class="..." (HTML) and className="..." (React/JSX) so whichever
|
|
// convention the file uses will match.
|
|
if (classes) {
|
|
const classList = splitClassList(classes);
|
|
if (classList.length > 1) {
|
|
const joined = classList.join(' ');
|
|
const sorted = [...classList].sort((a, b) => b.length - a.length);
|
|
queries.push('class="' + joined + '"');
|
|
queries.push('className="' + joined + '"');
|
|
for (const className of sorted) {
|
|
queries.push(className);
|
|
}
|
|
} else if (classList.length === 1) {
|
|
queries.push(classList[0]);
|
|
}
|
|
}
|
|
|
|
// 3. Tag + class combo (e.g., <section class="hero">).
|
|
// Same dual-emit for JSX compatibility.
|
|
if (tag && classes) {
|
|
const firstClass = splitClassList(classes)[0];
|
|
queries.push('<' + tag + ' class="' + firstClass);
|
|
queries.push('<' + tag + ' className="' + firstClass);
|
|
}
|
|
|
|
// 4. Raw fallback query
|
|
if (query) {
|
|
queries.push(query);
|
|
}
|
|
|
|
return queries;
|
|
}
|
|
|
|
function splitClassList(classes) {
|
|
return String(classes).split(/[,\s]+/).map(c => c.trim()).filter(Boolean);
|
|
}
|
|
|
|
function attrEscapeDouble(str) {
|
|
return String(str)
|
|
.replace(/&/g, '&')
|
|
.replace(/"/g, '"')
|
|
.replace(/</g, '<')
|
|
.replace(/>/g, '>');
|
|
}
|
|
|
|
function detectCommentSyntax(filePath) {
|
|
const ext = path.extname(filePath).toLowerCase();
|
|
if (ext === '.jsx' || ext === '.tsx') {
|
|
return { open: '{/*', close: '*/}' };
|
|
}
|
|
// HTML, Vue, Svelte, Astro all use HTML comments
|
|
return { open: '<!--', close: '-->' };
|
|
}
|
|
|
|
function detectStyleMode(filePath) {
|
|
const ext = path.extname(filePath).toLowerCase();
|
|
if (ext === '.astro') {
|
|
return {
|
|
mode: 'astro-global-prefixed',
|
|
styleTag: '<style is:inline data-impeccable-css="SESSION_ID">',
|
|
};
|
|
}
|
|
return {
|
|
mode: 'scoped',
|
|
styleTag: '<style data-impeccable-css="SESSION_ID">',
|
|
};
|
|
}
|
|
|
|
function buildCssSelectorPrefixExamples(styleMode, count) {
|
|
if (styleMode !== 'astro-global-prefixed') return [];
|
|
return Array.from({ length: count }, (_, i) => `[data-impeccable-variant="${i + 1}"]`);
|
|
}
|
|
|
|
function buildCssAuthoring(styleMode, count) {
|
|
const variantNumbers = Array.from({ length: count }, (_, i) => i + 1);
|
|
if (styleMode.mode === 'astro-global-prefixed') {
|
|
return {
|
|
mode: styleMode.mode,
|
|
styleTag: styleMode.styleTag,
|
|
strategy: 'global-prefixed',
|
|
rulePattern: '[data-impeccable-variant="N"] > .variant-class { ... }',
|
|
selectorExamples: variantNumbers.map((n) => `[data-impeccable-variant="${n}"] > .variant-class`),
|
|
requirements: [
|
|
'Use the styleTag exactly; the is:inline attribute is required for this file.',
|
|
'Put raw CSS directly between the styleTag opening and a plain </style> close.',
|
|
'Prefix every preview selector with the matching [data-impeccable-variant="N"] selector.',
|
|
'Keep selectors anchored to the generated variant wrapper; do not rely on component CSS scoping for preview rules.',
|
|
],
|
|
forbidden: [
|
|
'Do not use @scope for this styleMode.',
|
|
'Do not wrap style content in a JSX/TSX template literal ({` ... `}); that syntax is for .tsx/.jsx only.',
|
|
'Do not put { immediately after the style opening tag; Astro parses { as expression syntax.',
|
|
],
|
|
};
|
|
}
|
|
return {
|
|
mode: styleMode.mode,
|
|
styleTag: styleMode.styleTag,
|
|
strategy: 'scope-rule',
|
|
rulePattern: '@scope ([data-impeccable-variant="N"]) { :scope > .variant-class { ... } }',
|
|
selectorExamples: variantNumbers.map((n) => `@scope ([data-impeccable-variant="${n}"]) { :scope > .variant-class { ... } }`),
|
|
requirements: [
|
|
'Use @scope blocks keyed to each [data-impeccable-variant="N"] wrapper.',
|
|
'Inside each @scope block, make :scope rules step into the replacement element with a descendant combinator.',
|
|
'Use the styleTag exactly; do not add framework-specific style attributes unless this object says to.',
|
|
],
|
|
forbidden: [
|
|
'Do not use global [data-impeccable-variant="N"] selector prefixes for this styleMode.',
|
|
'Do not add is:inline to the style tag for this styleMode.',
|
|
],
|
|
};
|
|
}
|
|
|
|
/**
|
|
* Search project files for the query string (class name, ID, etc.)
|
|
* Returns the first matching file path, or null.
|
|
*/
|
|
function findFileWithQuery(query, cwd, genOpts = {}) {
|
|
const searchDirs = ['src', 'app', 'pages', 'components', 'public', 'views', 'templates', '.'];
|
|
const seen = new Set();
|
|
|
|
for (const dir of searchDirs) {
|
|
const absDir = path.join(cwd, dir);
|
|
if (!fs.existsSync(absDir)) continue;
|
|
const result = searchDir(absDir, query, seen, 0, genOpts);
|
|
if (result) return result;
|
|
}
|
|
return null;
|
|
}
|
|
|
|
function searchDir(dir, query, seen, depth, genOpts) {
|
|
if (depth > 5) return null; // don't go too deep
|
|
const realDir = fs.realpathSync(dir);
|
|
if (seen.has(realDir)) return null;
|
|
seen.add(realDir);
|
|
|
|
let entries;
|
|
try { entries = fs.readdirSync(dir, { withFileTypes: true }); }
|
|
catch { return null; }
|
|
|
|
// Check files first
|
|
for (const entry of entries) {
|
|
if (!entry.isFile()) continue;
|
|
const ext = path.extname(entry.name).toLowerCase();
|
|
if (!EXTENSIONS.includes(ext)) continue;
|
|
|
|
const filePath = path.join(dir, entry.name);
|
|
if (!genOpts.includeGenerated && isGeneratedFile(filePath, genOpts)) continue;
|
|
try {
|
|
const content = fs.readFileSync(filePath, 'utf-8');
|
|
if (content.includes(query)) return filePath;
|
|
} catch { /* skip unreadable files */ }
|
|
}
|
|
|
|
// Then recurse into directories. Always skip node_modules and .git (never
|
|
// project content). dist/build/out are left to the isGeneratedFile guard so
|
|
// the includeGenerated second-pass can still find the element there and
|
|
// report `generatedMatch`.
|
|
for (const entry of entries) {
|
|
if (!entry.isDirectory()) continue;
|
|
if (entry.name === 'node_modules' || entry.name === '.git') continue;
|
|
const result = searchDir(path.join(dir, entry.name), query, seen, depth + 1, genOpts);
|
|
if (result) return result;
|
|
}
|
|
|
|
return null;
|
|
}
|
|
|
|
/**
|
|
* Regex that matches a tag opener on a line. Allows the tag name to be
|
|
* followed by whitespace, `>`, `/`, or end-of-line so that multi-line JSX
|
|
* openers (e.g. `<section\n className="..."\n>`) are recognised.
|
|
*/
|
|
const OPENER_RE = /<([A-Za-z][A-Za-z0-9]*)(?=[\s/>]|$)/;
|
|
|
|
/**
|
|
* Find the element's start and end line in the file.
|
|
*
|
|
* `query` is a class name, attribute fragment (`class="..."`, `className="..."`,
|
|
* `id="..."`), or a raw text snippet. Because a query can appear on a
|
|
* continuation line of a multi-line tag (e.g. the `className="..."` row of a
|
|
* `<section\n className="..."\n>` JSX tag), we walk backward from the match
|
|
* line to find the actual tag opener. When `tag` is provided, opener candidates
|
|
* must match that tag name.
|
|
*/
|
|
/**
|
|
* Return the smallest leading-whitespace count across a set of lines,
|
|
* ignoring blank lines (whose indent isn't load-bearing). Used to compute
|
|
* the common base indent of a multi-line picked element so reindenting
|
|
* under the wrapper preserves the relative depth between lines.
|
|
*/
|
|
function minLeadingSpaces(lines) {
|
|
let min = Infinity;
|
|
for (const l of lines) {
|
|
if (l.trim() === '') continue;
|
|
const m = l.match(/^(\s*)/);
|
|
if (m && m[1].length < min) min = m[1].length;
|
|
}
|
|
return min === Infinity ? 0 : min;
|
|
}
|
|
|
|
function findElement(lines, query, tag = null) {
|
|
// Iterate all matches — the first substring hit isn't always the right one.
|
|
for (let i = 0; i < lines.length; i++) {
|
|
if (!lines[i].includes(query)) continue;
|
|
|
|
const stripped = lines[i].trim();
|
|
if (stripped.startsWith('<!--') || stripped.startsWith('{/*') || stripped.startsWith('//')) continue;
|
|
// Skip lines already inside a variant wrapper
|
|
if (lines[i].includes('data-impeccable-variant')) continue;
|
|
|
|
const openerLine = findOpenerLine(lines, i, tag);
|
|
if (openerLine === -1) continue;
|
|
|
|
const endLine = findClosingLine(lines, openerLine);
|
|
return { startLine: openerLine, endLine };
|
|
}
|
|
|
|
return null;
|
|
}
|
|
|
|
/**
|
|
* Like findElement, but returns every match. Used for ambiguity detection
|
|
* when the agent passes --text: when the same className appears on multiple
|
|
* sibling elements (a list of cards, repeated section variants, etc.),
|
|
* first-match silently lands on the wrong branch. Returning all matches lets
|
|
* the caller narrow by textContent or fail with a structured ambiguity error.
|
|
*/
|
|
function findAllElements(lines, query, tag = null) {
|
|
const out = [];
|
|
const seen = new Set();
|
|
for (let i = 0; i < lines.length; i++) {
|
|
if (!lines[i].includes(query)) continue;
|
|
const stripped = lines[i].trim();
|
|
if (stripped.startsWith('<!--') || stripped.startsWith('{/*') || stripped.startsWith('//')) continue;
|
|
if (lines[i].includes('data-impeccable-variant')) continue;
|
|
const openerLine = findOpenerLine(lines, i, tag);
|
|
if (openerLine === -1) continue;
|
|
if (seen.has(openerLine)) continue; // multiple matches inside the same element
|
|
seen.add(openerLine);
|
|
const endLine = findClosingLine(lines, openerLine);
|
|
out.push({ startLine: openerLine, endLine });
|
|
}
|
|
return out;
|
|
}
|
|
|
|
/**
|
|
* Narrow a candidate set to those whose source body matches a meaningful
|
|
* prefix of the picked element's textContent. The compare strips tags and
|
|
* JSX expressions, then checks two whitespace normalizations side-by-side:
|
|
*
|
|
* - single-space ("hero two second card body")
|
|
* - no-whitespace ("herotwosecondcardbody")
|
|
*
|
|
* Both are needed because `el.textContent` concatenates sibling text without
|
|
* inserting whitespace (e.g. `<h1>Hero Two</h1><p>Second…</p>` reads as
|
|
* `"Hero TwoSecond…"`), while the source has whitespace between tags. If
|
|
* EITHER normalization matches, the candidate keeps. A snippet shorter than
|
|
* 8 chars after stripping is too weak to disambiguate — the caller falls
|
|
* back to first-match.
|
|
*/
|
|
function filterByText(candidates, lines, text) {
|
|
const trimmed = text.replace(/\s+/g, ' ').trim().toLowerCase().slice(0, 80);
|
|
// Too short to disambiguate. Return [] so the caller's `filtered.length
|
|
// === 0` branch fires (fall back to first-match) — the previous
|
|
// `candidates.slice()` return forced `filtered.length > 1` and surfaced
|
|
// a spurious `element_ambiguous` error on every short-text picker event
|
|
// with multiple candidates.
|
|
if (trimmed.length < 8) return [];
|
|
const targetSpaced = trimmed;
|
|
const targetCompact = trimmed.replace(/\s+/g, '');
|
|
|
|
return candidates.filter((c) => {
|
|
const body = lines.slice(c.startLine, c.endLine + 1).join(' ');
|
|
const inner = body
|
|
.replace(/<[^>]*>/g, ' ') // strip HTML/JSX tags
|
|
.replace(/\{[^}]*\}/g, ' ') // strip JSX expressions
|
|
.toLowerCase();
|
|
const sourceSpaced = inner.replace(/\s+/g, ' ').trim();
|
|
const sourceCompact = inner.replace(/\s+/g, '');
|
|
return sourceSpaced.includes(targetSpaced) || sourceCompact.includes(targetCompact);
|
|
});
|
|
}
|
|
|
|
/**
|
|
* Resolve a match line to the real tag opener. If the match line itself opens
|
|
* a tag, return it. Otherwise walk up to 10 lines backward looking for the
|
|
* first tag opener. If `tag` is specified, the opener must match that tag
|
|
* name; an opener with a different tag name aborts the backward walk for this
|
|
* match (we don't jump across element boundaries).
|
|
*
|
|
* Returns the line index of the opener, or -1 if none can be resolved.
|
|
*/
|
|
function findOpenerLine(lines, matchLine, tag) {
|
|
const self = lines[matchLine].match(OPENER_RE);
|
|
if (self) {
|
|
if (!tag || self[1] === tag) return matchLine;
|
|
return -1;
|
|
}
|
|
const MAX_BACKWALK = 10;
|
|
for (let i = matchLine - 1; i >= Math.max(0, matchLine - MAX_BACKWALK); i--) {
|
|
const opener = lines[i].match(OPENER_RE);
|
|
if (!opener) continue;
|
|
if (!tag || opener[1] === tag) return i;
|
|
// Different tag name than requested — abort; we're inside a non-target opener.
|
|
return -1;
|
|
}
|
|
return -1;
|
|
}
|
|
|
|
/**
|
|
* Starting from a line with an opening tag, find the line with the matching
|
|
* closing tag by counting tag nesting depth.
|
|
*/
|
|
function findClosingLine(lines, start) {
|
|
const openMatch = lines[start].match(OPENER_RE);
|
|
if (!openMatch) return start; // caller passed a non-opener; nothing to span
|
|
|
|
const tagName = openMatch[1];
|
|
let depth = 0;
|
|
const openRe = new RegExp('<' + tagName + '(?=[\\s/>]|$)', 'g');
|
|
const selfCloseRe = new RegExp('<' + tagName + '[^>]*/>', 'g');
|
|
const closeRe = new RegExp('</' + tagName + '\\s*>', 'g');
|
|
|
|
for (let i = start; i < lines.length; i++) {
|
|
const line = lines[i];
|
|
const opens = (line.match(openRe) || []).length;
|
|
const selfCloses = (line.match(selfCloseRe) || []).length;
|
|
const closes = (line.match(closeRe) || []).length;
|
|
|
|
depth += opens - selfCloses - closes;
|
|
|
|
if (depth <= 0) return i;
|
|
}
|
|
|
|
// If we can't find the close, return a reasonable guess
|
|
return Math.min(start + 50, lines.length - 1);
|
|
}
|
|
|
|
// Auto-execute when run directly (node live-wrap.mjs ...)
|
|
const _running = process.argv[1];
|
|
if (_running?.endsWith('live-wrap.mjs') || _running?.endsWith('live-wrap.mjs/')) {
|
|
wrapCli();
|
|
}
|
|
|
|
// Test exports (used by tests/live-wrap.test.mjs)
|
|
export {
|
|
buildSearchQueries,
|
|
findElement,
|
|
findClosingLine,
|
|
detectCommentSyntax,
|
|
findAllElements,
|
|
filterByText,
|
|
findFileWithQuery,
|
|
detectStyleMode,
|
|
buildCssAuthoring,
|
|
buildCssSelectorPrefixExamples,
|
|
};
|