From 2b03a5721270319656038841da32f3f0245a4863 Mon Sep 17 00:00:00 2001 From: Norin Lavaee Date: Sun, 21 Jun 2026 20:33:01 -0700 Subject: [PATCH 1/7] feat(open-claude-design)!: discovery-first restructure with init, reference discovery, live QA Rework the builtin open-claude-design workflow around the accessible impeccable skill (/skill:impeccable ...): - Add a discovery interview stage (/skill:impeccable shape) that confirms the brief, output type, and references; user references take precedence over DESIGN.md/PRODUCT.md. - Always run a project-context init stage (/skill:impeccable init) that creates missing PRODUCT.md/DESIGN.md and reconciles existing files without clobbering. - Combine onboarding, gated gallery reference-discovery, and reference import into one concurrent context fan-out, then synthesize the design system; reference-discovery clicks into standout work and records a scroll-through video (full-page screenshot fallback) of the real design pages plus their destination URLs. - Drive /skill:impeccable live from the preview-display stages for in-browser variant QA; thread accepted variants (live_changes) through the refinement feedback. - Factor new logic into open-claude-design-setup.ts; add discoveryDecisionSchema/REFERENCE_PRECEDENCE to utils; update docs, changelogs, spec, and tests. BREAKING CHANGE: removed the open-claude-design inputs reference, output_type, and design_system; the discovery stage now asks for the output type and references. Remaining inputs: prompt, discover_references, max_refinements. Assistant-model: Claude Opus 4.8 --- packages/coding-agent/CHANGELOG.md | 6 + packages/coding-agent/docs/workflows.md | 33 +- packages/workflows/CHANGELOG.md | 11 + .../builtin/open-claude-design-feedback.ts | 373 +++++++++++ .../builtin/open-claude-design-phases.ts | 143 +++-- .../builtin/open-claude-design-runner.ts | 586 +++++++++--------- .../builtin/open-claude-design-setup.ts | 403 ++++++++++++ .../builtin/open-claude-design-utils.ts | 59 +- .../workflows/builtin/open-claude-design.d.ts | 8 +- .../workflows/builtin/open-claude-design.ts | 22 +- ...n-claude-design-init-references-live-qa.md | 200 ++++++ ...in-workflows-open_claude_design-01.test.ts | 272 +++++++- test/unit/open-claude-design-feedback.test.ts | 240 +++++++ test/unit/open-claude-design-setup.test.ts | 224 +++++++ 14 files changed, 2182 insertions(+), 398 deletions(-) create mode 100644 packages/workflows/builtin/open-claude-design-feedback.ts create mode 100644 packages/workflows/builtin/open-claude-design-setup.ts create mode 100644 specs/2026-06-21-open-claude-design-init-references-live-qa.md create mode 100644 test/unit/open-claude-design-feedback.test.ts create mode 100644 test/unit/open-claude-design-setup.test.ts diff --git a/packages/coding-agent/CHANGELOG.md b/packages/coding-agent/CHANGELOG.md index 58ec6134d5..e4af40daea 100644 --- a/packages/coding-agent/CHANGELOG.md +++ b/packages/coding-agent/CHANGELOG.md @@ -2,8 +2,14 @@ ## [Unreleased] +### Breaking Changes + +- Changed the bundled builtin `open-claude-design` workflow's inputs: removed `reference`, `output_type`, and `design_system` in favor of a new `discovery` interview stage that asks for the output type and references. Inputs are now `prompt`, `discover_references`, and `max_refinements`. Drop those removed arguments from existing invocations and let discovery ask (or describe them in `prompt`). + ### Added +- Restructured the bundled builtin `open-claude-design` workflow around the accessible `impeccable` skill. It now opens with a `discovery` stage (`/skill:impeccable shape`) that interviews you for a confirmed brief, the output type, and the references to emulate (references take precedence over `DESIGN.md`/`PRODUCT.md`); then **always** runs an `init` stage (`/skill:impeccable init`) that creates `PRODUCT.md`/`DESIGN.md` when missing and reconciles existing files against the brief (reusing the discovery answers); then a **single combined context phase** that concurrently runs design-system onboarding, the gated gallery `reference-discovery` pass (Awwwards, recent.design, Dribbble, Monet, Motionsites via `playwright-cli` — clicking into standout work to record a scroll-through video of each real design page so animations are captured, with a full-page screenshot fallback plus the real URLs, with a web-search fallback), and per-reference import before synthesizing the design system; then generation and impeccable `live`-driven in-browser refinement (`preview-display-*` drive `/skill:impeccable live`, capturing accepted variants and notes; degrades to `playwright-cli show --annotate`). A `discover_references` input (default `true`) gates the gallery pass. Updated the bundled workflow docs to describe the discovery interview, the trimmed input set, the always-run init, the combined context phase, references precedence, and live QA. + - Added the bundled builtin `goal` workflow's safe-by-default `create_pr` toggle and final `pull-request` stage. Goal now mirrors Ralph's PR handoff behavior: omitted or `false` skips PR/MR/review creation and omits `pr_report`, while strict `create_pr=true` authorizes only the final stage after reviewer quorum plus reducer approval to inspect the goal ledger, worker receipts, reviewer artifacts, final report, repository state, and provider credentials before attempting a provider-appropriate PR/MR/review request. Intermediate Goal worker/reviewer prompts now tell stages to ignore PR-creation requests so PR handoff stays confined to the final stage. Updated the bundled workflow docs, quickstart, README, and `/atomic` guide copy to describe the opt-in behavior. ## [0.9.0-alpha.3] - 2026-06-21 diff --git a/packages/coding-agent/docs/workflows.md b/packages/coding-agent/docs/workflows.md index b966851019..75ece078ae 100644 --- a/packages/coding-agent/docs/workflows.md +++ b/packages/coding-agent/docs/workflows.md @@ -160,7 +160,7 @@ For the builtin result tables below, `deep-research-codebase`, `goal`, and `ralp | `deep-research-codebase` | Scout + research-history chain → parallel specialist waves → aggregator. Indexes the whole repo and synthesizes findings. | Broad or cross-cutting research before you decide what to change. Prefer `/skill:research-codebase` for one subsystem. | | `goal` | Persisted goal ledger → bounded worker turns → receipts → three-reviewer gate → deterministic reducer → final report → optional final-stage PR handoff after approval. | Small-to-medium scope changes when you can identify the work surface, state the exact outcome, name the validation that proves it is done, and optionally allow only the final `pull-request` stage to attempt PR creation with `create_pr=true` after Goal reaches `complete`. | | `ralph` | Prompt-refinement → research-prompt-refinement → codebase/online research → sub-agent orchestration → multi-model parallel review → optional final-stage PR handoff. | Larger migrations, broad refactors, and multi-package changes where you want Atomic to refine the prompt for clarity, transform it into a research question, research the codebase before implementing, delegate through sub-agents, review, iterate, and optionally allow only the final `pull-request` stage to attempt PR creation with `create_pr=true`. | -| `open-claude-design` | Design-system onboarding → reference import → HTML generation → impeccable-driven refinement → quality gate → rich HTML handoff. Renders a live `preview.html` you can iterate against (opens through `browser` when available). | UI, page, component, theme, or design-token work that benefits from generation + critique loops. | +| `open-claude-design` | Discovery interview (`/skill:impeccable shape`) → project-context setup (`/skill:impeccable init`, always — creates missing `PRODUCT.md`/`DESIGN.md`, reconciles existing) → a combined context phase (design-system onboarding + curated gallery reference-discovery + user-reference import, run concurrently) → HTML generation → impeccable `live`-driven interactive refinement → quality gate → rich HTML handoff. The discovery stage asks what to build, the output type, and which references to emulate (references take precedence over `DESIGN.md`/`PRODUCT.md`). Renders a live `preview.html` you can iterate against in the browser (opens through impeccable `live` / the `playwright-cli` skill when available). | UI, page, component, theme, or design-token work that benefits from a guided brief, beautiful references, and generation + critique loops. | ### `deep-research-codebase` @@ -304,18 +304,18 @@ Inputs: | Input | Type | Required | Default | Description | |---|---|---|---|---| -| `prompt` | text | yes | — | What to design (dashboard, page, component, prototype, …). | -| `reference` | text | no | — | URL, file path, screenshot path, or design doc to import as a reference. | -| `output_type` | select | no | `prototype` | One of `prototype`, `wireframe`, `page`, `component`, `theme`, `tokens`. | -| `design_system` | text | no | — | Path(s) or description of an existing design system (e.g. `DESIGN.md`, `PRODUCT.md`). Skips onboarding when provided. | +| `prompt` | text | yes | — | What to design (dashboard, page, component, prototype, …). The discovery stage refines this into a confirmed brief and asks for the output type and references. | +| `discover_references` | boolean | no | `true` | Discover beautiful, current reference designs (Awwwards, recent.design, Dribbble, Monet, Motionsites) and feed them to generation. Set `false` to skip the network/browser reference pass. | | `max_refinements` | number | no | `3` | Maximum critique/apply refinement iterations. | +The output type (`prototype`, `wireframe`, `page`, `component`, `theme`, `tokens`) and any reference designs are **not** inputs — the discovery stage asks for them. There is no `design_system` input; the project's `DESIGN.md`/`PRODUCT.md` are established/loaded automatically. + Result fields: | Field | Meaning | |---|---| -| `output_type` | Kind of design artifact produced. | -| `design_system` | Design system source used for generation: supplied input or project-derived design system. | +| `output_type` | Kind of design artifact produced (chosen during the discovery interview). | +| `design_system` | Design system source used for generation: the project-derived design system. | | `artifact` | Latest final design summary from the approved preview artifact. | | `handoff` | Final rich HTML spec and implementation handoff summary. | | `approved_for_export` | Whether refinement completed before the final export gate. | @@ -331,14 +331,29 @@ Result fields: `open-claude-design` has no `result` output; it exposes only the declared fields listed above. Use the declared `artifact` and `handoff` fields for generated content. +**Discovery interview.** The workflow's first stage runs `/skill:impeccable shape` to interview you (via the structured question tool) about what you want to build, the **output type** (`prototype`, `wireframe`, `page`, `component`, `theme`, or `tokens`), and which **references** to emulate (URLs, local file paths, screenshots, or design docs). It produces a confirmed design brief; the references you name take **precedence over `DESIGN.md`/`PRODUCT.md`** during generation (the design system fills gaps the references don't cover, and `PRODUCT.md` still governs strategic register/voice). Headless runs infer a defensible brief, output type, and references rather than blocking. + +**Project design context (init).** After discovery, the workflow **always** runs an `init` stage that invokes `/skill:impeccable init` (reusing the discovery answers so it doesn't re-ask). It deterministically detects whether `PRODUCT.md` and `DESIGN.md` exist (project root, `.agents/context/`, or `docs/`, case-insensitive): it **creates** whichever is missing (capturing register, users/purpose, brand personality, anti-references, and accessibility needs) and **reconciles** any that already exist against the discovery brief, refreshing only genuine gaps and never clobbering them. This step is best-effort and never blocks the run. + +**Combined context phase.** Onboarding, gallery reference discovery, and user-reference import all run **concurrently in a single fan-out**, then the design-system synthesis closes it out: + +- *Design-system onboarding* — three parallel passes (`ds-locator` / `ds-analyzer` / `ds-patterns`) extract the project's design-system evidence, which `design-system-builder` synthesizes into the working design system. +- *Reference discovery* (gated by `discover_references=true`, the default) — the `reference-discovery` stage uses the `playwright-cli` skill to browse five curated galleries — [Awwwards](https://www.awwwards.com/websites/), [recent.design](https://recent.design/), [Dribbble recents](https://dribbble.com/shots/recent), [Monet](https://www.monet.design/c), and [Motionsites](https://motionsites.ai/) — then **clicks into the standout work** and, ideally, **records a scroll-through video of each real design page so its animations are captured** (with a full-page screenshot as a supplement/fallback) plus the real destination URL (it does not just screenshot the gallery thumbnails; web-search fallback when the browser is unavailable), persists the curated **references brief** to `/references.md`, and threads it into the generator (`reference_inspiration`) and refinement. Set `discover_references=false` to skip it. +- *Reference import* — each reference the discovery interview collected is imported (`web-capture-` for URLs, `file-parser-` for files/screenshots); the extracted requirements feed the generator and **take precedence over `DESIGN.md`/`PRODUCT.md`**. + +**Interactive live QA.** The `preview-display-*` stages drive `/skill:impeccable live` against the static `preview.html`: you pick elements in the browser, annotate them, and compare three on-brand variants, accepting one that is written into the preview in place. Accepted variants and your notes are captured (`live_changes` / `user_notes` / `annotated_snapshot`) and threaded through the refinement loop as the **primary** signal: the `user-feedback-*` stage receives them in a dedicated `user_annotations` block (and will not approve export while honest feedback is unaddressed), and the `apply-changes-*` stage consumes a merged refinement brief that orders your annotations and accepted live edits **above** the internal critique and screenshot/visual-QA findings. When `/skill:impeccable live` cannot boot, the stage degrades to `playwright-cli show --annotate`, then to a manual file path. Captured feedback is persisted as durable artifacts under `/feedback/iteration-.md` / `.json` (plus a best-effort copy of the annotated snapshot). If a preview captured notes but they fail to thread into the apply stage, the run fails loudly rather than silently refining from internal critique alone. + Run examples: ```text /workflow open-claude-design prompt="Refresh the settings page hierarchy" -/workflow open-claude-design prompt="Design a billing page" reference=https://stripe.com/billing output_type=page -/workflow open-claude-design prompt="Generate spacing and color tokens" output_type=tokens design_system=./DESIGN.md +/workflow open-claude-design prompt="Design a billing page like Stripe's" +/workflow open-claude-design prompt="Generate spacing and color tokens" +/workflow open-claude-design prompt="Design a marketing landing page" discover_references=false ``` +The discovery interview asks for the output type and any reference URLs/files, so you no longer pass `output_type`, `reference`, or `design_system` on the command line. + ### Launching with natural language You can also kick off a built-in workflow by describing the task in chat. Atomic picks the matching workflow and fills in inputs from your request: diff --git a/packages/workflows/CHANGELOG.md b/packages/workflows/CHANGELOG.md index 8a04fbdf20..3cd27684ea 100644 --- a/packages/workflows/CHANGELOG.md +++ b/packages/workflows/CHANGELOG.md @@ -6,10 +6,21 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/), ## [Unreleased] +### Breaking Changes + +- Restructured the builtin `open-claude-design` workflow's input contract. Removed the `reference`, `output_type`, and `design_system` inputs; the workflow now gathers those through a new `discovery` interview stage instead. The remaining inputs are `prompt`, `discover_references`, and `max_refinements`. Existing invocations that passed `reference=…`, `output_type=…`, or `design_system=…` should drop those arguments and let the discovery stage ask for the output type and references (or describe them in `prompt`). + ### Added +- Restructured the builtin `open-claude-design` workflow around the accessible `impeccable` skill (`/skill:impeccable …`). The new phase order is: (1) **discovery** — a `discovery` stage runs `/skill:impeccable shape` to interview the user (via the structured question tool) for a confirmed design brief, the output type (`prototype`/`wireframe`/`page`/`component`/`theme`/`tokens`), and the references to emulate (URLs/files/screenshots/design docs), returning a structured `{ brief, output_type, references }`; (2) **init (always runs)** — `ensureProjectDesignContext` invokes `/skill:impeccable init` on every run, reusing the discovery answers; it detects `PRODUCT.md`/`DESIGN.md` (root, `.agents/context/`, or `docs/`, case-insensitive), creates whichever is missing, and reconciles existing files against the brief without clobbering them; (3) **a single combined context phase** — one concurrent `ctx.parallel` fan-out runs design-system onboarding (`ds-locator`/`ds-analyzer`/`ds-patterns`), the gated gallery **reference-discovery** (Awwwards, recent.design, Dribbble, Monet, Motionsites via `playwright-cli` — clicking into standout work to record a scroll-through video of each real design page so its animations are captured, with a full-page screenshot as a supplement/fallback and the real destination URL, not just the gallery thumbnails — with a web-search fallback, persisted to `/references.md`), and per-reference **import** (`web-capture-` / `file-parser-`) together, after which `design-system-builder` synthesizes the design system; (4) **generation**; (5) **live-driven refinement**; (6) export. User-provided references take **precedence over `DESIGN.md`/`PRODUCT.md`** (a shared `REFERENCE_PRECEDENCE` note is threaded into the import, generator, and apply-changes prompts; `DESIGN.md` fills gaps the references don't cover, `PRODUCT.md` still governs strategic register/voice). The `preview-display-*` stages drive `/skill:impeccable live` against the static `preview.html` for in-browser element-level variant QA, capturing accepted variants via a new `live_changes` field threaded through the refinement feedback; live degrades to `playwright-cli show --annotate` then a manual file path. New logic lives in `open-claude-design-setup.ts` (`runDiscovery`, `detectDesignContextFiles`, `ensureProjectDesignContext`, `buildReferenceDiscoveryPrompt`, `persistReferencesBrief`, `buildLivePreviewDisplayPrompt`) and `open-claude-design-utils.ts` (`discoveryDecisionSchema`, `discoveryDecisionFromResult`, `REFERENCE_PRECEDENCE`) to keep the runner and phases files under the 500-line file-length gate. Added unit coverage for the discovery schema/parse, discovery prompt, always-run init + reconcile + discovery-context threading, the combined context fan-out, reference-discovery prompt/persist, the live-QA prompt, the trimmed input contract, a full-run `init` path, and `live_changes` capture/threading/persistence. + - Added a safe-by-default `create_pr` toggle to the builtin `goal` workflow, matching Ralph's final-stage PR handoff behavior. Goal now skips PR/MR/review creation unless `create_pr=true` **and** reviewer quorum plus the reducer mark the run `complete` within the turn budget, omits `pr_report` when disabled or not approved, and runs a provider-aware `pull-request` stage only at the end when explicitly authorized. The final stage reads the goal ledger, worker receipts, latest review artifact, final report, and sanitized `base_branch` before attempting GitHub, Azure Repos, GitLab, Bitbucket, Sapling, or Phabricator handoff tooling. Goal worker/reviewer prompts now include an intermediate-stage guardrail telling them to ignore PR-creation requests because only the final `pull-request` stage may attempt that handoff. +### Fixed + +- Fixed the builtin `open-claude-design` workflow dropping interactive Playwright annotation feedback between the `preview-display-*` stages and the downstream `user-feedback-*` / `apply-changes-*` refinement stages, so a user could annotate a preview and watch the next iteration apply only internal critique while the design stayed visually unchanged ([#1464](https://github.com/bastani-inc/atomic/issues/1464)). The initial and per-iteration `preview-display-*` results are now captured instead of awaited-and-discarded, parsed for the user's `user_notes` / `annotated_snapshot` (tolerant of heading/bullet/bold/backtick label styles and placeholder values), and carried through the refinement loop as a `previewFeedbackHistory` so every later iteration honors earlier annotations. `user-feedback-*` now receives the captured annotations as the PRIMARY signal in a dedicated `` block (and is told not to approve export while honest user feedback is unaddressed); `apply-changes-*` now consumes a single merged refinement brief built by the new `open-claude-design-feedback.ts` helper that orders **user annotations above** the reviewer decision, impeccable critique, and screenshot/visual-QA findings, with a prompt contract requiring each annotation to be visibly addressed or explicitly explained as a DESIGN.md conflict. Captured annotations are also persisted as durable workflow artifacts under `/feedback/iteration-.md` / `.json` (and a best-effort copy of the annotated snapshot `.png`/`.yaml`). A guardrail runs before each apply stage: if a `preview-display-*` stage captured `user_notes` but they did not thread into the apply prompt, the workflow now fails loudly instead of silently refining without user feedback. Added regression coverage that a `preview-display-*` annotation result threads verbatim into both `user-feedback-*` and `apply-changes-*` (ordered above internal critique) plus unit coverage for the parser, merged-brief ordering, guardrail, fallback, and artifact persistence. +- Fixed the builtin `open-claude-design` workflow polluting the project's `specs/design/` tree with per-run artifact folders during automated test runs; `prepareArtifactDir` now writes to the OS tmpdir when `NODE_ENV=test`. + ## [0.9.0-alpha.3] - 2026-06-21 ### Added diff --git a/packages/workflows/builtin/open-claude-design-feedback.ts b/packages/workflows/builtin/open-claude-design-feedback.ts new file mode 100644 index 0000000000..293900bdbe --- /dev/null +++ b/packages/workflows/builtin/open-claude-design-feedback.ts @@ -0,0 +1,373 @@ +/** + * open-claude-design feedback threading. + * + * The interactive `preview-display-*` stages capture Playwright annotation + * feedback (user notes + annotated snapshot) from the user. Historically that + * feedback was awaited-and-discarded, so the downstream `user-feedback-*` and + * `apply-changes-*` stages never saw it and refined from internal critique + * alone. This module is the durable carrier for that feedback: it parses the + * preview-display stage output, persists it as a workflow artifact, and builds + * the ordered refinement brief (user annotations FIRST, then internal critique) + * that the refinement stages consume. cross-ref: issue #1464. + */ + +import { copyFileSync, existsSync, mkdirSync, statSync, writeFileSync } from "node:fs"; +import { isAbsolute, join, resolve } from "node:path"; + +/** A single captured preview-display feedback round. */ +export type PreviewFeedback = { + /** 0 for the initial preview, 1..N for post-refinement previews. */ + readonly iteration: number; + /** Originating stage name, e.g. `preview-display-initial`. */ + readonly stageName: string; + /** Full markdown result text emitted by the preview-display stage. */ + readonly text: string; + /** Extracted user annotation notes when the user actually annotated. */ + readonly userNotes?: string; + /** Extracted annotated-snapshot artifact path when one was captured. */ + readonly annotatedSnapshot?: string; + /** Extracted summary of the variants/edits the user accepted in the live QA session. */ + readonly liveChanges?: string; + /** ISO timestamp when the feedback was captured. */ + readonly capturedAt: string; +}; + +type PreviewResultLike = { readonly text?: string }; + +/** + * Field labels the preview-display stages are instructed to emit, stored in + * canonical (alphanumeric-only, lowercase) form. Used to bound multi-line value + * extraction (a value ends when the next known field starts). + */ +const FIELD_LABELS = new Set([ + "displaymethod", + "previewpath", + "previewfileurl", + "annotatedsnapshot", + "usernotes", + "livechanges", + "nextactionhint", + "manualopeninstructions", + "specpath", +]); + +const PLACEHOLDER_TOKENS = new Set([ + "none", + "na", + "null", + "undefined", + "notavailable", + "unavailable", + "notcaptured", + "nonotes", + "nousernotes", + "nofeedback", + "noannotations", + "nonecaptured", + "tbd", + "pending", + "n", + "a", +]); + +function isPlaceholderValue(value: string): boolean { + const compact = value + .replace(/\//g, "") + .replace(/[\s().,*_`~–—\-:]/g, "") + .toLowerCase(); + if (compact.length === 0) return true; + return PLACEHOLDER_TOKENS.has(compact); +} + +/** Canonicalize a label to lowercase alphanumerics so `user_notes`, `User Notes`, + * and `**user_notes**` all compare equal. */ +function canonicalLabel(value: string): string { + return value.toLowerCase().replace(/[^a-z0-9]/g, ""); +} + +/** Normalize a candidate label line into a canonical key (or undefined). */ +function labelOf(line: string): string | undefined { + const stripped = line + .replace(/^\s*#{1,6}\s+/, "") + .replace(/^\s*[-*+]\s+/, "") + .replace(/^\s*\d+\.\s+/, ""); + const colonIdx = stripped.indexOf(":"); + const candidate = colonIdx >= 0 ? stripped.slice(0, colonIdx) : stripped; + const key = canonicalLabel(candidate); + return key.length > 0 ? key : undefined; +} + +/** Inline value following a `label:` on the same line. */ +function inlineValueOf(line: string): string { + const stripped = line + .replace(/^\s*#{1,6}\s+/, "") + .replace(/^\s*[-*+]\s+/, "") + .replace(/^\s*\d+\.\s+/, ""); + const colonIdx = stripped.indexOf(":"); + if (colonIdx < 0) return ""; + return stripped.slice(colonIdx + 1).replace(/[`*]/g, "").trim(); +} + +function isHorizontalRule(line: string): boolean { + return /^\s*([-*_])(\s*\1){2,}\s*$/.test(line); +} + +/** + * Extract the value of a labeled field (e.g. `user_notes`) from a preview-display + * markdown blob, tolerating heading / bullet / bold / backtick label styles and + * multi-line values that run until the next known field label or a rule. + */ +export function extractField(text: string, field: string): string | undefined { + if (text.trim().length === 0) return undefined; + const target = canonicalLabel(field); + const lines = text.split(/\r?\n/); + let collecting = false; + const collected: string[] = []; + for (const line of lines) { + if (collecting) { + const label = labelOf(line); + if (label !== undefined && label !== target && FIELD_LABELS.has(label)) break; + if (isHorizontalRule(line)) break; + collected.push(line); + continue; + } + if (labelOf(line) === target) { + const inline = inlineValueOf(line); + if (inline.length > 0) collected.push(inline); + collecting = true; + } + } + const value = collected.join("\n").trim(); + if (value.length === 0 || isPlaceholderValue(value)) return undefined; + return value; +} + +export function extractUserNotes(text: string): string | undefined { + return extractField(text, "user_notes"); +} + +export function extractAnnotatedSnapshot(text: string): string | undefined { + return extractField(text, "annotated_snapshot"); +} + +export function extractLiveChanges(text: string): string | undefined { + return extractField(text, "live_changes"); +} + +/** Build a PreviewFeedback record from a (possibly missing) stage result. */ +export function toPreviewFeedback(input: { + readonly iteration: number; + readonly stageName: string; + readonly result: PreviewResultLike | undefined; +}): PreviewFeedback { + const text = (input.result?.text ?? "").trim(); + const userNotes = extractUserNotes(text); + const annotatedSnapshot = extractAnnotatedSnapshot(text); + const liveChanges = extractLiveChanges(text); + return { + iteration: input.iteration, + stageName: input.stageName, + text, + capturedAt: new Date().toISOString(), + ...(userNotes !== undefined ? { userNotes } : {}), + ...(annotatedSnapshot !== undefined ? { annotatedSnapshot } : {}), + ...(liveChanges !== undefined ? { liveChanges } : {}), + }; +} + +export function hasMeaningfulUserNotes(feedback: PreviewFeedback): boolean { + return typeof feedback.userNotes === "string" && feedback.userNotes.length > 0; +} + +export function hasMeaningfulLiveChanges(feedback: PreviewFeedback): boolean { + return typeof feedback.liveChanges === "string" && feedback.liveChanges.length > 0; +} + +function feedbackLabel(feedback: PreviewFeedback): string { + return feedback.iteration === 0 + ? "the initial preview" + : `refinement iteration ${feedback.iteration}`; +} + +/** + * Render the captured user annotations (latest first) as a markdown section. + * Returns "" when no iteration captured meaningful user notes. + */ +export function buildUserAnnotationsSection(history: readonly PreviewFeedback[]): string { + const withFeedback = history.filter( + (feedback) => hasMeaningfulUserNotes(feedback) || hasMeaningfulLiveChanges(feedback), + ); + if (withFeedback.length === 0) return ""; + return [...withFeedback] + .reverse() + .map((feedback) => { + const lines = [ + `### User annotations from ${feedbackLabel(feedback)} (${feedback.stageName})`, + "", + ]; + if (hasMeaningfulUserNotes(feedback)) { + lines.push(feedback.userNotes ?? ""); + } + if (hasMeaningfulLiveChanges(feedback)) { + lines.push("", "Accepted live variants/edits:", feedback.liveChanges ?? ""); + } + if (feedback.annotatedSnapshot !== undefined) { + lines.push("", `Annotated snapshot: ${feedback.annotatedSnapshot}`); + } + return lines.join("\n"); + }) + .join("\n\n"); +} + +/** + * The user-annotations block injected into refinement prompts, plus whether any + * real annotations exist. When none exist, downstream stages are told to fall + * back to an impeccable critique rather than fabricating user feedback. + */ +export function userAnnotationsBlock(history: readonly PreviewFeedback[]): { + readonly hasNotes: boolean; + readonly text: string; +} { + const section = buildUserAnnotationsSection(history); + if (section.length === 0) { + return { + hasNotes: false, + text: "No interactive user annotations were captured in the preview-display stage(s). There is no user feedback to honor for this iteration; fall back to an impeccable critique of the live preview.", + }; + } + return { hasNotes: true, text: section }; +} + +/** + * Build the merged refinement brief consumed by `apply-changes-*`. User + * annotations are ordered ABOVE internal critique/QA so the apply stage honors + * the user's direction first. cross-ref: issue #1464 expected behavior (3). + */ +export function buildRefinementBrief(input: { + readonly userAnnotations: string; + readonly reviewerDecision: string; + readonly critique: string; + readonly screenshot: string; + readonly currentDesign: string; +}): string { + return [ + "## User annotations (highest priority — address these before any internal critique)", + "", + input.userAnnotations.trim(), + "", + "## Reviewer refinement decision", + "", + input.reviewerDecision.trim(), + "", + "## Impeccable critique findings", + "", + input.critique.trim(), + "", + "## Screenshot / visual QA findings", + "", + input.screenshot.trim(), + "", + "## Current design summary", + "", + input.currentDesign.trim(), + ].join("\n"); +} + +/** + * Guardrail: every captured user annotation must be present verbatim in the + * refinement prompt before the apply stage runs. If a `preview-display-*` stage + * captured `user_notes` but they did not thread through, fail loudly instead of + * silently refining without user feedback. cross-ref: issue #1464 fix (6). + */ +export function assertUserAnnotationsThreaded( + prompt: string, + history: readonly PreviewFeedback[], + stageName: string, +): void { + for (const feedback of history) { + if (!hasMeaningfulUserNotes(feedback)) continue; + const notes = (feedback.userNotes ?? "").trim(); + if (notes.length > 0 && !prompt.includes(notes)) { + throw new Error( + `open-claude-design ${stageName}: user annotations captured in ${feedback.stageName} were not threaded into the refinement context. Refusing to refine without user feedback (see issue #1464).`, + ); + } + } +} + +function copyAnnotationArtifacts( + feedbackDir: string, + slug: string, + feedback: PreviewFeedback, + workflowCwd: string, +): void { + if (feedback.annotatedSnapshot === undefined) return; + const raw = feedback.annotatedSnapshot.trim(); + if (raw.length === 0) return; + const source = isAbsolute(raw) ? raw : resolve(workflowCwd, raw); + try { + if (!existsSync(source) || !statSync(source).isFile()) return; + } catch { + return; + } + const extMatch = source.match(/\.[A-Za-z0-9]+$/); + const ext = extMatch ? extMatch[0] : ".png"; + try { + copyFileSync(source, join(feedbackDir, `${slug}-annotations${ext}`)); + } catch { + /* best-effort */ + } + for (const yamlExt of [".yaml", ".yml"]) { + const sibling = source.replace(/\.[A-Za-z0-9]+$/, yamlExt); + try { + if (existsSync(sibling) && statSync(sibling).isFile()) { + copyFileSync(sibling, join(feedbackDir, `${slug}-annotations${yamlExt}`)); + break; + } + } catch { + /* best-effort */ + } + } +} + +/** + * Persist captured annotations as durable workflow artifacts under + * `/feedback/`. Only writes when the user actually provided + * annotations (notes or an annotated snapshot). Best-effort: never throws. + * cross-ref: issue #1464 fix (5). + */ +export function persistPreviewFeedback(input: { + readonly artifactDir: string; + readonly workflowCwd: string; + readonly feedback: PreviewFeedback; +}): void { + const { feedback } = input; + if ( + !hasMeaningfulUserNotes(feedback) && + !hasMeaningfulLiveChanges(feedback) && + feedback.annotatedSnapshot === undefined + ) { + return; + } + try { + const feedbackDir = join(input.artifactDir, "feedback"); + mkdirSync(feedbackDir, { recursive: true }); + const slug = `iteration-${feedback.iteration}`; + writeFileSync(join(feedbackDir, `${slug}.md`), `${feedback.text}\n`); + writeFileSync( + join(feedbackDir, `${slug}.json`), + `${JSON.stringify( + { + ...feedback, + hasUserNotes: hasMeaningfulUserNotes(feedback), + hasLiveChanges: hasMeaningfulLiveChanges(feedback), + }, + null, + 2, + )}\n`, + ); + copyAnnotationArtifacts(feedbackDir, slug, feedback, input.workflowCwd); + } catch { + /* best-effort durability; never block the workflow */ + } +} diff --git a/packages/workflows/builtin/open-claude-design-phases.ts b/packages/workflows/builtin/open-claude-design-phases.ts index 5549673a7f..84df642dfb 100644 --- a/packages/workflows/builtin/open-claude-design-phases.ts +++ b/packages/workflows/builtin/open-claude-design-phases.ts @@ -3,10 +3,20 @@ import type { WorkflowTaskResult } from "../src/shared/types.js"; import { ANTI_SLOP_RULES, HTML_PREVIEW_RULES, + REFERENCE_PRECEDENCE, exportGateDecisionFromResult, refinementDecisionFromResult, taggedPrompt, } from "./open-claude-design-utils.js"; +import { + assertUserAnnotationsThreaded, + buildRefinementBrief, + persistPreviewFeedback, + toPreviewFeedback, + userAnnotationsBlock, + type PreviewFeedback, +} from "./open-claude-design-feedback.js"; +import { buildLivePreviewDisplayPrompt } from "./open-claude-design-setup.js"; type DesignContext = { task(name: string, options: object): Promise; @@ -28,16 +38,31 @@ type RefineOptions = { readonly latestDesign: string; readonly designModelConfig: ModelConfig; readonly refinementDecisionConfig: ModelConfig; + readonly workflowCwd: string; + readonly initialPreviewFeedback?: PreviewFeedback; + readonly referencesBrief?: string; + readonly importContext?: string; }; export async function refineOpenClaudeDesign(options: RefineOptions): Promise<{ readonly latestDesign: string; readonly approvedForExport: boolean; readonly refinementCount: number; }> { - const { designContext, prompt, outputType, maxRefinements, previewPath, previewFileUrl, artifactDir, browserBootstrapRules, designSystem, designModelConfig, refinementDecisionConfig } = options; + const { designContext, prompt, outputType, maxRefinements, previewPath, previewFileUrl, artifactDir, browserBootstrapRules, designSystem, designModelConfig, refinementDecisionConfig, workflowCwd } = options; + const referencesBrief = options.referencesBrief ?? ""; + const importContext = options.importContext ?? ""; let latestDesign = options.latestDesign; let approvedForExport = false; let refinementCount = 0; + // Durable carrier for interactive annotation feedback captured by the + // preview-display stages. Seeded with the initial preview's annotations so the + // very first refinement honors what the user drew on the page. #1464 + const previewFeedbackHistory: PreviewFeedback[] = []; + if (options.initialPreviewFeedback !== undefined) { + previewFeedbackHistory.push(options.initialPreviewFeedback); + } for (let iteration = 1; iteration <= maxRefinements; iteration += 1) { refinementCount = iteration; + const annotations = userAnnotationsBlock(previewFeedbackHistory); + const feedback = await designContext.task(`user-feedback-${iteration}`, { prompt: taggedPrompt([ [ @@ -50,15 +75,17 @@ export async function refineOpenClaudeDesign(options: RefineOptions): Promise<{ ], ["preview_path", previewPath], ["preview_file_url", previewFileUrl], + ["user_annotations", annotations.text], ["current_design_summary", "{previous}"], [ "instructions", [ - "1. If a previous `preview-display-*` step captured annotated user feedback or notes, honor them as the primary signal.", - "2. Otherwise, you may inspect the HTML file at preview_path directly (read it from disk) and run an impeccable `critique` against it.", - "3. Decide whether the current design is ready for export.", - "4. If refinement is still needed, put specific changes in required_changes ordered by user value and implementation risk.", - "5. Never request changes that contradict DESIGN.md unless you explicitly identify and explain the conflict.", + "1. Treat the `` block as the PRIMARY signal: it holds the interactive feedback the user drew/typed on the live preview. Honor every annotation it contains.", + "2. When `` contains real user notes, set ready_for_export=false unless the current design already satisfies every annotation; never approve export while honest user feedback remains unaddressed.", + "3. If `` says no annotations were captured, inspect the HTML file at preview_path directly (read it from disk) and run an impeccable `critique` against it instead.", + "4. Decide whether the current design is ready for export.", + "5. If refinement is still needed, put specific changes in required_changes ordered by user value and implementation risk; lead with the user annotations.", + "6. Never request changes that contradict DESIGN.md unless you explicitly identify and explain the conflict.", ].join("\n"), ], [ @@ -163,28 +190,43 @@ export async function refineOpenClaudeDesign(options: RefineOptions): Promise<{ { task: prompt }, ); - const applied = await designContext.task(`apply-changes-${iteration}`, { - prompt: taggedPrompt([ + const critiqueResult = + validation.find((result) => result.name === `critique-${iteration}`) ?? validation[0]; + const screenshotResult = + validation.find((result) => result.name === `screenshot-${iteration}`) ?? validation[1]; + const refinementBrief = buildRefinementBrief({ + userAnnotations: annotations.text, + reviewerDecision: feedback.text, + critique: critiqueResult?.text ?? "", + screenshot: screenshotResult?.text ?? "", + currentDesign: latestDesign, + }); + + const applyPrompt = taggedPrompt([ [ "role", "You are an opinionated staff design engineer.", ], [ "objective", - `Produce the next ${outputType} revision for: ${prompt}. Update the HTML file in place; do not branch the artifact. Apply the impeccable \`polish\` sub-skill to methodically apply the required changes, addressing every critique finding and screenshot-validated issue with surgical precision. This is not a redesign; it's a focused polish iteration to get from the current design to an export-ready state in one step.`, + `Produce the next ${outputType} revision for: ${prompt}. Update the HTML file in place; do not branch the artifact. Apply the impeccable \`polish\` sub-skill to methodically apply the required changes, addressing every user annotation, critique finding, and screenshot-validated issue with surgical precision. This is not a redesign; it's a focused polish iteration to get from the current design to an export-ready state in one step.`, ], ["design_system", designSystem], + ["reference_inspiration", referencesBrief], + ["reference_context", importContext], + ["reference_precedence", REFERENCE_PRECEDENCE], ["preview_artifact_path", previewPath], - ["revision_context", "{previous}"], + ["revision_context", refinementBrief], [ "instructions", [ "1. Read the current HTML at preview_artifact_path with your file-read tool.", - `2. Apply user feedback, critique findings, screenshot/visual QA findings, and DESIGN.md constraints together. Overwrite ${previewPath} with the revised HTML (full file rewrite, not patches — the artifact must always be self-contained).`, - "3. Preserve strong existing design decisions unless a finding requires change.", - "4. Resolve conflicting feedback explicitly; choose the safest DESIGN.md-aligned option and note the trade-off.", - "5. Update states, accessibility, responsiveness, and HTML implementation comments when changes affect them.", - "6. After writing, return a short markdown summary listing the changes, trade-offs, and remaining questions — do NOT paste the HTML body.", + "2. The `` block is a merged refinement brief. Treat its `## User annotations` section as the HIGHEST priority: every user annotation MUST be visibly addressed in this revision, or you must explicitly explain in your summary why a specific annotation conflicts with DESIGN.md/spec and cannot be applied. Only after honoring the user annotations should you apply the critique findings and screenshot/visual QA findings.", + `3. Apply the user annotations, critique findings, screenshot/visual QA findings, and DESIGN.md constraints together, honoring \`\` (the user references in \`\` win over DESIGN.md/PRODUCT.md where they conflict). Overwrite ${previewPath} with the revised HTML (full file rewrite, not patches — the artifact must always be self-contained).`, + "4. Preserve strong existing design decisions unless a finding requires change.", + "5. Resolve conflicting feedback explicitly; choose the safest DESIGN.md-aligned option and note the trade-off.", + "6. Update states, accessibility, responsiveness, and HTML implementation comments when changes affect them.", + "7. After writing, return a short markdown summary listing the changes, trade-offs, and remaining questions — do NOT paste the HTML body.", ].join("\n"), ], [ @@ -192,57 +234,48 @@ export async function refineOpenClaudeDesign(options: RefineOptions): Promise<{ [ "Markdown with headings:", "1. Revised artifact (path only)", - "2. Changes applied (bullet list, each tied to a critique or screenshot finding)", - "3. Trade-offs / conflicts resolved", - "4. Remaining questions", + "2. User annotations addressed (each annotation → how it was applied, or why it was deferred/conflicts)", + "3. Changes applied (bullet list, each tied to a user annotation, critique, or screenshot finding)", + "4. Trade-offs / conflicts resolved", + "5. Remaining questions", ].join("\n"), ], - ]), - previous: [ - { name: "current-design", text: latestDesign }, - feedback, - ...validation, - ], + ]); + + // Guardrail: if a preview-display stage captured user annotations, refuse to + // run the apply stage unless they actually threaded into this prompt. #1464 + assertUserAnnotationsThreaded(applyPrompt, previewFeedbackHistory, `apply-changes-${iteration}`); + + const applied = await designContext.task(`apply-changes-${iteration}`, { + prompt: applyPrompt, ...designModelConfig, }); latestDesign = applied.text; - // Re-display the freshly revised preview so the user can keep iterating. - await designContext + // Re-display the freshly revised preview with interactive `live` QA so the + // user can keep iterating element-by-element in the browser. + const revisedPreviewResult = await designContext .task(`preview-display-${iteration}`, { - prompt: taggedPrompt([ - [ - "role", - "You are a staff product manager with expertise in design. Re-open the revised HTML preview so the user can review the latest iteration.", - ], - [ - "objective", - `Show the user the revised preview after iteration ${iteration}/${maxRefinements} and capture any new annotated feedback for the next loop.`, - ], - ["preview_path", previewPath], - ["preview_file_url", previewFileUrl], - [ - "browser_use_bootstrap", + prompt: buildLivePreviewDisplayPrompt({ + previewPath, + previewFileUrl, browserBootstrapRules, - ], - [ - "instructions", - [ - `1. If \`playwright-cli\` is available, run \`playwright-cli open ${previewFileUrl}\`. If that reports a missing browser executable, follow the bootstrap rules and retry once.`, - "2. Then run `playwright-cli snapshot` and, for interactive review, `playwright-cli show --annotate`; otherwise ask the user to provide feedback inline.", - `3. If \`playwright-cli\` is unavailable or browser bootstrap fails, surface the path clearly: ${previewPath} (URL: ${previewFileUrl}).`, - "4. Return any captured annotations as structured notes the next user-feedback step can read.", - "5. Do not block on unavailable tooling.", - ].join("\n"), - ], - [ - "output_format", - "Markdown with: `display_method`, `preview_path`, `annotated_snapshot` (if any), `user_notes` (if any), `next_action_hint`.", - ], - ]), + iteration, + maxRefinements, + }), ...designModelConfig, }) .catch(() => undefined); + + // Capture the revised preview's annotation feedback so the NEXT iteration's + // user-feedback/apply-changes stages honor it too. #1464 + const revisedFeedback = toPreviewFeedback({ + iteration, + stageName: `preview-display-${iteration}`, + result: revisedPreviewResult, + }); + persistPreviewFeedback({ artifactDir, workflowCwd, feedback: revisedFeedback }); + previewFeedbackHistory.push(revisedFeedback); } diff --git a/packages/workflows/builtin/open-claude-design-runner.ts b/packages/workflows/builtin/open-claude-design-runner.ts index 0df5ddc5ed..e7913e07e3 100644 --- a/packages/workflows/builtin/open-claude-design-runner.ts +++ b/packages/workflows/builtin/open-claude-design-runner.ts @@ -5,18 +5,28 @@ import { HTML_PREVIEW_RULES, READ_ONLY_TOOLS, buildPlaywrightCliBootstrapRules, + discoveryDecisionSchema, exportGateDecisionSchema, isFileLike, isUrl, joinResults, - normalizeOutputType, positiveInteger, prepareArtifactDir, refinementDecisionSchema, taggedPrompt, ensurePlaywrightCli, + REFERENCE_PRECEDENCE, } from "./open-claude-design-utils.js"; import { exportOpenClaudeDesign, refineOpenClaudeDesign } from "./open-claude-design-phases.js"; +import { persistPreviewFeedback, toPreviewFeedback } from "./open-claude-design-feedback.js"; +import { + NO_REFERENCES_BRIEF, + buildLivePreviewDisplayPrompt, + buildReferenceDiscoveryPrompt, + ensureProjectDesignContext, + persistReferencesBrief, + runDiscovery, +} from "./open-claude-design-setup.js"; type OpenClaudeDesignOutputs = { readonly output_type?: string; readonly design_system?: string; readonly artifact?: string; readonly handoff?: string; @@ -27,7 +37,7 @@ type OpenClaudeDesignOutputs = { type OpenClaudeDesignContext = { readonly cwd?: string; - readonly inputs: { readonly prompt: string; readonly reference?: string; readonly output_type?: string; readonly design_system?: string; readonly max_refinements?: number }; + readonly inputs: { readonly prompt: string; readonly discover_references?: boolean; readonly max_refinements?: number }; task(name: string, options: WorkflowTaskOptions): Promise; parallel(steps: readonly WorkflowTaskStep[], options: WorkflowParallelOptions): Promise; }; @@ -36,18 +46,13 @@ export async function runOpenClaudeDesignWorkflow(ctx: OpenClaudeDesignContext): const designContext = ctx; // Initial deterministic setup step (no LLM): ensure the playwright-cli skill's - // `playwright-cli` command is installed before any design stage runs. Best-effort — - // a failed install never blocks the workflow; downstream stages keep their - // graceful-degradation fallback (surface the manual preview path / URL). + // `playwright-cli` command is installed before any design stage runs. Best-effort. const playwrightCli = ensurePlaywrightCli(); const browserBootstrapRules = buildPlaywrightCliBootstrapRules(playwrightCli); const inputs = designContext.inputs; - const prompt = inputs.prompt; - const reference = inputs.reference?.trim() ?? ""; - const outputType = normalizeOutputType(inputs.output_type); - const designSystemInput = (inputs.design_system ?? "").trim(); + const discoverReferences = inputs.discover_references !== false; const maxRefinements = positiveInteger( inputs.max_refinements, DEFAULT_MAX_REFINEMENTS, @@ -82,275 +87,282 @@ export async function runOpenClaudeDesignWorkflow(ctx: OpenClaudeDesignContext): schema: exportGateDecisionSchema, }; - let designSystem: string; - let onboarding: readonly WorkflowTaskResult[] = []; + // Phase 1: discovery — interview the user (impeccable `shape`) to confirm the + // design brief, output type, and references before onboarding or generation. + const discovery = await runDiscovery({ + designContext, + prompt, + discoveryConfig: { ...designModelConfig, schema: discoveryDecisionSchema }, + }); + const designBrief = discovery.brief; + const outputType = discovery.output_type; + const references = discovery.references; - if (designSystemInput.length > 0) { - const loaded = await designContext.task("load-design-system", { - prompt: taggedPrompt([ - [ - "role", - "You are an opinionated staff design engineer.", - ], - [ - "objective", - `Prepare a six-section DESIGN.md-shaped brief that will steer generation of: ${prompt}. Apply the impeccable \`document\` sub-skill to read an existing DESIGN.md / PRODUCT.md (or equivalent).`, - ], - ["design_system_reference", designSystemInput], - [ - "instructions", + // Phase 2: establish project design context (PRODUCT.md / DESIGN.md) via + // `/skill:impeccable init` when either is missing; reuse the discovery answers. + const discoveryContext = [ + `Confirmed design brief: ${designBrief}`, + `Output type: ${outputType}`, + references.length > 0 + ? `References to emulate (take precedence over DESIGN.md/PRODUCT.md): ${references.join(", ")}` + : "References to emulate: none provided.", + ].join("\n"); + const projectContext = await ensureProjectDesignContext({ + designContext, + cwd: workflowCwd, + prompt: designBrief, + discoveryContext, + designModelConfig, + }); + + // Phase 3 (combined): one concurrent context-gathering fan-out collects the + // project's design-system evidence (ds-*), the gallery references (gated), + // and the user-reference imports together; then the builder synthesizes. + const dsSteps: WorkflowTaskStep[] = [ + { + name: "ds-locator", + task: taggedPrompt([ + ["role", "You are an opinionated staff design engineer."], [ - "1. Read every reference path/URL supplied.", - "2. Extract: register (brand vs product), Creative North Star, color tokens with descriptive names, type stack, elevation philosophy, components/variants, accessibility constraints, and the named DO/DON'T rules.", - "3. Distinguish explicit rules in the source from inferred conventions; never invent rules.", - "4. State what could not be verified instead of guessing.", - ].join("\n"), - ], - [ - "output_format", + "objective", + `Find UI/design-system sources for this request: ${designBrief}. Apply the impeccable \`extract\` sub-skill to find design-system evidence already living in this codebase.`, + ], [ - "Markdown with the six required headings, in this exact order and case:", - "## Overview", - "## Colors", - "## Typography", - "## Elevation", - "## Components", - "## Do's and Don'ts", - "Then a final `## Gaps / Assumptions` section listing anything unverified.", - ].join("\n"), - ], - ]), - ...designModelConfig, - }); - designSystem = loaded.text; - onboarding = [loaded]; - } else { - onboarding = await designContext.parallel( - [ - { - name: "ds-locator", - task: taggedPrompt([ - [ - "role", - "You are an opinionated staff design engineer.", - ], - [ - "objective", - `Find UI/design-system sources for this request: ${prompt}. Apply the impeccable \`extract\` sub-skill to find design-system evidence already living in this codebase.`, - ], - [ - "instructions", - [ - "1. Locate UI components, stylesheets, tokens (CSS custom properties, Tailwind config, CSS-in-JS themes, design-token files), Storybook/examples, screenshots, tests, and design docs.", - "2. Return concrete file paths plus why each path informs design generation.", - "3. Separate primary sources from supporting examples.", - "4. If no explicit design system exists, identify the strongest implicit evidence (most-repeated literals, dominant component patterns).", - ].join("\n"), - ], + "instructions", [ - "output_format", - "Markdown table: Path | Evidence type | What it reveals | Repetitions seen | Confidence (low/med/high).", - ], - ]), - ...designModelConfig, - }, - { - name: "ds-analyzer", - task: taggedPrompt([ - [ - "role", - "You are an opinionated staff design engineer.", - ], - [ - "objective", - `Audit the project UI constraints that must shape: ${prompt}. Apply the impeccable \`audit\` sub-skill to evaluate the located design-system evidence against impeccable's six dimensions of design quality and produce a detailed report with actionable insights for generation.`, - ], + "1. Locate UI components, stylesheets, tokens (CSS custom properties, Tailwind config, CSS-in-JS themes, design-token files), Storybook/examples, screenshots, tests, and design docs.", + "2. Return concrete file paths plus why each path informs design generation.", + "3. Separate primary sources from supporting examples.", + "4. If no explicit design system exists, identify the strongest implicit evidence (most-repeated literals, dominant component patterns).", + ].join("\n"), + ], + [ + "output_format", + "Markdown table: Path | Evidence type | What it reveals | Repetitions seen | Confidence (low/med/high).", + ], + ]), + ...designModelConfig, + }, + { + name: "ds-analyzer", + task: taggedPrompt([ + ["role", "You are an opinionated staff design engineer."], + [ + "objective", + `Audit the project UI constraints that must shape: ${designBrief}. Apply the impeccable \`audit\` sub-skill to evaluate the located design-system evidence against impeccable's six dimensions of design quality and produce a detailed report with actionable insights for generation.`, + ], + [ + "impeccable_skill", + "audit — score 0–4 across Accessibility, Performance, Theming, Responsive, Anti-patterns. Tag every finding P0 (blocks release) → P3 (polish). Document, do not fix.", + ], + [ + "instructions", [ - "impeccable_skill", - "audit — score 0–4 across Accessibility, Performance, Theming, Responsive, Anti-patterns. Tag every finding P0 (blocks release) → P3 (polish). Document, do not fix.", - ], + "1. Inspect: UI stack, styling approach, token usage, responsive behavior, accessibility conventions, component APIs.", + "2. Ground every claim in exact paths, symbols, or code examples.", + "3. Call out constraints that generated designs MUST follow to integrate cleanly.", + "4. State uncertainty rather than guessing when evidence is incomplete.", + ].join("\n"), + ], + [ + "output_format", [ - "instructions", - [ - "1. Inspect: UI stack, styling approach, token usage, responsive behavior, accessibility conventions, component APIs.", - "2. Ground every claim in exact paths, symbols, or code examples.", - "3. Call out constraints that generated designs MUST follow to integrate cleanly.", - "4. State uncertainty rather than guessing when evidence is incomplete.", - ].join("\n"), - ], + "Markdown sections in this order:", + "1. Stack", + "2. Tokens", + "3. Components", + "4. Layout / responsiveness", + "5. Accessibility", + "6. Audit scores (per dimension, 0–4)", + "7. Hard constraints for generation", + ].join("\n"), + ], + ]), + ...designModelConfig, + }, + { + name: "ds-patterns", + task: taggedPrompt([ + ["role", "You are an opinionated staff design engineer."], + [ + "objective", + `Extract reusable patterns and anti-patterns for: ${designBrief}. Apply the impeccable \`extract\` sub-skill to find design patterns that should be reused and anti-patterns that must be avoided in generation.`, + ], + [ + "instructions", [ - "output_format", - [ - "Markdown sections in this order:", - "1. Stack", - "2. Tokens", - "3. Components", - "4. Layout / responsiveness", - "5. Accessibility", - "6. Audit scores (per dimension, 0–4)", - "7. Hard constraints for generation", - ].join("\n"), - ], - ]), - ...designModelConfig, - }, + "1. Find naming, variant, composition, state, animation, and layout patterns that should be reused.", + "2. Include examples with concrete paths and component/symbol names.", + "3. Identify anti-patterns the generated design must avoid — cross-reference impeccable's 25 deterministic anti-patterns (gradient text, AI palettes, nested cards, side-tab borders, line-length problems, etc.).", + "4. Do not generalize beyond the evidence found in the repository.", + ].join("\n"), + ], + [ + "output_format", + "Markdown with sections: Reusable patterns | Examples | Anti-patterns | Generation implications.", + ], + ]), + ...designModelConfig, + }, + ]; + + // Gallery reference discovery joins the same fan-out (gated by discover_references). + const referenceStep: WorkflowTaskStep[] = discoverReferences + ? [ { - name: "ds-patterns", - task: taggedPrompt([ - [ - "role", - "You are an opinionated staff design engineer.", - ], - [ - "objective", - `Extract reusable patterns and anti-patterns for: ${prompt}. Apply the impeccable \`extract\` sub-skill to find design patterns that should be reused and anti-patterns that must be avoided in generation.`, - ], - [ - "instructions", - [ - "1. Find naming, variant, composition, state, animation, and layout patterns that should be reused.", - "2. Include examples with concrete paths and component/symbol names.", - "3. Identify anti-patterns the generated design must avoid — cross-reference impeccable's 25 deterministic anti-patterns (gradient text, AI palettes, nested cards, side-tab borders, line-length problems, etc.).", - "4. Do not generalize beyond the evidence found in the repository.", - ].join("\n"), - ], - [ - "output_format", - "Markdown with sections: Reusable patterns | Examples | Anti-patterns | Generation implications.", - ], - ]), + name: "reference-discovery", + task: buildReferenceDiscoveryPrompt({ + prompt: designBrief, + outputType, + designContextHint: projectContext.summary, + artifactDir, + browserBootstrapRules, + }), ...designModelConfig, }, - ], - { task: prompt }, - ); + ] + : []; - const builder = await designContext.task("design-system-builder", { - prompt: taggedPrompt([ - [ - "role", - "You are a staff design enginer.", - ], - [ - "objective", - `Build the project DESIGN.md that will steer generation for: ${prompt}. Apply the impeccable \`document\` sub-skill to synthesize a coherent design system spec from the located evidence, audit findings, and pattern analysis. This is the most critical step for generation quality; use impeccable's design knowledge to make smart calls when evidence conflicts or is incomplete.`, - ], - ["onboarding_analysis", "{previous}"], - [ - "instructions", + // The user-provided references gathered in discovery are imported in the + // same fan-out; they take precedence over DESIGN.md/PRODUCT.md downstream. + const importSteps: WorkflowTaskStep[] = []; + references.forEach((ref, index) => { + const position = index + 1; + if (isUrl(ref)) { + importSteps.push({ + name: `web-capture-${position}`, + task: taggedPrompt([ + ["role", "You are a staff QA engineer with design expertise."], [ - "1. Synthesize locator + auditor + pattern-miner evidence into one coherent source of truth.", - "2. Keep every claim traceable to a path or symbol from the analysis.", - "3. Prefer concrete tokens, component conventions, and accessibility rules over vague style adjectives.", - "4. List assumptions in a separate trailing section; never mix them with verified rules.", - ].join("\n"), - ], - [ - "output_format", + "objective", + `Capture transferable design intent from this user-provided reference for: ${designBrief}. Apply the impeccable \`extract\` sub-skill to lift concrete, citable design traits from the reference URL. ${REFERENCE_PRECEDENCE} Use browser/screenshot tooling if available; never guess about visual traits without observable evidence.`, + ], + ["reference_url", ref], + ["browser_use_guidelines", browserBootstrapRules], [ - "Markdown with exactly these headings, in this order:", - "## Overview (include the Creative North Star)", - "## Colors", - "## Typography", - "## Elevation", - "## Components", - "## Do's and Don'ts (use the impeccable named-rule style)", - "## Verified vs Assumed", - ].join("\n"), - ], - ]), - previous: onboarding, - ...designModelConfig, - }); - designSystem = builder.text; - onboarding = [...onboarding, builder]; - } - - const importSteps: WorkflowTaskStep[] = []; - if (isUrl(reference)) { - importSteps.push({ - name: "web-capture", - task: taggedPrompt([ - [ - "role", - "You are a staff QA engineer with design expertise.", - ], - [ - "objective", - `Capture transferable design intent from this reference for: ${prompt}. Apply the impeccable \`extract\` sub-skill to lift concrete, citable design traits from the reference URL. Use browser/screenshot tooling if available; never guess about visual traits without observable evidence.`, - ], - ["reference_url", reference], - ["browser_use_guidelines", browserBootstrapRules], - [ - "instructions", + "instructions", + [ + "1. Use browser/screenshot tooling (for example the playwright-cli skill's `playwright-cli` command) if available; cite observable evidence rather than guessing.", + "2. If `playwright-cli` is available but opening the reference URL reports a missing browser executable, follow the bootstrap rules and retry once.", + "3. Analyze: layout, visual hierarchy, navigation, color, typography, spacing, states, interactions, responsive behavior.", + "4. Separate reference-specific styling from requirements that should transfer to this design.", + "5. If the URL is inaccessible or browser bootstrap fails, state that and provide a best-effort fallback based only on available information — never fabricate observations.", + ].join("\n"), + ], [ - "1. Use browser/screenshot tooling (for example the playwright-cli skill's `playwright-cli` command) if available; cite observable evidence rather than guessing.", - "2. If `playwright-cli` is available but opening the reference URL reports a missing browser executable, follow the bootstrap rules and retry once.", - "3. Analyze: layout, visual hierarchy, navigation, color, typography, spacing, states, interactions, responsive behavior.", - "4. Separate reference-specific styling from requirements that should transfer to this project's design system.", - "5. If the URL is inaccessible or browser bootstrap fails, state that and provide a best-effort fallback based only on available information — never fabricate observations.", - ].join("\n"), - ], - [ - "output_format", - "Markdown sections: Observable design traits | Transferable requirements | Assets/content | Uncertainty.", - ], - ]), - ...designModelConfig, - }); - } - if (isFileLike(reference)) { - importSteps.push({ - name: "file-parser", - task: taggedPrompt([ - [ - "role", - "You are an opinionated staff design engineer.", - ], - [ - "objective", - `Extract actionable design requirements for: ${prompt}. Apply the impeccable \`extract\` sub-skill to pull out concrete, citable design requirements from this reference file or doc. The reference might be a design file, a screenshot, a code file, or a design doc; adapt your extraction approach accordingly but never guess about traits that are not explicitly observable in the source.`, - ], - ["reference", reference], - [ - "instructions", + "output_format", + "Markdown sections: Observable design traits | Transferable requirements | Assets/content | Uncertainty.", + ], + ]), + ...designModelConfig, + }); + } else if (isFileLike(ref)) { + importSteps.push({ + name: `file-parser-${position}`, + task: taggedPrompt([ + ["role", "You are an opinionated staff design engineer."], [ - "1. Extract: requirements, tokens, layout details, interaction notes, assets, copy, constraints, acceptance criteria.", - "2. Quote or cite concrete sections/paths wherever possible.", - "3. Separate explicit requirements from inferred design direction.", - "4. If the reference cannot be read, say exactly what failed and what remains unknown.", - ].join("\n"), - ], - [ - "output_format", - "Markdown sections: Explicit requirements | Inferred direction | Assets/copy | Constraints | Unknowns.", - ], - ]), - ...designModelConfig, - }); - } + "objective", + `Extract actionable design requirements for: ${designBrief}. Apply the impeccable \`extract\` sub-skill to pull out concrete, citable design requirements from this user-provided reference file or doc. ${REFERENCE_PRECEDENCE} The reference might be a design file, a screenshot, a code file, or a design doc; adapt your extraction approach accordingly but never guess about traits that are not explicitly observable in the source.`, + ], + ["reference", ref], + [ + "instructions", + [ + "1. Extract: requirements, tokens, layout details, interaction notes, assets, copy, constraints, acceptance criteria.", + "2. Quote or cite concrete sections/paths wherever possible.", + "3. Separate explicit requirements from inferred design direction.", + "4. If the reference cannot be read, say exactly what failed and what remains unknown.", + ].join("\n"), + ], + [ + "output_format", + "Markdown sections: Explicit requirements | Inferred direction | Assets/copy | Constraints | Unknowns.", + ], + ]), + ...designModelConfig, + }); + } + }); + + // Run the whole context-gathering phase concurrently in a single fan-out. + const contextResults = await designContext.parallel( + [...dsSteps, ...referenceStep, ...importSteps], + { task: designBrief }, + ); + const dsNames = new Set(["ds-locator", "ds-analyzer", "ds-patterns"]); + const onboardingAnalysis = contextResults.filter((result) => + dsNames.has(result.name ?? ""), + ); + const referenceResult = contextResults.find( + (result) => result.name === "reference-discovery", + ); + const importResults = contextResults.filter( + (result) => + (result.name ?? "").startsWith("web-capture-") || + (result.name ?? "").startsWith("file-parser-"), + ); + + const referencesBriefRaw = (referenceResult?.text ?? "").trim(); + const referencesBrief = + referencesBriefRaw.length > 0 ? referencesBriefRaw : NO_REFERENCES_BRIEF; + if (referencesBriefRaw.length > 0) persistReferencesBrief(artifactDir, referencesBrief); - const imports = - importSteps.length > 0 - ? await designContext.parallel(importSteps, { task: prompt }) - : []; const importContext = - imports.length > 0 - ? joinResults(imports) - : "No external reference was provided; infer the design direction from the prompt and project design system."; + importResults.length > 0 + ? joinResults(importResults) + : "No user reference was provided; infer the design direction from the brief and project design system."; - const generated = await designContext.task("generator", { + const builder = await designContext.task("design-system-builder", { prompt: taggedPrompt([ + ["role", "You are a staff design enginer."], + [ + "objective", + `Build the project DESIGN.md that will steer generation for: ${designBrief}. Apply the impeccable \`document\` sub-skill to synthesize a coherent design system spec from the located evidence, audit findings, and pattern analysis. This is the most critical step for generation quality; use impeccable's design knowledge to make smart calls when evidence conflicts or is incomplete.`, + ], + ["onboarding_analysis", "{previous}"], + ["project_design_context", projectContext.summary], [ - "role", - "You are an opinionated staff design engineer.", + "instructions", + [ + "1. Synthesize locator + auditor + pattern-miner evidence into one coherent source of truth.", + "2. Keep every claim traceable to a path or symbol from the analysis.", + "3. Prefer concrete tokens, component conventions, and accessibility rules over vague style adjectives.", + "4. List assumptions in a separate trailing section; never mix them with verified rules.", + ].join("\n"), + ], + [ + "output_format", + [ + "Markdown with exactly these headings, in this order:", + "## Overview (include the Creative North Star)", + "## Colors", + "## Typography", + "## Elevation", + "## Components", + "## Do's and Don'ts (use the impeccable named-rule style)", + "## Verified vs Assumed", + ].join("\n"), ], + ]), + previous: onboardingAnalysis, + ...designModelConfig, + }); + const designSystem = builder.text; + const onboarding = [...onboardingAnalysis, builder]; + + const generated = await designContext.task("generator", { + prompt: taggedPrompt([ + ["role", "You are an opinionated staff design engineer."], [ "objective", - `Generate the first revision of a production-ready ${outputType} for: ${prompt}. Write it to disk as an interactive HTML preview the user can open in a browser. Apply the impeccable \`craft\` sub-skill to build the design with deliberate ordering and impeccable attention to detail. Every design decision must trace back to the brief, and every visual trait must be justified by the design system or reference context.`, + `Generate the first revision of a production-ready ${outputType} for: ${designBrief}. Write it to disk as an interactive HTML preview the user can open in a browser. Apply the impeccable \`craft\` sub-skill to build the design with deliberate ordering and impeccable attention to detail. Every design decision must trace back to the brief, and every visual trait must be justified by the references, design system, or reference context.`, ], + ["design_brief", designBrief], ["design_system", designSystem], ["reference_context", importContext], + ["reference_inspiration", referencesBrief], + ["reference_precedence", REFERENCE_PRECEDENCE], ["preview_artifact_path", previewPath], ["html_rules", HTML_PREVIEW_RULES], ["anti_design_slop_rules", ANTI_SLOP_RULES], @@ -358,11 +370,12 @@ export async function runOpenClaudeDesignWorkflow(ctx: OpenClaudeDesignContext): "instructions", [ `1. Use the Write tool to create the HTML artifact at exactly this path: ${previewPath}.`, - "2. Treat the verified DESIGN.md rules as hard constraints unless a conflict is explicitly flagged.", - `3. Build the artifact as the requested output_type (${outputType}). For prototypes/pages, render full layouts with realistic content. For components, render the component in 3+ representative contexts (default, with content variations, with state variations).`, - "4. Include structure, states, accessibility behavior, responsive behavior, and integration notes — but keep them in HTML comments inside the file so the rendered preview stays clean.", - "5. Do not use generic placeholder language when project conventions are available.", - "6. After writing the file, return a short markdown summary (NOT the HTML body) describing what you built, the decisions you made, and assumptions you are leaving for the user to confirm.", + "2. Follow the `` rule: the user-provided references in `` win over DESIGN.md/PRODUCT.md where they conflict; DESIGN.md fills the gaps the references do not cover.", + "3. Heavily reference the `` block: emulate the strongest direction(s) it ranks for this brief while staying consistent with the user references; never copy a reference wholesale or invent traits it does not contain.", + `4. Build the artifact as the requested output_type (${outputType}). For prototypes/pages, render full layouts with realistic content. For components, render the component in 3+ representative contexts (default, with content variations, with state variations).`, + "5. Include structure, states, accessibility behavior, responsive behavior, and integration notes — but keep them in HTML comments inside the file so the rendered preview stays clean.", + "6. Do not use generic placeholder language when project conventions are available.", + "7. After writing the file, return a short markdown summary (NOT the HTML body) describing what you built, the decisions you made, and assumptions you are leaving for the user to confirm.", ].join("\n"), ], [ @@ -378,7 +391,7 @@ export async function runOpenClaudeDesignWorkflow(ctx: OpenClaudeDesignContext): ].join("\n"), ], ]), - previous: [...onboarding, ...imports], + previous: [...onboarding, ...importResults], ...designModelConfig, }); @@ -386,44 +399,31 @@ export async function runOpenClaudeDesignWorkflow(ctx: OpenClaudeDesignContext): let approvedForExport = false; let refinementCount = 0; - // Try to display the freshly generated preview to the user via browser. - await designContext + // Display the preview and run interactive `live` QA (pick / annotate / accept + // variants); degrades to playwright-cli annotation, then a manual file path. + const initialPreviewResult = await designContext .task("preview-display-initial", { - prompt: taggedPrompt([ - [ - "role", - "You are an opinionated staff design engineer.", - ], - [ - "objective", - "Your job is to make the just-generated HTML artifact visible to the user so they can give feedback. Open the HTML preview file using the playwright-cli skill's `playwright-cli` command when available, then prompt the user for feedback. Gracefully degrade if browser automation is unavailable.", - ], - ["preview_path", previewPath], - ["preview_file_url", previewFileUrl], - ["browser_use_guidelines", browserBootstrapRules], - [ - "instructions", - [ - "1. Probe for `playwright-cli` availability using the bootstrap rules above.", - `2. If available, run: \`playwright-cli open ${previewFileUrl}\`. If that reports a missing browser executable, follow the bootstrap rules and retry once.`, - "3. Then run `playwright-cli snapshot` and, for interactive review, `playwright-cli show --annotate` so the user can draw on the page and add notes; if interactive review is unavailable, ask the user to review the visible page or manual file path and provide notes inline.", - "4. Capture any annotation artifact path, screenshot path, or user notes and surface them in your output.", - `5. If \`playwright-cli\` is NOT available or browser bootstrap fails, print a clear instruction block telling the user to open the file manually at: ${previewPath} (or via the URL ${previewFileUrl}).`, - "6. Never block the workflow on unavailable tooling; always exit with a non-empty status string.", - ].join("\n"), - ], - [ - "output_format", - "Markdown with: `display_method`, `preview_path`, `annotated_snapshot` (if available), `user_notes` (if available), `next_action_hint`.", - ], - ]), + prompt: buildLivePreviewDisplayPrompt({ + previewPath, + previewFileUrl, + browserBootstrapRules, + }), ...designModelConfig, }) .catch(() => undefined); + // Capture the interactive annotation feedback (do NOT discard it) so the + // refinement loop can thread it into user-feedback/apply-changes. #1464 + const initialPreviewFeedback = toPreviewFeedback({ + iteration: 0, + stageName: "preview-display-initial", + result: initialPreviewResult, + }); + persistPreviewFeedback({ artifactDir, workflowCwd, feedback: initialPreviewFeedback }); + const refinement = await refineOpenClaudeDesign({ designContext, - prompt, + prompt: designBrief, outputType, maxRefinements, previewPath, @@ -434,6 +434,10 @@ export async function runOpenClaudeDesignWorkflow(ctx: OpenClaudeDesignContext): latestDesign, designModelConfig, refinementDecisionConfig, + workflowCwd, + initialPreviewFeedback, + referencesBrief, + importContext, }); latestDesign = refinement.latestDesign; approvedForExport = refinement.approvedForExport; @@ -441,7 +445,7 @@ export async function runOpenClaudeDesignWorkflow(ctx: OpenClaudeDesignContext): const exportResult = await exportOpenClaudeDesign({ designContext, - prompt, + prompt: designBrief, outputType, previewPath, previewFileUrl, @@ -458,7 +462,7 @@ export async function runOpenClaudeDesignWorkflow(ctx: OpenClaudeDesignContext): return { output_type: outputType, - design_system: designSystemInput || "project-derived design system", + design_system: "project-derived design system", artifact: latestDesign, handoff: handoff.text, approved_for_export: approvedForExport, diff --git a/packages/workflows/builtin/open-claude-design-setup.ts b/packages/workflows/builtin/open-claude-design-setup.ts new file mode 100644 index 0000000000..5938f5abbd --- /dev/null +++ b/packages/workflows/builtin/open-claude-design-setup.ts @@ -0,0 +1,403 @@ +/** + * open-claude-design setup helpers. + * + * Three additive capabilities that all delegate to the accessible `impeccable` + * skill (`/skill:impeccable …`), factored into this module so the runner and + * phases files stay under the 500-line file-length gate: + * + * 1. Project design context (`init`): always run `/skill:impeccable init`, + * which detects PRODUCT.md / DESIGN.md (root, .agents/context/, docs/), + * creates whatever is missing, and reconciles existing files against the + * discovery brief without clobbering them. cross-ref: impeccable + * `reference/init.md`. + * 2. Reference discovery: browse five curated galleries (Awwwards, + * recent.design, Dribbble, Monet, Motionsites) and synthesize a references + * brief the generator heavily emulates. + * 3. Live interactive QA prompt: drive `/skill:impeccable live` against the + * static preview.html so the user picks elements, annotates, and accepts + * on-brand variants in the browser. cross-ref: impeccable `reference/live.md`. + */ + +import { mkdirSync, readdirSync, statSync, writeFileSync } from "node:fs"; +import { join } from "node:path"; +import type { WorkflowTaskResult } from "../src/shared/types.js"; +import { + OUTPUT_TYPES, + discoveryDecisionFromResult, + taggedPrompt, + type DiscoveryDecision, +} from "./open-claude-design-utils.js"; + +type SetupModelConfig = Record; +type SetupDesignContext = { + task(name: string, options: object): Promise; +}; + +// --------------------------------------------------------------------------- +// 0. Discovery interview (what to build, output type, references) +// --------------------------------------------------------------------------- + +function buildDiscoveryPrompt(prompt: string): string { + const outputTypes = OUTPUT_TYPES.join(", "); + return `/skill:impeccable shape\n\n${taggedPrompt([ + [ + "role", + "You are an opinionated staff design engineer running a short design-discovery interview before any code is written.", + ], + [ + "objective", + `Understand exactly what the user wants to build, starting from this request: ${prompt}. Apply the impeccable \`shape\` sub-skill to interview the user and arrive at a confirmed design brief. Do NOT write any files or generate any design yet.`, + ], + [ + "interview", + [ + "Use your structured question tool (AskUserQuestion) to ask the relevant questions you cannot infer from the request or repo.", + `Cover, at minimum: (a) what they want to build and the core jobs/screens; (b) the output type — one of: ${outputTypes}; (c) any reference designs they want to emulate (URLs, local file paths, screenshots, or design docs).`, + "Ask 2-3 questions per round and wait for answers; propose inferred answers as options, not finished facts.", + "Treat the user-provided references as the PRIMARY visual authority for generation — they take precedence over the project's DESIGN.md/PRODUCT.md where they conflict.", + ].join("\n"), + ], + [ + "references_guidance", + "Collect zero or more references. Each reference is a URL (https://…), a local file path, a screenshot path, or a design-doc path. Keep each one verbatim so later import stages can read it.", + ], + [ + "degradation", + "If you are headless and cannot ask the user, infer the most defensible brief, output type, and references from the request and repo signals; never block the workflow.", + ], + [ + "output_format", + `Return the structured final answer with: \`brief\` (the confirmed, expanded design brief in prose), \`output_type\` (one of ${outputTypes}), and \`references\` (array of verbatim URLs/paths the user wants to emulate; empty array when none).`, + ], + ])}`; +} + +/** + * Phase 1. Interview the user (impeccable `shape`) to confirm the design brief, + * the output type, and the references to emulate before onboarding/generation. + * Tolerant of headless runs: falls back to the raw prompt and an empty reference + * set when no structured answer is produced. + */ +export async function runDiscovery(args: { + readonly designContext: SetupDesignContext; + readonly prompt: string; + readonly discoveryConfig: SetupModelConfig; +}): Promise { + const result = await args.designContext.task("discovery", { + prompt: buildDiscoveryPrompt(args.prompt), + ...args.discoveryConfig, + }); + return discoveryDecisionFromResult(result, args.prompt); +} + +// --------------------------------------------------------------------------- +// 1. Project design context detection + init +// --------------------------------------------------------------------------- + +export type DesignContextDetection = { + readonly productPath?: string; + readonly designPath?: string; + readonly hasProduct: boolean; + readonly hasDesign: boolean; + readonly hasBoth: boolean; +}; + +/** Directories impeccable's init flow checks for PRODUCT.md / DESIGN.md. */ +const CONTEXT_DIRS = ["", ".agents/context", "docs"] as const; + +function findContextFile(cwd: string, target: "product.md" | "design.md"): string | undefined { + for (const rel of CONTEXT_DIRS) { + const dir = rel.length === 0 ? cwd : join(cwd, rel); + let entries: string[]; + try { + if (!statSync(dir).isDirectory()) continue; + entries = readdirSync(dir); + } catch { + continue; + } + for (const entry of entries) { + if (entry.toLowerCase() !== target) continue; + const full = join(dir, entry); + try { + if (statSync(full).isFile()) return full; + } catch { + /* ignore unreadable entry */ + } + } + } + return undefined; +} + +/** + * Deterministically report whether PRODUCT.md / DESIGN.md already exist in the + * project (root, `.agents/context/`, or `docs/`, case-insensitive). Pure read; + * never writes, never throws. + */ +export function detectDesignContextFiles(cwd: string): DesignContextDetection { + const productPath = findContextFile(cwd, "product.md"); + const designPath = findContextFile(cwd, "design.md"); + const hasProduct = productPath !== undefined; + const hasDesign = designPath !== undefined; + return { productPath, designPath, hasProduct, hasDesign, hasBoth: hasProduct && hasDesign }; +} + +export type ProjectDesignContextResult = { + readonly initRan: boolean; + readonly summary: string; + readonly detection: DesignContextDetection; +}; + +function buildInitPrompt(args: { + readonly prompt: string; + readonly detection: DesignContextDetection; + readonly discoveryContext: string; +}): string { + const productLine = args.detection.hasProduct + ? `PRODUCT.md already exists at ${args.detection.productPath}; review it and refresh only if the brief reveals a gap — never clobber it without confirming.` + : "PRODUCT.md does not exist yet; create it."; + const designLine = args.detection.hasDesign + ? `DESIGN.md already exists at ${args.detection.designPath}; review it and refresh only if the brief reveals a gap — never clobber it without confirming.` + : "DESIGN.md does not exist yet; create it (seed it from a few quick questions when there is no code to scan)."; + const missing = [ + args.detection.hasProduct ? undefined : "PRODUCT.md", + args.detection.hasDesign ? undefined : "DESIGN.md", + ].filter((value): value is string => value !== undefined); + const statusLine = + missing.length > 0 + ? `This project is missing ${missing.join(" and ")} — create the missing file(s) and reconcile any existing one with the brief.` + : "PRODUCT.md and DESIGN.md already exist — review and reconcile them against the discovery brief, refreshing only what the brief reveals as a gap; never overwrite without confirming."; + return `/skill:impeccable init\n\n${taggedPrompt([ + [ + "role", + "You are an opinionated staff design engineer running impeccable's `init` setup for this project.", + ], + [ + "objective", + `Establish or refresh the project's design context BEFORE any design generation for: ${args.prompt}. ${statusLine} Run the impeccable \`init\` flow so every downstream stage designs on-brand instead of producing generic output.`, + ], + ["discovery_context", args.discoveryContext], + [ + "why_this_matters", + "Impeccable's setup is explicit that skipping the register/brand step produces generic output. PRODUCT.md captures register (brand vs product), target users, purpose, brand personality, anti-references, design principles, and accessibility needs; DESIGN.md captures the visual system (color strategy, typography, components, motion).", + ], + [ + "clarifying_questions", + [ + "Use your structured question tool (AskUserQuestion) to interview the user for design/branding that cannot be inferred from the codebase or the `` above — do NOT re-ask anything the discovery interview already captured, and do NOT synthesize PRODUCT.md from the design prompt alone.", + "When PRODUCT.md/DESIGN.md already exist, keep this light: load them, reconcile against the brief, and only ask about genuine gaps instead of re-running the full interview.", + "Round 1 (when files are missing): confirm register (brand vs product), users/purpose, and the desired outcome.", + "Round 2 (when files are missing): brand personality (3 words), specific named references, explicit anti-references, and accessibility needs.", + "Ask 2-3 questions per round and wait for answers; offer inferred answers as hypotheses/options, not finished facts. Do NOT ask about colors/fonts/radii here — those belong to DESIGN.md.", + ].join("\n"), + ], + [ + "files_to_write", + [ + "Write or refresh PRODUCT.md (strategic) and DESIGN.md (visual system) at the project root, following the impeccable init reference. Never silently overwrite an existing file.", + productLine, + designLine, + ].join("\n"), + ], + [ + "degradation", + "If you are running headless and cannot ask the user, infer the most defensible register/brand from the prompt and any repo signals, write PRODUCT.md/DESIGN.md with an explicit `## Gaps / Assumptions` section, and never block the workflow.", + ], + [ + "output_format", + "Return a short markdown summary: register chosen (brand/product), files written or reconciled (absolute paths), the 3-5 design principles, and any assumptions. Do NOT paste the full file bodies.", + ], + ])}`; +} + +/** + * Phase 2. ALWAYS run `/skill:impeccable init`: it creates whatever of + * PRODUCT.md / DESIGN.md is missing and reconciles existing files against the + * discovery brief (without clobbering them). Best-effort: a headless / failed + * init never blocks the workflow. + */ +export async function ensureProjectDesignContext(args: { + readonly designContext: SetupDesignContext; + readonly cwd: string; + readonly prompt: string; + readonly discoveryContext: string; + readonly designModelConfig: SetupModelConfig; +}): Promise { + const before = detectDesignContextFiles(args.cwd); + + const init = await args.designContext + .task("init", { + prompt: buildInitPrompt({ + prompt: args.prompt, + detection: before, + discoveryContext: args.discoveryContext, + }), + ...args.designModelConfig, + }) + .catch(() => undefined); + + const after = detectDesignContextFiles(args.cwd); + const missingBefore = [ + before.hasProduct ? undefined : "PRODUCT.md", + before.hasDesign ? undefined : "DESIGN.md", + ] + .filter((value): value is string => value !== undefined) + .join(" and "); + const statusBefore = before.hasBoth + ? "reviewed existing PRODUCT.md + DESIGN.md against the brief" + : `created missing ${missingBefore}`; + return { + initRan: true, + detection: after, + summary: [ + `Ran \`/skill:impeccable init\` (${statusBefore}).`, + (init?.text ?? "").trim(), + `Detected after init: PRODUCT.md=${after.productPath ?? "pending"}, DESIGN.md=${after.designPath ?? "pending"}.`, + ] + .filter((part) => part.length > 0) + .join("\n\n"), + }; +} + +// --------------------------------------------------------------------------- +// 2. Reference discovery +// --------------------------------------------------------------------------- + +/** Curated galleries of beautiful, current reference designs. */ +export const REFERENCE_DESIGN_SITES: readonly { readonly name: string; readonly url: string }[] = [ + { name: "Awwwards", url: "https://www.awwwards.com/websites/" }, + { name: "recent.design", url: "https://recent.design/" }, + { name: "Dribbble (recent shots)", url: "https://dribbble.com/shots/recent" }, + { name: "Monet", url: "https://www.monet.design/c" }, + { name: "Motionsites", url: "https://motionsites.ai/" }, +]; + +export const NO_REFERENCES_BRIEF = + "Reference discovery was skipped. Generate from the project design system and the prompt; do not fabricate external references."; + +export function buildReferenceDiscoveryPrompt(args: { + readonly prompt: string; + readonly outputType: string; + readonly designContextHint: string; + readonly artifactDir: string; + readonly browserBootstrapRules: string; +}): string { + const siteList = REFERENCE_DESIGN_SITES.map( + (site, index) => `${index + 1}. ${site.name} — ${site.url}`, + ).join("\n"); + return taggedPrompt([ + [ + "role", + "You are an opinionated staff design engineer and design researcher curating best-in-class, current visual references.", + ], + [ + "objective", + `Find beautiful, current reference designs the team can heavily reference to build a stunning ${args.outputType} for: ${args.prompt}. Open each gallery, CLICK THROUGH to the actual design pages of interest, and — ideally — record a scroll-through video of each page so its ANIMATIONS are captured (with a full-page screenshot as a supplement/fallback) plus its real destination URL. Apply the impeccable \`extract\` sub-skill to lift concrete, citable design traits — never vague adjectives.`, + ], + ["reference_galleries", siteList], + ["design_context", args.designContextHint], + ["browser_use_guidelines", args.browserBootstrapRules], + ["screenshot_dir", args.artifactDir], + [ + "instructions", + [ + "1. Use the playwright-cli skill to open each gallery above; if `playwright-cli` reports a missing browser executable, follow the bootstrap rules and retry once.", + "2. On each gallery, scan the thumbnail grid and pick 1-3 designs of interest whose aesthetic fits this brief.", + "3. CLICK INTO each chosen design to open its ACTUAL page — the live site or project detail the thumbnail links to (for example the gallery's 'visit site' / shot-detail link). Do NOT capture the gallery grid or the thumbnail; navigate to the real design page first.", + `4. Capture the design's MOTION, not just a still: record a scroll-through video of the ENTIRE page so scroll-triggered animations, parallax, reveals, and transitions are captured. Start with \`playwright-cli video-start ${join(args.artifactDir, "ref--.webm")}\`, then scroll smoothly from top to bottom — a \`playwright-cli run-code\` script that scrolls in small increments with short waits, or repeated \`playwright-cli mousewheel 0 600\` with pauses — so animations fire and lazy content loads, then \`playwright-cli video-stop\`.`, + `5. ALSO take a FULL-PAGE still as a supplement/fallback: \`playwright-cli screenshot --full-page --filename=${join(args.artifactDir, "ref--.png")}\`. If video recording is unavailable, the full-page screenshot is the minimum.`, + "6. Record the FULL destination URL you actually landed on (the live site / project URL, not the gallery listing URL), plus the work's title and author.", + "7. For every reference, extract the CONCRETE transferable trait (layout topology, type pairing, color strategy, spacing rhythm) AND the MOTION vocabulary you saw in the recording (entrance animations, scroll reveals, easing, parallax, hover/active states) — cite what you observed on the real page, not what you imagine.", + "8. For on-brand fit, consult the project's DESIGN.md / PRODUCT.md on disk (see for where they live); prefer references that fit, and flag any that would require departing from the project's system.", + "9. If `playwright-cli` is unavailable or a site blocks automation, fall back to web search / page fetch to reach the actual design pages, and clearly mark any reference you could not capture with a recording or full-page screenshot.", + "10. Never fabricate references or visual claims; if a gallery yielded nothing usable, say so.", + ].join("\n"), + ], + [ + "output_format", + [ + "Markdown sections:", + "1. Curated references (table: Source gallery | Work (title/author) | Full page URL (destination) | Scroll-through video path | Full-page screenshot path | Transferable trait (incl. motion) | On-brand?)", + "2. Synthesis: the 3-5 strongest directions to emulate for THIS design, ranked by fit, calling out motion/animation worth reproducing.", + "3. What to avoid (anti-references observed on the real pages).", + "4. Verification notes (which references have a scroll-through recording and/or full-page screenshot of the actual design page vs search-only).", + ].join("\n"), + ], + ]); +} + +/** Persist the curated references brief to `/references.md`. Best-effort. */ +export function persistReferencesBrief(artifactDir: string, brief: string): void { + try { + mkdirSync(artifactDir, { recursive: true }); + writeFileSync(join(artifactDir, "references.md"), `${brief}\n`); + } catch { + /* best-effort durability; never block the workflow */ + } +} + +// --------------------------------------------------------------------------- +// 3. Live interactive QA prompt (shared by initial + per-iteration display) +// --------------------------------------------------------------------------- + +/** + * Build the interactive-QA prompt for the `preview-display-*` stages. Drives + * `/skill:impeccable live` against the static preview so the user can pick + * elements in the browser, annotate, and accept on-brand variants; degrades to + * `playwright-cli show --annotate` and finally to a manual file path. The output + * labels (`user_notes`, `annotated_snapshot`, `live_changes`) are parsed by the + * refinement feedback threading. + */ +export function buildLivePreviewDisplayPrompt(args: { + readonly previewPath: string; + readonly previewFileUrl: string; + readonly browserBootstrapRules: string; + readonly iteration?: number; + readonly maxRefinements?: number; +}): string { + const isInitial = args.iteration === undefined; + const label = isInitial + ? "the just-generated HTML artifact" + : `the revised preview after iteration ${args.iteration}/${args.maxRefinements}`; + return taggedPrompt([ + [ + "role", + "You are an opinionated staff design engineer running impeccable's interactive `live` QA so the user can iterate on the design in a real browser.", + ], + [ + "objective", + `Make ${label} visible to the user, run an interactive design-QA session against it, then capture the user's feedback for the refinement loop. Drive \`/skill:impeccable live\` against the static preview when possible; degrade gracefully when browser automation is unavailable.`, + ], + ["preview_path", args.previewPath], + ["preview_file_url", args.previewFileUrl], + ["browser_use_guidelines", args.browserBootstrapRules], + [ + "interactive_live_qa", + [ + `1. Run \`/skill:impeccable live\` targeted at the preview file so the user can pick elements in the browser, annotate them, and compare on-brand variants. The preview is a single static HTML file at ${args.previewPath}; point live at it (configure \`.impeccable/live/config.json\` for that file or pass \`--target ${args.previewPath}\` per the live reference) and open ${args.previewFileUrl} in the browser.`, + "2. For each element the user picks, follow the live contract: read any annotation screenshot, extract the page identity FIRST, then generate three DISTINCT on-brand variants and let the user accept one. Accepted variants are written into the preview HTML in place; do NOT branch the artifact.", + "3. Also handle the live `steer` path for page-level direction the user types/speaks, and treat any freeform prompt as the ceiling on direction.", + "4. Keep iterating until the user signals they are done with this round.", + ].join("\n"), + ], + [ + "graceful_degradation", + [ + `If \`/skill:impeccable live\` cannot boot (no dev server/HMR for the static file, missing config, or sandbox limits), fall back to opening the preview directly: \`playwright-cli open ${args.previewFileUrl}\`, then \`playwright-cli snapshot\` and \`playwright-cli show --annotate\` so the user can draw/type notes on the page. If a \`playwright-cli\` command reports a missing browser executable, follow the bootstrap rules and retry once.`, + `If \`playwright-cli\` is also unavailable, print a clear instruction block telling the user to open the file manually at ${args.previewPath} (or ${args.previewFileUrl}) and provide notes inline.`, + "Never block the workflow on unavailable tooling; always exit with a non-empty status string.", + ].join("\n"), + ], + [ + "output_format", + [ + "Markdown with these exact labels so the refinement loop can parse the captured feedback:", + "`display_method` (live | playwright-annotate | manual)", + "`preview_path`", + "`live_changes` (summary of every element/variant the user ACCEPTED in the live session; `none` when no live edits were made)", + "`annotated_snapshot` (path to any annotated screenshot, if captured)", + "`user_notes` (the user's verbatim notes/annotations for the next iteration; `none` when the user gave no notes)", + "`next_action_hint`", + ].join("\n"), + ], + ]); +} diff --git a/packages/workflows/builtin/open-claude-design-utils.ts b/packages/workflows/builtin/open-claude-design-utils.ts index 50c2b1cb0c..5963598112 100644 --- a/packages/workflows/builtin/open-claude-design-utils.ts +++ b/packages/workflows/builtin/open-claude-design-utils.ts @@ -125,6 +125,48 @@ export function exportGateDecisionFromResult(result: WorkflowTaskResult): Export return decision; } +export type DiscoveryDecision = { + readonly brief: string; + readonly output_type: OutputType; + readonly references: readonly string[]; +}; + +export const discoveryDecisionSchema = Type.Object( + { + brief: Type.String(), + output_type: Type.Union([...OUTPUT_TYPES].map((value) => Type.Literal(value))), + references: Type.Array(Type.String()), + }, + { additionalProperties: false }, +); + +/** + * Parse the discovery stage's structured result, tolerating a missing/invalid + * structured payload (headless / mock runs) by falling back to the raw prompt as + * the brief, the default output type, and an empty reference list. + */ +export function discoveryDecisionFromResult( + result: WorkflowTaskResult, + fallbackBrief: string, +): DiscoveryDecision { + const decision = result.structured as Partial | undefined; + const brief = + typeof decision?.brief === "string" && decision.brief.trim().length > 0 + ? decision.brief.trim() + : fallbackBrief; + const references = Array.isArray(decision?.references) + ? decision.references + .filter((ref): ref is string => typeof ref === "string") + .map((ref) => ref.trim()) + .filter((ref) => ref.length > 0) + : []; + return { + brief, + output_type: normalizeOutputType(decision?.output_type), + references, + }; +} + export function joinResults(results: readonly WorkflowTaskResult[]): string { return results .map((result) => `### ${result.name}\n\n${result.text}`) @@ -144,10 +186,15 @@ export function prepareArtifactDir(cwd = process.cwd()): { readonly specPath: string; } { const runId = `${new Date().toISOString().replace(/[:.]/g, "-")}-${Math.random().toString(36).slice(2, 8)}`; - const candidates = [ - join(cwd, "specs", "design", runId), - join(tmpdir(), "open-claude-design", runId), - ]; + // Under automated tests, prefer the OS tmpdir so a full `d.run()` does not + // pollute the project's `specs/design/` tree with per-run artifact folders. + const candidates = + process.env.NODE_ENV === "test" + ? [join(tmpdir(), "open-claude-design", runId)] + : [ + join(cwd, "specs", "design", runId), + join(tmpdir(), "open-claude-design", runId), + ]; for (const candidate of candidates) { try { mkdirSync(candidate, { recursive: true }); @@ -187,6 +234,10 @@ export const ANTI_SLOP_RULES = [ "Commit to a specific aesthetic direction; do not hedge with generic SaaS defaults.", ].join("\n"); +/** Reference-import precedence note shared by import, generation, and refinement. */ +export const REFERENCE_PRECEDENCE = + "User-provided references in are the PRIMARY visual authority: when they conflict with DESIGN.md/PRODUCT.md, follow the references. DESIGN.md governs decisions the references do not cover; PRODUCT.md still governs strategic register/voice."; + export type PlaywrightCliStatus = { /** Whether the `playwright-cli` command is expected to be available to downstream stages. */ readonly available: boolean; diff --git a/packages/workflows/builtin/open-claude-design.d.ts b/packages/workflows/builtin/open-claude-design.d.ts index 5d7b0c3726..793defcb6f 100644 --- a/packages/workflows/builtin/open-claude-design.d.ts +++ b/packages/workflows/builtin/open-claude-design.d.ts @@ -4,17 +4,13 @@ export type OpenClaudeDesignOutputType = "prototype" | "wireframe" | "page" | "c export type OpenClaudeDesignWorkflowInputs = WorkflowInputValues & { readonly prompt: string; - readonly reference?: string; - readonly output_type: OpenClaudeDesignOutputType; - readonly design_system?: string; + readonly discover_references: boolean; readonly max_refinements: number; }; export type OpenClaudeDesignWorkflowRunInputs = WorkflowInputValues & { readonly prompt: string; - readonly reference?: string; - readonly output_type?: OpenClaudeDesignOutputType; - readonly design_system?: string; + readonly discover_references?: boolean; readonly max_refinements?: number; }; diff --git a/packages/workflows/builtin/open-claude-design.ts b/packages/workflows/builtin/open-claude-design.ts index 52a636e6d5..4baae57c0d 100644 --- a/packages/workflows/builtin/open-claude-design.ts +++ b/packages/workflows/builtin/open-claude-design.ts @@ -25,28 +25,20 @@ import { workflow } from "../src/authoring/workflow.js"; import { runOpenClaudeDesignWorkflow } from "./open-claude-design-runner.js"; import { DEFAULT_MAX_REFINEMENTS, - DEFAULT_OUTPUT_TYPE, - OUTPUT_TYPES, } from "./open-claude-design-utils.js"; export default workflow({ name: "open-claude-design", - description: "AI-powered design workflow: design-system onboarding → reference import → HTML generation → impeccable-driven refinement → quality gate → rich HTML handoff. Each stage delegates to a specific impeccable sub-skill; the user can iteratively review the generated HTML through the playwright-cli skill.", + description: "AI-powered design workflow: discovery interview (impeccable `shape`) → optional project-context setup (`/skill:impeccable init`) when DESIGN.md/PRODUCT.md are missing → design-system onboarding → curated reference discovery → reference import → HTML generation → impeccable `live`-driven refinement → quality gate → rich HTML handoff. The discovery stage asks what to build, the output type, and which references to emulate (references take precedence over DESIGN.md/PRODUCT.md). The user iteratively reviews the generated HTML through impeccable `live` / the playwright-cli skill.", inputs: { prompt: Type.String({ - description: "What to design (for example, a dashboard, page, component, or prototype).", + description: "What to design (for example, a dashboard, page, component, or prototype). The discovery stage refines this into a confirmed brief and asks for the output type and references.", }), - reference: Type.Optional(Type.String({ - description: "URL, file path, screenshot path, or design doc to import as a reference.", - })), - output_type: Type.Union( - [...OUTPUT_TYPES].map((value) => Type.Literal(value)), - { default: DEFAULT_OUTPUT_TYPE, description: "Kind of design artifact to produce." }, - ), - design_system: Type.Optional(Type.String({ + discover_references: Type.Boolean({ + default: true, description: - "Path(s) or description of an existing design system (DESIGN.md, PRODUCT.md, etc.); skips onboarding when provided.", - })), + "Discover beautiful, current reference designs (Awwwards, recent.design, Dribbble, Monet, Motionsites) and feed them to generation. Set false to skip the network/browser reference pass.", + }), max_refinements: Type.Number({ default: DEFAULT_MAX_REFINEMENTS, description: `Maximum critique/apply refinement iterations (default ${DEFAULT_MAX_REFINEMENTS}).`, @@ -54,7 +46,7 @@ export default workflow({ }, outputs: { output_type: Type.Optional(Type.String({ description: "Kind of design artifact produced." })), - design_system: Type.Optional(Type.String({ description: "Design system source used for generation: supplied input or project-derived design system." })), + design_system: Type.Optional(Type.String({ description: "Design system source used for generation: the project-derived design system." })), artifact: Type.Optional(Type.String({ description: "Latest final design summary from the approved preview artifact." })), handoff: Type.Optional(Type.String({ description: "Final rich HTML spec and implementation handoff summary." })), approved_for_export: Type.Optional(Type.Boolean({ description: "Whether refinement completed before the final export gate." })), diff --git a/specs/2026-06-21-open-claude-design-init-references-live-qa.md b/specs/2026-06-21-open-claude-design-init-references-live-qa.md new file mode 100644 index 0000000000..0f2be9bfa8 --- /dev/null +++ b/specs/2026-06-21-open-claude-design-init-references-live-qa.md @@ -0,0 +1,200 @@ +# Open Claude Design — Init, Reference Discovery & Live Interactive QA + +| Document Metadata | Details | +| ---------------------- | ------------------------------- | +| Author(s) | flora131 | +| Status | Draft (WIP) | +| Team / Owner | Atomic CLI / Workflows | +| Created / Last Updated | 2026-06-21 | +| Compatibility posture | Breaking input change (removes `reference`/`output_type`/`design_system`) | + +## 1. Executive Summary + +This RFC restructures the builtin `open-claude-design` workflow's front door around the accessible `impeccable` skill (`/skill:impeccable …`): + +1. **Phase 1 — Discovery interview.** A new first `discovery` stage runs `/skill:impeccable shape` to interview the user for a confirmed design brief, the **output type** (`prototype`/`wireframe`/`page`/`component`/`theme`/`tokens`), and the **references** to emulate (URLs/files/screenshots/design docs). It returns a structured `{ brief, output_type, references }`. User references take **precedence over `DESIGN.md`/`PRODUCT.md`** during generation. +2. **Phase 2 — Project context (`init`, always).** The workflow always runs an `init` stage that invokes `/skill:impeccable init` (reusing the discovery answers). It detects `PRODUCT.md`/`DESIGN.md` (root, `.agents/context/`, `docs/`, case-insensitive), creates whichever is missing, and reconciles existing files against the brief without clobbering them. +3. **Combined context phase.** Onboarding (`ds-*` → builder), the gated gallery `reference-discovery`, and user-reference import all run **concurrently in one fan-out**, then the design-system synthesis closes it. A `discover_references` boolean input (default `true`) gates the gallery pass; user references take **precedence over `DESIGN.md`/`PRODUCT.md`**. +4. **Live interactive QA.** The `preview-display-*` stages drive `/skill:impeccable live` against the static `preview.html`: pick elements, annotate, generate three on-brand variants, accept; captured notes/accepts thread through the refinement feedback loop. Degrades to `playwright-cli show --annotate`. + +The public input set is trimmed to `prompt`, `discover_references`, and `max_refinements`; `reference`, `output_type`, and `design_system` are removed and gathered by the discovery interview instead. + +## 2. Context and Motivation + +### 2.1 Current State + +`open-claude-design` (`packages/workflows/builtin/open-claude-design*.ts`) runs: onboarding (locator/analyzer/patterns → design-system-builder) → import → generator (`preview.html`) → bounded refinement loop (preview-display annotation → user-feedback → critique + screenshot → apply-changes) → export gate → rich HTML spec. Each stage already delegates to a specific impeccable sub-skill by name in its prompt. + +- Onboarding assumes a design system can be derived from the repo, but never **establishes** `PRODUCT.md`/`DESIGN.md` when the project is greenfield — so branding/register intent is inferred, not confirmed with the user. +- The generator works only from the repo-derived system + an optional single `reference`; there is no proactive search for best-in-class visual references. +- Interactive review uses `playwright-cli show --annotate` (passive annotation), not impeccable's richer in-browser variant QA (`live`). + +### 2.2 The Problem + +- **No confirmed design north star.** Greenfield runs produce generic output because register/brand/anti-references were never captured (impeccable's own `init`/`setup` requires this first; skipping it "produces generic output"). +- **No reference inspiration.** Beautiful, current design references materially raise output quality; today the user must supply one URL by hand. +- **Thin interactive QA.** Annotation capture is one-directional; the user cannot pick an element and compare on-brand variants in the browser as impeccable `live` allows. + +## 3. Goals and Non-Goals + +### 3.1 Functional Goals + +- [ ] **G1:** Run a `discovery` stage first (`/skill:impeccable shape`) that interviews the user for the design brief, output type, and references, returning structured `{ brief, output_type, references }`. +- [ ] **G2:** Run `init` second and conditionally: detect `PRODUCT.md`/`DESIGN.md` and only invoke `/skill:impeccable init` when missing, reusing discovery answers; skip when both exist or headless (best-effort, never blocks). +- [ ] **G3:** Trim inputs to `prompt`, `discover_references`, `max_refinements`; remove `reference`, `output_type`, `design_system`. +- [ ] **G4:** Make user-provided references take precedence over `DESIGN.md`/`PRODUCT.md` in import, generation, and refinement. +- [ ] **G5:** Add a gated `reference-discovery` gallery stage and thread its brief into the generator and refinement. +- [ ] **G6:** Drive `/skill:impeccable live` from the `preview-display-*` stages; capture accepted variants/notes (`live_changes`) into `previewFeedbackHistory`; degrade to `playwright-cli show --annotate`. +- [ ] **G7:** Keep every touched file ≤ 500 physical lines (file-length gate); put new logic in `open-claude-design-setup.ts`. + +### 3.2 Non-Goals + +- [ ] No new model providers; reuse the existing `designModelConfig` chain. +- [ ] No change to the export gate, handoff spec, or output contract (no new outputs). +- [ ] No bespoke re-implementation of the impeccable `init`/`live` scripts inside the workflow — delegate to `/skill:impeccable …`; only replicate "similar logic" (detection + degradation) in TS. +- [ ] No removal of the existing annotation-capture fallback; live is the preferred path, annotation is the floor. + +## 4. Proposed Solution (High-Level Design) + +### 4.1 Stage Flow + +```mermaid +flowchart TB + classDef new fill:#ed8936,stroke:#dd6b20,stroke-width:2.5px,color:#fff,font-weight:600 + classDef existing fill:#4a90e2,stroke:#357abd,stroke-width:2px,color:#fff + + Start([open-claude-design]):::existing + Disc["Phase 1: discovery (NEW)\n/skill:impeccable shape\n→ brief + output_type + references"]:::new + Init["Phase 2: init (NEW, ALWAYS)\n/skill:impeccable init\ncreate missing / reconcile existing"]:::new + Ctx["Phase 3: combined context fan-out (NEW)\n‖ ds-locator/analyzer/patterns\n‖ reference-discovery (galleries, gated)\n‖ web-capture- / file-parser-\n→ design-system-builder synthesizes"]:::new + Gen["generator (brief + designSystem +\nreferences + REFERENCE_PRECEDENCE)"]:::existing + Loop["refinement loop\npreview-display → /skill:impeccable live\n→ user-feedback → critique+screenshot → apply"]:::new + Export["export gate → handoff spec"]:::existing + + Start --> Disc --> Init --> Ctx --> Gen --> Loop --> Export +``` + +### 4.2 Architectural Pattern + +Phased pipeline with a bounded refinement loop (unchanged), extended with a **classify-and-act** front door (init: detect → conditionally interview) and a **fan-in reference** stage (gather curated references → single brief). Interactive QA is a **generate-and-select** loop driven by the external impeccable `live` skill. + +### 4.3 The Door Set at a Glance (Stranger-Across-Time View) + +Public input door (the only caller-facing surface): + +- `prompt`, `reference`, `output_type`, `design_system`, `max_refinements`, **`discover_references` (NEW)**. + +Internal stage doors (named for design joints, not tools): + +- `init` ⚠ (writes `PRODUCT.md`/`DESIGN.md` to the project root) → onboarding → `reference-discovery` → import → `generator` ⚠ (writes `preview.html`) → `preview-display` (drives live; may write `preview.html`) → refinement → export ⚠ (writes `spec.html`). + +Reading these names alone: the workflow first *establishes the brand*, then *gathers inspiration*, then *generates*, then *iterates with the user in the browser*, then *hands off*. + +## 5. Detailed Design + +### 5.1 The Doors (Entrypoint Contracts) + +Public input set after the change (`open-claude-design.ts` + `.d.ts`): `prompt`, `discover_references` (boolean, default `true`), `max_refinements`. The `reference`, `output_type`, and `design_system` inputs are removed; the discovery interview gathers them instead. + +```ts +discover_references: Type.Boolean({ + default: true, + description: + "Discover beautiful, current reference designs (Awwwards, recent.design, Dribbble, Monet, Motionsites) and feed them to generation. Set false to skip the network/browser reference pass.", +}) +``` + +New module `open-claude-design-setup.ts` exposes four internal doors (typed pseudocode): + +```ts +// Phase 1. Interview the user (impeccable `shape`) for the design brief. +runDiscovery(args): Promise<{ brief: string; output_type: OutputType; references: string[] }> +// Guarantee: returns the confirmed brief, output type, and references to emulate. Tolerant of +// headless runs (falls back to the raw prompt, default output type, and an empty reference set). + +// Deterministic, no LLM. Searches root, .agents/context/, docs/ (case-insensitive). +detectDesignContextFiles(cwd: string): { + productPath?: string; designPath?: string; hasProduct: boolean; hasDesign: boolean; hasBoth: boolean; +} +// Guarantee: reports which design-context files already exist on disk. Never writes, never throws. + +// Phase 2. Best-effort; runs at most one `init` task stage, reusing discovery answers. +ensureProjectDesignContext(args): Promise<{ initRan: boolean; summary: string; detection: }> +// Guarantee: ensures PRODUCT.md/DESIGN.md exist by delegating to /skill:impeccable init when missing, +// skipped when both already exist. Never blocks the workflow: a failed/headless init degrades to "skipped". + +// Reference discovery stage. Gated by discover_references upstream. +discoverReferenceDesigns(args): Promise +// Guarantee: returns a curated references brief (markdown) drawn from the five galleries, or an +// explicit "no references" sentinel when gathering fails. Best-effort; persists references.md. +``` + +Shared helper (used by both runner and phases to keep each ≤500 lines): + +```ts +buildLivePreviewDisplayPrompt(args): string +// Builds the interactive-QA-via-/skill:impeccable live prompt for preview-display-initial and +// preview-display-, with graceful degradation to playwright-cli show --annotate. +``` + +**Per-door audit:** + +| Door | Joint | One sentence | Honest name | Every exit | Chokepoint | +|---|---|---|---|---|---| +| `discover_references` (input) | ✅ "discover references" | ✅ toggles the reference pass | ✅ default true, opt-out | `false` → stage skipped, brief = sentinel | n/a | +| `detectDesignContextFiles` | ✅ "detect context" | ✅ reports existence only | ✅ pure read | missing dirs → `false` flags | n/a | +| `ensureProjectDesignContext` ⚠ | ✅ "establish brand context" | ✅ ensures files exist | ✅ delegates, never fabricates | headless/skip → `initRan:false` | the only door that triggers `init` | +| `discoverReferenceDesigns` | ✅ "gather inspiration" | ✅ returns one brief | ✅ best-effort | gather fail → sentinel brief | the only reference-gathering door | + +### 5.2 Wiring (`open-claude-design-runner.ts`) + +1. After `prepareArtifactDir`, before onboarding: `const init = await ensureProjectDesignContext({ designContext, cwd: workflowCwd, prompt, designSystemInput, designModelConfig });` +2. Onboarding unchanged; the `init` summary is appended to the design-system-builder context so the builder respects freshly written `PRODUCT.md`/`DESIGN.md`. +3. After `designSystem` is resolved, before import/generator: + `const referencesBrief = inputs.discover_references === false ? NO_REFERENCES_SENTINEL : await discoverReferenceDesigns({ designContext, prompt, outputType, designSystem, artifactDir, workflowCwd, browserBootstrapRules, designModelConfig });` +4. Generator prompt gains a `reference_inspiration` block = `referencesBrief`. +5. `preview-display-initial` uses `buildLivePreviewDisplayPrompt(...)`; same prompt builder is used per-iteration in `refineOpenClaudeDesign`. +6. `referencesBrief` is passed into `refineOpenClaudeDesign` and surfaced to `apply-changes-*` so iterations keep pulling from the references. + +### 5.3 Live QA Feedback Threading (`open-claude-design-feedback.ts`) + +- Add a `live_changes` extracted field (alongside `user_notes` / `annotated_snapshot`) to `FIELD_LABELS` for bounded multi-line extraction. +- `toPreviewFeedback` captures `liveChanges`; `buildUserAnnotationsSection` includes accepted live changes inside the user-annotations block so `apply-changes-*` honors them above internal critique (existing ordering preserved). +- Since live accepts edit `preview.html` directly, the artifact already reflects them; the captured summary ensures the reviewer/apply stages know what the user explicitly approved. + +### 5.4 Reference Galleries + +`REFERENCE_DESIGN_SITES` = Awwwards (`/websites/`), recent.design, Dribbble (`/shots/recent`), Monet (`/c`), Motionsites. The stage prompt: open each with `playwright-cli`, screenshot 1–3 standout works each into `artifactDir`, capture title/author/URL and the concrete transferable trait (layout, type, motion, color), and synthesize a brief ranked by relevance to `prompt`/`output_type`/`designSystem`. Web search/fetch fallback when the browser is unavailable; never fabricate visual claims. + +## 6. Alternatives Considered + +| Option | Pros | Cons | Verdict | +|---|---|---|---| +| Init via in-TS `ctx.ui` interview | deterministic, testable | duplicates the skill's interview; drifts from impeccable | Rejected — delegate to `/skill:impeccable init`. | +| References folded into import phase | fewer stages | conflates user-supplied reference with gallery discovery; harder to gate | Rejected — dedicated gated stage. | +| Keep annotation-only QA | no live config complexity | misses element-level variant QA the user asked for | Rejected — drive `live`, keep annotation as floor. | + +## 7. Cross-Cutting Concerns + +- **Best-effort & non-blocking.** Init, reference discovery, and live all degrade gracefully (headless/test, no browser, no network) and never fail the run; the existing manual-path fallbacks remain. +- **File-length gate.** New logic lives in `open-claude-design-setup.ts`; runner/phases shrink by extracting the shared preview-display prompt, staying ≤500 lines. +- **No new outputs / no breaking changes.** Output contract and existing tests' assertions stay valid; new tests cover the added input, init gating, reference stage, and live prompt. + +## 8. Test Plan + +- **Input contract:** `discover_references` present, boolean, default `true`. +- **Init gating:** with no context files and a writable temp cwd, the `init` task runs and its prompt invokes `/skill:impeccable init`; with `design_system` supplied or both files present, no `init` task is recorded. +- **Reference stage:** runs when `discover_references !== false`; prompt names all five galleries and the `playwright-cli` bootstrap; skipped (sentinel brief, no `reference-discovery` task) when `false`. +- **Generator:** receives a `reference_inspiration` block. +- **Live QA:** `preview-display-*` prompts reference `/skill:impeccable live` and retain the `playwright-cli` degradation and `user_notes`/`annotated_snapshot` labels; existing annotation-threading tests still pass. +- **Gates:** `bun run typecheck`, `bun run lint`, `bun run check:file-length`, and the two open-claude-design unit suites. + +## 9. Open Questions / Unresolved Issues + +- [x] Init approach → delegate to `/skill:impeccable init`, run **second** and only when `PRODUCT.md`/`DESIGN.md` are missing (user-confirmed). +- [x] Discovery → a first `discovery` stage (`/skill:impeccable shape`) asks for the brief, output type, and references (user-confirmed). +- [x] Inputs → remove `reference`, `output_type`, `design_system`; keep `prompt`, `discover_references`, `max_refinements` (user-confirmed). +- [x] References precedence → user references are primary, `DESIGN.md` fills gaps (user-confirmed). +- [x] Live QA depth → drive `/skill:impeccable live` on `preview.html` (user-confirmed). +- [x] Reference gating → new `discover_references` input, default true (user-confirmed). +- [x] Reference tooling → browser + screenshots, web-search fallback (user-confirmed). diff --git a/test/unit/builtin-workflows-open_claude_design-01.test.ts b/test/unit/builtin-workflows-open_claude_design-01.test.ts index 006afedcfb..f2aa182291 100644 --- a/test/unit/builtin-workflows-open_claude_design-01.test.ts +++ b/test/unit/builtin-workflows-open_claude_design-01.test.ts @@ -72,24 +72,24 @@ describe("open-claude-design", () => { function refinementDecision(readyForEx const mod = await import("../../packages/workflows/builtin/open-claude-design.js"); const d = mod.default; - for (const inputName of [ - "prompt", - "reference", - "output_type", - "design_system", - "max_refinements", - ]) { + for (const inputName of ["prompt", "discover_references", "max_refinements"]) { assert.notEqual(d.inputs[inputName], undefined, inputName); } + // Removed inputs: reference, output_type, design_system are now gathered + // by the discovery interview rather than passed as parameters. + assert.equal(d.inputs["reference"], undefined); + assert.equal(d.inputs["output_type"], undefined); + assert.equal(d.inputs["design_system"], undefined); assert.equal(d.inputs["output-type"], undefined); assert.equal(d.inputs["design-system"], undefined); assert.equal(fieldRequired(d.inputs["prompt"]), true); }); - test("output_type supports canonical underscore choices", async () => { - const mod = - await import("../../packages/workflows/builtin/open-claude-design.js"); - const schema = mod.default.inputs["output_type"]; + test("discovery decision schema offers the canonical output types", async () => { + const utils = + await import("../../packages/workflows/builtin/open-claude-design-utils.js"); + const schema = (utils.discoveryDecisionSchema as { properties: Record }) + .properties["output_type"]; assert.equal(fieldKind(schema), "select"); const choices = fieldChoices(schema); for (const choice of [ @@ -102,7 +102,130 @@ describe("open-claude-design", () => { function refinementDecision(readyForEx ]) { assert.ok(choices.includes(choice), choice); } - assert.equal(fieldDefault(schema), "prototype"); + }); + + test("declares discover_references boolean input defaulting true", async () => { + const mod = + await import("../../packages/workflows/builtin/open-claude-design.js"); + const schema = mod.default.inputs["discover_references"]; + assert.equal(fieldKind(schema), "boolean"); + assert.equal(fieldDefault(schema), true); + assert.ok(fieldDescription(schema).length > 0); + }); + + test("runs reference-discovery by default and feeds the generator reference inspiration", async () => { + const mod = + await import("../../packages/workflows/builtin/open-claude-design.js"); + const d = mod.default as unknown as WorkflowDefinition; + const ctx = makeMockCtx( + { prompt: "Design a landing page", max_refinements: 1 }, + { + task: (name) => { + if (name.startsWith("user-feedback-")) + return refinementDecision(true); + if (name === "pre-export-scan") + return exportGateDecision(false); + return undefined; + }, + }, + ); + await d.run(ctx); + assert.ok(ctx.calls.task.includes("reference-discovery")); + const refPrompt = ctx.calls.prompts["reference-discovery"]?.[0] ?? ""; + assert.match(refPrompt, /awwwards\.com\/websites/); + assert.match(refPrompt, /motionsites\.ai/); + const genPrompt = ctx.calls.prompts["generator"]?.[0] ?? ""; + assert.match(genPrompt, //); + }); + + test("runs /skill:impeccable init in a full run when the project lacks PRODUCT.md/DESIGN.md", async () => { + const mod = + await import("../../packages/workflows/builtin/open-claude-design.js"); + const d = mod.default as unknown as WorkflowDefinition; + const dir = mkdtempSync(join(tmpdir(), "ocd-run-init-")); + try { + const ctx = makeMockCtx( + { prompt: "Design a dashboard", max_refinements: 1 }, + { + task: (name) => { + if (name.startsWith("user-feedback-")) + return refinementDecision(true); + if (name === "pre-export-scan") + return exportGateDecision(false); + return undefined; + }, + }, + ); + // Point the run at an empty project dir so init detects missing files. + (ctx as { cwd?: string }).cwd = dir; + const result = await d.run(ctx); + assert.ok(ctx.calls.task.includes("init")); + const initPrompt = ctx.calls.prompts["init"]?.[0] ?? ""; + assert.match(initPrompt, /\/skill:impeccable init/); + assert.match(initPrompt, //); + const builderPrompt = + ctx.calls.prompts["design-system-builder"]?.[0] ?? ""; + assert.match(builderPrompt, //); + const artifactDir = result["artifact_dir"] as string | undefined; + if (artifactDir) rmSync(artifactDir, { recursive: true, force: true }); + } finally { + rmSync(dir, { recursive: true, force: true }); + } + }); + + test("skips reference-discovery when discover_references=false", async () => { + const mod = + await import("../../packages/workflows/builtin/open-claude-design.js"); + const d = mod.default as unknown as WorkflowDefinition; + const ctx = makeMockCtx( + { + prompt: "Design a landing page", + discover_references: false, + max_refinements: 1, + }, + { + task: (name) => { + if (name.startsWith("user-feedback-")) + return refinementDecision(true); + if (name === "pre-export-scan") + return exportGateDecision(false); + return undefined; + }, + }, + ); + await d.run(ctx); + assert.equal(ctx.calls.task.includes("reference-discovery"), false); + }); + + test("always runs init (Phase 2) and drives /skill:impeccable live in preview-display", async () => { + const mod = + await import("../../packages/workflows/builtin/open-claude-design.js"); + const d = mod.default as unknown as WorkflowDefinition; + // Phase 2 always runs now, even when PRODUCT.md/DESIGN.md already exist + // (repo root has them committed); init reconciles rather than skipping. + const ctx = makeMockCtx( + { prompt: "Design a dashboard", max_refinements: 1 }, + { + task: (name) => { + if (name.startsWith("user-feedback-")) + return refinementDecision(true); + if (name === "pre-export-scan") + return exportGateDecision(false); + return undefined; + }, + }, + ); + await d.run(ctx); + assert.ok(ctx.calls.task.includes("init")); + assert.ok(ctx.calls.task.includes("discovery")); + assert.match( + ctx.calls.prompts["discovery"]?.[0] ?? "", + /\/skill:impeccable shape/, + ); + const previewPrompt = + ctx.calls.prompts["preview-display-initial"]?.[0] ?? ""; + assert.match(previewPrompt, /\/skill:impeccable live/); + assert.match(previewPrompt, /`live_changes`/); }); test("declares child workflow output contract", async () => { @@ -133,12 +256,16 @@ describe("open-claude-design", () => { function refinementDecision(readyForEx const ctx = makeMockCtx( { prompt: "Design a kanban board", - reference: "https://example.com/reference", - output_type: "component", max_refinements: 2, }, { task: (name) => { + if (name === "discovery") + return JSON.stringify({ + brief: "Confirmed: a kanban board component.", + output_type: "component", + references: ["https://example.com/reference"], + }); if (name.startsWith("user-feedback-")) return refinementDecision(true); if (name === "pre-export-scan") @@ -151,6 +278,7 @@ describe("open-claude-design", () => { function refinementDecision(readyForEx const result = await d.run(ctx); assert.deepEqual(ctx.calls.stage, []); + assert.ok(ctx.calls.task.includes("discovery")); assert.ok( ctx.calls.parallel.some( (names) => @@ -159,7 +287,7 @@ describe("open-claude-design", () => { function refinementDecision(readyForEx ), ); assert.ok( - ctx.calls.parallel.some((names) => names.includes("web-capture")), + ctx.calls.parallel.some((names) => names.includes("web-capture-1")), ); assert.ok(ctx.calls.task.includes("design-system-builder")); assert.ok(ctx.calls.task.includes("generator")); @@ -211,12 +339,16 @@ describe("open-claude-design", () => { function refinementDecision(readyForEx const ctx = makeMockCtx( { prompt: "Design a dashboard", - reference: "https://example.com/reference", - design_system: "Use the existing app design system.", max_refinements: 1, }, { task: (name) => { + if (name === "discovery") + return JSON.stringify({ + brief: "A dashboard.", + output_type: "page", + references: ["https://example.com/reference"], + }); if (name.startsWith("user-feedback-")) return refinementDecision(true); if (name === "pre-export-scan") @@ -228,7 +360,7 @@ describe("open-claude-design", () => { function refinementDecision(readyForEx await d.run(ctx); - const webCapturePrompt = ctx.calls.prompts["web-capture"]?.[0] ?? ""; + const webCapturePrompt = ctx.calls.prompts["web-capture-1"]?.[0] ?? ""; const previewPrompt = ctx.calls.prompts["preview-display-initial"]?.[0] ?? ""; const finalPrompt = ctx.calls.prompts["final-display"]?.[0] ?? ""; @@ -252,6 +384,110 @@ describe("open-claude-design", () => { function refinementDecision(readyForEx } }); + const annotationNotes = [ + "- I don't like this background; simplify it to a black to grey gradient with solid texture.", + "- The top-left masthead text is too light on this background; ensure WCAG/a11y standards across the page.", + "- The copy button font is too generic; make it less generic with better design craft.", + "- Good call to action on the Start a loop CTA; keep it.", + "- Make the overall vibe more polished, closer to the Apple website.", + ].join("\n"); + + const previewWithAnnotations = [ + "display_method: playwright-cli interactive annotation", + "preview_path: /tmp/preview.html", + "annotated_snapshot: .playwright-cli/annotations-test.png", + "user_notes:", + annotationNotes, + "next_action_hint: proceed to refinement", + ].join("\n"); + + test("threads captured preview annotations into user-feedback and apply-changes", async () => { + const mod = + await import("../../packages/workflows/builtin/open-claude-design.js"); + const d = mod.default as unknown as WorkflowDefinition; + const ctx = makeMockCtx( + { prompt: "Redesign the Atomic website", max_refinements: 1 }, + { + task: (name) => { + if (name === "preview-display-initial") + return previewWithAnnotations; + if (name.startsWith("user-feedback-")) + return refinementDecision(false); + if (name === "pre-export-scan") + return exportGateDecision(false); + return undefined; + }, + }, + ); + + const result = await d.run(ctx); + + // user-feedback receives the annotations as a primary signal. + const ufPrompt = ctx.calls.prompts["user-feedback-1"]?.[0] ?? ""; + assert.match(ufPrompt, //); + assert.ok(ufPrompt.includes("I don't like this background")); + assert.ok(ufPrompt.includes("Apple website")); + + // apply-changes receives the merged brief with annotations FIRST. + const applyPrompt = ctx.calls.prompts["apply-changes-1"]?.[0] ?? ""; + assert.ok(applyPrompt.includes("I don't like this background")); + assert.ok(applyPrompt.includes("Apple website")); + const annotationsIdx = applyPrompt.indexOf("## User annotations"); + const critiqueHeaderIdx = applyPrompt.indexOf( + "## Impeccable critique findings", + ); + assert.ok(annotationsIdx >= 0); + assert.ok(critiqueHeaderIdx >= 0); + assert.ok(annotationsIdx < critiqueHeaderIdx); + assert.ok( + applyPrompt.indexOf("I don't like this background") < + applyPrompt.indexOf("[mock-task:critique-1]"), + ); + + // Annotations persisted as durable workflow artifacts. + const artifactDir = result["artifact_dir"] as string; + const mdPath = join(artifactDir, "feedback", "iteration-0.md"); + const jsonPath = join(artifactDir, "feedback", "iteration-0.json"); + assert.ok(existsSync(mdPath)); + assert.match(readFileSync(mdPath, "utf8"), /I don't like this background/); + const persisted = JSON.parse(readFileSync(jsonPath, "utf8")); + assert.equal(persisted.hasUserNotes, true); + assert.match(persisted.userNotes, /Apple website/); + rmSync(artifactDir, { recursive: true, force: true }); + }); + + test("falls back gracefully and does not block when no annotations were captured", async () => { + const mod = + await import("../../packages/workflows/builtin/open-claude-design.js"); + const d = mod.default as unknown as WorkflowDefinition; + const ctx = makeMockCtx( + { prompt: "Design a dashboard", max_refinements: 1 }, + { + task: (name) => { + if (name.startsWith("user-feedback-")) + return refinementDecision(false); + if (name === "pre-export-scan") + return exportGateDecision(false); + return undefined; + }, + }, + ); + + const result = await d.run(ctx); + + // apply-changes still ran (guardrail did not throw) with the no-notes + // fallback, and no feedback artifacts were persisted. + const applyPrompt = ctx.calls.prompts["apply-changes-1"]?.[0] ?? ""; + assert.match( + applyPrompt, + /No interactive user annotations were captured/, + ); + assert.equal(typeof result["handoff"], "string"); + const artifactDir = result["artifact_dir"] as string; + assert.equal(existsSync(join(artifactDir, "feedback")), false); + rmSync(artifactDir, { recursive: true, force: true }); + }); + test("definition is frozen (immutable)", async () => { const mod = await import("../../packages/workflows/builtin/open-claude-design.js"); diff --git a/test/unit/open-claude-design-feedback.test.ts b/test/unit/open-claude-design-feedback.test.ts new file mode 100644 index 0000000000..5525c7bf4d --- /dev/null +++ b/test/unit/open-claude-design-feedback.test.ts @@ -0,0 +1,240 @@ +// @ts-nocheck +import { afterEach, describe, test } from "bun:test"; +import assert from "node:assert/strict"; +import { existsSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { + assertUserAnnotationsThreaded, + buildRefinementBrief, + buildUserAnnotationsSection, + extractAnnotatedSnapshot, + extractLiveChanges, + extractUserNotes, + persistPreviewFeedback, + toPreviewFeedback, + userAnnotationsBlock, +} from "../../packages/workflows/builtin/open-claude-design-feedback.js"; + +describe("open-claude-design feedback threading (#1464)", () => { + const tempDirs: string[] = []; + afterEach(() => { + while (tempDirs.length > 0) { + const dir = tempDirs.pop(); + if (dir) rmSync(dir, { recursive: true, force: true }); + } + }); + + test("extracts user_notes across markdown label styles", () => { + const colonBlock = [ + "display_method: playwright-cli", + "user_notes:", + "- Simplify the hero background.", + "- Match the Apple website polish.", + "next_action_hint: refine", + ].join("\n"); + assert.match(extractUserNotes(colonBlock) ?? "", /Simplify the hero background/); + assert.match(extractUserNotes(colonBlock) ?? "", /Apple website/); + + const headingBlock = [ + "## display_method", + "playwright-cli", + "## user_notes", + "The masthead text is too light; fix contrast.", + "## next_action_hint", + "refine", + ].join("\n"); + assert.match(extractUserNotes(headingBlock) ?? "", /too light/); + + const inlineBold = "**user_notes:** The copy button font is too generic."; + assert.match(extractUserNotes(inlineBold) ?? "", /too generic/); + + const backtick = "`user_notes`: keep the CTA, polish everything else."; + assert.match(extractUserNotes(backtick) ?? "", /keep the CTA/); + }); + + test("treats placeholder / missing notes as absent", () => { + assert.equal(extractUserNotes("user_notes: none"), undefined); + assert.equal(extractUserNotes("user_notes: (not available)"), undefined); + assert.equal(extractUserNotes("user_notes: N/A"), undefined); + assert.equal(extractUserNotes("display_method: manual\npreview_path: /tmp/x.html"), undefined); + assert.equal(extractUserNotes(""), undefined); + }); + + test("extracts the annotated_snapshot path", () => { + const text = [ + "user_notes: simplify the hero", + "annotated_snapshot: .playwright-cli/annotations-test.png", + ].join("\n"); + assert.equal( + extractAnnotatedSnapshot(text), + ".playwright-cli/annotations-test.png", + ); + }); + + test("captures and threads live_changes from an impeccable live QA session", () => { + const liveText = [ + "display_method: live", + "preview_path: /tmp/preview.html", + "live_changes:", + "- Accepted variant 2 for the hero: tighter density, committed accent.", + "- Accepted a new footer layout.", + "user_notes: none", + "next_action_hint: proceed", + ].join("\n"); + // live_changes parses even when user_notes is the `none` placeholder. + assert.match(extractLiveChanges(liveText) ?? "", /Accepted variant 2 for the hero/); + assert.match(extractLiveChanges(liveText) ?? "", /new footer layout/); + assert.equal(extractUserNotes(liveText), undefined); + + const feedback = toPreviewFeedback({ + iteration: 1, + stageName: "preview-display-1", + result: { text: liveText }, + }); + assert.match(feedback.liveChanges ?? "", /tighter density/); + + // Accepted live variants thread into the user-annotations block so the + // apply stage honors them even with no typed notes. + const block = userAnnotationsBlock([feedback]); + assert.equal(block.hasNotes, true); + assert.match(block.text, /Accepted live variants\/edits/); + assert.match(block.text, /tighter density/); + }); + + test("buildUserAnnotationsSection orders latest feedback first", () => { + const first = toPreviewFeedback({ + iteration: 0, + stageName: "preview-display-initial", + result: { text: "user_notes: simplify the hero background" }, + }); + const second = toPreviewFeedback({ + iteration: 1, + stageName: "preview-display-1", + result: { text: "user_notes: now fix the footer spacing" }, + }); + const section = buildUserAnnotationsSection([first, second]); + assert.ok(section.indexOf("footer spacing") < section.indexOf("simplify the hero")); + }); + + test("userAnnotationsBlock falls back when no notes captured", () => { + const empty = userAnnotationsBlock([ + toPreviewFeedback({ + iteration: 0, + stageName: "preview-display-initial", + result: { text: "display_method: manual fallback" }, + }), + ]); + assert.equal(empty.hasNotes, false); + assert.match(empty.text, /No interactive user annotations were captured/); + }); + + test("buildRefinementBrief puts user annotations above internal critique", () => { + const brief = buildRefinementBrief({ + userAnnotations: "Simplify the hero background.", + reviewerDecision: "Not ready: honor user notes.", + critique: "Heuristic score 3/4 on visibility.", + screenshot: "Contrast fails WCAG AA on masthead.", + currentDesign: "A landing page.", + }); + assert.ok( + brief.indexOf("## User annotations") < + brief.indexOf("## Impeccable critique findings"), + ); + assert.ok( + brief.indexOf("Simplify the hero background") < + brief.indexOf("Heuristic score"), + ); + assert.ok(brief.includes("## Screenshot / visual QA findings")); + }); + + test("assertUserAnnotationsThreaded throws when notes are dropped", () => { + const feedback = toPreviewFeedback({ + iteration: 0, + stageName: "preview-display-initial", + result: { text: "user_notes: simplify the hero background" }, + }); + // Threaded prompt -> no throw. + assert.doesNotThrow(() => + assertUserAnnotationsThreaded( + "context includes: simplify the hero background", + [feedback], + "apply-changes-1", + ), + ); + // Missing notes -> throws a clear workflow error. + assert.throws( + () => assertUserAnnotationsThreaded("nothing relevant", [feedback], "apply-changes-1"), + /were not threaded into the refinement context/, + ); + }); + + test("persistPreviewFeedback writes durable artifacts only when notes exist", () => { + const dir = mkdtempSync(join(tmpdir(), "ocd-feedback-")); + tempDirs.push(dir); + const withNotes = toPreviewFeedback({ + iteration: 0, + stageName: "preview-display-initial", + result: { text: "user_notes: simplify the hero background" }, + }); + persistPreviewFeedback({ artifactDir: dir, workflowCwd: dir, feedback: withNotes }); + const mdPath = join(dir, "feedback", "iteration-0.md"); + const jsonPath = join(dir, "feedback", "iteration-0.json"); + assert.ok(existsSync(mdPath)); + assert.match(readFileSync(mdPath, "utf8"), /simplify the hero background/); + const json = JSON.parse(readFileSync(jsonPath, "utf8")); + assert.equal(json.hasUserNotes, true); + + // No-notes feedback writes nothing. + const noNotes = toPreviewFeedback({ + iteration: 1, + stageName: "preview-display-1", + result: { text: "display_method: manual fallback" }, + }); + persistPreviewFeedback({ artifactDir: dir, workflowCwd: dir, feedback: noNotes }); + assert.equal(existsSync(join(dir, "feedback", "iteration-1.md")), false); + }); + + test("persistPreviewFeedback persists live_changes-only feedback", () => { + const dir = mkdtempSync(join(tmpdir(), "ocd-feedback-")); + tempDirs.push(dir); + const liveOnly = toPreviewFeedback({ + iteration: 2, + stageName: "preview-display-2", + result: { + text: [ + "display_method: live", + "live_changes: Accepted variant 1 for the pricing table.", + "user_notes: none", + ].join("\n"), + }, + }); + persistPreviewFeedback({ artifactDir: dir, workflowCwd: dir, feedback: liveOnly }); + const jsonPath = join(dir, "feedback", "iteration-2.json"); + assert.ok(existsSync(jsonPath)); + const json = JSON.parse(readFileSync(jsonPath, "utf8")); + assert.equal(json.hasLiveChanges, true); + assert.equal(json.hasUserNotes, false); + }); + + test("persistPreviewFeedback copies the annotated snapshot artifact", () => { + const dir = mkdtempSync(join(tmpdir(), "ocd-feedback-")); + tempDirs.push(dir); + const snapshot = join(dir, "annotations-test.png"); + writeFileSync(snapshot, "fake-png-bytes"); + writeFileSync(join(dir, "annotations-test.yaml"), "annotations: []"); + const feedback = toPreviewFeedback({ + iteration: 0, + stageName: "preview-display-initial", + result: { + text: [ + "user_notes: simplify the hero", + `annotated_snapshot: ${snapshot}`, + ].join("\n"), + }, + }); + persistPreviewFeedback({ artifactDir: dir, workflowCwd: dir, feedback }); + assert.ok(existsSync(join(dir, "feedback", "iteration-0-annotations.png"))); + assert.ok(existsSync(join(dir, "feedback", "iteration-0-annotations.yaml"))); + }); +}); diff --git a/test/unit/open-claude-design-setup.test.ts b/test/unit/open-claude-design-setup.test.ts new file mode 100644 index 0000000000..d7089fb794 --- /dev/null +++ b/test/unit/open-claude-design-setup.test.ts @@ -0,0 +1,224 @@ +// @ts-nocheck +import { afterEach, describe, test } from "bun:test"; +import assert from "node:assert/strict"; +import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { + REFERENCE_DESIGN_SITES, + buildLivePreviewDisplayPrompt, + buildReferenceDiscoveryPrompt, + detectDesignContextFiles, + ensureProjectDesignContext, + persistReferencesBrief, + runDiscovery, +} from "../../packages/workflows/builtin/open-claude-design-setup.js"; + +function makeRecorder(taskText) { + const calls = { tasks: [], prompts: {} }; + const designContext = { + task: async (name, options) => { + calls.tasks.push(name); + calls.prompts[name] = options.prompt; + const text = taskText?.(name) ?? `[mock:${name}]`; + let structured; + try { + structured = JSON.parse(text); + } catch { + structured = undefined; + } + return { name, stageName: name, text, structured }; + }, + }; + return { calls, designContext }; +} + +describe("open-claude-design setup", () => { + const tempDirs = []; + afterEach(() => { + while (tempDirs.length > 0) { + const dir = tempDirs.pop(); + if (dir) rmSync(dir, { recursive: true, force: true }); + } + }); + const tempDir = () => { + const dir = mkdtempSync(join(tmpdir(), "ocd-setup-")); + tempDirs.push(dir); + return dir; + }; + + describe("detectDesignContextFiles", () => { + test("reports missing when neither file exists", () => { + const detection = detectDesignContextFiles(tempDir()); + assert.equal(detection.hasProduct, false); + assert.equal(detection.hasDesign, false); + assert.equal(detection.hasBoth, false); + }); + + test("detects PRODUCT.md / DESIGN.md at the project root", () => { + const dir = tempDir(); + writeFileSync(join(dir, "PRODUCT.md"), "# Product"); + writeFileSync(join(dir, "DESIGN.md"), "# Design"); + const detection = detectDesignContextFiles(dir); + assert.equal(detection.hasBoth, true); + assert.equal(detection.productPath, join(dir, "PRODUCT.md")); + assert.equal(detection.designPath, join(dir, "DESIGN.md")); + }); + + test("detects case-insensitive files under .agents/context and docs", () => { + const dir = tempDir(); + mkdirSync(join(dir, ".agents", "context"), { recursive: true }); + mkdirSync(join(dir, "docs"), { recursive: true }); + writeFileSync(join(dir, ".agents", "context", "product.md"), "# Product"); + writeFileSync(join(dir, "docs", "Design.md"), "# Design"); + const detection = detectDesignContextFiles(dir); + assert.equal(detection.hasProduct, true); + assert.equal(detection.hasDesign, true); + assert.equal(detection.hasBoth, true); + }); + }); + + describe("runDiscovery", () => { + test("asks via impeccable shape and parses the structured brief/output_type/references", async () => { + const { calls, designContext } = makeRecorder(() => + JSON.stringify({ + brief: "A confirmed kanban board brief.", + output_type: "component", + references: ["https://example.com/a", "./mock.png"], + }), + ); + const decision = await runDiscovery({ + designContext, + prompt: "Design a kanban board", + discoveryConfig: {}, + }); + assert.ok(calls.tasks.includes("discovery")); + const prompt = calls.prompts["discovery"] ?? ""; + assert.match(prompt, /\/skill:impeccable shape/); + assert.match(prompt, /AskUserQuestion/); + assert.match(prompt, /prototype, wireframe, page, component, theme, tokens/); + assert.equal(decision.brief, "A confirmed kanban board brief."); + assert.equal(decision.output_type, "component"); + assert.deepEqual(decision.references, [ + "https://example.com/a", + "./mock.png", + ]); + }); + + test("falls back to the raw prompt and empty references when unstructured", async () => { + const { designContext } = makeRecorder(() => "not json"); + const decision = await runDiscovery({ + designContext, + prompt: "Design a dashboard", + discoveryConfig: {}, + }); + assert.equal(decision.brief, "Design a dashboard"); + assert.equal(decision.output_type, "prototype"); + assert.deepEqual(decision.references, []); + }); + }); + + describe("ensureProjectDesignContext", () => { + test("runs /skill:impeccable init with discovery context when files are missing", async () => { + const dir = tempDir(); + const { calls, designContext } = makeRecorder(); + const result = await ensureProjectDesignContext({ + designContext, + cwd: dir, + prompt: "Design a dashboard", + discoveryContext: "Confirmed design brief: a dashboard.", + designModelConfig: {}, + }); + assert.equal(result.initRan, true); + assert.ok(calls.tasks.includes("init")); + const initPrompt = calls.prompts["init"] ?? ""; + assert.match(initPrompt, /\/skill:impeccable init/); + assert.match(initPrompt, //); + assert.match(initPrompt, /Confirmed design brief: a dashboard/); + assert.match(initPrompt, /PRODUCT\.md/); + assert.match(initPrompt, /DESIGN\.md/); + }); + + test("always runs init and reconciles when both files already exist", async () => { + const dir = tempDir(); + writeFileSync(join(dir, "PRODUCT.md"), "# Product"); + writeFileSync(join(dir, "DESIGN.md"), "# Design"); + const { calls, designContext } = makeRecorder(); + const result = await ensureProjectDesignContext({ + designContext, + cwd: dir, + prompt: "Design a dashboard", + discoveryContext: "brief", + designModelConfig: {}, + }); + // Phase 2 always runs now — even when both files exist. + assert.equal(result.initRan, true); + assert.ok(calls.tasks.includes("init")); + const initPrompt = calls.prompts["init"] ?? ""; + assert.match(initPrompt, /already exist/); + assert.match(initPrompt, /never clobber|never overwrite|never silently overwrite/i); + assert.match(result.summary, /reviewed existing/); + }); + }); + + describe("reference discovery", () => { + test("buildReferenceDiscoveryPrompt names every gallery + the playwright bootstrap", () => { + const prompt = buildReferenceDiscoveryPrompt({ + prompt: "Design a landing page", + outputType: "page", + designContextHint: "PRODUCT.md=/p DESIGN.md=/d", + artifactDir: "/tmp/run", + browserBootstrapRules: "which playwright-cli ... @playwright/cli", + }); + for (const site of REFERENCE_DESIGN_SITES) { + assert.ok(prompt.includes(site.url), site.url); + } + assert.match(prompt, //); + assert.match(prompt, //); + assert.match(prompt, /video-start/); + assert.match(prompt, /scroll-through video/i); + assert.match(prompt, /screenshot --full-page/); + assert.match(prompt, /CLICK INTO/); + assert.match(prompt, /destination URL/i); + }); + + test("persistReferencesBrief writes references.md", () => { + const dir = tempDir(); + persistReferencesBrief(dir, "## Curated references\n\n- Awwwards hero."); + assert.ok(existsSync(join(dir, "references.md"))); + assert.match( + readFileSync(join(dir, "references.md"), "utf8"), + /Awwwards hero/, + ); + }); + }); + + describe("buildLivePreviewDisplayPrompt", () => { + test("initial preview prompt drives /skill:impeccable live and keeps the feedback labels", () => { + const prompt = buildLivePreviewDisplayPrompt({ + previewPath: "/tmp/run/preview.html", + previewFileUrl: "file:///tmp/run/preview.html", + browserBootstrapRules: "which playwright-cli ... @playwright/cli ... missing browser executable ... screenshot --filename", + }); + assert.match(prompt, /\/skill:impeccable live/); + assert.match(prompt, //); + assert.match(prompt, /playwright-cli show --annotate/); + assert.match(prompt, /`user_notes`/); + assert.match(prompt, /`annotated_snapshot`/); + assert.match(prompt, /`live_changes`/); + assert.match(prompt, /the just-generated HTML artifact/); + assert.ok(prompt.includes("/tmp/run/preview.html")); + }); + + test("per-iteration prompt labels the iteration", () => { + const prompt = buildLivePreviewDisplayPrompt({ + previewPath: "/tmp/run/preview.html", + previewFileUrl: "file:///tmp/run/preview.html", + browserBootstrapRules: "rules", + iteration: 2, + maxRefinements: 3, + }); + assert.match(prompt, /iteration 2\/3/); + }); + }); +}); From b0f490f5d410d623bd53bfc08f9df6f400ff33d1 Mon Sep 17 00:00:00 2001 From: Norin Lavaee Date: Sun, 21 Jun 2026 20:33:27 -0700 Subject: [PATCH 2/7] chore(impeccable): refresh bundled impeccable skill assets Sync the vendored impeccable skill that was already modified in the working tree: SKILL.md (v3.8.0), reference/ docs, and the detector/live-mode scripts. Reorganizes live-mode helpers under scripts/live/ and scripts/lib/, adds detector/design-system.mjs plus detector inline-ignore support, and drops deprecated standalone script files. Bundled here alongside the open-claude-design workflow changes per request. Assistant-model: Claude Opus 4.8 --- packages/workflows/skills/impeccable/SKILL.md | 37 +- .../skills/impeccable/reference/brand.md | 4 +- .../skills/impeccable/reference/live.md | 29 +- .../impeccable/scripts/cleanup-deprecated.mjs | 284 -- .../impeccable/scripts/context-signals.mjs | 2 +- .../skills/impeccable/scripts/context.mjs | 753 ++- .../impeccable/scripts/critique-storage.mjs | 2 +- .../detector/browser/injected/index.mjs | 226 +- .../impeccable/scripts/detector/cli/main.mjs | 68 +- .../scripts/detector/design-system.mjs | 750 +++ .../detector/detect-antipatterns-browser.js | 705 ++- .../scripts/detector/detect-antipatterns.mjs | 7 + .../detector/engines/browser/detect-url.mjs | 33 +- .../detector/engines/regex/detect-text.mjs | 57 +- .../engines/static-html/css-cascade.mjs | 29 + .../engines/static-html/detect-html.mjs | 28 +- .../scripts/detector/node/file-system.mjs | 2 +- .../detector/registry/antipatterns.mjs | 29 + .../scripts/detector/rules/checks.mjs | 451 +- .../detector/shared/inline-ignores.mjs | 148 + .../scripts/detector/shared/page.mjs | 9 +- .../impeccable/scripts/impeccable-paths.mjs | 126 - .../scripts/{ => lib}/design-parser.mjs | 9 +- .../scripts/lib/impeccable-config.mjs | 638 +++ .../scripts/lib/impeccable-paths.mjs | 128 + .../scripts/{ => lib}/is-generated.mjs | 0 .../impeccable/scripts/lib/target-args.mjs | 42 + .../skills/impeccable/scripts/live-accept.mjs | 243 +- .../impeccable/scripts/live-browser-dom.js | 146 + .../skills/impeccable/scripts/live-browser.js | 4395 +++++++++++++---- .../scripts/live-commit-manual-edits.mjs | 4 +- .../impeccable/scripts/live-complete.mjs | 4 +- .../scripts/live-discard-manual-edits.mjs | 2 +- .../skills/impeccable/scripts/live-inject.mjs | 142 +- .../skills/impeccable/scripts/live-insert.mjs | 44 +- .../scripts/live-manual-edit-evidence.mjs | 8 +- .../skills/impeccable/scripts/live-poll.mjs | 36 +- .../skills/impeccable/scripts/live-resume.mjs | 2 +- .../skills/impeccable/scripts/live-server.mjs | 1474 +----- .../skills/impeccable/scripts/live-status.mjs | 4 +- .../skills/impeccable/scripts/live-target.mjs | 30 + .../skills/impeccable/scripts/live-wrap.mjs | 104 +- .../skills/impeccable/scripts/live.mjs | 95 +- .../scripts/live/browser-script-parts.mjs | 49 + .../completion.mjs} | 1 + .../event-validation.mjs} | 11 +- .../insert-ui.mjs} | 0 .../impeccable/scripts/live/manual-apply.mjs | 939 ++++ .../scripts/live/manual-edit-routes.mjs | 357 ++ .../manual-edits-buffer.mjs} | 2 +- .../session-store.mjs} | 24 +- .../scripts/live/svelte-component.mjs | 826 ++++ .../scripts/live/sveltekit-adapter.mjs | 274 + .../impeccable/scripts/live/ui-core.mjs | 180 + .../impeccable/scripts/live/vocabulary.mjs | 36 + 55 files changed, 10961 insertions(+), 3067 deletions(-) delete mode 100644 packages/workflows/skills/impeccable/scripts/cleanup-deprecated.mjs create mode 100644 packages/workflows/skills/impeccable/scripts/detector/design-system.mjs create mode 100644 packages/workflows/skills/impeccable/scripts/detector/shared/inline-ignores.mjs delete mode 100644 packages/workflows/skills/impeccable/scripts/impeccable-paths.mjs rename packages/workflows/skills/impeccable/scripts/{ => lib}/design-parser.mjs (99%) create mode 100644 packages/workflows/skills/impeccable/scripts/lib/impeccable-config.mjs create mode 100644 packages/workflows/skills/impeccable/scripts/lib/impeccable-paths.mjs rename packages/workflows/skills/impeccable/scripts/{ => lib}/is-generated.mjs (100%) create mode 100644 packages/workflows/skills/impeccable/scripts/lib/target-args.mjs create mode 100644 packages/workflows/skills/impeccable/scripts/live-browser-dom.js create mode 100644 packages/workflows/skills/impeccable/scripts/live-target.mjs create mode 100644 packages/workflows/skills/impeccable/scripts/live/browser-script-parts.mjs rename packages/workflows/skills/impeccable/scripts/{live-completion.mjs => live/completion.mjs} (89%) rename packages/workflows/skills/impeccable/scripts/{live-event-validation.mjs => live/event-validation.mjs} (94%) rename packages/workflows/skills/impeccable/scripts/{live-insert-ui.mjs => live/insert-ui.mjs} (100%) create mode 100644 packages/workflows/skills/impeccable/scripts/live/manual-apply.mjs create mode 100644 packages/workflows/skills/impeccable/scripts/live/manual-edit-routes.mjs rename packages/workflows/skills/impeccable/scripts/{live-manual-edits-buffer.mjs => live/manual-edits-buffer.mjs} (98%) rename packages/workflows/skills/impeccable/scripts/{live-session-store.mjs => live/session-store.mjs} (87%) create mode 100644 packages/workflows/skills/impeccable/scripts/live/svelte-component.mjs create mode 100644 packages/workflows/skills/impeccable/scripts/live/sveltekit-adapter.mjs create mode 100644 packages/workflows/skills/impeccable/scripts/live/ui-core.mjs create mode 100644 packages/workflows/skills/impeccable/scripts/live/vocabulary.mjs diff --git a/packages/workflows/skills/impeccable/SKILL.md b/packages/workflows/skills/impeccable/SKILL.md index ad618f6bcd..80459fa94b 100644 --- a/packages/workflows/skills/impeccable/SKILL.md +++ b/packages/workflows/skills/impeccable/SKILL.md @@ -1,6 +1,7 @@ --- name: impeccable description: Use when the user wants to design, redesign, shape, critique, audit, polish, clarify, distill, harden, optimize, adapt, animate, colorize, extract, or otherwise improve a frontend interface. Covers websites, landing pages, dashboards, product UI, app shells, components, forms, settings, onboarding, and empty states. Handles UX review, visual hierarchy, information architecture, cognitive load, accessibility, performance, responsive behavior, theming, anti-patterns, typography, fonts, spacing, layout, alignment, color, motion, micro-interactions, UX copy, error states, edge cases, i18n, and reusable design systems or tokens. Also use for bland designs that need to become bolder or more delightful, loud designs that should become quieter, live browser iteration on UI elements, or ambitious visual effects that should feel technically extraordinary. Not for backend-only or non-UI tasks. +version: 3.8.0 --- Designs and iterates production-grade frontend interfaces. Real working code, committed design choices, exceptional craft. @@ -9,11 +10,10 @@ Designs and iterates production-grade frontend interfaces. Real working code, co You MUST do these steps before proceeding: -1. Run `node .agents/skills/impeccable/scripts/context.mjs` once per session. If you've already seen its output in this conversation, do not re-run it. The script either prints the project's PRODUCT.md (and DESIGN.md when present) as a markdown block, or tells you it's missing. Follow whatever it prints. **If it reports `NO_PRODUCT_MD`, stop and follow `reference/init.md` before doing anything else.** If the output ends with an `UPDATE_AVAILABLE` directive, follow it (ask the user once about updating, then continue). It never blocks the current task. -2. If the user invoked a sub-command (`craft`, `shape`, `audit`, `polish`, ...), you MUST read `reference/.md` next. Non-optional. The reference defines the command's flow; without it you will skip steps the user expects. -3. Familiarize yourself with any existing design system, conventions, and components in the code. Read at least one project file (CSS / tokens / theme / a representative component or page). **Required even when you've loaded a sub-command reference in step 2.** Don't reinvent the wheel; use what's there when it works, branch out when the UX wins. -4. Read the matching register reference. **This is non-optional; skipping it produces generic output.** If the project is marketing, a landing page, a campaign, long-form content, or a portfolio (design IS the product), read `reference/brand.md`. If it is app UI, admin, a dashboard, or a tool (design SERVES the product), read `reference/product.md`. Pick by first match: (1) task cue ("landing page" vs "dashboard"); (2) surface in focus (the page, file, or route being worked on); (3) `register` field in PRODUCT.md. -5. **If the project is brand-new (no existing CSS tokens / theme / committed brand colors found in step 3)**, run `node .agents/skills/impeccable/scripts/palette.mjs` to receive a brand seed color and composition guidance. This is the anchor for your primary brand color. Compose the rest of the palette (bg, surface, ink, accent, muted) around it per the script's instructions. Use OKLCH throughout. **Skip this step only if step 3 found committed brand colors in existing tokens; in that case identity-preservation wins.** +1. If the user invoked a sub-command (`craft`, `shape`, `audit`, `polish`, ...), you MUST read `reference/.md` next. Non-optional. The reference defines the command's flow; without it you will skip steps the user expects. +2. Familiarize yourself with any existing design system, conventions, and components in the code. Read at least one project file (CSS / tokens / theme / a representative component or page). **Required even when you've loaded a sub-command reference in step 2.** Don't reinvent the wheel; use what's there when it works, branch out when the UX wins. +3. Read the matching register reference. **This is non-optional; skipping it produces generic output.** If the project is marketing, a landing page, a campaign, long-form content, or a portfolio (design IS the product), read `reference/brand.md`. If it is app UI, admin, a dashboard, or a tool (design SERVES the product), read `reference/product.md`. Pick by first match: (1) task cue ("landing page" vs "dashboard"); (2) surface in focus (the page, file, or route being worked on); (3) `register` field in PRODUCT.md. +4. **If the project is brand-new (no existing CSS tokens / theme / committed brand colors found in step 3)**, run `node .agents/skills/impeccable/scripts/palette.mjs` to receive a brand seed color and composition guidance. This is the anchor for your primary brand color. Compose the rest of the palette (bg, surface, ink, accent, muted) around it per the script's instructions. Use OKLCH throughout. **Skip this step only if step 3 found committed brand colors in existing tokens; in that case identity-preservation wins.** ## Design guidance @@ -29,16 +29,12 @@ Produce ready-to-ship, production-grade code, not prototypes or starting points. #### Typography - Cap body line length at 65–75ch. -- Hierarchy through scale + weight contrast (≥1.25 ratio between steps). Avoid flat scales. -- Cap font-family count at 3 (display + body + optional mono). More than 3 reads as indecision, not richness. One well-tuned family with weight contrast usually beats three competing typefaces. - Don't pair fonts that are similar but not identical (two geometric sans-serifs, two humanist sans-serifs). Pair on a contrast axis (serif + sans, geometric + humanist) or use one family in multiple weights. -- No all-caps body copy. Reserve uppercase for short labels (≤4 words), section eyebrows (used sparingly per the Absolute bans), and badges. Sentences in ALL CAPS are unreadable at body sizes. - Hero / display heading ceiling: clamp() max ≤ 6rem (~96px). Above that the page is shouting, not designing. - Display heading letter-spacing floor: ≥ -0.04em. Anything tighter and letters touch; cramped, not "designed". - Use `text-wrap: balance` on h1–h3 for even line lengths; `text-wrap: pretty` on long prose to reduce orphans. -Two hard typographic ceilings you currently miss: -- Hero clamp() max ≤ 6rem. 8–11rem (128–176px) reads as comically loud, not bold. +One hard typographic ceiling you currently miss: - Display letter-spacing ≥ -0.04em. Your default of -0.05 to -0.085em on display H1s makes the letters touch and reads as cramped. -0.02 to -0.03em is plenty for tight grotesque display; -0.04em is the floor. #### Layout @@ -63,15 +59,6 @@ Two hard typographic ceilings you currently miss: - Dropdowns rendered with `position: absolute` inside an `overflow: hidden` or `overflow: auto` container will be clipped. Use the native `` / popover API, `position: fixed`, or a portal to escape the stacking context. -### Copy - -- Every word earns its place. No restated headings, no intros that repeat the title. -- **No em dashes.** Use commas, colons, semicolons, periods, or parentheses. Also not `--`. -- **No aphoristic-cadence body copy as a default voice.** Don't fall into the rhythm of "serious statement, then punchy short negation" as the page's recurring voice. If three or more section copy blocks on the page land on a short rebuttal-shaped sentence, rewrite. Specific, not aphoristic. -- **No marketing buzzwords.** The streamline / empower / supercharge / leverage / unleash / transform / seamless / world-class / enterprise-grade / next-generation / cutting-edge / game-changer / mission-critical family of phrases. Pick a specific noun and a verb that describes what the product literally does. -- Button labels: verb + object. "Save changes" beats "OK"; "Delete project" beats "Yes". The label should say what will happen. -- Link text needs standalone meaning. "View pricing plans" beats "Click here"; screen readers announce links out of context. - ### New projects only (when no prior work exists) #### Color & Theme @@ -105,7 +92,7 @@ Match-and-refuse. If you're about to write any of these, rewrite the element wit - **`border-radius: 32px+` on cards / sections / inputs.** You over-round. Cards top out at 12–16px; full-pill is fine for tags/buttons. Picking 24/28/32/40px on a card is the codex tell; no brand wants "insanely rounded". - **Hand-drawn / sketchy SVG illustrations.** Class names like `loose-sketch`, `*-sketch`, `doodle`, `wavy`; `feTurbulence` / `feDisplacementMap` "paper grain" filters; 5-to-30 path crude scenes meant to depict a tangible subject (an otter, a table-and-fork, an album cover). All of these read as amateurish, not whimsical. If you can't render the scene with real assets, ship no illustration. Don't attempt sketchy SVG as a fallback. - **`repeating-linear-gradient(...)` stripe backgrounds.** Diagonal stripes in `body:before` or section backgrounds are pure codex decoration. Don't. -- **"X theater" / "actually X" / "not just X, it's Y" copy.** "Productivity theater", "engagement theater", "growth theater": instant AI slop. Choose a specific noun, not a meta-criticism phrase. +- **Meta-criticism copy.** Naming a concept then layering an ironic modifier, or staging a strawman to "correct" it. Make the specific claim instead. ### The AI slop test @@ -144,7 +131,7 @@ If someone could look at this interface and say "AI made that" without doubt, it | `optimize [target]` | Fix | Diagnose and fix UI performance | [reference/optimize.md](reference/optimize.md) | | `live` | Iterate | Visual variant mode: pick elements in the browser, generate alternatives | [reference/live.md](reference/live.md) | -Plus two management commands: `pin ` and `unpin `, detailed below. +Plus three management commands: `pin `, `unpin `, and `hooks `, detailed below. ### Routing rules @@ -161,7 +148,7 @@ Plus two management commands: `pin ` and `unpin `, detailed be **If `scan.targets` is non-empty, run `node .agents/skills/impeccable/scripts/detect.mjs --json ` once** (the bundled detector over local files: no network, no npx). `scan.via` tells you what they are: `git-changes` (the markup/style files in your dirty tree, the most relevant set), `source-dir` (e.g. `src`, `app`), `html`, or `root`. Fold the hits into your picks: many quality / contrast hits → `audit` or `polish`; a specific slop family → the matching command (gradient text or eyebrows → `quieter` / `typeset`, flat or gray palette → `colorize`, and so on). It's a real, current signal that beats guessing. If detect errors or the tree is large and slow, skip it and recommend the user run `audit` themselves; never block the suggestion on it. Keep it to 2-3 pointed picks with the exact command to type. The menu stays the fallback; the recommendation is the lede. -2. **First word matches a command**: load its reference file and follow its instructions. Everything after the command name is the target. +2. **First word matches a command** (table above OR `pin` / `unpin` / `hooks`): load its reference file and follow its instructions. Everything after the command name is the target. 3. **First word doesn't match, but the intent clearly maps to one command** (e.g. "fix the spacing" → `layout`, "rewrite this error message" → `clarify`, "the colors feel flat" → `colorize`): load that command's reference and proceed as if invoked. If two commands could fit, ask once which. 4. **No clear command match**: general design invocation. Apply the setup steps, the General rules, and the loaded register reference, using the full argument as context. @@ -179,4 +166,8 @@ If the first word is `craft`, setup still runs first, but [reference/craft.md](r node .agents/skills/impeccable/scripts/pin.mjs ``` -Valid `` is any command from the table above. Report the script's result concisely. Confirm the new shortcut on success, relay stderr verbatim on error. \ No newline at end of file +Valid `` is any command from the table above. Report the script's result concisely. Confirm the new shortcut on success, relay stderr verbatim on error. + +## Hooks + +`$impeccable hooks ` manages the design detector hook for this project. The hook auto-runs the detector after direct UI file edits and surfaces findings as system reminders. Full flow is in [reference/hooks.md](reference/hooks.md); load it when the user invokes `$impeccable hooks` with any argument. \ No newline at end of file diff --git a/packages/workflows/skills/impeccable/reference/brand.md b/packages/workflows/skills/impeccable/reference/brand.md index 194514e953..a461c5484a 100644 --- a/packages/workflows/skills/impeccable/reference/brand.md +++ b/packages/workflows/skills/impeccable/reference/brand.md @@ -60,7 +60,7 @@ Brand surfaces have permission for Committed, Full palette, and Drenched strateg - Name a real reference before picking a strategy. "Klim Type Foundry #ff4500 orange drench", "Stripe purple-on-white restraint", "Liquid Death acid-green full palette", "Mailchimp yellow full palette", "Condé Nast Traveler muted navy restraint", "Vercel pure black monochrome". Unnamed ambition becomes beige. - Palette IS voice. A calm brand and a restless brand should not share palette mechanics. - When the strategy is Committed or Drenched, color carries the brand. Don't hedge with neutrals around the edges. Commit. -- Don't converge across projects. If the last brand surface was restrained-on-cream, this one is not. +- Don't converge across projects. Each brand surface differentiates from the last. - When a cultural-symbol palette is the obvious pull, reach past it. Let the cultural reading come from typography, imagery, and copy, not the palette. ## Layout @@ -74,7 +74,7 @@ Brand surfaces have permission for Committed, Full palette, and Drenched strateg Brand surfaces lean on imagery. A restaurant, hotel, magazine, or product landing page without any imagery reads as incomplete, not as restrained. A solid-color rectangle where a hero image should go is worse than a representative stock photo. -**When the brief implies imagery (restaurants, hotels, magazines, photography, hobbyist communities, food, travel, fashion, product), you must ship imagery.** Zero images is a bug, not a design choice. "Restraint" is not an excuse. If the approved comp or brief is image-led, ship real project assets, generated raster assets, or a credible canvas/SVG/WebGL scene. Do not replace photographic, architectural, product, or place imagery with generic CSS panels, decorative diagrams, cards, bullets, or copy. +**When the brief implies imagery, you must ship imagery.** Zero images is a bug, not a design choice. "Restraint" is not an excuse. If the approved comp or brief is image-led, ship real project assets, generated raster assets, or a credible canvas/SVG/WebGL scene. Do not replace photographic, architectural, product, or place imagery with generic CSS panels, decorative diagrams, cards, bullets, or copy. - **For greenfield work without local assets, use stock imagery.** Unsplash is the default. The URL shape is `https://images.unsplash.com/photo-{id}?auto=format&fit=crop&w=1600&q=80`. **Verify the URLs before referencing them.** If you have an image-search MCP, web-fetch tool, or browser access, use it to find real photo IDs and confirm they resolve. Guessed IDs (even ones that look real) often 404 and ship as broken-image placeholders. Without a verification path, pick fewer photos you're confident exist over more that you guessed; never substitute colored `
` placeholders. - **Search for the brand's physical object**, not the generic category: "handmade pasta on a scratched wooden table" beats "Italian food"; "cypress trees above a limestone hotel facade at dusk" beats "luxury hotel". diff --git a/packages/workflows/skills/impeccable/reference/live.md b/packages/workflows/skills/impeccable/reference/live.md index fa7a43c10f..bc1e3e9ead 100644 --- a/packages/workflows/skills/impeccable/reference/live.md +++ b/packages/workflows/skills/impeccable/reference/live.md @@ -10,7 +10,7 @@ Codex: run live helper commands, the app dev server, and any dependency-installi Execute in order. No step skipped, no step reordered. -1. `live.mjs`: boot. +1. `live.mjs`: boot. If the request names or implies a file, route, or app inside a monorepo, infer the concrete path and run `node .agents/skills/impeccable/scripts/live.mjs --target ` instead; then run the rest of this live session from the returned `projectRoot`. 2. Open the app URL that serves `pageFile` (infer from `package.json`, docs, terminal output, or an open tab). Never use `serverPort`; it's the helper, not the app. **Cursor:** `browser_navigate` to that URL before polling; do not skip. **Other harnesses:** use the available browser tool; if the URL is uncertain, ask the user once. 3. Poll loop with the default long timeout (600000 ms). After every event or `--reply`, run `live-poll.mjs` again immediately. Never pass a short `--timeout=`. @@ -113,7 +113,9 @@ node .agents/skills/impeccable/scripts/live-insert.mjs --id EVENT_ID --count EVE 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). Write all variants in one edit, then `--reply done`. -On accept/discard, `live-accept.mjs` removes the wrapper block; the anchor element is untouched. +For Svelte/SvelteKit targets, `live-insert.mjs` returns `previewMode: "svelte-component"` with `mode: "insert"`, `file` pointing at a temporary `node_modules/.impeccable-live//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 `' : '')); + if (paramValues && Object.keys(paramValues).length > 0) { + lines.push( + bodyIndent + commentSyntax.open + ' impeccable-param-values ' + id + ': ' + JSON.stringify(paramValues) + ' ' + commentSyntax.close, + ); + } + lines.push(bodyIndent + commentSyntax.open + ' impeccable-carbonize-end ' + id + ' ' + commentSyntax.close); + lines.push(bodyIndent + '
'); + lines.push(...bodyRestored); + lines.push(bodyIndent + '
'); + }; + + if (isJsx) { + const wrapperStyle = 'style={{ display: "contents" }}'; + lines.push(indent + '
'); + pushCarbonizeBody(indent + ' '); + lines.push(indent + '
'); + } else { + pushCarbonizeBody(indent); + } + + return lines; +} + +function reindentContent(contentLines, fromIndent, toIndent) { + return contentLines.map((line) => { + if (line.trim() === '') return ''; + if (line.startsWith(fromIndent)) return toIndent + line.slice(fromIndent.length); + return toIndent + line.trimStart(); + }); +} + function handleAccept(id, variantNum, lines, targetFile, paramValues) { const block = findMarkerBlock(id, lines); if (!block) return { handled: false, error: 'Markers not found' }; @@ -235,45 +358,17 @@ function handleAccept(id, variantNum, lines, targetFile, paramValues) { const hasHelperAttrs = variantText.includes('data-impeccable-variant'); const needsCarbonize = !!(cssContent || hasHelperAttrs); - // Build the replacement const restored = deindentContent(variantContent, indent); - const replacement = []; - - if (cssContent) { - replacement.push(indent + commentSyntax.open + ' impeccable-carbonize-start ' + id + ' ' + commentSyntax.close); - // JSX targets need the CSS body wrapped in a template literal so that the - // `{` and `}` in CSS rules don't get parsed as JSX expressions. - replacement.push(indent + '' : '')); - if (paramValues && Object.keys(paramValues).length > 0) { - // Preserve the user's knob positions for the carbonize-cleanup agent - // to bake into the final CSS when it collapses scoped rules. - replacement.push(indent + commentSyntax.open + ' impeccable-param-values ' + id + ': ' + JSON.stringify(paramValues) + ' ' + commentSyntax.close); - } - replacement.push(indent + commentSyntax.open + ' impeccable-carbonize-end ' + id + ' ' + commentSyntax.close); - } - - // Keep the `@scope ([data-impeccable-variant="N"])` selectors in the - // carbonize CSS block working visually by re-wrapping the accepted content - // in a data-impeccable-variant="N" div with `display: contents` (so layout - // isn't affected). The carbonize agent strips this attribute + wrapper when - // it moves the CSS to a proper stylesheet. - // - // Style attribute syntax has to follow the host file's flavor — JSX files - // need the object form, otherwise React 19 throws "Failed to set indexed - // property [0] on CSSStyleDeclaration" while parsing the string char-by-char. - if (cssContent) { - const styleAttr = isJsx ? "style={{ display: 'contents' }}" : 'style="display: contents"'; - replacement.push(indent + '
'); - replacement.push(...restored); - replacement.push(indent + '
'); - } else { - replacement.push(...restored); - } + const replacement = buildCarbonizeReplacement({ + indent, + commentSyntax, + isJsx, + id, + variantNum, + cssContent, + paramValues, + restored, + }); const newLines = [ ...lines.slice(0, replaceRange.start), @@ -285,6 +380,34 @@ function handleAccept(id, variantNum, lines, targetFile, paramValues) { return { carbonize: needsCarbonize, acceptedOriginalText: originalContent.join('\n') }; } +function readSourceShadowPreviewMeta(content, id) { + const escaped = escapeRegExp(id); + const wrapperRe = new RegExp('<[^>]+data-impeccable-variants=(["\'])' + escaped + '\\1[^>]*>'); + const match = String(content || '').match(wrapperRe); + if (!match) return null; + const tag = match[0]; + if (readHtmlAttr(tag, 'data-impeccable-preview') !== 'source-shadow') return null; + const sourceFile = readHtmlAttr(tag, 'data-impeccable-source-file'); + const sourceStartLine = Number(readHtmlAttr(tag, 'data-impeccable-source-start')); + const sourceEndLine = Number(readHtmlAttr(tag, 'data-impeccable-source-end')); + if (!sourceFile || !Number.isFinite(sourceStartLine) || !Number.isFinite(sourceEndLine)) return null; + return { sourceFile, sourceStartLine, sourceEndLine }; +} + +function readHtmlAttr(tag, name) { + const match = String(tag || '').match(new RegExp('\\s' + escapeRegExp(name) + '\\s*=\\s*(["\'])(.*?)\\1')); + if (!match) return null; + return decodeHtmlAttr(match[2]); +} + +function decodeHtmlAttr(value) { + return String(value || '') + .replace(/"/g, '"') + .replace(/</g, '<') + .replace(/>/g, '>') + .replace(/&/g, '&'); +} + // --------------------------------------------------------------------------- // Parsing helpers // --------------------------------------------------------------------------- @@ -405,16 +528,19 @@ function stripStyleAndJoin(lines, block) { let line = lines[i]; if (!inStyle) { - // An unclosed , or an unclosed opener through end - // of line — so the result provably cannot retain a . @@ -432,8 +558,7 @@ function stripStyleAndJoin(lines, block) { /** * Find the inner content of `…` inside `text`, * handling nested same-tag elements via depth counting. `attrMatch` is a - * regex source fragment that must appear inside the opener tag; callers must - * pre-escape any dynamic (non-constant) portion with `escapeRegExp`. + * regex source fragment that must appear inside the opener tag. * Returns the inner string (may be empty), or null if not found. */ function extractInnerByAttr(text, attrMatch) { @@ -481,7 +606,7 @@ function extractOriginal(lines, block) { */ function extractVariant(lines, block, variantNum) { const text = stripStyleAndJoin(lines, block); - const inner = extractInnerByAttr(text, 'data-impeccable-variant="' + escapeRegExp(variantNum) + '"'); + const inner = extractInnerByAttr(text, 'data-impeccable-variant="' + variantNum + '"'); if (inner === null) return null; const result = inner.split('\n'); // Collapse a lone empty leading/trailing line (common after string splice). @@ -684,4 +809,4 @@ if (_running?.endsWith('live-accept.mjs') || _running?.endsWith('live-accept.mjs acceptCli(); } -export { findMarkerBlock, extractOriginal, extractVariant, extractCss, deindentContent, detectCommentSyntax, scrubManualEditsAgainstFile, scrubManualEditsAgainstOriginalBlock }; +export { findMarkerBlock, extractOriginal, extractVariant, extractCss, deindentContent, detectCommentSyntax, scrubManualEditsAgainstFile, scrubManualEditsAgainstOriginalBlock, applyDeferredSvelteComponentAccepts }; diff --git a/packages/workflows/skills/impeccable/scripts/live-browser-dom.js b/packages/workflows/skills/impeccable/scripts/live-browser-dom.js new file mode 100644 index 0000000000..ad6a794b38 --- /dev/null +++ b/packages/workflows/skills/impeccable/scripts/live-browser-dom.js @@ -0,0 +1,146 @@ +/** + * Browser-side DOM helpers for Impeccable live mode. + * + * Kept separate from live-browser.js so future browser script parts can share + * chrome mounting, lookup, focus, and picker helpers without depending on the + * full overlay UI bundle. + */ +(function (root) { + 'use strict'; + if (!root) return; + + function createLiveBrowserDomHelpers({ + prefix, + skipTags, + document: doc = root.document, + css = root.CSS, + crypto = root.crypto, + } = {}) { + if (!prefix) throw new Error('prefix required'); + if (!doc) throw new Error('document required'); + const tagsToSkip = skipTags || new Set(); + + function own(el) { + return el && (el.id?.startsWith(prefix) || el.closest?.('[id^="' + prefix + '"]')); + } + + function pickable(el) { + if (!el || el.nodeType !== 1) return false; + if (tagsToSkip.has(String(el.tagName || '').toLowerCase())) return false; + if (own(el)) return false; + const r = el.getBoundingClientRect(); + return r.width >= 20 && r.height >= 20; + } + + function desc(el) { + if (!el) return ''; + let s = el.tagName.toLowerCase(); + if (el.id) s += '#' + el.id; + else if (el.classList.length) s += '.' + [...el.classList].slice(0, 2).join('.'); + return s; + } + + function rectIsUsableAnchor(rect) { + return !!rect && rect.width > 0.5 && rect.height > 0.5; + } + + function makeFrozenAnchor(el) { + if (!el || !el.getBoundingClientRect) return null; + const r = el.getBoundingClientRect(); + if (!rectIsUsableAnchor(r)) return null; + const rect = { + x: r.x, y: r.y, + top: r.top, left: r.left, + right: r.right, bottom: r.bottom, + width: r.width, height: r.height, + }; + return { + __impeccableFrozenAnchor: true, + tagName: el.tagName || 'DIV', + id: el.id || '', + classList: el.classList ? [...el.classList] : [], + hasAttribute: () => false, + getBoundingClientRect: () => rect, + }; + } + + function id8() { + if (crypto?.randomUUID) return crypto.randomUUID().replace(/-/g, '').slice(0, 8); + return (Math.random().toString(16).slice(2) + Date.now().toString(16)).slice(0, 8); + } + + function cssId(id) { + if (css?.escape) return css.escape(id); + return String(id).replace(/([ !"#$%&'()*+,./:;<=>?@[\\\]^`{|}~])/g, '\\$1'); + } + + function liveUiRoot() { + const uiRoot = root.__IMPECCABLE_LIVE_UI_ROOT__; + if (uiRoot && typeof uiRoot.appendChild === 'function') return uiRoot; + return doc.body; + } + + function uiAppend(el) { + liveUiRoot().appendChild(el); + return el; + } + + function uiAppendStyle(styleEl) { + const uiRoot = liveUiRoot(); + if (uiRoot && uiRoot !== doc.body) uiRoot.appendChild(styleEl); + else doc.head.appendChild(styleEl); + return styleEl; + } + + function uiGetById(id) { + const uiRoot = liveUiRoot(); + if (uiRoot?.getElementById) { + const found = uiRoot.getElementById(id); + if (found) return found; + } + if (uiRoot?.querySelector) { + const found = uiRoot.querySelector('#' + cssId(id)); + if (found) return found; + } + return doc.getElementById(id); + } + + function activeElementDeep() { + let active = doc.activeElement; + while (active?.shadowRoot?.activeElement) active = active.shadowRoot.activeElement; + return active; + } + + function defangOutsideHandlers(rootEl, { setPointerEvents = true } = {}) { + if (!rootEl) return; + if (setPointerEvents) { + rootEl.style.setProperty('pointer-events', 'auto', 'important'); + } + const stop = (e) => e.stopPropagation(); + rootEl.addEventListener('pointerdown', stop); + rootEl.addEventListener('mousedown', stop); + rootEl.addEventListener('focusin', stop); + } + + return { + own, + pickable, + desc, + rectIsUsableAnchor, + makeFrozenAnchor, + id8, + cssId, + liveUiRoot, + uiAppend, + uiAppendStyle, + uiGetById, + activeElementDeep, + defangOutsideHandlers, + }; + } + + root.__IMPECCABLE_LIVE_DOM__ = { + version: 1, + createLiveBrowserDomHelpers, + }; +})(typeof window !== 'undefined' ? window : globalThis); diff --git a/packages/workflows/skills/impeccable/scripts/live-browser.js b/packages/workflows/skills/impeccable/scripts/live-browser.js index d888ce5e93..bd4d56e36e 100644 --- a/packages/workflows/skills/impeccable/scripts/live-browser.js +++ b/packages/workflows/skills/impeccable/scripts/live-browser.js @@ -1,11 +1,11 @@ /** - * Impeccable Live Variant Mode — Browser Script + * Impeccable Live Variant Mode - Browser Script * * Injected into the user's page via \n\n` + out; + } + } + + if (!out.includes(SVELTE_LAYOUT_MARKER_OPEN)) { + const block = `${SVELTE_LAYOUT_MARKER_OPEN}\n\n${SVELTE_LAYOUT_MARKER_CLOSE}\n`; + const renderMatch = out.match(/\{@render\s+children(?:\?\.)?\(\)\s*\}/); + const slotMatch = out.match(//); + const match = renderMatch || slotMatch; + if (match) { + out = out.slice(0, match.index) + block + out.slice(match.index); + } else { + out = out.replace(/\s*$/, '\n\n' + block); + } + } + + return out; +} + +export function unpatchSvelteLayout(content) { + let out = String(content || ''); + const blockRe = new RegExp( + '([ \\t]*)' + escapeRegExp(SVELTE_LAYOUT_MARKER_OPEN) + + '\\n\\n' + + escapeRegExp(SVELTE_LAYOUT_MARKER_CLOSE) + + '\\n?', + 'g', + ); + out = out.replace(blockRe, '$1'); + out = out.replace(new RegExp('^\\s*' + escapeRegExp(SVELTE_ROOT_IMPORT) + '\\s*\\n?', 'gm'), ''); + out = out.replace(/ +`; +} + +function findSvelteKitAppHtml(cwd, config) { + const files = Array.isArray(config?.files) ? config.files : ['src/app.html']; + for (const rel of files) { + if (rel.includes('*')) continue; + const normalized = rel.split(path.sep).join('/'); + if (!normalized.endsWith('app.html')) continue; + const abs = path.join(cwd, normalized); + if (fs.existsSync(abs)) return normalized; + } + const fallback = 'src/app.html'; + return fs.existsSync(path.join(cwd, fallback)) ? fallback : null; +} + +function findSvelteKitLayout(cwd) { + const candidates = [ + 'src/routes/+layout.svelte', + 'src/routes/(app)/+layout.svelte', + ]; + for (const rel of candidates) { + if (fs.existsSync(path.join(cwd, rel))) return rel; + } + return 'src/routes/+layout.svelte'; +} + +function defaultSvelteLayout() { + return `\n\n{@render children?.()}\n`; +} + +function packageHasSvelteKit(cwd) { + const file = path.join(cwd, 'package.json'); + if (!fs.existsSync(file)) return false; + try { + const pkg = JSON.parse(fs.readFileSync(file, 'utf-8')); + const deps = { + ...(pkg.dependencies || {}), + ...(pkg.devDependencies || {}), + ...(pkg.peerDependencies || {}), + }; + return Boolean(deps['@sveltejs/kit'] || deps['@sveltejs/vite-plugin-svelte'] || deps.svelte); + } catch { + return false; + } +} + +function fileIncludes(file, text) { + try { + return fs.readFileSync(file, 'utf-8').includes(text); + } catch { + return false; + } +} + +function pruneEmptyDir(dir, stopDir) { + let current = dir; + while (current.startsWith(stopDir) && current !== stopDir) { + try { + if (fs.readdirSync(current).length > 0) return; + fs.rmdirSync(current); + current = path.dirname(current); + } catch { + return; + } + } +} + +function escapeRegExp(value) { + return String(value).replace(/[.*+?^${}()|[\]\\]/g, '\\$&'); +} diff --git a/packages/workflows/skills/impeccable/scripts/live/ui-core.mjs b/packages/workflows/skills/impeccable/scripts/live/ui-core.mjs new file mode 100644 index 0000000000..bbb2c5c35e --- /dev/null +++ b/packages/workflows/skills/impeccable/scripts/live/ui-core.mjs @@ -0,0 +1,180 @@ +/** + * Framework-neutral Impeccable live chrome contract. + * + * The production browser bundle is intentionally plain DOM so Svelte, React, + * Vue, and static adapters can all mount the same chrome. This module is the + * testable contract/inventory for that bundle; live-browser.js mirrors these + * values at runtime because it is served as a standalone script. + */ + +export const LIVE_CHROME_MOUNT_CONTRACT = Object.freeze([ + 'root', + 'transport', + 'state', + 'actions', +]); + +export const LIVE_UI_SURFACES = Object.freeze([ + { + key: 'global-bottom-bar', + ids: [ + 'impeccable-live-global-bar', + 'impeccable-live-global-bar-brand', + 'impeccable-live-pick-toggle', + 'impeccable-live-insert-toggle', + 'impeccable-live-detect-toggle', + 'impeccable-live-detect-badge', + 'impeccable-live-design-toggle', + 'impeccable-live-page-chat', + 'impeccable-live-page-chat-input', + 'impeccable-live-page-chat-voice', + ], + states: ['rest', 'hover', 'focus-visible', 'pressed', 'active', 'tooltip'], + }, + { + key: 'pending-copy-edit-dock', + ids: ['impeccable-live-pending-dock'], + states: ['closed', 'open', 'hover', 'pressed', 'loading', 'rollback', 'keep-fixing'], + }, + { + key: 'element-selection-chrome', + ids: [ + 'impeccable-live-highlight', + 'impeccable-live-tooltip', + 'impeccable-live-bar', + 'impeccable-live-selection-pill', + 'impeccable-live-input', + 'impeccable-live-configure-voice', + 'impeccable-live-configure-bar-tooltip', + ], + states: ['rest', 'hover', 'focus-visible', 'pressed', 'disabled'], + }, + { + key: 'action-picker', + ids: ['impeccable-live-picker'], + states: ['closed', 'open', 'option-hover', 'option-focus'], + }, + { + key: 'edit-chrome', + ids: ['impeccable-live-edit-badge'], + states: ['enabled', 'disabled', 'editing', 'cancel', 'save', 'edited-content'], + }, + { + key: 'generating-row', + ids: ['impeccable-live-bar', 'impeccable-live-shader'], + states: ['action-label', 'animated-dots', 'generating', 'done'], + }, + { + key: 'variant-cycling-row', + ids: ['impeccable-live-bar', 'impeccable-live-params-panel'], + states: ['variant-1', 'variant-2', 'variant-3', 'left-disabled', 'right-disabled', 'dot-click', 'accept', 'discard'], + }, + { + key: 'variant-params-panel', + ids: ['impeccable-live-params-panel'], + states: ['closed', 'open-above', 'open-below', 'range', 'steps', 'toggle'], + }, + { + key: 'saving-confirmed-rows', + ids: ['impeccable-live-bar'], + states: ['saving', 'applying-variant', 'confirmed'], + }, + { + key: 'insert-mode-chrome', + ids: [ + 'impeccable-live-insert-line', + 'impeccable-live-insert-placeholder', + 'impeccable-live-placeholder-resize', + 'impeccable-live-insert-input', + 'impeccable-live-insert-voice', + 'impeccable-live-insert-create', + 'impeccable-live-insert-create-tooltip', + ], + states: ['toggle-active', 'line', 'placeholder', 'resize', 'enabled', 'disabled', 'tooltip'], + }, + { + key: 'annotation-chrome', + ids: [ + 'impeccable-live-annot', + 'impeccable-live-annot-svg', + 'impeccable-live-annot-pins', + 'impeccable-live-annot-clear', + ], + states: ['overlay', 'drawing', 'pin', 'pin-edit', 'clear'], + }, + { + key: 'design-system-panel', + ids: ['impeccable-live-design-host'], + states: ['closed', 'open', 'tabs', 'token-tiles', 'copy'], + }, + { + key: 'toasts-and-errors', + ids: ['impeccable-live-toast'], + states: ['normal', 'error', 'no-variants-mounted'], + }, + { + key: 'css-isolation-boundary', + ids: ['impeccable-live-root'], + states: ['shadow-root', 'style-tags', 'hostile-css'], + }, +]); + +export const LIVE_UI_COMPONENT_IDS = Object.freeze([ + ...new Set(LIVE_UI_SURFACES.flatMap((surface) => surface.ids)), +]); + +export function resolveLiveUiRoot(env = globalThis) { + const doc = env?.document; + const explicit = env?.__IMPECCABLE_LIVE_UI_ROOT__ + || env?.window?.__IMPECCABLE_LIVE_UI_ROOT__; + if (explicit && typeof explicit.appendChild === 'function') return explicit; + return doc?.body || null; +} + +export function getLiveUiElementById(id, env = globalThis) { + const doc = env?.document; + const root = resolveLiveUiRoot(env); + if (!id) return null; + if (root?.getElementById) { + const found = root.getElementById(id); + if (found) return found; + } + if (root?.querySelector) { + const found = root.querySelector('#' + escapeCssIdent(id)); + if (found) return found; + } + return doc?.getElementById?.(id) || null; +} + +export function appendToLiveUiRoot(el, env = globalThis) { + const root = resolveLiveUiRoot(env); + if (!root) throw new Error('Impeccable live UI root is not available'); + root.appendChild(el); + return el; +} + +export function appendStyleToLiveUiRoot(styleEl, env = globalThis) { + const doc = env?.document; + const root = resolveLiveUiRoot(env); + if (root && root !== doc?.body) { + root.appendChild(styleEl); + } else { + (doc?.head || doc?.body || root).appendChild(styleEl); + } + return styleEl; +} + +export function activeElementDeep(doc = globalThis.document) { + let active = doc?.activeElement || null; + while (active?.shadowRoot?.activeElement) { + active = active.shadowRoot.activeElement; + } + return active; +} + +function escapeCssIdent(value) { + if (typeof CSS !== 'undefined' && typeof CSS.escape === 'function') { + return CSS.escape(String(value)); + } + return String(value).replace(/([ !"#$%&'()*+,./:;<=>?@[\\\]^`{|}~])/g, '\\$1'); +} diff --git a/packages/workflows/skills/impeccable/scripts/live/vocabulary.mjs b/packages/workflows/skills/impeccable/scripts/live/vocabulary.mjs new file mode 100644 index 0000000000..5c7b0b713a --- /dev/null +++ b/packages/workflows/skills/impeccable/scripts/live/vocabulary.mjs @@ -0,0 +1,36 @@ +/** + * Canonical design-command vocabulary for Live Mode: each command's value, human + * label, and SVG icon. Icons stack above the chip label; strokes use currentColor + * so the icon recolors when its chip is selected. + * + * Single source of truth, consumed by: + * - skill/scripts/live/event-validation.mjs — re-exports VISUAL_ACTIONS. + * - skill/scripts/live-browser.js — the real picker. It is served raw and + * injected as an IIFE, so it cannot import this at runtime; live-server.mjs + * serializes LIVE_COMMANDS into window.__IMPECCABLE_VOCAB__ alongside the + * token/port, and live-browser.js builds its ICONS + ACTIONS from that. + * - site/components/LiveDemoPalette.astro — the marketing demo palette (imported + * at build time). + * + * Add, rename, or reorder a verb here and all three follow. + */ + +const ICON_ATTRS = 'width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round" style="display:block"'; + +export const LIVE_COMMANDS = [ + { value: 'impeccable', label: 'Freeform', icon: `` }, + { value: 'bolder', label: 'Bolder', icon: `` }, + { value: 'quieter', label: 'Quieter', icon: `` }, + { value: 'distill', label: 'Distill', icon: `` }, + { value: 'polish', label: 'Polish', icon: `` }, + { value: 'typeset', label: 'Typeset', icon: `` }, + { value: 'colorize', label: 'Colorize', icon: `` }, + { value: 'layout', label: 'Layout', icon: `` }, + { value: 'adapt', label: 'Adapt', icon: `` }, + { value: 'animate', label: 'Animate', icon: `` }, + { value: 'delight', label: 'Delight', icon: `` }, + { value: 'overdrive', label: 'Overdrive', icon: `` }, +]; + +// Action values accepted by the live event protocol, in palette order. +export const VISUAL_ACTIONS = LIVE_COMMANDS.map((c) => c.value); From 30f0b5b232c9bf519ff03374325562cbf1ec7302 Mon Sep 17 00:00:00 2001 From: Norin Lavaee Date: Sun, 21 Jun 2026 20:50:37 -0700 Subject: [PATCH 3/7] fix(impeccable): resolve CodeQL findings in bundled skill scripts Address the CodeQL alerts on PR #1470, all in the vendored impeccable skill scripts: make the HTML strip regexes whitespace-tolerant (match ``/``) and strip script/style/comment blocks to a fixpoint so partial overlaps cannot survive one pass (Bad HTML filtering regexp + Incomplete multi-character sanitization in svelte-component.mjs and detector/shared/page.mjs); drop the redundant `String(stack || '')` fallback now that `stack` is guaranteed truthy by the earlier `!stack` guard (detector/browser/injected/index.mjs and detect-antipatterns-browser.js); and remove the unused `outputLines` variable and `attrEscapeDouble` function (live-wrap.mjs). Assistant-model: Claude Opus 4.8 --- .../detector/browser/injected/index.mjs | 2 +- .../detector/detect-antipatterns-browser.js | 2 +- .../scripts/detector/shared/page.mjs | 9 +++++++- .../skills/impeccable/scripts/live-wrap.mjs | 9 -------- .../scripts/live/svelte-component.mjs | 21 +++++++++++++------ 5 files changed, 25 insertions(+), 18 deletions(-) diff --git a/packages/workflows/skills/impeccable/scripts/detector/browser/injected/index.mjs b/packages/workflows/skills/impeccable/scripts/detector/browser/injected/index.mjs index fff811491e..01e08b0bab 100644 --- a/packages/workflows/skills/impeccable/scripts/detector/browser/injected/index.mjs +++ b/packages/workflows/skills/impeccable/scripts/detector/browser/injected/index.mjs @@ -1276,7 +1276,7 @@ if (IS_BROWSER) { function browserPrimaryFont(stack) { if (!stack || /var\(/i.test(stack)) return ''; - return String(stack || '') + return String(stack) .split(',') .map(normalizeBrowserFontName) .find(font => font && !GENERIC_FONTS.has(font)) || ''; diff --git a/packages/workflows/skills/impeccable/scripts/detector/detect-antipatterns-browser.js b/packages/workflows/skills/impeccable/scripts/detector/detect-antipatterns-browser.js index b2091c6098..0cc7ccb421 100644 --- a/packages/workflows/skills/impeccable/scripts/detector/detect-antipatterns-browser.js +++ b/packages/workflows/skills/impeccable/scripts/detector/detect-antipatterns-browser.js @@ -4475,7 +4475,7 @@ if (IS_BROWSER) { function browserPrimaryFont(stack) { if (!stack || /var\(/i.test(stack)) return ''; - return String(stack || '') + return String(stack) .split(',') .map(normalizeBrowserFontName) .find(font => font && !GENERIC_FONTS.has(font)) || ''; diff --git a/packages/workflows/skills/impeccable/scripts/detector/shared/page.mjs b/packages/workflows/skills/impeccable/scripts/detector/shared/page.mjs index b0f6e1ab53..7db2824a4e 100644 --- a/packages/workflows/skills/impeccable/scripts/detector/shared/page.mjs +++ b/packages/workflows/skills/impeccable/scripts/detector/shared/page.mjs @@ -1,6 +1,13 @@ /** Check if content looks like a full page (not a component/partial) */ function isFullPage(content) { - const stripped = content.replace(//g, ''); + // Strip comments to a fixpoint so nested/overlapping comment markers cannot + // survive a single pass (CodeQL: complete sanitization). + let stripped = String(content); + let prev; + do { + prev = stripped; + stripped = stripped.replace(//g, ''); + } while (stripped !== prev); return /]|]/i.test(stripped); } diff --git a/packages/workflows/skills/impeccable/scripts/live-wrap.mjs b/packages/workflows/skills/impeccable/scripts/live-wrap.mjs index 438c01b686..e5d6da7139 100644 --- a/packages/workflows/skills/impeccable/scripts/live-wrap.mjs +++ b/packages/workflows/skills/impeccable/scripts/live-wrap.mjs @@ -310,7 +310,6 @@ The agent should insert variant HTML at insertLine.`); ]; let outputFile = targetFile; - let outputLines; let outputStartLine = startLine + 1; let outputEndLine = startLine + wrapperLines.length + (originalLines.length - 1); let insertLine; @@ -571,14 +570,6 @@ function splitClassList(classes) { return String(classes).split(/[,\s]+/).map(c => c.trim()).filter(Boolean); } -function attrEscapeDouble(str) { - return String(str) - .replace(/&/g, '&') - .replace(/"/g, '"') - .replace(//g, '>'); -} - function detectCommentSyntax(filePath) { const ext = path.extname(filePath).toLowerCase(); if (ext === '.jsx' || ext === '.tsx') { diff --git a/packages/workflows/skills/impeccable/scripts/live/svelte-component.mjs b/packages/workflows/skills/impeccable/scripts/live/svelte-component.mjs index dc35dc0cec..5fa04267b1 100644 --- a/packages/workflows/skills/impeccable/scripts/live/svelte-component.mjs +++ b/packages/workflows/skills/impeccable/scripts/live/svelte-component.mjs @@ -97,7 +97,7 @@ export function substitutePropsWithExprs(markup, contract) { export function parseSvelteComponentFile(content) { const text = String(content || ''); - const scriptMatch = text.match(/^([\s\S]*?)]*>[\s\S]*?<\/script>/i); + const scriptMatch = text.match(/^([\s\S]*?)]*>[\s\S]*?<\/script\s*>/i); const withoutScript = scriptMatch ? text.slice(scriptMatch[0].length) : text; const styleMatch = withoutScript.match(/]*>[\s\S]*?<\/style\s*>/i); const styleBlock = styleMatch ? styleMatch[0] : ''; @@ -632,15 +632,24 @@ function inlineSvelteComponentInsertAccept({ } function svelteMarkupHasVisibleContent(markup) { - const text = String(markup || '') - .replace(//gi, '') - .replace(//gi, '') - .replace(//g, '') + const raw = String(markup || ''); + // Strip script/style/comment blocks to a fixpoint so partially-overlapping + // sequences cannot survive a single pass (CodeQL: complete sanitization). + let text = raw; + let prev; + do { + prev = text; + text = text + .replace(/]*>[\s\S]*?<\/script\s*>/gi, '') + .replace(/]*>[\s\S]*?<\/style\s*>/gi, '') + .replace(//g, ''); + } while (text !== prev); + text = text .replace(/<[^>]+>/g, ' ') .replace(/\s+/g, ' ') .trim(); if (text.length > 0) return true; - return /<(img|svg|canvas|video|audio|picture|input|button|select|textarea)\b/i.test(markup || ''); + return /<(img|svg|canvas|video|audio|picture|input|button|select|textarea)\b/i.test(raw); } function mergeOriginalTopLevelAttrs(markup, originalMarkup) { From fb5d2fddf1eb5312c678f8e032a4d61d0b2d68c9 Mon Sep 17 00:00:00 2001 From: Norin Lavaee Date: Sun, 21 Jun 2026 21:10:04 -0700 Subject: [PATCH 4/7] fix(impeccable): harden HTML-strip regexes for CodeQL (bad-tag-filter, sanitization) Make script/style end-tag regexes tolerate junk before `>` (``) by using `[^>]*>` instead of `\s*>`, which clears both the js/bad-tag-filter alerts and the dependent js/incomplete-multi-character-sanitization alerts (an unmatched closer left ` `-ms-`; js/identity-replacement), escape backslashes before quotes when building the variant selector (js/incomplete-sanitization), and run `git check-ignore` via execFileSync with an argv array instead of a shell string (js/shell-command-injection-from-environment). Assistant-model: Claude Opus 4.8 --- .../scripts/detector/detect-antipatterns-browser.js | 4 ++-- .../scripts/detector/engines/regex/detect-text.mjs | 6 +++--- .../skills/impeccable/scripts/detector/rules/checks.mjs | 4 ++-- .../skills/impeccable/scripts/lib/is-generated.mjs | 4 ++-- .../workflows/skills/impeccable/scripts/live-accept.mjs | 4 ++-- .../workflows/skills/impeccable/scripts/live-browser.js | 6 +++--- .../skills/impeccable/scripts/live/svelte-component.mjs | 8 ++++---- .../skills/impeccable/scripts/live/sveltekit-adapter.mjs | 2 +- 8 files changed, 19 insertions(+), 19 deletions(-) diff --git a/packages/workflows/skills/impeccable/scripts/detector/detect-antipatterns-browser.js b/packages/workflows/skills/impeccable/scripts/detector/detect-antipatterns-browser.js index 0cc7ccb421..27c4150f32 100644 --- a/packages/workflows/skills/impeccable/scripts/detector/detect-antipatterns-browser.js +++ b/packages/workflows/skills/impeccable/scripts/detector/detect-antipatterns-browser.js @@ -1177,8 +1177,8 @@ function checkHtmlPatterns(html) { // runs in the bundled browser path too, not just the CLI/static path. { const bodyText = html - .replace(/]*>[\s\S]*?<\/script>/gi, ' ') - .replace(/]*>[\s\S]*?<\/style>/gi, ' ') + .replace(/]*>[\s\S]*?<\/script[^>]*>/gi, ' ') + .replace(/]*>[\s\S]*?<\/style[^>]*>/gi, ' ') .replace(/<[^>]+>/g, ' '); const tm = /\b(\w+)\s+theater\b/i.exec(bodyText); if (tm) findings.push({ id: 'theater-slop-phrase', snippet: `"${tm[0].trim()}"` }); diff --git a/packages/workflows/skills/impeccable/scripts/detector/engines/regex/detect-text.mjs b/packages/workflows/skills/impeccable/scripts/detector/engines/regex/detect-text.mjs index abbdd7b1ce..719f0c782f 100644 --- a/packages/workflows/skills/impeccable/scripts/detector/engines/regex/detect-text.mjs +++ b/packages/workflows/skills/impeccable/scripts/detector/engines/regex/detect-text.mjs @@ -19,8 +19,8 @@ const isSafeElement = (line) => /<(?:blockquote|nav[\s>]|pre[\s>]|code[\s>]|a\s| * content-text analyzers don't false-positive on code or CSS. */ function stripHtmlToText(html) { return html - .replace(/]*>[\s\S]*?<\/script>/gi, ' ') - .replace(/]*>[\s\S]*?<\/style>/gi, ' ') + .replace(/]*>[\s\S]*?<\/script[^>]*>/gi, ' ') + .replace(/]*>[\s\S]*?<\/style[^>]*>/gi, ' ') .replace(//g, ' ') .replace(/<[^>]+>/g, ' ') .replace(/\s+/g, ' '); @@ -347,7 +347,7 @@ function extractStyleBlocks(content, ext) { ext = ext.toLowerCase(); if (ext !== '.vue' && ext !== '.svelte') return []; const blocks = []; - const re = /]*>([\s\S]*?)<\/style>/gi; + const re = /]*>([\s\S]*?)<\/style[^>]*>/gi; let m; while ((m = re.exec(content)) !== null) { const before = content.substring(0, m.index); diff --git a/packages/workflows/skills/impeccable/scripts/detector/rules/checks.mjs b/packages/workflows/skills/impeccable/scripts/detector/rules/checks.mjs index 747d9a10f4..cac7940485 100644 --- a/packages/workflows/skills/impeccable/scripts/detector/rules/checks.mjs +++ b/packages/workflows/skills/impeccable/scripts/detector/rules/checks.mjs @@ -578,8 +578,8 @@ function checkHtmlPatterns(html) { // runs in the bundled browser path too, not just the CLI/static path. { const bodyText = html - .replace(/]*>[\s\S]*?<\/script>/gi, ' ') - .replace(/]*>[\s\S]*?<\/style>/gi, ' ') + .replace(/]*>[\s\S]*?<\/script[^>]*>/gi, ' ') + .replace(/]*>[\s\S]*?<\/style[^>]*>/gi, ' ') .replace(/<[^>]+>/g, ' '); const tm = /\b(\w+)\s+theater\b/i.exec(bodyText); if (tm) findings.push({ id: 'theater-slop-phrase', snippet: `"${tm[0].trim()}"` }); diff --git a/packages/workflows/skills/impeccable/scripts/lib/is-generated.mjs b/packages/workflows/skills/impeccable/scripts/lib/is-generated.mjs index 165e1ca807..a7e4d6ec3d 100644 --- a/packages/workflows/skills/impeccable/scripts/lib/is-generated.mjs +++ b/packages/workflows/skills/impeccable/scripts/lib/is-generated.mjs @@ -13,7 +13,7 @@ * within the first ~300 characters — catches non-git projects. */ -import { execSync } from 'node:child_process'; +import { execFileSync } from 'node:child_process'; import fs from 'node:fs'; import path from 'node:path'; @@ -41,7 +41,7 @@ export function isGeneratedFile(filePath, options = {}) { function isGitIgnored(absPath, cwd) { try { - execSync(`git check-ignore --quiet ${JSON.stringify(absPath)}`, { + execFileSync('git', ['check-ignore', '--quiet', absPath], { cwd, stdio: 'ignore', }); diff --git a/packages/workflows/skills/impeccable/scripts/live-accept.mjs b/packages/workflows/skills/impeccable/scripts/live-accept.mjs index 278dfbb2e5..3cfaab639e 100644 --- a/packages/workflows/skills/impeccable/scripts/live-accept.mjs +++ b/packages/workflows/skills/impeccable/scripts/live-accept.mjs @@ -531,7 +531,7 @@ function stripStyleAndJoin(lines, block) { // Strip any complete ', ) .replace(/\bclassName\s*=\s*\{\s*`([^`]*?)`\s*\}/g, (_match, value) => { @@ -5640,7 +5640,7 @@ let out = String(prop || '').trim().replace(/^["']|["']$/g, ''); if (!out) return ''; if (out.startsWith('--')) return out; - return out.replace(/[A-Z]/g, (ch) => '-' + ch.toLowerCase()).replace(/^-ms-/, '-ms-'); + return out.replace(/[A-Z]/g, (ch) => '-' + ch.toLowerCase()).replace(/^ms-/, '-ms-'); } function buildSvelteExpressionTextMap(sourceOriginal, liveOriginal) { diff --git a/packages/workflows/skills/impeccable/scripts/live/svelte-component.mjs b/packages/workflows/skills/impeccable/scripts/live/svelte-component.mjs index 5fa04267b1..1d68a06b26 100644 --- a/packages/workflows/skills/impeccable/scripts/live/svelte-component.mjs +++ b/packages/workflows/skills/impeccable/scripts/live/svelte-component.mjs @@ -97,9 +97,9 @@ export function substitutePropsWithExprs(markup, contract) { export function parseSvelteComponentFile(content) { const text = String(content || ''); - const scriptMatch = text.match(/^([\s\S]*?)]*>[\s\S]*?<\/script\s*>/i); + const scriptMatch = text.match(/^([\s\S]*?)]*>[\s\S]*?<\/script[^>]*>/i); const withoutScript = scriptMatch ? text.slice(scriptMatch[0].length) : text; - const styleMatch = withoutScript.match(/]*>[\s\S]*?<\/style\s*>/i); + const styleMatch = withoutScript.match(/]*>[\s\S]*?<\/style[^>]*>/i); const styleBlock = styleMatch ? styleMatch[0] : ''; const markup = styleMatch ? withoutScript.slice(0, styleMatch.index).trim() @@ -640,8 +640,8 @@ function svelteMarkupHasVisibleContent(markup) { do { prev = text; text = text - .replace(/]*>[\s\S]*?<\/script\s*>/gi, '') - .replace(/]*>[\s\S]*?<\/style\s*>/gi, '') + .replace(/]*>[\s\S]*?<\/script[^>]*>/gi, '') + .replace(/]*>[\s\S]*?<\/style[^>]*>/gi, '') .replace(//g, ''); } while (text !== prev); text = text diff --git a/packages/workflows/skills/impeccable/scripts/live/sveltekit-adapter.mjs b/packages/workflows/skills/impeccable/scripts/live/sveltekit-adapter.mjs index f5087c189c..5b37013ab5 100644 --- a/packages/workflows/skills/impeccable/scripts/live/sveltekit-adapter.mjs +++ b/packages/workflows/skills/impeccable/scripts/live/sveltekit-adapter.mjs @@ -132,7 +132,7 @@ export function unpatchSvelteLayout(content) { ); out = out.replace(blockRe, '$1'); out = out.replace(new RegExp('^\\s*' + escapeRegExp(SVELTE_ROOT_IMPORT) + '\\s*\\n?', 'gm'), ''); - out = out.replace(/` match: this line only removes Svelte's empty-script compiler artifact, and the broader pattern made CodeQL's js/bad-tag-filter treat it as a (bad) general script-tag filter. Assistant-model: Claude Opus 4.8 --- .../skills/impeccable/scripts/live/sveltekit-adapter.mjs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/packages/workflows/skills/impeccable/scripts/live/sveltekit-adapter.mjs b/packages/workflows/skills/impeccable/scripts/live/sveltekit-adapter.mjs index 5b37013ab5..f5087c189c 100644 --- a/packages/workflows/skills/impeccable/scripts/live/sveltekit-adapter.mjs +++ b/packages/workflows/skills/impeccable/scripts/live/sveltekit-adapter.mjs @@ -132,7 +132,7 @@ export function unpatchSvelteLayout(content) { ); out = out.replace(blockRe, '$1'); out = out.replace(new RegExp('^\\s*' + escapeRegExp(SVELTE_ROOT_IMPORT) + '\\s*\\n?', 'gm'), ''); - out = out.replace(/]*>\s*<\/script[^>]*>\s*\n?/g, ''); + out = out.replace(/