diff --git a/README.md b/README.md
index bd0bb70..611bfd7 100644
--- a/README.md
+++ b/README.md
@@ -941,7 +941,7 @@ Whenever the `coverage` category runs on a **base** canvas, the result also carr
| Param | Type | Description |
|-------|------|-------------|
| `canvasId` | string | Canvas ID to evaluate |
-| `mode` | `"fast"` \| `"detailed"` \| `"llm"` | `"fast"` = JSON-tree analysis only (<100ms). `"detailed"` adds Puppeteer-based pixel-level overlap checks, laid out at the canvas's artboard size. `"llm"` runs fast-mode heuristics plus a vision-model critique (provider picked from `FRAMESMITH_LLM_PROVIDER` or whichever of `ANTHROPIC_API_KEY` / `OPENAI_API_KEY` is set — costs one paid API call per invocation). Default `"fast"`. |
+| `mode` | `"fast"` \| `"detailed"` \| `"llm"` | `"fast"` = JSON-tree analysis only (<100ms). `"detailed"` adds Puppeteer-based pixel-level overlap checks, laid out at the canvas's artboard size in the design system's own fonts, as `screenshot` and `canvas_stress` render them (a face that cannot load falls back, and the result then carries a `Font warnings` item). `"llm"` runs fast-mode heuristics plus a vision-model critique (provider picked from `FRAMESMITH_LLM_PROVIDER` or whichever of `ANTHROPIC_API_KEY` / `OPENAI_API_KEY` is set — costs one paid API call per invocation). Default `"fast"`. |
| `categories` | string[]? | Subset of `spacing`, `color`, `typography`, `structure`, `consistency`, `cliche`, `coverage`, `usability`. Defaults to all. |
| `genre` | string? | Style that relaxes specific `cliche` gates — `"material"` allows purple and white elevated surfaces; `"data"` (alias `"dashboard"`) allows realistic figures on a screen whose numbers are the user's own data (dashboards, activity, finance, fitness, logistics); `"commerce"` (alias `"checkout"`) allows the money on a transactional screen — cart, checkout, order confirmation, billing history. Defaults to the canvas's stored genre (`canvas_set_genre` stamps it durably, no token churn; `apply_preset` never changes it). Replaces only the genre: a material-preset canvas keeps the material relaxation. Pick by what the screen is *for* (read screens with the user's own figures → `data`; a screen you complete a purchase on → `commerce`; the Material style → `material` (an editor or admin console is type `"desktop-app"`, not a genre); a pricing page is marketing and gets none of them), not what it contains — the result's `genre` field audits the choice. |
@@ -1080,7 +1080,7 @@ Content stress test — does the design survive real data? Re-renders the canvas
| `empty` | Detected tables lose their data rows (and runs of two or more consecutive `list-row`s are emptied; on a desktop-app canvas also runs of `nav-item`, `tree-row`, `menu-row` or `property-row`, and card grids) |
| `many` | Data rows ×3 (and `list-row` runs ×3; on a desktop-app canvas also runs of `nav-item`, `tree-row`, `menu-row` or `property-row`, and card grids, a grid of three or more same-shaped children). Copies drop `active`, so a tripled list keeps one current row |
-Finding kinds: `clip` (content cut off — *info* when a designed `text-overflow: ellipsis` is doing its job, or when it's a primitive's label hitting its designed ellipsis, or a root with an authored `overflow` clipping or scrolling inside itself; the vertical overflow of a sheet or of any frame with `overflow: "auto"` (an app pane) scrolls and is never a clip, while its horizontal overflow still is; *warning* otherwise), `overflow-x` (a node escapes its parent box or the canvas), `layout-shift` (an **untouched** node ballooning — perturbed nodes, their ancestors, and a stretch sibling that merely follows a legitimately growing parent are exempt). Only **new** breakage counts: anything already clipping at baseline is the design's standing state. Tables are found with the same inventory drift and coverage use; component instances are expanded first.
+Finding kinds: `clip` (content cut off — *info* when a designed `text-overflow: ellipsis` is doing its job, or when it's a primitive's label hitting its designed ellipsis, or a root with an authored `overflow` clipping or scrolling inside itself; the vertical overflow of a sheet, a `drawer`, or any frame, `popover` or `menu` with `overflow: "auto"` (an app pane, a popover whose body scrolls) scrolls and is never a clip, while its horizontal overflow still is; *warning* otherwise), `overflow-x` (a node escapes its parent box or the canvas), `layout-shift` (an **untouched** node ballooning — perturbed nodes, their ancestors, and a stretch sibling that merely follows a legitimately growing parent are exempt). Only **new** breakage counts: anything already clipping at baseline is the design's standing state. Tables are found with the same inventory drift and coverage use; component instances are expanded first.
| Param | Type | Description |
|-------|------|-------------|
diff --git a/VISION.md b/VISION.md
index 7af0cfb..9e88f13 100644
--- a/VISION.md
+++ b/VISION.md
@@ -575,7 +575,11 @@ Run on its own viewer (2026-11-08), framesmith scored every page's usability 100
- [ ] Follow-up — a disabled control inside a component instance renders undimmed, because instances render after variable resolution (`resolveInstance`); resolve instance subtrees too, so `disabled` and `state` dim inside components as they do outside
- [x] Slice H — state checks: focus rings, active indicators, disabled renders and control boundaries checked analytically on every interactive primitive, without being drawn, in each theme; text inside a disabled target is exempt from text contrast on every type
- [ ] Follow-up — `select` is not in the boundary check, though its `$border` is its only boundary too; and `tree-row` and the contained `tabs` draw no indicator mark when active (a tint and a heavier weight only), so the active-indicator check has nothing to measure on them
-- [ ] Slice I — the acceptance re-run: the viewer's gallery, detail with inspector and archive rebuilt as canvases, with the comment popover and delete-confirm states
+- [x] Slice I — the acceptance re-run: the viewer's gallery, detail with inspector and archive rebuilt as canvases, with the comment popover and delete-confirm states and the empty archive, all six CLEAN in fast and detailed mode in both themes with a CLEAN stress run, and the six baseline defects fixed (`test-viewer-rebuild.ts`); detailed evaluate now lays out in the design system's own fonts, and a drawer or a scrolling popover reads as scrolling under stress
+- [ ] Follow-up — a misspelt `$token` in a non-colour prop (`gap: "$space-xxs"`, which does not exist) resolves to nothing and evaluate says nothing; the slice I rebuild caught one only through its own resolved-tree check. Warn on any `$ref` the merged tokens do not define
+- [ ] Follow-up — `nav-item.count` is not a stress slot, so a sidebar count of "999+" is never exercised; add it (and `tabs.items[].count`) to the big-numbers perturbation
+
+All nine slices are merged and the acceptance re-run passed. The phase is closed.
_Full spec-driven breakdown in [`docs/specs/PHASE-31-SPEC.md`](docs/specs/PHASE-31-SPEC.md). Deliberately out of scope: porting the viewer's code, anchored overlay rendering, keyboard behaviour, narrow-window collapse, the command palette and bulk-selection variants, importer work, and desktop-app rules on web._
diff --git a/docs/GUIDELINES.md b/docs/GUIDELINES.md
index f6eecb9..f9e477c 100644
--- a/docs/GUIDELINES.md
+++ b/docs/GUIDELINES.md
@@ -117,7 +117,7 @@ Start an application screen from a desktop-app realisation, not a web page: see
On web and desktop-app canvases every pointer target is measured against WCAG 2.5.8's 24px floor: the four controls (toggle, checkbox, radio, select) and the clickable primitives (`button`, `list-row`, each `tab-bar` tab and the FAB, each `nav-bar` action, and the [desktop-app vocabulary](#desktop-app-vocabulary): `link`, `text-input`, `nav-item`, each tab of a `tabs` node, `tree-row`, `menu-row`), a modal's close button and actions, and a toast's action. Inline text links and `divider`s are not targets. A lone control first grows to its padded row, two levels up, as before, and a control that is the only target directly inside a `property-row`, `nav-item`, `menu-row` or `list-row` (no link, input or button beside it) is measured by that row's box; a disabled target is neither measured nor in anyone's way; nodes inside a component instance are judged as rendered and reported on the instance. What is still below 24px passes only by WCAG's **spacing exception**: a 24px circle centred on it must reach no other target's box and no other undersized target's circle (circles that only touch pass; a target nested inside another is not its neighbour). Spacing needs rendered positions, so:
-- **Detailed mode** (`canvas_evaluate({ canvasId, mode: "detailed" })`) runs the circle test and is the authority: a failure is an **error** that names the neighbour it reaches.
+- **Detailed mode** (`canvas_evaluate({ canvasId, mode: "detailed" })`) runs the circle test and is the authority: a failure is an **error** that names the neighbour it reaches. It lays the canvas out in the design system's own fonts, as `screenshot` and `canvas_stress` render it, so its boxes are the ones on screen (a face that cannot load falls back, and the result carries a `Font warnings` item).
- **Fast mode** cannot see spacing, so a target below 24px is a **warning** that names the exception and detailed mode. It blocks presenting until you grow the target or a detailed run clears it.
Mobile keeps its own 44px rule (`mobile-touch-target`), which has no spacing exception.
@@ -152,8 +152,8 @@ Wherever you insert an overlay in the tree, it renders in **one overlay layer**
The six overlays take their colours from `$bg-surface`, `$border`, `$text-primary` and `$text-secondary`, and their depth from `$elevation.overlay` (a fallback shadow without it); `fill`, `stroke` and `color` override.
- **`tooltip`** `{ text, x, y }` is a short hint, inverted (`$text-primary` fill, `$bg-surface` text, so light on a dark theme), wrapping at 240px. Text only: it never renders children.
-- **`popover`** `{ x, y, size?: "xs" | "sm" | "md" | "lg", children }` is a panel 192 / 320 / 480 / 640 wide (320 by default; a numeric `width` wins), vertical with 12px padding by default; `layout`, `gap` and `padding` apply as on a frame. A comment box or a filter form.
-- **`menu`** `{ x, y, children }` holds `menu-row`s and `divider`s: 4px padding, at least 192 wide, hugging its rows.
+- **`popover`** `{ x, y, size?: "xs" | "sm" | "md" | "lg", children }` is a panel 192 / 320 / 480 / 640 wide (320 by default; a numeric `width` wins), vertical with 12px padding by default; `layout`, `gap` and `padding` apply as on a frame. A comment box or a filter form. Give it a numeric `height` so fast mode can box it, and `overflow: "auto"` so long content scrolls inside it instead of being cut (stress reads it as scrolling, as it does a `drawer`).
+- **`menu`** `{ x, y, children }` holds `menu-row`s and `divider`s: 4px padding, at least 192 wide, hugging its rows. With a numeric `height`, add `overflow: "auto"` so long rows scroll inside it.
- **`modal`** `{ title, size?: "sm" | "md" | "lg", actions?: [{ label, variant?, state? }], closeLabel?, children }` is 480 / 640 / 960 wide (640 by default), centred over its own scrim, which always covers the artboard (`x` / `y` place the modal's top-left instead). It is never taller than the artboard less 64px (less the insets on a phone). Its header holds the title and a close button named "Close" (`closeLabel` renames it). The body holds the children (vertical, 12px gap) and scrolls when tall, between the header and the actions. `actions` render right-aligned as 32px buttons; an action with no variant renders `secondary`, and the filled ones (`primary`, `destructive`) render rightmost. For a delete confirmation: `actions: [{ label: "Cancel" }, { label: "Delete", variant: "destructive" }]`.
- **`toast`** `{ text, tone?: "neutral" | "success" | "warning" | "danger", action?: { label, state? } }` sits bottom-centre, 24px above the artboard's bottom edge (`x` / `y` place its top-left instead); it hugs its text up to 480px. The tone colours a leading glyph (`$success`, `$warning`, `$danger`, neutral `$text-secondary`; `iconColor` overrides); the text stays `$text-primary`. `danger` renders `role="alert"`.
- **`drawer`** `{ size?: "sm" | "md", scrim?, children }` is a 320 / 480 panel pinned to the right edge at full height, 16px padding; `scrim: true` dims what is behind it.
@@ -486,7 +486,7 @@ The happy path of one static frame with ideal data is half a design. Real UX liv
**The evaluator demands them.** The `coverage` category warns — directive-blocking — when a base canvas carries data-bearing content with no designed states: a detected table demands `empty` + `loading`; a form (3+ input controls: toggles, checkboxes, radios, selects and `text-input`s outside tables, on every type, so an inspector of three text fields counts too) demands `error`. (Table detection requires three matching horizontal rows — two stacked rows are a layout, not data — so the rare header-plus-one-row table goes undetected; name the frame `Table` to claim the shape explicitly. A list whose every row leads with an icon, a dot or a small image is navigation and never detects.) Variant canvases and non-data screens are silent. The result's `coverage: { dataBearing, states, missing }` tells you where you stand, and `canvas_list` shows the designed states per screen.
-**Then stress it.** `canvas_stress` re-renders the canvas under hostile-but-realistic content — `long-text` (×2.2 + an unbroken German compound), `i18n` (×1.4), `big-numbers` (`9` → `999+`, `$1.5M` → `$1,520,847.33`), `empty`, `many` (rows ×3; tables and runs of `list-row`s on every type, and on a desktop-app canvas also runs of `nav-item`, `tree-row`, `menu-row` or `property-row` and card grids, a grid of three or more same-shaped children; a tripled list keeps one active row) — and reports what broke, by node id: `clip` (info when a designed ellipsis is doing its job, or when it's a primitive's label hitting its designed ellipsis, or a root with an authored `overflow` clipping or scrolling inside itself; the vertical overflow of a sheet or of any frame with `overflow: "auto"` scrolls and is never a clip, while its horizontal overflow still is; warning otherwise), `overflow-x`, `layout-shift` (an untouched node ballooning — perturbed nodes, their ancestors, and a stretch sibling that merely follows a legitimately growing parent, like a full-height sidebar next to a growing table, are all exempt). Only *new* breakage counts. Fix findings with the [width strategies](#width-strategies) above — fluid widths, `minWidth` or `minHeight` floors, wrapping — or give a must-stay-single-line label `textOverflow: "ellipsis"` (the designed-truncation property: the clip downgrades to info because truncating is the design) — and re-run until `CLEAN`. A data screen goes to the user with its states designed and a `CLEAN` stress verdict, the same way it goes with a >95 score. `canvas_evaluate` holds you to it: once stress has recorded a verdict, the evaluate result carries a `stress` field (`{ verdict, warnings, type, current }` — `current` is false after an edit or a type change since the run), and a `FRAGILE` verdict keeps the directive `NOT READY` until a full `CLEAN` run (all five perturbations) replaces it — a subset run can record `FRAGILE` but never clear it. The verdict lives in server memory, so a restart forgets it.
+**Then stress it.** `canvas_stress` re-renders the canvas under hostile-but-realistic content — `long-text` (×2.2 + an unbroken German compound), `i18n` (×1.4), `big-numbers` (`9` → `999+`, `$1.5M` → `$1,520,847.33`), `empty`, `many` (rows ×3; tables and runs of `list-row`s on every type, and on a desktop-app canvas also runs of `nav-item`, `tree-row`, `menu-row` or `property-row` and card grids, a grid of three or more same-shaped children; a tripled list keeps one active row) — and reports what broke, by node id: `clip` (info when a designed ellipsis is doing its job, or when it's a primitive's label hitting its designed ellipsis, or a root with an authored `overflow` clipping or scrolling inside itself; the vertical overflow of a sheet, a `drawer`, or any frame, `popover` or `menu` with `overflow: "auto"` scrolls and is never a clip, while its horizontal overflow still is; warning otherwise), `overflow-x`, `layout-shift` (an untouched node ballooning — perturbed nodes, their ancestors, and a stretch sibling that merely follows a legitimately growing parent, like a full-height sidebar next to a growing table, are all exempt). Only *new* breakage counts. Fix findings with the [width strategies](#width-strategies) above — fluid widths, `minWidth` or `minHeight` floors, wrapping — or give a must-stay-single-line label `textOverflow: "ellipsis"` (the designed-truncation property: the clip downgrades to info because truncating is the design) — and re-run until `CLEAN`. A data screen goes to the user with its states designed and a `CLEAN` stress verdict, the same way it goes with a >95 score. `canvas_evaluate` holds you to it: once stress has recorded a verdict, the evaluate result carries a `stress` field (`{ verdict, warnings, type, current }` — `current` is false after an edit or a type change since the run), and a `FRAGILE` verdict keeps the directive `NOT READY` until a full `CLEAN` run (all five perturbations) replaces it — a subset run can record `FRAGILE` but never clear it. The verdict lives in server memory, so a restart forgets it.
## Reviewing the set
diff --git a/docs/specs/PHASE-31-SPEC.md b/docs/specs/PHASE-31-SPEC.md
index 0079903..6efab40 100644
--- a/docs/specs/PHASE-31-SPEC.md
+++ b/docs/specs/PHASE-31-SPEC.md
@@ -396,6 +396,30 @@ One profile ships, keyed by id so a second size is one table row later. Values i
**Slice I: acceptance (FR-J1)**
- `test-viewer-rebuild.ts` in the full tier, building the viewer canvases from the realisations and asserting FR-J1's numbers, the way `test-ridgeline.ts` pins Phase 30's re-run.
+**Slice I — contracts pinned before build (2026-11-18; amended after the pre-freeze verifier, frozen at the commit that adds this block).** A pre-freeze verifier broke the draft on paper (FR-J1's run is a gate over generated output whose verdict reads earlier stress runs): 13 findings, all folded in below. Four would have failed the build: three twins that never fire as first written, and the stamped editor's form controls demanding an `error` variant.
+- **V1: the path.** `test-viewer-rebuild.ts` drives one MCP server process over stdio through the real tool handlers, as `test-ridgeline.ts` does (its own `FRAMESMITH_HOME` and working dir in the OS temp dir, the viewer pointed at a dead URL; stress records live in that process's memory), and joins the runner's `CHROME_ANYWAY` list, so it runs in the full tier. One project, `project_create({ workspaceId: "default-workspace", name: "framesmith viewer" })`. One design system for the whole app, written at project scope before any canvas exists: `generate_design_system({ projectId, seed: "#B45309", personality: "technical", baseSize: 14 })` (amber, as the viewer's accent; the slice D gate holds every realisation clean under this seed and personality; a project has no type, so the 14px desktop-app pivot is passed explicitly, and it generates the same variables as the desktop-app pivot). Three base canvases, each `canvas_create({ type: "desktop-app", projectId })`, then `apply_structure` with the anatomy name (resolution picks the realisation), then `batch_design`: **Gallery** from `browser` (`browser-app`), **Canvas detail** from `editor-inspector` (`editor-inspector-app`), **Archive** from `split-workbench` (`split-workbench-app`). Three variants by `canvas_add_variant`, each made after its base's last edit, then edited by `batch_design`: the detail's `comment-open` and `confirm-delete`, and the archive's `empty`. No `canvas_autofix`, no `set_variables` and no rule changes in the build, so every canvas's own `variables` stay `{}` (asserted) and everything resolves through the project. The test addresses nodes by the stamp's ids or by ids it sets on inserted nodes, never by position.
+- **V2: the content is the viewer's.** Copy and structure follow the live viewer and the baseline fixtures (`test-fixtures/viewer-baseline/`), adapted where the realisation's anatomy differs. Gallery: a sidebar of five project `nav-item`s with identity `dotColor` dots (`$chart-1` to `$chart-5`; the amber seed yields five series hues) and counts, the current project active, Archive as a secondary item with its count; a header with the project name and the canvas count; type filter `tabs` with counts; canvas cards (a preview, the name as a `link`, size and date meta, the score). Canvas detail: a header with a "Back" `link` (icon `arrow-left`), the canvas name and size; the breakpoint `tabs`, the view actions and the lifecycle actions as primitives; the canvas preview in the work area; an inspector of `tabs` (Quality, Design system, Feedback; Quality active), the score, its eight categories as a run of `property-row`s, and the issue cards. The stamp's form controls are replaced: no base holds three or more of `toggle`, `checkbox`, `radio`, `select`, `text-input`, so no base demands an `error` variant. Archive: the sidebar with Archive active; the archived canvases as `tree-row`s grouped by project (depth 0 the project, depth 1 its canvases, one canvas `active`: `list-row` has no selected state), and the detail panel showing the selected canvas as `property-row`s with Restore and, set apart below a `divider`, a permanent delete. `comment-open`: a `popover` anchored to the Comment `button`, placed under it from the button's `snapshot_layout` box with numeric `x`, `y`, `width` and `height` inside the window, holding a `text-input` (`rows: 3`) and two `sm` buttons (Cancel, Post). `confirm-delete`: a `sm` `modal` titled "Delete canvas?", a body paragraph naming what is lost, actions Cancel and Delete (`variant: "destructive"`). `empty`: the tree replaced by a designed empty state (icon, title, one line saying how a canvas gets archived), the detail panel, its divider and its toggle removed, counts at 0. Data is the viewer's own kind (canvas names, sizes, dates, scores, finding text from the baseline). Every base holds data-like text (scores, counts, sizes), so `big-numbers` has something to perturb.
+- **V3: the verdicts, per canvas (all six).** In this order, after the canvas's last edit: `canvas_stress` with the default set, then `canvas_evaluate` fast, then detailed. (a) Stress: the five default perturbations ran and none was skipped; the verdict is `CLEAN` and no finding is a warning or error; long-text, i18n and big-numbers each touch at least one node on every canvas; `many` and `empty` each touch at least one node on every canvas (runs of `nav-item`, `tree-row` or `property-row`, or the card grid, S5); the count of designed-truncation infos is quoted. `nav-item.count` is not a stress slot (`PRIMITIVE_TEXT_PROPS` has no `count`), so a "999+" project count is knowingly not exercised. (b) Each mode: zero errors, zero warnings, zero cliché tells; the directive starts `READY`; the result's `stress` field is present with `verdict: "CLEAN"`, `current: true` and `type: "desktop-app"` (a canvas never stressed, including a fresh variant, which starts with no record, would otherwise read READY); the score is quoted, not gated (Phase 30 G1's precedent). (c) Both themes: the merged tokens carry a dark colour layer (so the dark run is not vacuous) and no dark-tagged finding is a warning or error. Detailed mode's layout rules read the light render, whose geometry no theme changes; the dark theme is covered by the token checks evaluate runs in both modes (text contrast and the four state rules), which is what "both themes" means for a verdict. (d) `desktop-app-handbuilt-target`: zero findings in either mode. (e) The surface report: `surface.type` is `desktop-app`, every `desktop-app-*` rule id is in `rulesOn` (the list spelled out in the test, not read from `src/surfaces.ts`), and `type-scale-ratio` is in `rulesOff`. `rulesOn` lists the rules enabled, not the rules that found something to measure; the twins (V5) show the rules this rebuild depends on are live, and `desktop-app-row-rhythm` (no detected table on any of the six) is enabled but not exercised, stated in the PR. (f) Coverage: each base's `coverage.missing` is `[]`. (g) No silent skips: no `desktop-app-focus-visible`, `desktop-app-state-contrast` or `desktop-app-boundary` finding of any severity, which rules out the info a state rule raises when it cannot read a backdrop.
+- **V4: the six defects, checked by name** (the baseline's E1 to E6). (1) **Back**: the detail's back control is a `link` (id set by the test) labelled "Back"; detailed evaluate raises no `desktop-app-target` finding naming it, and `snapshot_layout` reads it at least 24 tall. (2) **Inspector tabs**: the inspector holds one `tabs` node whose labels are Quality, Design system and Feedback, exactly one active. (3) **Issue cards**: every issue card (frames named "Issue card") is plain content holding at least one clickable primitive, and V3(d) holds. (4) **Muted labels**: every text node carries an explicit colour that is a `$name` present in the merged tokens, and no string value anywhere in the resolved tree (light and dark) still starts with `$` (a misspelt token would otherwise pass as "a token"); the colour fields scanned are `fill`, `stroke`, `color`, `iconColor`, `secondaryColor`, `badgeColor`, `dotColor`, `borderBottom.color` and `shadows[].color`, and every one that is set on any node is a `$name` too. `$text-secondary` measures at least 4.5:1 against `$bg-primary`, `$bg-surface` and `$bg-elevated` in each theme (the dark layer merged over the light colours, computed in the test with `src/color-math.ts`; measured before build at 5.58 / 6.00 / 5.58 light and 4.64 / 5.38 / 4.64 dark), and evaluate raises no contrast error (V3). (5) **Grouped issues**: no two issue cards carry the same message text, and the card for the repeated baseline finding (display text at 28px with default tracking, four nodes) holds a text naming its count of four nodes. (6) **Delete apart from Archive**: in the detail header, Delete is a `button` with `variant: "destructive"`, Archive a `button` that is neither destructive nor primary; they have different parent ids or, under one parent, a `divider` sits between them by index; the archive's permanent delete is destructive and sits below a `divider` from Restore.
+- **V5: twins** (each rule the verdicts lean on is shown live on these canvases). Run after V3 and V4, on the base canvases (on `comment-open` for (f)); each restores what it changed, and the test then re-runs the full stress on that canvas and asserts the restored canvas is back to V3(b) (`READY`, stress `CLEAN` and `current: true`). (a) A dark-only contrast failure (dark `text-secondary` set to the dark `bg-surface` with `set_variables` on the canvas) raises a dark-tagged error; restored by setting the canvas's `variables` back to `{}` (asserted). (b) The "Back" `link` replaced by the baseline's hand-built form, a horizontal frame 17 tall holding an `arrow-left` icon (`iconSize` 14) and the text "Back", raises a `desktop-app-handbuilt-target` info in fast and detailed mode. (A bare text frame is not FR-C2's shape and is out of scope.) (c) Two `xs` icon-only buttons with `height: 20` (an icon-only button is square, so the box is 20×20) and `ariaLabel`s, adjacent in a gap-0 horizontal frame, raise two `desktop-app-target` errors in detailed mode and two warnings in fast mode. (d) The V4(5) predicate run on a list with a duplicated card message fails (a unit check of the predicate, no tool call). (e) A short text that fits on one line in a fixed-height `overflow: "hidden"` frame at baseline, which long-text's ×2.2 wraps and clips, makes `canvas_stress` record `FRAGILE`, and the next fast evaluate is not `READY`. (f) The `comment-open` popover moved so its box leaves the window raises a `desktop-app-overlay` warning in fast mode. (g) `focus-ring` set on the canvas to the inspector's `bg-surface` raises a `desktop-app-focus-visible` error.
+- **V6: evidence.** `VIEWER_OUT=
` writes, per canvas, light and dark screenshots, the stress and evaluate JSON, and the canvas JSON, plus one crop per defect (`screenshot` with `nodeId`). The PR commits the six defect crops and one dark screenshot per canvas under `docs/viewer-rebuild/` and embeds them; without `VIEWER_OUT` the test writes nothing outside its temp dirs. The verdicts assume the design system's fonts loaded: the test fails on a `Font warnings` item, as `test-ridgeline.ts` does (the full tier needs the network for Google Fonts).
+- **V7: a rule that misfires on a correct idiom** is fixed in this slice (ANALYZE, "Scope"): the fix lands in `src/` with a fixture in the rule's own test that fails before and passes after, and is recorded in "Slice I — as built". A finding that is right about the rebuild is fixed in the canvases, never by switching the rule off.
+- **Spec change S11 (Victor-approved 2026-11-18): detailed evaluate measures in the real fonts.** Detailed `canvas_evaluate` rendered its layout in the system fallback stack (`evaluateCanvas` called `renderToHtml` without render options), while `canvas_stress`, `screenshot` and `snapshot_layout` render through `prepareRender` with the design system's faces, so a detailed CLEAN was judged on other glyph widths than the screen shows. `evaluateCanvas` gains an optional `renderOpts` (the `RenderOptions` `prepareRender` returns: `extraFonts`, `bodyFontFamily`), used by both of its renders (the detailed layout and the mobile-rules layout); the `canvas_evaluate` handler passes it in detailed mode only (fast mode renders nothing and stays offline), with the font warnings `prepareRender` returns added to the result as a `Font warnings` content item, as `screenshot` does. Callers that pass none (tests, the viewer, `project_evaluate`, `canvas_autofix`) keep today's renders. On every type. The slice I PR re-runs `test-ridgeline.ts`, the desktop gates (`test-patterns-desktop.ts`, `test-patterns-desktop-window.ts`) and the full tier, and lists any verdict that moved.
+- **V8: the inputs the verdicts cover** (hard rule 6, the verifier's list): six canvases (three bases, three variants) × two modes × two themes × the five stress perturbations; the overlay kinds the rebuild uses (`popover`, `modal`); every clickable primitive kind it uses (`link`, `button` in `xs` and `sm`, `nav-item` with `dotColor` and `count`, `tabs` line and contained, `text-input` multi-line, `tree-row`); the stress state the directive reads (none, `CLEAN`, `FRAGILE`, stale after an edit, a fresh variant with no record); the project-scope design system inherited by every canvas; detailed mode with and without render options (S11).
+- **V9: agent surfaces and docs.** No new tool, node type, property or rule id is planned, so the discoverability lists do not change unless V7 adds one. S11 changes behaviour, so the `canvas_evaluate` docstring, GUIDELINES and README (where detailed mode is described) say detailed mode renders in the design system's fonts and may return font warnings. VISION ticks slice I and closes Phase 31; this spec gains an as-built block.
+
+**Slice I — as built (recorded 2026-11-18).** S11 above; V1 to V9 held except W1 and W2. Decisions the contracts did not settle:
+- **W1: the twins run on throwaway clones.** `set_variables` merges and cannot return a canvas to empty `variables`, so twins (a) and (g) could not restore the canvas V3 asserts on. Every V5 twin runs on its own `canvas_add_variant` clone of the detail page (state `twin--`; (f) inserts its own off-window popover, since a clone of a variant clones the root base), and the restore-and-re-stress step becomes a check that each of the six judged canvases is still `READY` on its own current `CLEAN` stress run after the twins.
+- **W2: `big-numbers` skips the empty archive.** An empty archive shows no figures, so `big-numbers` has nothing to widen there; inventing a number to perturb would be fabricated content. V3(a)'s "touches at least one node" holds on the other five canvases for all five perturbations, and on the empty archive for the other four.
+- **W3: a V7 fix — overlays that scroll.** S4 marks every `overflow: "auto"` node with `data-fs-scroll`, but overlays build their own attributes and missed it, so the comment popover (a fixed `height`, its body scrolling) and every `drawer` (which always scrolls) read as clipped under `long-text`. `renderOverlay` now marks a `drawer` always and a `popover` or `menu` that authors `overflow: "auto"`. Fixture in `test-overlays-render.ts`, red on 9dc76ad and green on the fix: a fitting 170px popover with `overflow: "auto"` and a drawer of 30 lines raise no clip under `long-text`, the same popover with `overflow: "hidden"` still clips, and the markers appear only where they should. GUIDELINES, README and the `batch_design` and `canvas_stress` docstrings say so; GUIDELINES recommends `overflow: "auto"` on a fixed-height popover.
+- **W4: the detail header.** Long-text pushed the lifecycle actions past the window: the actions group shrinks (`minWidth: 0`), its labelled buttons keep their content width capped at 140, and the breakpoint `tabs` sit in a shrinkable slot (slice D's H7). The canvas size text keeps its content width, so it never wraps under a shrinking breadcrumb. Archive sits with the view actions and a `divider` separates Delete (V4(6)).
+- **W5: the card score sits on the preview.** A title row beside the link took the card to 9 levels (the structure advisory's 8 is a warning), so the score is a badge text inside the preview frame, top right, as the live viewer overlays it.
+- **W6: twin (b) names the slot.** FR-C2 reports the outermost frame that holds only the icon and label, so the finding names the breadcrumb slot ("Parent", 44×17) that wraps the hand-built back control; the twin asserts the rule fires, not which frame it names.
+- **W7: what the rebuild found beyond its scope**, left as VISION follow-ups: a misspelt non-colour token (the rebuild's own `gap: "$space-xxs"`, the token is `$space-3xs`) resolves to nothing with no finding, caught only by the test's resolved-tree check (V4(4)); `nav-item.count` (and `tabs.items[].count`) are not stress slots.
+- **Verify round 1 fixes** (on d7875ff; four delegates: conformance, test adequacy by mutation, a review of the src diff, the docs steward). (a) **S11 had no test**: dropping the fonts from either detailed render, or from the handler, failed nothing. New `test-evaluate-fonts.ts` (full tier, over MCP) sets the body token to the generic `monospace`, which needs no download and is far wider than any sans: a toast that fits in sans leaves the window (the main detailed layout) and a 20px button pushed right by a run of "i"s lands on another 20px button (the 24px-circle layout), with a `sans-serif` twin where neither fires; a face that cannot load returns a `Font warnings` item in detailed mode and none in fast. (b) A family used only inside a component was never loaded (an instance has no children, so `collectReferencedFamilies` never saw it), in detailed evaluate and in `screenshot` and stress alike: `ensureFontsForRender` also walks `canvas.components` (fixture in `test-fonts-by-name.ts`, with a twin). (c) A scroller that overflows sideways still clips, but stress reported it with its height: the clip axis now ignores a scroller's vertical overflow (`compareLayouts`; fixture in `test-overlays-render.ts`). (d) The menu branch of W3 had no test: a menu with `overflow: "auto"` carries the marker and one with `"hidden"` does not. (e) The test now checks evaluate's own `Font warnings` item in both modes, that `big-numbers` is the only perturbation skipped and only on the empty archive, that each canvas sits in the project, that the bases are not data-bearing (so coverage's empty list is stated, not vacuous), that the inspector holds exactly one `tabs`, that the dark layer restates `$text-secondary`, that Confirm delete raises no primary-count info, and three more twins: a never-stressed clone has no `stress` field (h), an edit after a CLEAN run reads `current: false` (i), and two primary actions in one dialog raise the primary-count info (j). (f) A VISION follow-up was wrong and is dropped: stress does report a non-scrolling popover's spill (as a clip); the slice's own fixture spilled 1px, inside the tolerance. Accepted as found: `overflow: "scroll"` on a popover or menu is not read as scrolling, consistent with frames (S4 marks `auto` only, and the docs say `auto`); the contrast and 24px thresholds have no data inside the mutation gap (4.64:1 and exactly 24px), which only a data mutant could close.
+- **After verify round 2 (3b)** (on 5da0ed8; proved red on d7875ff and green on the fix; not re-verified by an agent). The 3b verifier confirmed every round 1 fix, killed all three S11 mutants with `test-evaluate-fonts.ts`, and found one unrecorded effect of fix (c): the clip axis also feeds the root's "page grows taller" downgrade, so a scrolling root (`overflow: "auto"`) that overflows sideways as well as down was reported as that info and now warns on its width, which is the verdict a horizontal root clip always meant to get. A fixture pins it in `test-overlays-render.ts`; a scrolling root that overflows only downwards still raises nothing, and a root without `overflow: "auto"` keeps its info. Accepted as found: fix (b) walks every component definition, so a component that no instance uses but that names a family that cannot load adds a `Font warnings` item to each render of the canvas (the same cost a used one already had); the monospace fixture assumes the platform's `monospace` is a ~0.6em face, as DejaVu Sans Mono and Liberation Mono are; the VISION line closing the phase is written for the merge.
+- **Numbers** (the PR quotes the run): six canvases at 99 or 100 in both modes, every stress run `CLEAN`, zero `desktop-app-handbuilt-target`, every `desktop-app-*` rule enabled and `desktop-app-row-rhythm` not exercised (no table on any of the six).
+
**Every slice** touches the shared agent surfaces in the same PR (the CLAUDE.md discoverability rule): the tool docstrings, `INSTRUCTIONS`, the `init` GOTCHAS where behaviour changes, `docs/GUIDELINES.md`, and `test-discoverability.ts`'s lists (new node types, rule ids, structures).
---
diff --git a/docs/viewer-rebuild/archive-dark.png b/docs/viewer-rebuild/archive-dark.png
new file mode 100644
index 0000000..4c49dc7
Binary files /dev/null and b/docs/viewer-rebuild/archive-dark.png differ
diff --git a/docs/viewer-rebuild/archive-empty-dark.png b/docs/viewer-rebuild/archive-empty-dark.png
new file mode 100644
index 0000000..0e18c8b
Binary files /dev/null and b/docs/viewer-rebuild/archive-empty-dark.png differ
diff --git a/docs/viewer-rebuild/canvas-detail-dark.png b/docs/viewer-rebuild/canvas-detail-dark.png
new file mode 100644
index 0000000..02acfc8
Binary files /dev/null and b/docs/viewer-rebuild/canvas-detail-dark.png differ
diff --git a/docs/viewer-rebuild/comment-open-dark.png b/docs/viewer-rebuild/comment-open-dark.png
new file mode 100644
index 0000000..242523b
Binary files /dev/null and b/docs/viewer-rebuild/comment-open-dark.png differ
diff --git a/docs/viewer-rebuild/confirm-delete-dark.png b/docs/viewer-rebuild/confirm-delete-dark.png
new file mode 100644
index 0000000..5913989
Binary files /dev/null and b/docs/viewer-rebuild/confirm-delete-dark.png differ
diff --git a/docs/viewer-rebuild/defect-1-muted-labels.png b/docs/viewer-rebuild/defect-1-muted-labels.png
new file mode 100644
index 0000000..2bcf386
Binary files /dev/null and b/docs/viewer-rebuild/defect-1-muted-labels.png differ
diff --git a/docs/viewer-rebuild/defect-2-back.png b/docs/viewer-rebuild/defect-2-back.png
new file mode 100644
index 0000000..e2ec867
Binary files /dev/null and b/docs/viewer-rebuild/defect-2-back.png differ
diff --git a/docs/viewer-rebuild/defect-3-inspector-tabs.png b/docs/viewer-rebuild/defect-3-inspector-tabs.png
new file mode 100644
index 0000000..082ba7d
Binary files /dev/null and b/docs/viewer-rebuild/defect-3-inspector-tabs.png differ
diff --git a/docs/viewer-rebuild/defect-4-issue-cards.png b/docs/viewer-rebuild/defect-4-issue-cards.png
new file mode 100644
index 0000000..524431c
Binary files /dev/null and b/docs/viewer-rebuild/defect-4-issue-cards.png differ
diff --git a/docs/viewer-rebuild/defect-5-grouped-issue.png b/docs/viewer-rebuild/defect-5-grouped-issue.png
new file mode 100644
index 0000000..f351126
Binary files /dev/null and b/docs/viewer-rebuild/defect-5-grouped-issue.png differ
diff --git a/docs/viewer-rebuild/defect-6-delete-apart.png b/docs/viewer-rebuild/defect-6-delete-apart.png
new file mode 100644
index 0000000..afc5d30
Binary files /dev/null and b/docs/viewer-rebuild/defect-6-delete-apart.png differ
diff --git a/docs/viewer-rebuild/gallery-dark.png b/docs/viewer-rebuild/gallery-dark.png
new file mode 100644
index 0000000..7145503
Binary files /dev/null and b/docs/viewer-rebuild/gallery-dark.png differ
diff --git a/scripts/run-tests.ts b/scripts/run-tests.ts
index e9b6da8..6cc2223 100644
--- a/scripts/run-tests.ts
+++ b/scripts/run-tests.ts
@@ -38,6 +38,10 @@ const CHROME_ANYWAY = new Set([
// Drives the MCP server over stdio, and the server renders in Chrome for
// detailed evaluate, canvas_stress and screenshots.
'test-ridgeline.ts',
+ // Phase 31's acceptance re-run, the same shape as test-ridgeline.ts.
+ 'test-viewer-rebuild.ts',
+ // Drives canvas_evaluate's detailed mode over MCP (S11's font path).
+ 'test-evaluate-fonts.ts',
]);
/** Direct use of the browser is the honest signal — these are the entry points
diff --git a/src/evaluate.ts b/src/evaluate.ts
index 535d386..b3b0db1 100644
--- a/src/evaluate.ts
+++ b/src/evaluate.ts
@@ -1,7 +1,7 @@
import type { Canvas, SceneNode, DesignVariables, TabItem } from './types.js';
import { resolveVariables } from './variables.js';
import { getCanvasTokens } from './workspaces.js';
-import { renderToHtml, resolveInstance } from './renderer.js';
+import { renderToHtml, resolveInstance, type RenderOptions } from './renderer.js';
import { computeLayout, type LayoutRect } from './screenshot.js';
import {
checkCurrent, checkDesktopArtboard, checkHandbuiltTargetsApp, checkIconLabels, checkOverlays, checkPrimaryCount, checkRowRhythm, checkTruncation,
@@ -2496,7 +2496,13 @@ function reportOnInstances(issues: EvaluationIssue[], owners: Map {
// Resolve variables so $tokens become actual values for contrast checks.
// Tokens flow through workspace → project → canvas inheritance (Phase 9),
@@ -2598,7 +2604,7 @@ export async function evaluateCanvas(
// On a mobile canvas render the tree the mobile rules read: the same
// pixels as the canvas render, with every node inside an instance under
// its own id, so the rects are unambiguous. Web keeps the canvas render.
- const html = expandedRules ? renderToHtml(mobileRoot, w, h, canvas) : renderToHtml(resolvedRoot, w, h, canvas);
+ const html = renderToHtml(expandedRules ? mobileRoot : resolvedRoot, w, h, canvas, options.renderOpts);
detailedLayout = await computeLayout(html, undefined, expandedRules ? 25 : 10, { width: w, height: h });
}
// Phase 31 slice C — the desktop-app rules' view of the canvas.
@@ -2659,7 +2665,7 @@ export async function evaluateCanvas(
const targets = pointerTargets(targetEntries, mobile.width);
let rects: Map | undefined;
if (options.mode === 'detailed' && undersizedTargets(targets).length > 0) {
- const layout = await computeLayout(renderToHtml(mobileRoot, mobile.width, mobile.height, canvas), undefined, 25, { width: mobile.width, height: mobile.height });
+ const layout = await computeLayout(renderToHtml(mobileRoot, mobile.width, mobile.height, canvas, options.renderOpts), undefined, 25, { width: mobile.width, height: mobile.height });
// computeLayout returns a tree (each rect nests its children).
rects = new Map();
const index = (r: LayoutRect) => { rects!.set(r.nodeId, r); r.children?.forEach(index); };
diff --git a/src/fonts.ts b/src/fonts.ts
index 225b9bb..01e45ad 100644
--- a/src/fonts.ts
+++ b/src/fonts.ts
@@ -435,7 +435,15 @@ export async function ensureFontsForRender(
const warnings: string[] = [];
const declared = new Set((canvas.fonts ?? []).map((f) => f.family.toLowerCase()));
- for (const family of collectReferencedFamilies(resolvedRoot, merged)) {
+ // An instance has no children of its own: a family used only inside a
+ // component is found in the component's definition.
+ const families = [...collectReferencedFamilies(resolvedRoot, merged)];
+ for (const component of Object.values(canvas.components ?? {})) {
+ for (const family of collectReferencedFamilies(component)) {
+ if (!families.some((f) => f.toLowerCase() === family.toLowerCase())) families.push(family);
+ }
+ }
+ for (const family of families) {
if (declared.has(family.toLowerCase())) continue;
try {
await resolveFamily(family, opts); // cache hit or one network resolve
diff --git a/src/index.ts b/src/index.ts
index fb1fb6d..988a8fd 100644
--- a/src/index.ts
+++ b/src/index.ts
@@ -606,8 +606,8 @@ Labels truncate to one line with an ellipsis and carry their full text as a titl
Overlays (screen states — put one in a state variant made with canvas_add_variant, e.g. "menu-open", "comment-open", "confirm-delete", "toast"): wherever you insert an overlay in the tree, it renders in ONE overlay layer above all content — never clipped by a scrolling or clipping pane, never under a sticky or fixed bar — stacked by kind, never by a z-index (there is none): popover and menu 400, the modal's scrim 500, modal and drawer 510, toast 600, tooltip 800 (so a menu or popover on a screen with a modal, or a drawer with scrim: true, renders under the scrim; desktop-app-overlay warns). x / y are offsets from the ROOT's top-left (root coordinates), not from the parent; the layer is the artboard box. Insert it wherever it belongs logically (a menu beside the button that opens it) and set anchor: "" (never rendered; desktop-app-overlay reads it: an anchor naming no node, or a node that is not a clickable primitive or control, is an info). To open a menu under a button, its y is the button's ROOT y plus its height: read both from snapshot_layout. Colours default from $bg-surface / $border / $text-primary / $text-secondary and $elevation.overlay depth; fill / stroke / color override.
- tooltip { text, x, y } — inverted ($text-primary fill), wraps at 240px; text only, never children.
- - popover { x, y, size?: "xs"|"sm"|"md"|"lg" (192/320/480/640, default 320) or width, children } — a panel (vertical, padding 12 by default; layout / gap / padding apply as on a frame): a comment box, a filter form.
- - menu { x, y, children: menu-row and divider nodes } — padding 4, at least 192 wide, hugs its rows.
+ - popover { x, y, size?: "xs"|"sm"|"md"|"lg" (192/320/480/640, default 320) or width, children } — a panel (vertical, padding 12 by default; layout / gap / padding apply as on a frame): a comment box, a filter form. With a numeric height, add overflow: "auto" so long content scrolls inside it (canvas_stress reads it as scrolling, as it does a drawer).
+ - menu { x, y, children: menu-row and divider nodes } — padding 4, at least 192 wide, hugs its rows. With a numeric height, add overflow: "auto" so long rows scroll inside it (canvas_stress reads it as scrolling).
- modal { title, size?: "sm"|"md"|"lg" (480/640/960, default md), actions?: [{ label, variant?, state? }], closeLabel?, children } — centred over its own full scrim (x / y place its top-left instead); a header with the title and a close button named "Close" (closeLabel renames it); the body holds the children (vertical, gap 12) and scrolls when tall; actions render right-aligned as 32px buttons, an action with no variant as "secondary", the filled ones ("primary", "destructive") rightmost. A modal is a region of its own for the primary-count and wayfinding rules.
- toast { text, tone?: "neutral"|"success"|"warning"|"danger", action?: { label, state? } } — bottom-centre, 24px above the artboard's bottom edge (x / y place it); the tone colours a leading glyph, the text stays $text-primary.
- drawer { size?: "sm"|"md" (320/480) or width, scrim?: false, children } — pinned to the right edge, full height, padding 16; scrim: true dims what is behind it.
@@ -2147,7 +2147,7 @@ server.tool(
'canvas_evaluate',
`Auto-score a design canvas against quality criteria. Returns an overall score (0-100), category scores, and actionable issues referencing specific node IDs. Categories: spacing, color, typography, structure, consistency (craft), plus "cliche" — the machine-made tells: default purple/indigo accents, gradient/glow overuse, fake browser/phone chrome (traffic-light dots), the hanging eyebrow-beside-heading header, fabricated-looking metrics/testimonials/logos, too many eyebrow labels (template rhythm — an eyebrow above nearly every section), slop copy (stock AI phrasing: filler verbs, scroll cues, placeholder names like "Jane Doe", hype labels), mixed radius systems (radius consistency — too many distinct corner radii), pure black/white (harsh #000000 ink or a stark #ffffff page vs a designed off-black/off-white), and competing accents (accent consistency — more than one accent hue). cliche issues carry a "tell" discriminator and are warning/info severity — but EVERY tell blocks the directive regardless of severity. The tells know dashboard vocabulary: a violet reached only through a $chart-* or $*-tint token doesn't trip the default-purple tell (a literal violet, or one through any OTHER token, still does), a gradient reached through a $token doesn't count toward gradient-overuse, thin rounded sparkline bars no longer match fake-chrome's small-circle census (it now requires a near-square shape: both dimensions ≤20px, aspect ratio ≤1.5:1, and round), and an uppercase label sitting beside a large tabular figure reads as a KPI-card metric — not counted in the eyebrow-rhythm census. The color category is DUAL-THEME aware: when the design system has a dark token layer (dark.colors — see set_variables / generate_color_system), contrast is checked in BOTH themes — dark-run issues carry theme: "dark", the category score takes the worse theme, and dark failures point at the dark token layer instead of carrying a literal fix (a node-level literal would break the light theme). Contrast is measured as rendered: translucent fills (rgba / #RRGGBBAA) composite over the fills behind them (over the white page when no opaque fill is behind), translucent text blends into that, and "transparent" is see-through — so a tinted selected or hover fill is judged by its real color, and the message names the composited one. WCAG 2.2 remains the gate; WCAG-passing pairs that are perceptually weak by APCA (Lc below ~75 body / ~60 large) get an INFO advisory — APCA is a candidate method, not a standard, and never blocks. Plus "coverage" (Phase 24): a BASE canvas whose content carries data — a detected table (empty + loading demanded) or a form of 3+ input controls, text-inputs included (error demanded) — gets a directive-blocking WARNING per missing state variant (table detection needs THREE matching horizontal rows to read as data — two stacked rows are a layout, not a table — unless the frame is import-named "Table", which keeps the looser two-row shape); the result's "coverage" field reports { dataBearing, states, missing }. Designing the state is one canvas_add_variant + one scaffold stamp (empty-state / skeleton-table / skeleton-card / skeleton-stat-card); variant canvases themselves and non-data screens get no coverage findings. On a "loading" variant, coverage also flags a HALF-DESIGNED loading state — a data surface (a detected table, or a frame holding 2+ large tabular/numeric texts) still showing live values while a sibling region is skeletoned, one warning per offending region naming it and pointing at the matching skeleton scaffold. Plus "usability" (Phase 27): the mechanical UX floors beyond contrast — on web and desktop-app canvases every pointer target (the four controls and the clickable primitives: button, list-row, each tab-bar tab and FAB, each nav-bar action, link, text-input, nav-item, each tab of a tabs node, tree-row, menu-row — inline text links and dividers are not targets, and a control that is the only target directly inside a property-row, nav-item, menu-row or list-row is measured by that row's box) is held to the 24px WCAG 2.5.8 floor with its SPACING EXCEPTION: a target still below 24 after the padded-row step passes only when a 24px circle centred on it reaches no other target's box and no other undersized target's circle (touching passes; nested targets and disabled ones never count). Spacing needs rendered rects, so DETAILED mode runs the circle test (ERROR when it fails, naming the neighbour) and FAST mode WARNS on any target below 24, naming detailed mode — grow it or run mode "detailed" before presenting. Instances are expanded for this census and findings report on the instance. (The effective target counts a lone control's padded row, so a well-padded settings row passes; two controls sharing a row are measured bare; phone-width WEB artboards additionally get a 44px touch-first info on the four controls; on a canvas declared mobile, 44px is an ERROR instead — see the surface paragraph), a control with no text label in its row or group is a WARNING (selects carry their own value text and are exempt), and vague action copy ("Click here" / "Learn more" / "Read more" / "Submit" as the exact label) is an INFO — name the action instead. The structure category also WARNS (directive-blocking, -10 structure score each) on every icon node, and every mobile primitive icon prop (button.icon, list-row / nav-bar leading.icon, nav-bar trailing[].icon, tab-bar items[].icon — required, so a tab with no icon warns too — and tab-bar fab.icon), whose name resolves in neither bundled set — it would render as an empty slot, invisible in a screenshot: the suggestion names the spellings that do resolve (hyphen/underscore swap, or the missing material: prefix), and when exactly one does — or several do but only one matches the icon set the rest of the canvas uses — an icon node or button.icon carries a fix canvas_autofix applies (the nested props name the spelling to write). Icons inside component instances are checked too; they point at the component definition and carry no fix op. Modes:
- "fast": JSON-only, <100ms, deterministic heuristics only.
- - "detailed": adds Puppeteer-based pixel overlap detection in the consistency category, laid out at the canvas's artboard size (siblings that content scrolls under — absolute, sticky, pinned chrome, a sheet, a bar pinned to the bottom — are exempt; a bar pinned to the top over in-flow content still counts).
+ - "detailed": adds Puppeteer-based pixel overlap detection in the consistency category, laid out at the canvas's artboard size in the design system's own fonts, as screenshot and canvas_stress render them (a face that cannot load renders in the fallback stack and the result carries a "Font warnings" item) (siblings that content scrolls under — absolute, sticky, pinned chrome, a sheet, a bar pinned to the bottom — are exempt; a bar pinned to the top over in-flow content still counts).
- "llm": fast-mode heuristics plus a vision-model critique against a FIXED rubric (provider picked from FRAMESMITH_LLM_PROVIDER env var, or whichever of ANTHROPIC_API_KEY / OPENAI_API_KEY is set). Adds an "llmCritique" field: { rubric: { hierarchy, execution, specificity, restraint, variety } each {score 1-5, rationale}, score (0-100 derived), summary, suggestions, needsRevision, failingAxes }. The verdict is stamped on the canvas (metadata.critique) + the per-project build log for auditability. Cost: one paid API call per invocation. To CLOSE the loop and auto-fix failing axes, use canvas_revise.
Designed for generator-evaluator loops: generate with batch_design, evaluate with canvas_evaluate, fix issues targeting the returned nodeIds (canvas_autofix handles the mechanical subset). The result includes a "directive" field — a present/keep-working verdict: it turns on BLOCKING findings, not the score — resolve every error/warning/cliché tell and it reads READY. The score (aim for > 95) is always reported alongside it and is the quality bar to keep climbing, but once nothing blocking is left, a sub-bar score no longer withholds readiness; the directive says so explicitly and names the remaining advisory findings as the lever. An "openFeedback" field (when > 0) counts the user's open point-and-tell comments — they block presenting even at a READY directive; read them with get_feedback and close them with resolve_feedback. A "stress" field ({ verdict: "CLEAN"|"FRAGILE", warnings, type, current }) appears once canvas_stress has recorded a verdict for this canvas — type is the canvas type the run used; current says whether that run was on the canvas's present versionHash AND type. A FRAGILE verdict keeps the directive NOT READY even with zero evaluate issues, until a full CLEAN canvas_stress run replaces it; when a FRAGILE run's current is false the directive says to re-run stress, naming whether an edit or a type change made it stale (the verdict still blocks); a stale CLEAN run just reads current: false. The verdict lives in server memory: a restart forgets it. canvas_evaluate never runs stress itself.
@@ -2177,7 +2177,11 @@ REPEATED FINDINGS FOLD in this result: three or more warnings or infos sharing a
// Phase 24 slice C — the coverage check needs to know which state
// variants exist for this canvas (sibling lookup, store-level).
const designedStates = listCanvases().find((r) => r.id === canvasId)?.variants?.map((v) => v.state) ?? [];
- const result = await evaluateCanvas(canvas, { mode, categories, genre, designedStates });
+ // Phase 31 S11 — detailed mode measures layout in the design system's
+ // faces, as stress, screenshot and snapshot_layout render them. Fast mode
+ // renders nothing, so it stays offline.
+ const detailedRender = mode === 'detailed' ? await prepareRender(canvas) : undefined;
+ const result = await evaluateCanvas(canvas, { mode, categories, genre, designedStates, renderOpts: detailedRender?.renderOpts });
let llmNote: string | undefined;
if (mode === 'llm') {
@@ -2218,7 +2222,7 @@ REPEATED FINDINGS FOLD in this result: three or more warnings or infos sharing a
const { directive } = buildEvaluateDirective(result, openFeedback, stress && { ...stress, ...(sameType ? {} : { ranAsType: stressRun!.type }) });
return {
- content: [{ type: 'text', text: JSON.stringify({ ...result, issues: foldIssues(result.issues), ...(llmNote ? { llmNote } : {}), ...(openFeedback > 0 ? { openFeedback } : {}), ...(stress ? { stress } : {}), directive }, null, 2) }],
+ content: [{ type: 'text', text: JSON.stringify({ ...result, issues: foldIssues(result.issues), ...(llmNote ? { llmNote } : {}), ...(openFeedback > 0 ? { openFeedback } : {}), ...(stress ? { stress } : {}), directive }, null, 2) }, ...fontWarningContent(detailedRender?.fontWarnings ?? [])],
};
}
);
@@ -2298,7 +2302,7 @@ server.tool(
Perturbations (default: all): long-text (non-data text ×2.2 plus one long unbroken token — the wrap-breaker), i18n (×1.4 — the German/Finnish expansion rule), big-numbers (data-like text to its widest realistic form: "9" → "999+", "$1.5M" → "$1,520,847.33"), empty (detected tables lose their data rows), many (data rows ×3). Tables are found with the same inventory drift and coverage use; runs of two or more list-rows are lists too, and on a desktop-app canvas so are runs of nav-item, tree-row, menu-row or property-row and card grids (a grid of three or more same-shaped children). A tripled list keeps one active row.
-Finding kinds: clip (content cut off — INFO when a designed text-overflow ellipsis is doing its job (a primitive's label truncating included), or when it is just a root with an authored overflow clipping or scrolling inside itself; WARNING otherwise; the vertical overflow of a sheet or of any frame with overflow "auto" (an app pane) scrolls and is never a clip; its horizontal overflow still is), overflow-x (a node escapes its parent box or the canvas), layout-shift (an UNTOUCHED node ballooning — perturbed nodes, their ancestors, and siblings that merely stretch with a growing parent are exempt). Only NEW breakage counts: anything already clipping at baseline is the design's standing state, not the perturbation's fault. verdict is CLEAN only with zero warnings — fix findings with fluid widths, minWidth or minHeight floors, wrapping, or textOverflow: "ellipsis" on labels that must stay single-line (that is the designed-truncation property the info path rewards), then re-run. The verdict is remembered for canvas_evaluate, with the canvas type it ran under: any run with warnings records FRAGILE (the directive stays NOT READY), and only a run of the full default set records CLEAN — a passing subset never clears an earlier FRAGILE. On a mobile canvas, long-text leaves strings of three characters or fewer alone (monograms, short labels), and the tab and nav-bar action labels (fixed vocabulary; i18n still lengthens them). The mobile primitives' own copy is perturbed (button label, list-row title / subtitle / trailing text, nav-bar title and action labels, tab labels), and two or more consecutive sibling list-rows are a list for empty and many. Chrome required; ~1 render per perturbation.`,
+Finding kinds: clip (content cut off — INFO when a designed text-overflow ellipsis is doing its job (a primitive's label truncating included), or when it is just a root with an authored overflow clipping or scrolling inside itself; WARNING otherwise; the vertical overflow of a sheet, a drawer, or any frame, popover or menu with overflow "auto" (an app pane, a popover whose body scrolls) scrolls and is never a clip; its horizontal overflow still is), overflow-x (a node escapes its parent box or the canvas), layout-shift (an UNTOUCHED node ballooning — perturbed nodes, their ancestors, and siblings that merely stretch with a growing parent are exempt). Only NEW breakage counts: anything already clipping at baseline is the design's standing state, not the perturbation's fault. verdict is CLEAN only with zero warnings — fix findings with fluid widths, minWidth or minHeight floors, wrapping, or textOverflow: "ellipsis" on labels that must stay single-line (that is the designed-truncation property the info path rewards), then re-run. The verdict is remembered for canvas_evaluate, with the canvas type it ran under: any run with warnings records FRAGILE (the directive stays NOT READY), and only a run of the full default set records CLEAN — a passing subset never clears an earlier FRAGILE. On a mobile canvas, long-text leaves strings of three characters or fewer alone (monograms, short labels), and the tab and nav-bar action labels (fixed vocabulary; i18n still lengthens them). The mobile primitives' own copy is perturbed (button label, list-row title / subtitle / trailing text, nav-bar title and action labels, tab labels), and two or more consecutive sibling list-rows are a list for empty and many. Chrome required; ~1 render per perturbation.`,
{
canvasId: z.string().describe('Canvas to stress'),
perturbations: z.array(z.enum(['long-text', 'i18n', 'big-numbers', 'empty', 'many'])).optional()
diff --git a/src/renderer.ts b/src/renderer.ts
index 57810f7..fde9164 100644
--- a/src/renderer.ts
+++ b/src/renderer.ts
@@ -1732,7 +1732,11 @@ function scrimHtml(node: SceneNode): string {
}
function renderOverlay(node: SceneNode, rc: RenderCtx): string {
- const dataAttr = ` data-node-id="${node.id}" data-fs-overlay="${node.type}"`;
+ // A drawer always scrolls its content, a popover or menu when it authors
+ // overflow "auto": marked like any scrolling pane (S4), so stress reads
+ // their vertical overflow as scrolling, not a clip (Phase 31 slice I).
+ const scrolls = node.type === 'drawer' || ((node.type === 'popover' || node.type === 'menu') && node.overflow === 'auto');
+ const dataAttr = ` data-node-id="${node.id}" data-fs-overlay="${node.type}"${scrolls ? ' data-fs-scroll' : ''}`;
switch (node.type) {
case 'tooltip': return renderTooltip(node, `${dataAttr} data-fs-primitive role="tooltip"`);
case 'modal': return renderModal(node, rc, `${dataAttr} data-fs-primitive role="dialog" aria-modal="true"`);
diff --git a/src/stress.ts b/src/stress.ts
index 573b4a2..7579fb1 100644
--- a/src/stress.ts
+++ b/src/stress.ts
@@ -317,7 +317,8 @@ export function compareLayouts(
if (clips(r) && !(b && clips(b as FlatRect))) {
// Report the axis that actually overflows (vertical clip on a fixed-
// height box is the common wrap case).
- const vertical = r.scrollHeight !== undefined && r.clientHeight !== undefined && r.scrollHeight > r.clientHeight + 1;
+ // A scroller's vertical overflow is scrolling, so its clip is the width.
+ const vertical = !r.scrolls && r.scrollHeight !== undefined && r.clientHeight !== undefined && r.scrollHeight > r.clientHeight + 1;
const scroll = vertical ? r.scrollHeight : r.scrollWidth;
const box = vertical ? r.clientHeight : r.clientWidth;
// The page outgrowing its fixed artboard vertically is scrolling, not
diff --git a/test-evaluate-fonts.ts b/test-evaluate-fonts.ts
new file mode 100644
index 0000000..91d7369
--- /dev/null
+++ b/test-evaluate-fonts.ts
@@ -0,0 +1,100 @@
+// Phase 31 slice I, spec change S11 — detailed canvas_evaluate lays out in
+// the design system's fonts, as screenshot and canvas_stress render them.
+// Driven through the real canvas_evaluate handler over MCP stdio, because the
+// handler is where the fonts are prepared. The body token's family is the
+// generic `monospace` (it needs no download and is far wider than any sans on
+// every OS), so the face decides two detailed verdicts:
+// - a toast that fits in a sans face leaves the window in monospace
+// (desktop-app-overlay reads the main detailed layout), and
+// - a 20px button pushed right by a run of "i"s lands on top of another 20px
+// button only in monospace (desktop-app-target's 24px circle reads the
+// census layout).
+// The twin is the same canvas whose body is `sans-serif`: neither fires.
+// Also: a family that cannot load comes back as a "Font warnings" item in
+// detailed mode, and fast mode renders nothing, so it has none.
+//
+// Usage: npx tsx test-evaluate-fonts.ts
+
+import { mkdtempSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join, resolve } from 'node:path';
+import { Client } from '@modelcontextprotocol/sdk/client/index.js';
+import { StdioClientTransport } from '@modelcontextprotocol/sdk/client/stdio.js';
+
+let allPass = true;
+function check(name: string, cond: boolean, extra?: string) {
+ if (!cond) allPass = false;
+ console.log(`${cond ? 'PASS' : 'FAIL'} ${name}${extra ? ` — ${extra}` : ''}`);
+}
+
+const home = mkdtempSync(join(tmpdir(), 'framesmith-evaluate-fonts-'));
+const cwd = mkdtempSync(join(tmpdir(), 'framesmith-evaluate-fonts-cwd-'));
+const transport = new StdioClientTransport({
+ command: resolve('node_modules/.bin/tsx'),
+ args: [resolve('src/index.ts')],
+ cwd,
+ env: { ...process.env, FRAMESMITH_HOME: home, CANVAS_MCP_PROJECT_DIR: cwd, FRAMESMITH_VIEWER_URL: 'http://localhost:1' } as Record,
+ stderr: 'ignore',
+});
+const client = new Client({ name: 'test-evaluate-fonts', version: '0' });
+await client.connect(transport);
+
+type Content = { type: string; text?: string };
+async function call(name: string, args: Record): Promise {
+ const r = await client.callTool({ name, arguments: args }, undefined, { timeout: 170_000 }) as { content: Content[] };
+ return r.content;
+}
+const json = (c: Content[]) => JSON.parse(c[0]?.text ?? '{}');
+type Issue = { severity: string; rule?: string; nodeId?: string; nodeIds?: string[]; message?: string };
+
+const RUN = 'i'.repeat(16);
+const OPS = `
+row1=I("document", { type: "frame", name: "Row 1", layout: "horizontal", alignItems: "start", gap: 0 })
+I(row1, { type: "text", name: "Run", content: "${RUN}", fontSize: 14, lineHeight: 1.4, color: "#1F2937" })
+I(row1, { type: "button", name: "A", icon: "plus", ariaLabel: "Add", variant: "ghost", size: "xs", height: 20, color: "#1F2937" })
+row2=I("document", { type: "frame", name: "Row 2", layout: "horizontal", alignItems: "start", gap: 0 })
+I(row2, { type: "frame", name: "Spacer", width: 134, height: 20 })
+I(row2, { type: "button", name: "B", icon: "minus", ariaLabel: "Remove", variant: "ghost", size: "xs", height: 20, color: "#1F2937" })
+I("document", { type: "toast", name: "Toast", text: "${'i'.repeat(60)}", x: 1040, y: 820 })
+`;
+
+async function canvasWithBody(family: string) {
+ const c = json(await call('canvas_create', { name: `body ${family}`, type: 'desktop-app' }));
+ await call('set_variables', { canvasId: c.canvasId, variables: { typography: { body: { fontSize: 14, fontFamily: family } } } });
+ const b = json(await call('batch_design', { canvasId: c.canvasId, operations: OPS }));
+ check(`${family}: the fixture applies`, (b.errors ?? []).length === 0, JSON.stringify(b.errors ?? []).slice(0, 200));
+ return c.canvasId as string;
+}
+
+try {
+ for (const [family, fires] of [['monospace', true], ['sans-serif', false]] as const) {
+ const id = await canvasWithBody(family);
+ const issues = json(await call('canvas_evaluate', { canvasId: id, mode: 'detailed' })).issues as Issue[];
+ const overlay = issues.filter((i) => i.rule === 'desktop-app-overlay' && i.severity === 'warning' && /viewport/.test(i.message ?? ''));
+ const targets = issues.filter((i) => i.rule === 'desktop-app-target' && i.severity === 'error');
+ const describe = (l: Issue[]) => l.map((i) => `${i.severity}:${(i.message ?? '').slice(0, 80)}`).join(' | ');
+ if (fires) {
+ check('monospace body: the wide toast leaves the window in detailed mode (the main layout reads the face)', overlay.length === 1, describe(overlay));
+ check('monospace body: the pushed 20px button meets the other one (the 24px-circle layout reads the face)', targets.length === 2, describe(targets));
+ } else {
+ check('twin, sans-serif body: the toast fits the window', overlay.length === 0, describe(overlay));
+ check('twin, sans-serif body: the two 20px buttons stay apart', targets.length === 0, describe(targets));
+ }
+ }
+
+ // A family that cannot load: a Font warnings item in detailed mode only.
+ const c = json(await call('canvas_create', { name: 'missing face', type: 'desktop-app' }));
+ await call('set_variables', { canvasId: c.canvasId, variables: { typography: { body: { fontSize: 14, fontFamily: 'Zzqxv Nonexistent Sans' } } } });
+ await call('batch_design', { canvasId: c.canvasId, operations: 'I("document", { type: "text", content: "Hello", fontSize: 14, color: "#1F2937" })' });
+ const detailed = await call('canvas_evaluate', { canvasId: c.canvasId, mode: 'detailed' });
+ const fast = await call('canvas_evaluate', { canvasId: c.canvasId, mode: 'fast' });
+ const warned = detailed.filter((x) => x.type === 'text' && x.text?.startsWith('Font warnings'));
+ check('detailed: the result stays in the first content item', typeof json(detailed).overallScore === 'number');
+ check('detailed: a face that cannot load comes back as a Font warnings item naming it', warned.length === 1 && /Zzqxv Nonexistent Sans/.test(warned[0].text ?? ''), warned.map((x) => x.text).join(' ').slice(0, 160));
+ check('fast: renders nothing, so no Font warnings item', fast.length === 1, `${fast.length} items`);
+} finally {
+ await client.close();
+}
+
+console.log(allPass ? '\nAll checks passed.' : '\nSome checks FAILED.');
+process.exit(allPass ? 0 : 1);
diff --git a/test-fonts-by-name.ts b/test-fonts-by-name.ts
index cbabfbe..e2c0249 100644
--- a/test-fonts-by-name.ts
+++ b/test-fonts-by-name.ts
@@ -210,6 +210,16 @@ const fontsDir = join(process.env.FRAMESMITH_HOME!, 'fonts');
const { fetchImpl: failFetch } = makeStubFetch({ failAll: true });
const warned = await ensureFontsForRender(badRoot, canvas, undefined, { fetchImpl: failFetch });
expect('failure degrades to a warning', warned.extraFonts.length === 0 && warned.warnings.length === 1 && warned.warnings[0].includes('set_fonts'), warned.warnings.join(' | '));
+
+ // Phase 31 slice I — a family used only inside a component: the instance
+ // has no children, so the definition is where the backstop finds it.
+ const instanceRoot: SceneNode = { id: 'doc', type: 'document', children: [{ id: 'i1', type: 'instance', componentId: 'card' }] };
+ const withComponent = { ...canvas, components: { card: { id: 'card', type: 'component', children: [{ id: 'ct', type: 'text', content: 'x', fontFamily: 'Inter' }] } } } as unknown as Canvas;
+ const { fetchImpl: compFetch } = makeStubFetch();
+ const fromComponent = await ensureFontsForRender(instanceRoot, withComponent, undefined, { fetchImpl: compFetch });
+ expect('a family used only inside a component is loaded', fromComponent.extraFonts.length === 2, `${fromComponent.extraFonts.length} faces`);
+ const noComponent = await ensureFontsForRender(instanceRoot, canvas, undefined, { fetchImpl: compFetch });
+ expect('twin: the same instance with no such component loads nothing', noComponent.extraFonts.length === 0);
}
// ── 8. stylesheet-URL registration ───────────────────────────────────────────
diff --git a/test-overlays-render.ts b/test-overlays-render.ts
index b37bc59..b01faac 100644
--- a/test-overlays-render.ts
+++ b/test-overlays-render.ts
@@ -195,6 +195,65 @@ const tech = generateDesignSystem('#2563EB', 'technical').variables;
}
}
+// ── Slice I (V7): a scrolling popover and a drawer read as scrolling ────────
+// The comment popover of the viewer rebuild has a fixed height and scrolls its
+// body; a drawer always scrolls. Overlays build their own attributes, so they
+// missed S4's data-fs-scroll marker and stress read their growth as a clip.
+{
+ const pop = (overflow: 'auto' | 'hidden'): SceneNode => ({
+ id: 'pop', name: 'pop', type: 'popover', x: 600, y: 100, width: 320, height: 170, overflow, children: [
+ { id: 'pt', name: 'pt', type: 'text', content: 'Comment on dashboard before it ships to the team', fontSize: 14 },
+ { id: 'pi', name: 'pi', type: 'text-input', placeholder: 'Add a comment', rows: 3, width: '100%' },
+ ],
+ });
+ const drawer: SceneNode = { id: 'dr', name: 'dr', type: 'drawer', children: Array.from({ length: 30 }, (_, i) => ({ id: `dl${i}`, name: `dl${i}`, type: 'text' as const, content: `Filter option number ${i + 1}`, fontSize: 14 })) };
+ const warningsOn = async (children: SceneNode[], id: string) => {
+ const root = canvasOf(children, tech).root;
+ const resolve = (r: SceneNode) => resolveVariables(r, tech);
+ const baseline = await computeLayout(renderToHtml(resolve(root), 1440, 900), undefined, 25, { width: 1440, height: 900 });
+ const { root: pert, touched } = applyPerturbation('long-text', root, { type: 'desktop-app' });
+ const after = await computeLayout(renderToHtml(resolve(pert), 1440, 900), undefined, 25, { width: 1440, height: 900 });
+ return compareLayouts(baseline, after, touched, 1440).filter((f) => f.severity === 'warning' && f.nodeId === id);
+ };
+ check('a fixed-height popover with overflow auto scrolls under long-text (no clip)', (await warningsOn([pop('auto')], 'pop')).length === 0);
+ const twin = await warningsOn([pop('hidden')], 'pop');
+ check('twin: the same popover with overflow hidden still clips', twin.some((f) => f.kind === 'clip'), JSON.stringify(twin));
+ check('a drawer scrolls its content under long-text (no clip)', (await warningsOn([drawer], 'dr')).length === 0);
+ check('the drawer and a scrolling popover carry data-fs-scroll; a plain popover and a menu do not',
+ /data-node-id="dr" data-fs-overlay="drawer" data-fs-scroll/.test(htmlOf(canvasOf([drawer], tech)))
+ && /data-node-id="pop" data-fs-overlay="popover" data-fs-scroll/.test(htmlOf(canvasOf([pop('auto')], tech)))
+ && !/data-fs-overlay="popover" data-fs-scroll/.test(htmlOf(canvasOf([pop('hidden')], tech)))
+ && !/data-fs-overlay="menu" data-fs-scroll/.test(htmlOf(canvasOf([{ id: 'mn', name: 'mn', type: 'menu', x: 10, y: 10, children: [] }], tech))));
+ const menuOf = (overflow: 'auto' | 'hidden'): SceneNode => ({ id: 'mn', name: 'mn', type: 'menu', x: 10, y: 10, height: 120, overflow, children: [] });
+ check('a menu with overflow auto carries data-fs-scroll; one with overflow hidden does not',
+ /data-node-id="mn" data-fs-overlay="menu" data-fs-scroll/.test(htmlOf(canvasOf([menuOf('auto')], tech)))
+ && !/data-fs-overlay="menu" data-fs-scroll/.test(htmlOf(canvasOf([menuOf('hidden')], tech))));
+ // A scroller that overflows sideways still clips, and says it is the width.
+ const wideDrawer: SceneNode = { id: 'dw', name: 'dw', type: 'drawer', children: [
+ { id: 'dwt', name: 'dwt', type: 'text', content: 'Filters', fontSize: 14 },
+ ...Array.from({ length: 60 }, (_, i) => ({ id: `dwl${i}`, name: `dwl${i}`, type: 'text' as const, content: `Option ${i + 1}`, fontSize: 14 })),
+ ] };
+ const wideRoot = canvasOf([wideDrawer], tech).root;
+ const resolveTech = (r: SceneNode) => resolveVariables(r, tech);
+ const wideBase = await computeLayout(renderToHtml(resolveTech(wideRoot), 1440, 900), undefined, 25, { width: 1440, height: 900 });
+ const widened: SceneNode = structuredClone(wideRoot);
+ widened.children![0].children![0] = { id: 'dwt', name: 'dwt', type: 'frame', width: 600, minWidth: 600, height: 20 };
+ const wideAfter = await computeLayout(renderToHtml(resolveTech(widened), 1440, 900), undefined, 25, { width: 1440, height: 900 });
+ const sideways = compareLayouts(wideBase, wideAfter, ['dwt'], 1440).filter((f) => f.nodeId === 'dw' && f.kind === 'clip');
+ // A scrolling root that also overflows sideways: its vertical overflow is
+ // scrolling, so the width clip is a warning, not the "page grows taller"
+ // info its height used to earn it.
+ const rootOf = (wide: number): SceneNode => canvasOf([
+ { id: 'wide', name: 'wide', type: 'frame', width: wide, minWidth: wide, height: 20 },
+ ...Array.from({ length: 60 }, (_, i) => ({ id: `rl${i}`, name: `rl${i}`, type: 'text' as const, content: `Row ${i + 1}`, fontSize: 14 })),
+ ], tech, { overflow: 'auto' }).root;
+ const rootBase = await computeLayout(renderToHtml(resolveTech(rootOf(1000)), 1440, 900), undefined, 25, { width: 1440, height: 900 });
+ const rootAfter = await computeLayout(renderToHtml(resolveTech(rootOf(2000)), 1440, 900), undefined, 25, { width: 1440, height: 900 });
+ const rootClip = compareLayouts(rootBase, rootAfter, ['wide'], 1440).filter((f) => f.nodeId === 'document' && f.kind === 'clip');
+ check('a scrolling root that overflows sideways is a width warning', rootClip.length === 1 && rootClip[0].severity === 'warning' && /\(width \d+px vs box \d+px\)/.test(rootClip[0].detail), JSON.stringify(rootClip));
+ check('a drawer that overflows sideways still clips, reported as width', sideways.length === 1 && sideways[0].severity === 'warning' && /\(width \d+px vs box \d+px\)/.test(sideways[0].detail), JSON.stringify(sideways));
+}
+
// ── Round 1 fixes: neighbours and phones ────────────────────────────────────
{
// A modal's box is never a 24px-circle neighbour (its scrim covers what is outside).
diff --git a/test-viewer-rebuild.ts b/test-viewer-rebuild.ts
new file mode 100644
index 0000000..8c42ab1
--- /dev/null
+++ b/test-viewer-rebuild.ts
@@ -0,0 +1,610 @@
+// Phase 31 slice I (FR-J1) — the acceptance re-run. framesmith's own viewer
+// (the gallery, a canvas's detail page with its inspector, and the archive),
+// rebuilt as desktop-app canvases on the finished phase through the REAL tool
+// handlers over MCP stdio: one project, one project-scope design system,
+// apply_structure from the app realisations, then batch_design. Six canvases
+// (three bases and the comment-open, confirm-delete and empty states) must
+// each reach CLEAN in fast and detailed mode in both themes with a full
+// canvas_stress run CLEAN, and the six defects the 2026-11-08 baseline found
+// in the live viewer must be fixed, each checked by name. The numbers it
+// prints are the ones the slice I PR quotes. Contracts: V1 to V9 in
+// docs/specs/PHASE-31-SPEC.md.
+//
+// Usage: npx tsx test-viewer-rebuild.ts
+// VIEWER_OUT= also writes screenshots, crops and JSON there.
+
+import { mkdirSync, mkdtempSync, readFileSync, writeFileSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join, resolve } from 'node:path';
+import { Client } from '@modelcontextprotocol/sdk/client/index.js';
+import { StdioClientTransport } from '@modelcontextprotocol/sdk/client/stdio.js';
+import { contrastRatio, parseColor } from './src/color-math.js';
+import { resolveVariables } from './src/variables.js';
+import type { DesignVariables, SceneNode } from './src/types.js';
+
+let allPass = true;
+function check(name: string, cond: boolean, extra?: string) {
+ if (!cond) allPass = false;
+ console.log(`${cond ? 'PASS' : 'FAIL'} ${name}${extra ? ` — ${extra}` : ''}`);
+}
+
+// Spelled out, not read from src/surfaces.ts, so dropping a rule from the
+// ruleset cannot also drop it from what this gate expects.
+const DESKTOP_RULE_IDS = [
+ 'desktop-app-artboard', 'desktop-app-target', 'desktop-app-handbuilt-target', 'desktop-app-icon-label',
+ 'desktop-app-current', 'desktop-app-type-ladder', 'desktop-app-row-rhythm', 'desktop-app-truncation',
+ 'desktop-app-primary-count', 'desktop-app-overlay', 'desktop-app-focus-visible', 'desktop-app-state-contrast',
+ 'desktop-app-boundary', 'desktop-app-disabled',
+];
+const STATE_RULES = ['desktop-app-focus-visible', 'desktop-app-state-contrast', 'desktop-app-boundary'];
+const STRESS_DEFAULTS = ['long-text', 'i18n', 'big-numbers', 'empty', 'many'];
+const COLOR_FIELDS = ['fill', 'stroke', 'color', 'iconColor', 'secondaryColor', 'badgeColor', 'dotColor'] as const;
+const out = process.env.VIEWER_OUT;
+if (out) mkdirSync(out, { recursive: true });
+
+// ── the content (V2) ────────────────────────────────────────────────────────
+// The viewer's own data: the baseline fixtures' projects, canvases, scores and
+// findings. The amber seed yields five series hues, so five projects.
+
+const PROJECTS: Array<[string, number]> = [
+ ['Design system', 1], ['UI', 5], ['Releases', 2], ['Pattern library', 11], ['Foundations', 0],
+];
+
+/** The sidebar's projects over a realisation's nav-items (`existing` of them),
+ * the current one active; the secondary item becomes Archive. */
+function sidebar(prefix: string, current: string | null, archived: number, existing: number): string {
+ const lines = [
+ `U("${prefix}-brand", { content: "framesmith" })`,
+ `ws=I("${prefix}", { type: "text", name: "Workspace label", content: "Personal", fontSize: "$caption", fontWeight: 600, color: "$text-secondary", padding: [0, 8] })`,
+ `M(ws, "${prefix}", 1)`,
+ ];
+ PROJECTS.forEach(([label, count], i) => {
+ const props = `label: "${label}", count: ${count}, dotColor: "$chart-${i + 1}", icon: null, active: ${label === current}`;
+ lines.push(i < existing ? `U("${prefix}-nav-${i + 1}", { ${props} })` : `I("${prefix}-nav", { type: "nav-item", ${props} })`);
+ });
+ for (let i = PROJECTS.length + 1; i <= existing; i++) lines.push(`D("${prefix}-nav-${i}")`);
+ lines.push(`U("${prefix}-more-1", { label: "Archive", icon: "archive", count: ${archived}, active: ${current === null} })`);
+ return lines.join('\n');
+}
+
+const CARDS: Array<[string, number]> = [
+ ['auth', 100], ['bento-grid', 100], ['catalogue', 100], ['dashboard', 95], ['onboarding', 100], ['settings', 98],
+];
+
+const GALLERY = `
+${sidebar('bra-sidebar', 'Pattern library', 3, 3)}
+U("bra-header-title", { content: "Pattern library", title: "Pattern library" })
+D("bra-new")
+I("bra-header-actions", { type: "text", name: "Canvas count", content: "11 canvases", fontSize: "$caption", color: "$text-secondary" })
+U("bra-search", { placeholder: "Search canvases" })
+U("bra-tabs", { items: [{ label: "All", count: 11, active: true }, { label: "Web", count: 9 }, { label: "Mobile", count: 1 }, { label: "Desktop app", count: 1 }] })
+${CARDS.map(([name, score], i) => {
+ const id = `bra-card-${i + 1}`;
+ return [
+ `U("${id}", { name: "Canvas card" })`,
+ `U("${id}-media", { layout: "horizontal", justifyContent: "end", alignItems: "start", padding: "$space-sm" })`,
+ `I("${id}-media", { type: "text", name: "Score", content: "${score}", title: "Quality score ${score} of 100", fontSize: "$caption", fontWeight: 600, color: "$text-primary", tabularNums: true, fill: "$bg-surface", cornerRadius: "$radius-sm", padding: [2, 8] })`,
+ `U("${id}-title", { label: "${name}" })`,
+ `U("${id}-meta", { content: "1440 × 900 · Jun 26, 2026", title: "1440 × 900 · Jun 26, 2026" })`,
+ ].join('\n');
+}).join('\n')}
+`;
+
+const CATEGORIES: Array<[string, number]> = [
+ ['Spacing', 100], ['Color', 100], ['Typography', 100], ['Structure', 100],
+ ['Consistency', 100], ['Usability', 100], ['Coverage', 30], ['Cliché', 100],
+];
+
+/** The baseline inspector's 18 findings, one card per distinct finding. */
+const ISSUES: Array<{ category: string; message: string; nodes: number; fixable?: boolean }> = [
+ { category: 'Typography', message: 'Display text at 28px with default tracking reads loose. Tighten it to -0.5.', nodes: 4, fixable: true },
+ { category: 'Consistency', message: 'Corner radius 8 equals the $md token. Reference the token instead.', nodes: 5, fixable: true },
+ { category: 'Consistency', message: 'Corner radius 16 equals the $lg token. Reference the token instead.', nodes: 5, fixable: true },
+ { category: 'Coverage', message: 'The data table has no empty state variant.', nodes: 1 },
+ { category: 'Coverage', message: 'The data table has no loading state variant.', nodes: 1 },
+ { category: 'Structure', message: 'No component instances in 43 nodes. Promote a repeated subtree.', nodes: 1 },
+ { category: 'Color', message: 'Weak perceptual contrast on the primary link (APCA advisory).', nodes: 1 },
+];
+const FINDINGS = ISSUES.reduce((n, i) => n + i.nodes, 0);
+
+function issueCard(i: number, issue: typeof ISSUES[number]): string {
+ const card = `card${i}`;
+ const nodes = issue.nodes === 1 ? '1 node' : `${issue.nodes} nodes`;
+ return [
+ `${card}=I(issues, { type: "frame", name: "Issue card", width: "100%", layout: "vertical", gap: "$space-xs", padding: "$space-sm", cornerRadius: "$radius-md", fill: "$bg-primary", stroke: "$border", strokeWidth: 1 })`,
+ `I(${card}, { type: "text", name: "Issue category", content: "${issue.category}${issue.fixable ? ' · auto-fixable' : ''}", fontSize: "$caption", fontWeight: 600, color: "$text-secondary" })`,
+ `I(${card}, { type: "text", name: "Issue message", content: "${issue.message}", fontSize: "$label", color: "$text-primary" })`,
+ `I(${card}, { type: "link", name: "Issue nodes", label: "Show ${nodes}" })`,
+ ].join('\n');
+}
+
+const ACTION = 'minWidth: "max-content", maxWidth: 140, variant: "secondary", size: "sm"';
+const DETAIL = `
+U("eia-crumb-parent", { name: "Back link", label: "Back", icon: "arrow-left" })
+D("eia-crumb-sep")
+U("eia-title", { content: "dashboard", title: "dashboard", fontSize: "$body" })
+I("eia-crumbs", { type: "text", name: "Canvas size", content: "1440 × 900", minWidth: "max-content", fontSize: "$caption", color: "$text-secondary" })
+D("eia-share")
+D("eia-publish")
+U("eia-actions", { minWidth: 0 })
+bp=I("eia-actions", { type: "frame", name: "Breakpoints", minWidth: 0 })
+I(bp, { type: "tabs", name: "Breakpoint tabs", variant: "contained", size: "sm", items: [{ label: "Mobile" }, { label: "Tablet" }, { label: "Desktop", active: true }, { label: "Compare" }] })
+I("eia-actions", { type: "divider", name: "View divider", orientation: "vertical" })
+I("eia-actions", { type: "button", name: "JSON button", label: "JSON", icon: "braces", ${ACTION} })
+I("eia-actions", { type: "button", name: "Comment button", label: "Comment", icon: "message-square", ${ACTION} })
+I("eia-actions", { type: "button", name: "Archive button", label: "Archive", icon: "archive", ${ACTION} })
+I("eia-actions", { type: "divider", name: "Danger divider", orientation: "vertical" })
+I("eia-actions", { type: "button", name: "Delete button", label: "Delete", icon: "trash-2", minWidth: "max-content", maxWidth: 140, variant: "destructive", size: "sm" })
+D("eia-tool-select")
+D("eia-tool-pan")
+I("eia-tools", { type: "button", icon: "scan", ariaLabel: "Fit to window", variant: "ghost", size: "xs", color: "$text-secondary" })
+U("eia-canvas-label", { content: "Canvas preview, 1440 × 900" })
+U("eia-tabs", { name: "Inspector tabs", items: [{ label: "Quality", active: true }, { label: "Design system" }, { label: "Feedback" }] })
+U("eia-props-title", { content: "Score 95 of 100 · Excellent" })
+D("eia-prop-name")
+D("eia-prop-width")
+D("eia-prop-mode")
+D("eia-prop-visible")
+D("eia-prop-source")
+${CATEGORIES.map(([c, v]) => `I("eia-props", { type: "property-row", label: "${c}", children: [{ type: "text", content: "${v}", fontSize: "$label", color: "$text-primary", tabularNums: true }] })`).join('\n')}
+I("eia-inspector", { type: "text", name: "Issues title", content: "Issues · ${FINDINGS} findings in ${ISSUES.length} groups", fontSize: "$body", fontWeight: 600, color: "$text-primary" })
+issues=I("eia-inspector", { type: "frame", name: "Issues", width: "100%", layout: "vertical", gap: "$space-xs" })
+${ISSUES.map((x, i) => issueCard(i, x)).join('\n')}
+`;
+
+const ARCHIVE = `
+${sidebar('swa-sidebar', null, 3, 4)}
+U("swa-header-title", { content: "Archive", title: "Archive" })
+D("swa-secondary")
+D("swa-primary")
+meta=I("swa-header-actions", { type: "text", name: "Archive count", content: "3 canvases across all projects", fontSize: "$caption", color: "$text-secondary" })
+M(meta, "swa-header-actions", 0)
+D("swa-canvas")
+tree=I("swa-work", { type: "frame", name: "Archived canvases", width: "100%", layout: "vertical", gap: "$space-3xs" })
+I(tree, { type: "tree-row", label: "Pattern library", depth: 0, expanded: true, icon: "folder" })
+I(tree, { type: "tree-row", label: "marquee-hero", depth: 1, icon: "file", active: true })
+I(tree, { type: "tree-row", label: "catalogue", depth: 1, icon: "file" })
+I(tree, { type: "tree-row", label: "UI", depth: 0, expanded: true, icon: "folder" })
+I(tree, { type: "tree-row", label: "checkout-northrail-coffee-loading", depth: 1, icon: "file" })
+U("swa-panel-title", { content: "marquee-hero", title: "marquee-hero" })
+U("swa-prop-1", { label: "Project" })
+U("swa-prop-1-value", { content: "Pattern library", title: "Pattern library" })
+U("swa-prop-2", { label: "Archived" })
+U("swa-prop-2-value", { content: "Nov 8, 2026", title: "Nov 8, 2026" })
+U("swa-prop-3", { label: "Size" })
+U("swa-prop-3-value", { content: "1440 × 900", title: "1440 × 900" })
+I("swa-props", { type: "property-row", label: "Score", children: [{ type: "text", content: "100", fontSize: "$label", color: "$text-primary", tabularNums: true }] })
+I("swa-panel", { type: "button", name: "Restore button", label: "Restore", icon: "archive-restore", size: "sm", maxWidth: "100%" })
+I("swa-panel", { type: "divider", name: "Danger divider" })
+danger=I("swa-panel", { type: "frame", name: "Delete permanently", width: "100%", layout: "vertical", gap: "$space-xs" })
+I(danger, { type: "text", content: "Deleting removes the canvas and its variants for good.", fontSize: "$label", color: "$text-secondary" })
+I(danger, { type: "button", name: "Delete permanently button", label: "Delete permanently", icon: "trash-2", variant: "destructive", size: "sm", maxWidth: "100%" })
+`;
+
+/** Ops on a variant: its node ids are re-keyed, so `v` maps a base id. */
+type VariantOps = (v: (id: string) => string) => string;
+
+const CONFIRM: VariantOps = (v) => `
+I("${v('eia-shell')}", { type: "modal", name: "Delete dialog", size: "sm", title: "Delete canvas?", actions: [{ label: "Cancel" }, { label: "Delete", variant: "destructive" }], children: [{ type: "text", content: "“dashboard” and its 2 variants will be permanently deleted. This cannot be undone.", fontSize: "$label", color: "$text-primary" }] })
+`;
+
+const EMPTY: VariantOps = (v) => `
+U("${v('swa-sidebar-more-1')}", { count: 0 })
+U("${v('meta')}", { content: "0 canvases" })
+D("${v('tree')}")
+D("${v('swa-panel')}")
+D("${v('swa-div-2')}")
+D("${v('swa-toggle')}")
+empty=I("${v('swa-work')}", { type: "frame", name: "Empty state", width: "100%", height: "100%", layout: "vertical", alignItems: "center", justifyContent: "center", gap: "$space-sm" })
+I(empty, { type: "icon", icon: "archive", iconSize: 32, iconColor: "$text-secondary" })
+I(empty, { type: "text", content: "No archived canvases", fontSize: "$body", fontWeight: 600, color: "$text-primary", textAlign: "center" })
+I(empty, { type: "text", content: "Archive a canvas from its page, or have your agent call canvas_archive.", fontSize: "$body", color: "$text-secondary", textAlign: "center", maxWidth: 360 })
+`;
+
+// ── harness ─────────────────────────────────────────────────────────────────
+
+const home = mkdtempSync(join(tmpdir(), 'framesmith-viewer-rebuild-'));
+const cwd = mkdtempSync(join(tmpdir(), 'framesmith-viewer-rebuild-cwd-'));
+const transport = new StdioClientTransport({
+ command: resolve('node_modules/.bin/tsx'),
+ args: [resolve('src/index.ts')],
+ cwd,
+ env: { ...process.env, FRAMESMITH_HOME: home, CANVAS_MCP_PROJECT_DIR: cwd, FRAMESMITH_VIEWER_URL: 'http://localhost:1' } as Record,
+ stderr: 'ignore',
+});
+const client = new Client({ name: 'test-viewer-rebuild', version: '0' });
+await client.connect(transport);
+
+type Content = { type: string; text?: string; data?: string };
+async function call(name: string, args: Record): Promise {
+ const r = await client.callTool({ name, arguments: args }, undefined, { timeout: 170_000 }) as { content: Content[] };
+ return r.content;
+}
+async function tool(name: string, args: Record) {
+ const text = (await call(name, args))[0]?.text ?? '';
+ try { return JSON.parse(text); } catch { return text; }
+}
+
+type Node = { id: string; type: string; name?: string; label?: string; content?: string; variant?: string; active?: boolean; items?: Array<{ label: string; active?: boolean }>; children?: Node[]; [k: string]: unknown };
+const walk = (n: Node, acc: Node[] = []): Node[] => { acc.push(n); (n.children ?? []).forEach((c) => walk(c, acc)); return acc; };
+const readCanvas = (id: string) => JSON.parse(readFileSync(join(home, 'canvases', `${id}.json`), 'utf-8'));
+const byName = (root: Node, name: string) => walk(root).filter((n) => n.name === name);
+const parentOf = (root: Node, id: string): Node | undefined => walk(root).find((n) => (n.children ?? []).some((c) => c.id === id));
+
+type Issue = { severity: string; rule?: string; tell?: string; theme?: string; message?: string; detail?: string; nodeId?: string; nodeIds?: string[] };
+const describe = (issues: Issue[]) => issues.map((i) => `${i.severity}:${i.rule ?? i.tell ?? ''}${i.theme ? '(dark)' : ''} ${i.nodeId ?? ''} ${(i.message ?? i.detail ?? '').slice(0, 90)}`).join(' | ');
+const opErrors = (b: unknown) => (typeof b === 'string' ? [b] : ((b as { errors?: unknown[] }).errors ?? []));
+
+/** V4(5)'s predicate: every card message distinct. */
+export const distinctMessages = (messages: string[]) => new Set(messages).size === messages.length;
+
+async function build(name: string, projectId: string, anatomy: string, ops: string) {
+ const c = await tool('canvas_create', { name, type: 'desktop-app', projectId });
+ const s = await tool('apply_structure', { canvasId: c.canvasId, structure: anatomy });
+ const b = await tool('batch_design', { canvasId: c.canvasId, operations: ops });
+ check(`${name}: canvas_create declares a 1440×900 desktop-app canvas`, c.type === 'desktop-app' && c.width === 1440 && c.height === 900, JSON.stringify({ type: c.type, width: c.width, height: c.height }));
+ check(`${name}: apply_structure("${anatomy}") stamps ${anatomy}-app`, s.applied === `${anatomy}-app`, s.applied);
+ check(`${name}: the adaptation applies without op errors`, opErrors(b).length === 0, JSON.stringify(opErrors(b)).slice(0, 300));
+ return { id: c.canvasId as string, bindings: (b.nodeIds ?? {}) as Record };
+}
+
+async function variant(name: string, baseId: string, state: string, ops: VariantOps, baseBindings: Record) {
+ const r = await tool('canvas_add_variant', { canvasId: baseId, state });
+ const idMap = r.idMap as Record;
+ const v = (id: string) => idMap[baseBindings[id] ?? id] ?? id;
+ const b = await tool('batch_design', { canvasId: r.canvasId, operations: ops(v) });
+ check(`${name}: the ${state} adaptation applies without op errors`, opErrors(b).length === 0, JSON.stringify(opErrors(b)).slice(0, 300));
+ return { id: r.canvasId as string, v };
+}
+
+type Verdict = { name: string; id: string; scores: Record; truncations: number; stress: string };
+const verdicts: Verdict[] = [];
+
+/** V3 on one canvas: stress, then fast, then detailed. */
+async function judge(name: string, id: string, projectId: string, opts: { base: boolean; bigNumbers: boolean }) {
+ const shot = await call('screenshot', { canvasId: id });
+ const fontWarnings = shot.filter((x) => x.type === 'text' && x.text?.startsWith('Font warnings'));
+ check(`${name}: the design system's fonts load (no Font warnings)`, fontWarnings.length === 0, fontWarnings.map((x) => x.text).join(' '));
+
+ const st = await tool('canvas_stress', { canvasId: id });
+ if (out) writeFileSync(join(out, `${slug(name)}-stress.json`), JSON.stringify(st, null, 2));
+ const runs = (st.perturbations ?? []) as Array<{ name: string; touchedCount?: number; skipped?: string; findings?: Issue[] }>;
+ const ran = runs.map((p) => p.name).sort();
+ check(`${name}: canvas_stress ran the full default set`, JSON.stringify(ran) === JSON.stringify([...STRESS_DEFAULTS].sort()), ran.join(', '));
+ const stressWarnings = runs.flatMap((p) => p.findings ?? []).filter((f) => f.severity !== 'info');
+ check(`${name}: canvas_stress is CLEAN`, /^CLEAN\b/.test(st.verdict) && stressWarnings.length === 0, `${st.verdict?.slice(0, 60)}${stressWarnings.length ? ' — ' + describe(stressWarnings) : ''}`);
+ const touched = (n: string) => runs.find((p) => p.name === n)?.touchedCount ?? 0;
+ const must = STRESS_DEFAULTS.filter((n) => n !== 'big-numbers' || opts.bigNumbers);
+ check(`${name}: every perturbation it must run touched a node (${must.join(', ')})`, must.every((n) => touched(n) > 0), runs.map((p) => `${p.name}:${p.touchedCount ?? 'skipped'}`).join(' '));
+ const skipped = runs.filter((p) => p.skipped).map((p) => p.name);
+ check(`${name}: no perturbation skipped${opts.bigNumbers ? '' : ' but big-numbers (no figures to widen)'}`, JSON.stringify(skipped) === JSON.stringify(opts.bigNumbers ? [] : ['big-numbers']), skipped.join(', '));
+ const truncations = runs.flatMap((p) => p.findings ?? []).filter((f) => f.severity === 'info').length;
+
+ const canvas = readCanvas(id);
+ check(`${name}: the canvas sits in the viewer project`, canvas.projectId === projectId, canvas.projectId);
+ check(`${name}: the canvas's own variables are empty (all tokens from the project)`, JSON.stringify(canvas.variables ?? {}) === '{}', JSON.stringify(canvas.variables).slice(0, 120));
+
+ const scores: Record = {};
+ for (const mode of ['fast', 'detailed'] as const) {
+ const content = await call('canvas_evaluate', { canvasId: id, mode });
+ const ev = JSON.parse(content[0]?.text ?? '{}');
+ // Detailed mode lays out in the design system's faces (S11) and says so
+ // when one cannot load; fast mode renders nothing.
+ const evalFonts = content.filter((x) => x.type === 'text' && x.text?.startsWith('Font warnings'));
+ check(`${name} ${mode}: no Font warnings from evaluate`, evalFonts.length === 0, evalFonts.map((x) => x.text).join(' ').slice(0, 160));
+ if (out) writeFileSync(join(out, `${slug(name)}-evaluate-${mode}.json`), JSON.stringify(ev, null, 2));
+ const issues = ev.issues as Issue[];
+ scores[mode] = ev.overallScore;
+ const blocking = issues.filter((i) => i.severity === 'error' || i.severity === 'warning' || i.tell);
+ check(`${name} ${mode}: CLEAN — zero errors, warnings and tells, READY`, blocking.length === 0 && /^READY/.test(ev.directive), `${ev.overallScore}/100${blocking.length ? ' — ' + describe(blocking) : ''}`);
+ check(`${name} ${mode}: the directive read this canvas's own current CLEAN stress run`, ev.stress?.verdict === 'CLEAN' && ev.stress?.current === true && ev.stress?.type === 'desktop-app', JSON.stringify(ev.stress));
+ const dark = issues.filter((i) => i.theme === 'dark' && i.severity !== 'info');
+ check(`${name} ${mode}: no dark-theme warning or error`, dark.length === 0, describe(dark));
+ const handbuilt = issues.filter((i) => i.rule === 'desktop-app-handbuilt-target');
+ check(`${name} ${mode}: zero desktop-app-handbuilt-target findings`, handbuilt.length === 0, describe(handbuilt));
+ const states = issues.filter((i) => STATE_RULES.includes(i.rule ?? ''));
+ check(`${name} ${mode}: no state-rule finding of any severity (nothing skipped silently)`, states.length === 0, describe(states));
+ const on = new Set(ev.surface?.rulesOn ?? []);
+ const missing = DESKTOP_RULE_IDS.filter((r) => !on.has(r));
+ check(`${name} ${mode}: the surface report enables every desktop-app rule and disables type-scale-ratio`,
+ ev.surface?.type === 'desktop-app' && missing.length === 0 && (ev.surface?.rulesOff ?? []).includes('type-scale-ratio'),
+ missing.length ? `missing ${missing.join(', ')}` : '');
+ if (mode === 'fast' && opts.base) {
+ // None of the bases is data-bearing (no detected table, fewer than
+ // three form controls), so coverage has nothing to demand: the check
+ // says so rather than passing on an empty list by accident.
+ check(`${name}: coverage asks for no state variant (not data-bearing)`, ev.coverage?.dataBearing === false && JSON.stringify(ev.coverage?.missing ?? []) === '[]', JSON.stringify(ev.coverage));
+ }
+ console.log(` ${mode} score ${ev.overallScore}/100 · ${issues.length} findings (${issues.filter((i) => i.severity === 'info').length} info)`);
+ }
+ verdicts.push({ name, id, scores, truncations, stress: String(st.verdict).split(' ')[0] });
+ return canvas;
+}
+
+const slug = (s: string) => s.toLowerCase().replace(/[^a-z0-9]+/g, '-').replace(/^-|-$/g, '');
+
+/** Every colour on the canvas is a $token the merged tokens define, and
+ * nothing resolves to a leftover `$` string in either theme (V4(4)). */
+function tokenOnly(name: string, canvas: { root: Node }, defined: Set) {
+ const bad: string[] = [];
+ const texts: string[] = [];
+ const ref = (v: unknown) => typeof v === 'string' && v.startsWith('$') && defined.has(v.slice(1));
+ for (const n of walk(canvas.root)) {
+ if (n.type === 'text' && !ref(n.color)) texts.push(n.id);
+ for (const f of COLOR_FIELDS) if (n[f] !== undefined && n[f] !== null && !ref(n[f])) bad.push(`${n.id}.${f}=${String(n[f])}`);
+ const bb = n.borderBottom as { color?: string } | undefined;
+ if (bb?.color !== undefined && !ref(bb.color)) bad.push(`${n.id}.borderBottom.color=${bb.color}`);
+ for (const s of (n.shadows as Array<{ color?: string }> | undefined) ?? []) if (!ref(s.color)) bad.push(`${n.id}.shadows.color=${s.color}`);
+ }
+ check(`${name}: every text has an explicit $token colour`, texts.length === 0, texts.join(', '));
+ check(`${name}: every colour field set is a defined $token`, bad.length === 0, bad.slice(0, 6).join(', '));
+}
+
+try {
+ // ── build (V1, V2) ────────────────────────────────────────────────────────
+ const ws = await tool('workspace_list', {});
+ const workspaceId = (Array.isArray(ws) ? ws : ws.workspaces)[0].id;
+ const project = await tool('project_create', { workspaceId, name: 'framesmith viewer' });
+ const projectId = project.id as string;
+ const ds = await tool('generate_design_system', { projectId, seed: '#B45309', personality: 'technical', baseSize: 14 });
+ check('generate_design_system writes the project with the 14px pivot', ds.wroteTo?.layer === 'project' && ds.baseSize === 14, JSON.stringify(ds.wroteTo));
+
+ const gallery = await build('Gallery', projectId, 'browser', GALLERY);
+ const detail = await build('Canvas detail', projectId, 'editor-inspector', DETAIL);
+ const archive = await build('Archive', projectId, 'split-workbench', ARCHIVE);
+
+ // comment-open: the popover goes under the Comment button, read from its
+ // rendered box, as GUIDELINES tells an agent to place one.
+ const commentVariant = await variant('Comment open', detail.id, 'comment-open', () => '', {});
+ const cv = readCanvas(commentVariant.id);
+ const commentButton = byName(cv.root, 'Comment button')[0];
+ const box = await tool('snapshot_layout', { canvasId: commentVariant.id, nodeId: commentButton.id });
+ const btn = (Array.isArray(box) ? box[0] : box.layout?.[0] ?? box) as { x: number; y: number; width: number; height: number };
+ const popW = 320;
+ const popX = Math.round(btn.x + btn.width - popW);
+ const popY = Math.round(btn.y + btn.height + 8);
+ const pop = await tool('batch_design', { canvasId: commentVariant.id, operations: `
+pop=I("${parentOf(cv.root, commentButton.id)!.id}", { type: "popover", name: "Comment popover", anchor: "${commentButton.id}", x: ${popX}, y: ${popY}, width: ${popW}, gap: "$space-sm", overflow: "auto" })
+I(pop, { type: "text", content: "Comment on dashboard", fontSize: "$label", fontWeight: 600, color: "$text-primary" })
+I(pop, { type: "text-input", name: "Comment field", placeholder: "Add a comment", rows: 3, width: "100%" })
+row=I(pop, { type: "frame", name: "Comment actions", width: "100%", layout: "horizontal", justifyContent: "end", gap: "$space-xs", wrap: true })
+I(row, { type: "button", label: "Cancel", variant: "secondary", size: "sm", maxWidth: "100%" })
+I(row, { type: "button", label: "Post", size: "sm", maxWidth: "100%" })
+` });
+ check('Comment open: the popover inserts without op errors', opErrors(pop).length === 0, JSON.stringify(opErrors(pop)).slice(0, 300));
+ const popNode = byName(readCanvas(commentVariant.id).root, 'Comment popover')[0];
+ const popBox = await tool('snapshot_layout', { canvasId: commentVariant.id, nodeId: popNode.id });
+ const popRect = (Array.isArray(popBox) ? popBox[0] : popBox.layout?.[0] ?? popBox) as { height: number };
+ const fix = await tool('batch_design', { canvasId: commentVariant.id, operations: `U("${popNode.id}", { height: ${Math.ceil(popRect.height)} })` });
+ check('Comment open: the popover takes its measured height', opErrors(fix).length === 0 && popRect.height > 0, `${popX},${popY} ${popW}×${Math.ceil(popRect.height)}`);
+
+ const confirmVariant = await variant('Confirm delete', detail.id, 'confirm-delete', CONFIRM, detail.bindings);
+ const emptyVariant = await variant('Archive empty', archive.id, 'empty', EMPTY, archive.bindings);
+
+ // ── verdicts (V3) ─────────────────────────────────────────────────────────
+ const six: Array<[string, string, { base: boolean; bigNumbers: boolean }]> = [
+ ['Gallery', gallery.id, { base: true, bigNumbers: true }],
+ ['Canvas detail', detail.id, { base: true, bigNumbers: true }],
+ ['Archive', archive.id, { base: true, bigNumbers: true }],
+ ['Comment open', commentVariant.id, { base: false, bigNumbers: true }],
+ ['Confirm delete', confirmVariant.id, { base: false, bigNumbers: true }],
+ // An empty archive shows no figures, so big-numbers has nothing to widen.
+ ['Archive empty', emptyVariant.id, { base: false, bigNumbers: false }],
+ ];
+ const canvases: Record = {};
+ for (const [name, id, opts] of six) canvases[name] = await judge(name, id, projectId, opts);
+
+ // ── the six defects (V4) ──────────────────────────────────────────────────
+ const detailRoot = canvases['Canvas detail'].root;
+ // (1) Back
+ const back = byName(detailRoot, 'Back link')[0];
+ check('E3 Back: the back control is a link labelled "Back"', back?.type === 'link' && back.label === 'Back', JSON.stringify(back).slice(0, 120));
+ const evDetail = await tool('canvas_evaluate', { canvasId: detail.id, mode: 'detailed' });
+ const backTarget = (evDetail.issues as Issue[]).filter((i) => i.rule === 'desktop-app-target' && (i.nodeId === back.id || i.nodeIds?.includes(back.id)));
+ check('E3 Back: detailed evaluate raises no desktop-app-target finding on it', backTarget.length === 0, describe(backTarget));
+ const backBox = await tool('snapshot_layout', { canvasId: detail.id, nodeId: back.id });
+ const backRect = (Array.isArray(backBox) ? backBox[0] : backBox.layout?.[0] ?? backBox) as { height: number };
+ check('E3 Back: it renders at least 24 tall', backRect.height >= 24, `${backRect.height}px (the baseline's was 17)`);
+ // (2) Inspector tabs
+ const tabs = byName(detailRoot, 'Inspector tabs');
+ const inspector = walk(detailRoot).find((n) => n.id === 'eia-inspector')!;
+ check('E4 Inspector tabs: the inspector holds exactly one tabs node', walk(inspector).filter((n) => n.type === 'tabs').length === 1);
+ const labels = tabs[0]?.items?.map((t) => t.label) ?? [];
+ check('E4 Inspector tabs: one tabs node with Quality, Design system and Feedback, exactly one active',
+ tabs.length === 1 && tabs[0].type === 'tabs' && JSON.stringify(labels) === JSON.stringify(['Quality', 'Design system', 'Feedback']) && tabs[0].items!.filter((t) => t.active).length === 1,
+ labels.join(', '));
+ // (3) Issue cards
+ const CLICKABLE = new Set(['button', 'link', 'text-input', 'nav-item', 'tabs', 'tree-row', 'menu-row', 'list-row', 'toggle', 'checkbox', 'radio', 'select']);
+ const cards = byName(detailRoot, 'Issue card');
+ check('E4 Issue cards: every card is plain content holding a clickable primitive',
+ cards.length === ISSUES.length && cards.every((c) => c.type === 'frame' && walk(c).some((n) => CLICKABLE.has(n.type))),
+ `${cards.length} cards`);
+ // (4) Muted labels
+ // Every canvas's own variables are empty (judge), so the project's design
+ // system is what each one resolves.
+ const system = await tool('project_get_design_system', { projectId });
+ const tokens = (system.designSystem ?? system.variables ?? system) as { colors?: Record; dark?: { colors?: Record } };
+ const colors = tokens.colors ?? {};
+ const darkColors = { ...colors, ...(tokens.dark?.colors ?? {}) };
+ check('the project design system carries a dark colour layer that restates $text-secondary', Object.keys(tokens.dark?.colors ?? {}).length > 0 && !!tokens.dark?.colors?.['text-secondary'] && tokens.dark.colors['text-secondary'] !== colors['text-secondary']);
+ for (const [theme, c] of [['light', colors], ['dark', darkColors]] as const) {
+ for (const bg of ['bg-primary', 'bg-surface', 'bg-elevated']) {
+ const fg = parseColor(c['text-secondary']);
+ const back2 = parseColor(c[bg]);
+ const ratio = fg && back2 ? Math.round(contrastRatio(fg, back2) * 100) / 100 : 0;
+ check(`E1/E2 Muted labels: $text-secondary on $${bg} is 4.5:1 or more (${theme})`, ratio >= 4.5, `${ratio}:1`);
+ }
+ }
+ const defined = new Set(Object.keys(darkColors));
+ for (const [name] of six) tokenOnly(name, canvases[name], defined);
+ // Any $ref, colour or not (a misspelt "$space-sm" or "$caption"), would be
+ // left in the resolved tree as a literal string the renderer drops.
+ for (const [name] of six) {
+ for (const theme of ['light', 'dark'] as const) {
+ const resolved = resolveVariables(canvases[name].root as unknown as SceneNode, tokens as DesignVariables, { theme });
+ const left: string[] = [];
+ const scan = (v: unknown, path: string) => {
+ if (typeof v === 'string') { if (v.startsWith('$')) left.push(`${path}=${v}`); }
+ else if (Array.isArray(v)) v.forEach((x, i) => scan(x, `${path}[${i}]`));
+ else if (v && typeof v === 'object') for (const [k, x] of Object.entries(v)) scan(x, path ? `${path}.${k}` : k);
+ };
+ scan(resolved, '');
+ check(`${name}: no unresolved $ref in the ${theme} tree`, left.length === 0, left.slice(0, 4).join(', '));
+ }
+ }
+ // (5) Grouped issues
+ const messages = cards.map((c) => walk(c).find((n) => n.name === 'Issue message')?.content ?? '');
+ check('E5 Grouped issues: no two issue cards carry the same message', distinctMessages(messages));
+ const tracking = cards.find((c) => /28px with default tracking/.test(walk(c).find((n) => n.name === 'Issue message')?.content ?? ''));
+ check('E5 Grouped issues: the repeated tracking finding is one card naming its four nodes',
+ !!tracking && walk(tracking).some((n) => /\b4 nodes\b/.test(String(n.label ?? n.content ?? ''))));
+ check('twin (d): the distinct-message predicate fails on a duplicated card', !distinctMessages([...messages, messages[0]]));
+ // (6) Delete apart from Archive: a different weight, and either another
+ // group or a divider between them.
+ const del = byName(detailRoot, 'Delete button')[0];
+ const arc = byName(detailRoot, 'Archive button')[0];
+ const delParent = parentOf(detailRoot, del.id)!;
+ const arcParent = parentOf(detailRoot, arc.id)!;
+ const kids = delParent.children!.map((c) => c.id);
+ const lo = Math.min(kids.indexOf(arc.id), kids.indexOf(del.id));
+ const hi = Math.max(kids.indexOf(arc.id), kids.indexOf(del.id));
+ const apart = arcParent.id !== delParent.id || delParent.children!.slice(lo + 1, hi).some((n) => n.type === 'divider');
+ check('E6 Delete: a destructive button; Archive is neither destructive nor primary',
+ del.type === 'button' && del.variant === 'destructive' && arc.type === 'button' && typeof arc.variant === 'string' && !['destructive', 'primary'].includes(arc.variant as string),
+ `${del.variant} / ${arc.variant}`);
+ check('E6 Delete: set apart from Archive (another group, or a divider between them)', apart);
+ const confirmIssues = (await tool('canvas_evaluate', { canvasId: confirmVariant.id, mode: 'fast' })).issues as Issue[];
+ check('Confirm delete: the dialog\'s one filled action raises no primary-count info', !confirmIssues.some((i) => i.rule === 'desktop-app-primary-count'));
+ const archiveRoot = canvases['Archive'].root;
+ const permanent = byName(archiveRoot, 'Delete permanently button')[0];
+ const panel = walk(archiveRoot).find((n) => n.id === 'swa-panel')!;
+ const pk = panel.children!.map((c) => c.name ?? c.id);
+ check('E6 Delete: the archive\'s permanent delete is destructive and sits below a divider from Restore',
+ permanent?.variant === 'destructive' && pk.indexOf('Danger divider') > pk.indexOf('Restore button') && pk.indexOf('Delete permanently') > pk.indexOf('Danger divider'),
+ pk.join(' > '));
+
+ // ── twins (V5) ────────────────────────────────────────────────────────────
+ // Each twin runs on a throwaway clone of the detail page (canvas_add_variant
+ // under a twin-* state), so the six judged canvases are never touched:
+ // set_variables only merges, so a canvas once overridden can't return to
+ // the empty variables V3 asserts.
+ let twins = 0;
+ async function twin(state: string, ops: VariantOps, setup?: (id: string) => Promise) {
+ const t = await variant(`twin ${state}`, detail.id, `twin-${++twins}-${state}`, ops, detail.bindings);
+ if (setup) await setup(t.id);
+ return t;
+ }
+ const fastIssues = async (id: string) => (await tool('canvas_evaluate', { canvasId: id, mode: 'fast' })).issues as Issue[];
+ const detailedIssues = async (id: string) => (await tool('canvas_evaluate', { canvasId: id, mode: 'detailed' })).issues as Issue[];
+
+ // (a) a dark-only contrast failure surfaces, so V3(c) is live.
+ const darkTwin = await twin('dark-contrast', () => '', async (id) => {
+ await tool('set_variables', { canvasId: id, variables: { dark: { colors: { 'text-secondary': darkColors['bg-surface'] } } } });
+ });
+ const darkErr = (await fastIssues(darkTwin.id)).filter((i) => i.theme === 'dark' && i.severity === 'error');
+ check('twin (a): a dark-only contrast failure raises a dark-tagged error', darkErr.length > 0, describe(darkErr.slice(0, 2)));
+
+ // (b) the baseline's hand-built back control is named, so V3(d) is live.
+ const handTwin = await twin('handbuilt-back', (v) => `
+D("${v('eia-crumb-parent')}")
+hb=I("${v('eia-crumb-slot')}", { type: "frame", name: "Hand-built back", height: 17, layout: "horizontal", alignItems: "center", gap: 4 })
+I(hb, { type: "icon", icon: "arrow-left", iconSize: 14, iconColor: "$text-secondary" })
+I(hb, { type: "text", content: "Back", fontSize: "$caption", color: "$text-secondary" })
+`);
+ for (const [mode, issues] of [['fast', await fastIssues(handTwin.id)], ['detailed', await detailedIssues(handTwin.id)]] as const) {
+ const hit = issues.filter((i) => i.rule === 'desktop-app-handbuilt-target');
+ check(`twin (b) ${mode}: the baseline's hand-built Back raises desktop-app-handbuilt-target`, hit.length > 0, describe(hit));
+ }
+
+ // (c) two packed 20px targets fail the 24px circle, so V4(1)'s rule is live.
+ const packTwin = await twin('packed-targets', (v) => `
+pk=I("${v('eia-work')}", { type: "frame", name: "Packed tools", layout: "horizontal", gap: 0 })
+I(pk, { type: "button", icon: "zoom-in", ariaLabel: "Zoom in", variant: "ghost", size: "xs", height: 20, color: "$text-secondary" })
+I(pk, { type: "button", icon: "zoom-out", ariaLabel: "Zoom out", variant: "ghost", size: "xs", height: 20, color: "$text-secondary" })
+`);
+ const packFast = (await fastIssues(packTwin.id)).filter((i) => i.rule === 'desktop-app-target');
+ const packDetailed = (await detailedIssues(packTwin.id)).filter((i) => i.rule === 'desktop-app-target');
+ check('twin (c) fast: two packed 20px buttons warn', packFast.filter((i) => i.severity === 'warning').length === 2, describe(packFast));
+ check('twin (c) detailed: two packed 20px buttons are errors', packDetailed.filter((i) => i.severity === 'error').length === 2, describe(packDetailed));
+
+ // (e) a FRAGILE stress run blocks presenting, so V3(a)/(b) read live state.
+ const clipTwin = await twin('clipped-label', (v) => `
+cl=I("${v('eia-work')}", { type: "frame", name: "Clipped label", width: 160, height: 20, overflow: "hidden" })
+I(cl, { type: "text", content: "Short label", fontSize: "$label", color: "$text-primary" })
+`);
+ const clipStress = await tool('canvas_stress', { canvasId: clipTwin.id });
+ const clipEval = await tool('canvas_evaluate', { canvasId: clipTwin.id, mode: 'fast' });
+ check('twin (e): a label that wraps and clips under long-text makes stress FRAGILE', /^FRAGILE\b/.test(clipStress.verdict), clipStress.verdict?.slice(0, 60));
+ check('twin (e): the next fast evaluate is not READY', !/^READY/.test(clipEval.directive) && clipEval.stress?.verdict === 'FRAGILE', clipEval.directive?.slice(0, 60));
+
+ // (f) a popover leaving the window warns, so desktop-app-overlay is live.
+ const popTwin = await twin('popover-off-window', (v) => `
+I("${v('eia-actions')}", { type: "popover", name: "Off-window popover", x: 1300, y: ${popY}, width: 320, height: 120, children: [{ type: "text", content: "Comment on dashboard", fontSize: "$label", color: "$text-primary" }] })
+`);
+ const off = (await fastIssues(popTwin.id)).filter((i) => i.rule === 'desktop-app-overlay' && i.severity === 'warning');
+ check('twin (f) fast: a popover leaving the window raises a desktop-app-overlay warning', off.length > 0, describe(off));
+
+ // (g) a focus ring the colour of the panel fails, so the state rules are live.
+ const ringTwin = await twin('focus-ring', () => '', async (id) => {
+ await tool('set_variables', { canvasId: id, variables: { colors: { 'focus-ring': colors['bg-surface'] } } });
+ });
+ const ring = (await fastIssues(ringTwin.id)).filter((i) => i.rule === 'desktop-app-focus-visible' && i.severity === 'error');
+ check('twin (g): a focus ring the colour of the inspector panel raises desktop-app-focus-visible', ring.length > 0, describe(ring.slice(0, 1)));
+
+ // (h) a clone never stressed carries no stress record, so the judge's
+ // "stress field present" check is live; (i) a clone stressed CLEAN and then
+ // edited reads current: false.
+ const freshTwin = await twin('never-stressed', () => '');
+ const fresh = await tool('canvas_evaluate', { canvasId: freshTwin.id, mode: 'fast' });
+ check('twin (h): a canvas never stressed has no stress field', fresh.stress === undefined, JSON.stringify(fresh.stress));
+ const staleTwin = await twin('stale-stress', () => '');
+ const staleRun = await tool('canvas_stress', { canvasId: staleTwin.id });
+ await tool('batch_design', { canvasId: staleTwin.id, operations: `U("${staleTwin.v('eia-canvas-label')}", { content: "Canvas preview" })` });
+ const stale = await tool('canvas_evaluate', { canvasId: staleTwin.id, mode: 'fast' });
+ check('twin (i): an edit after a CLEAN stress run reads current: false', /^CLEAN\b/.test(staleRun.verdict) && stale.stress?.verdict === 'CLEAN' && stale.stress?.current === false, JSON.stringify(stale.stress));
+ // (j) a dialog with two filled primaries raises the primary-count info that
+ // Confirm delete must not.
+ const primaryTwin = await twin('two-primaries', (v) => `
+I("${v('eia-shell')}", { type: "modal", size: "sm", title: "Delete canvas?", actions: [{ label: "Keep", variant: "primary" }, { label: "Delete", variant: "primary" }], children: [{ type: "text", content: "This cannot be undone.", fontSize: "$label", color: "$text-primary" }] })
+`);
+ check('twin (j): two primary actions in one dialog raise desktop-app-primary-count', ((await fastIssues(primaryTwin.id)).some((i) => i.rule === 'desktop-app-primary-count')));
+
+ // The judged canvases were not touched by the twins.
+ for (const [name, id] of six) {
+ const ev = await tool('canvas_evaluate', { canvasId: id, mode: 'fast' });
+ check(`${name}: still READY on its own current CLEAN stress run after the twins`, /^READY/.test(ev.directive) && ev.stress?.current === true && ev.stress?.verdict === 'CLEAN');
+ }
+
+ // ── evidence (V6) ─────────────────────────────────────────────────────────
+ if (out) {
+ for (const [name, id] of six) {
+ for (const theme of ['light', 'dark'] as const) {
+ const img = (await call('screenshot', { canvasId: id, theme })).find((x) => x.type === 'image');
+ if (img?.data) writeFileSync(join(out, `${slug(name)}-${theme}.png`), Buffer.from(img.data, 'base64'));
+ }
+ writeFileSync(join(out, `${slug(name)}.json`), JSON.stringify(readCanvas(id), null, 2));
+ }
+ const crops: Array<[string, string, string]> = [
+ ['defect-1-muted-labels', gallery.id, 'bra-sidebar'],
+ ['defect-2-back', detail.id, 'eia-crumbs'],
+ ['defect-3-inspector-tabs', detail.id, byName(detailRoot, 'Inspector tabs')[0].id],
+ ['defect-4-issue-cards', detail.id, byName(detailRoot, 'Issues')[0].id],
+ ['defect-5-grouped-issue', detail.id, tracking!.id],
+ ['defect-6-delete-apart', detail.id, 'eia-actions'],
+ ];
+ for (const [file, id, nodeId] of crops) {
+ const img = (await call('screenshot', { canvasId: id, nodeId, theme: 'dark' })).find((x) => x.type === 'image');
+ if (img?.data) writeFileSync(join(out, `${file}.png`), Buffer.from(img.data, 'base64'));
+ }
+ }
+
+ // ── the numbers the PR quotes ─────────────────────────────────────────────
+ console.log('\nCanvas fast detailed stress designed truncations');
+ for (const v of verdicts) console.log(`${v.name.padEnd(18)}${String(v.scores.fast).padEnd(6)}${String(v.scores.detailed).padEnd(10)}${v.stress.padEnd(8)}${v.truncations}`);
+ console.log('\nDone.');
+} finally {
+ await client.close();
+}
+
+console.log(allPass ? '\nAll checks passed.' : '\nSome checks FAILED.');
+process.exit(allPass ? 0 : 1);