An open source design system that's fully customizable and agent ready
TypeScript
fix(rtl-audit): give a worker a fresh page after a story fails on it (#7023)
Cindy Zhanga8b2251434e1
diff --git a/.github/scripts/rtl-audit-pool.test.mjs b/.github/scripts/rtl-audit-pool.test.mjsnew file mode 100644index 0000000000..0fcf983777--- /dev/null+++ b/.github/scripts/rtl-audit-pool.test.mjs@@ -0,0 +1,313 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++import {describe, expect, it} from 'vitest';+import {+ closePageQuietly,+ createCuratedPages,+ createPagePool,+ mapPool,+ runSteps,+} from '../../apps/storybook/rtl-audit/rtl-audit-pool.mjs';++const TIMEOUT = 'TimeoutError: page.goto: Timeout 30000ms exceeded.';++/**+ * Fake pages. A page that loads the poisoning story fails that story and+ * every later navigation, as a page with a stuck renderer does.+ */+function fakeBrowser({hangOnClose = false} = {}) {+ const opened = [];+ return {+ opened,+ openPage: async () => {+ const page = {+ id: opened.length,+ poisoned: false,+ closed: false,+ close: () =>+ hangOnClose+ ? new Promise(() => {})+ : Promise.resolve().then(() => {+ page.closed = true;+ }),+ };+ opened.push(page);+ return page;+ },+ };+}++function stories(count, poisonAt) {+ return Array.from({length: count}, (_, index) => ({+ storyId: `core-story--${index}`,+ poison: poisonAt.includes(index),+ }));+}++/** One scan phase, counting how often each story is scanned. */+function phase(scanCounts) {+ return {+ scan: async (story, page) => {+ scanCounts.set(story.storyId, (scanCounts.get(story.storyId) ?? 0) + 1);+ await new Promise(resolve => setTimeout(resolve, 1));+ if (page.poisoned) throw new Error(TIMEOUT);+ if (story.poison) {+ page.poisoned = true;+ throw new Error(TIMEOUT);+ }+ return {storyId: story.storyId, verdict: 'N-A', page: page.id};+ },+ onError: (story, error) => ({+ storyId: story.storyId,+ verdict: 'ERROR',+ notes: [String(error)],+ }),+ describe: story => ({storyId: story.storyId}),+ };+}++describe('RTL audit worker pages', () => {+ it('fails only the story that broke a page; the worker continues on a fresh page', async () => {+ const browser = fakeBrowser();+ const pool = await createPagePool({size: 4, openPage: browser.openPage});+ const scanCounts = new Map();+ const results = await mapPool(stories(200, [5]), pool, phase(scanCounts));++ expect(results.filter(result => result.verdict === 'ERROR')).toEqual([+ {+ storyId: 'core-story--5',+ verdict: 'ERROR',+ notes: [`Error: ${TIMEOUT}`],+ },+ ]);+ expect(results.map(result => result.storyId)).toEqual(+ stories(200, []).map(story => story.storyId),+ );+ // No story is scanned twice: the failed one is recorded, not retried.+ expect([...scanCounts.values()].every(count => count === 1)).toBe(true);+ expect(scanCounts.size).toBe(200);+ expect(pool.recoveries).toEqual([+ expect.objectContaining({+ storyId: 'core-story--5',+ error: `Error: ${TIMEOUT}`,+ }),+ ]);+ const [broken] = browser.opened.filter(page => page.poisoned);+ expect(broken.closed).toBe(true);+ expect(pool.pages()).not.toContain(broken);+ expect(browser.opened).toHaveLength(5);+ });++ it('keeps the recovery across phases, and the first page follows its slot', async () => {+ const browser = fakeBrowser();+ const pool = await createPagePool({size: 4, openPage: browser.openPage});+ const firstBefore = pool.first();+ // The first story goes to the first worker, so the first page breaks.+ const d5 = await mapPool(stories(120, [0, 61]), pool, phase(new Map()));+ const d6 = await mapPool(stories(120, []), pool, phase(new Map()));++ expect(+ d5.filter(result => result.verdict === 'ERROR').map(r => r.storyId),+ ).toEqual(['core-story--0', 'core-story--61']);+ expect(d6.filter(result => result.verdict === 'ERROR')).toEqual([]);+ expect(pool.first()).not.toBe(firstBefore);+ expect(pool.first().poisoned).toBe(false);+ expect(pool.recoveries.map(recovery => recovery.storyId)).toEqual([+ 'core-story--0',+ 'core-story--61',+ ]);+ });++ it('does not wait on a page that never acknowledges its close', async () => {+ const browser = fakeBrowser({hangOnClose: true});+ const pool = await createPagePool({+ size: 2,+ openPage: browser.openPage,+ closePage: page => closePageQuietly(page, 10),+ });+ const results = await mapPool(stories(20, [3]), pool, phase(new Map()));++ expect(results.filter(result => result.verdict === 'ERROR')).toHaveLength(+ 1,+ );+ await pool.close();+ });++ it('closes quietly when closing throws', async () => {+ await expect(+ closePageQuietly(+ {close: () => Promise.reject(new Error('Target closed'))},+ 10,+ ),+ ).resolves.toBeUndefined();+ });++ describe('curated pass', () => {+ /** Runs curated targets the way the audit does: one target at a time. */+ async function scoreTargets(targets, pages, poison) {+ const results = [];+ for (const target of targets) {+ const dims = {};+ await runSteps(target.dims, pages, {+ pageFor: dim => (dim === 'D7' ? 'coarse' : 'main'),+ run: async (dim, page) => {+ await new Promise(resolve => setTimeout(resolve, 1));+ if (page.poisoned) throw new Error(TIMEOUT);+ if (poison === `${target.storyId}:${dim}`) {+ page.poisoned = true;+ throw new Error(TIMEOUT);+ }+ dims[dim] = `pass on page ${page.id}`;+ },+ onError: dim => {+ dims[dim] = 'ERROR';+ },+ describe: dim => ({phase: 'curated', storyId: target.storyId, dim}),+ });+ results.push({storyId: target.storyId, dims});+ }+ return results;+ }++ const TARGETS = [+ {storyId: 'core-a--default', dims: ['D2', 'D8']},+ {storyId: 'core-b--default', dims: ['D2']},+ {storyId: 'core-c--default', dims: ['D7', 'D2']},+ ];++ async function curatedPages() {+ const browser = fakeBrowser();+ const coarseBrowser = fakeBrowser();+ const pool = await createPagePool({size: 1, openPage: browser.openPage});+ const pages = createCuratedPages({+ pool,+ coarsePage: await coarseBrowser.openPage(),+ openCoarsePage: coarseBrowser.openPage,+ });+ return {browser, coarseBrowser, pool, pages};+ }++ it('fails only the step that broke the page; later steps and targets run on a fresh page', async () => {+ const {browser, coarseBrowser, pool, pages} = await curatedPages();+ const results = await scoreTargets(TARGETS, pages, 'core-a--default:D2');++ expect(results).toEqual([+ {storyId: 'core-a--default', dims: {D2: 'ERROR', D8: 'pass on page 1'}},+ {storyId: 'core-b--default', dims: {D2: 'pass on page 1'}},+ {+ storyId: 'core-c--default',+ dims: {D7: 'pass on page 0', D2: 'pass on page 1'},+ },+ ]);+ expect(pool.recoveries).toEqual([+ {+ worker: 0,+ phase: 'curated',+ storyId: 'core-a--default',+ dim: 'D2',+ error: `Error: ${TIMEOUT}`,+ },+ ]);+ expect(browser.opened[0].closed).toBe(true);+ expect(coarseBrowser.opened).toHaveLength(1);+ });++ it('replaces only the coarse-pointer page when a coarse step breaks it', async () => {+ const {browser, coarseBrowser, pool, pages} = await curatedPages();+ const results = await scoreTargets(+ [...TARGETS, {storyId: 'core-d--default', dims: ['D7']}],+ pages,+ 'core-c--default:D7',+ );++ expect(results.at(-2)).toEqual({+ storyId: 'core-c--default',+ dims: {D7: 'ERROR', D2: 'pass on page 0'},+ });+ expect(results.at(-1)).toEqual({+ storyId: 'core-d--default',+ dims: {D7: 'pass on page 1'},+ });+ expect(pool.recoveries.map(recovery => recovery.worker)).toEqual([+ 'coarse',+ ]);+ expect(coarseBrowser.opened[0].closed).toBe(true);+ expect(browser.opened).toHaveLength(1);+ });+ });++ it('ends the run, naming both failures, when a page cannot be replaced', async () => {+ const browser = fakeBrowser();+ let opens = 0;+ const pool = await createPagePool({+ size: 1,+ openPage: async () => {+ opens += 1;+ if (opens > 1)+ throw new Error('Target page, context or browser has been closed');+ return browser.openPage();+ },+ });+ await expect(+ mapPool(stories(5, [2]), pool, {+ ...phase(new Map()),+ describe: story => ({phase: 'D5', storyId: story.storyId}),+ }),+ ).rejects.toThrow(+ `cannot replace the page after D5 core-story--2 failed (Error: ${TIMEOUT}): Error: Target page, context or browser has been closed`,+ );+ expect(pool.recoveries).toEqual([]);++ const coarseBrowser = fakeBrowser();+ const pages = createCuratedPages({+ pool: await createPagePool({size: 1, openPage: browser.openPage}),+ coarsePage: await coarseBrowser.openPage(),+ openCoarsePage: async () => {+ throw new Error('Target page, context or browser has been closed');+ },+ });+ await expect(+ runSteps(['D7', 'D2'], pages, {+ pageFor: () => 'coarse',+ run: async () => {+ throw new Error(TIMEOUT);+ },+ onError: () => {},+ describe: dim => ({phase: 'curated', storyId: 'core-a--default', dim}),+ }),+ ).rejects.toThrow(+ `cannot replace the page after curated core-a--default D7 failed (Error: ${TIMEOUT})`,+ );+ });++ it('does not wait on a curated page that never acknowledges its close', async () => {+ const browser = fakeBrowser({hangOnClose: true});+ const coarseBrowser = fakeBrowser({hangOnClose: true});+ const quickClose = page => closePageQuietly(page, 10);+ const pool = await createPagePool({+ size: 1,+ openPage: browser.openPage,+ closePage: quickClose,+ });+ const pages = createCuratedPages({+ pool,+ coarsePage: await coarseBrowser.openPage(),+ openCoarsePage: coarseBrowser.openPage,+ closePage: quickClose,+ });+ const failed = [];+ await runSteps(['D2', 'D7', 'D8'], pages, {+ pageFor: dim => (dim === 'D7' ? 'coarse' : 'main'),+ run: async dim => {+ if (dim !== 'D8') throw new Error(TIMEOUT);+ },+ onError: dim => failed.push(dim),+ });++ expect(failed).toEqual(['D2', 'D7']);+ expect(pool.recoveries.map(recovery => recovery.worker)).toEqual([+ 0,+ 'coarse',+ ]);+ });+});diff --git a/apps/storybook/rtl-audit/rtl-audit-pool.mjs b/apps/storybook/rtl-audit/rtl-audit-pool.mjsnew file mode 100644index 0000000000..573c916917--- /dev/null+++ b/apps/storybook/rtl-audit/rtl-audit-pool.mjs@@ -0,0 +1,197 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file rtl-audit-pool.mjs+ * @input A page opener (`openPage`) and the number of workers; work items and+ * a per-item scan function with its error record; for the curated pass, a+ * coarse-pointer page opener and each target's steps.+ * @output createPagePool, a fixed set of worker slots that each hold one page+ * at a time, and mapPool, which runs items over those slots. A slot whose+ * scan throws gets a fresh page before it takes another item.+ * createCuratedPages and runSteps do the same for the serial curated pass:+ * a step that throws gets the page it ran on replaced before the next step.+ * @position Used by rtl-audit.mjs for the D1, D5, and D6 auto-discovery passes+ * and the curated pass. A page that failed a story can be unusable — a+ * navigation that never commits, a crashed or hung renderer — and a worker+ * that kept it would fail every later story it was handed. Recovery never+ * retries the failed story: its error record stays, and only what follows+ * runs on the new page.+ */++/** How long to wait for a discarded page to close before moving on. */+const CLOSE_WAIT_MS = 5000;++/** The first line of an error, as a recovery record keeps it. */+function firstLine(error) {+ return String(error).split('\n')[0].slice(0, 160);+}++/**+ * Runs `replace(reason)` after a failure. A page that cannot be replaced ends+ * the run, and the error names the failure that needed the replacement, so+ * neither failure is lost.+ */+async function recover(replace, reason) {+ try {+ await replace(reason);+ } catch (replaceError) {+ const failed = [reason.phase, reason.storyId, reason.dim]+ .filter(Boolean)+ .join(' ');+ throw new Error(+ `cannot replace the page after ${failed || 'a scan'} failed (${reason.error}): ${firstLine(replaceError)}`,+ {cause: replaceError},+ );+ }+}++/**+ * Closes `page` without letting a wedged page stall the caller: a page whose+ * renderer is stuck may never acknowledge the close.+ */+export async function closePageQuietly(page, waitMs = CLOSE_WAIT_MS) {+ let timer;+ await Promise.race([+ Promise.resolve()+ .then(() => page.close())+ .catch(() => {}),+ new Promise(resolve => {+ timer = setTimeout(resolve, waitMs);+ }),+ ]);+ clearTimeout(timer);+}++/**+ * Opens `size` worker pages with `openPage`. Every page comes from the same+ * opener, so a replacement has exactly the options its predecessor had.+ */+export async function createPagePool({+ size,+ openPage,+ closePage = closePageQuietly,+}) {+ const slots = await Promise.all(+ Array.from({length: Math.max(1, size)}, async (_, id) => ({+ id,+ page: await openPage(),+ replacements: 0,+ })),+ );+ const recoveries = [];+ return {+ slots,+ recoveries,+ /** The page in the first slot now; it changes when that slot recovers. */+ first() {+ return slots[0].page;+ },+ pages() {+ return slots.map(slot => slot.page);+ },+ /**+ * Gives `slot` a fresh page and discards its old one. `reason` names the+ * story whose failure made the old page untrustworthy.+ */+ async replace(slot, reason) {+ const discarded = slot.page;+ slot.page = await openPage();+ slot.replacements += 1;+ recoveries.push({worker: slot.id, ...reason});+ await closePage(discarded);+ },+ async close() {+ await Promise.all(slots.map(slot => closePage(slot.page)));+ },+ };+}++/**+ * Runs `scan(item, page)` over `items` with one worker per pool slot. Results+ * are written by index, so the output is in input order regardless of which+ * worker finished first. When `scan` throws, the item's result is+ * `onError(item, error)`, and that worker's page is replaced before it takes+ * its next item. `describe(item)` names the item in the recovery record.+ */+export async function mapPool(+ items,+ pool,+ {scan, onError, describe = () => ({})},+) {+ const out = new Array(items.length);+ let next = 0;+ const workers = pool.slots.slice(+ 0,+ Math.max(1, Math.min(pool.slots.length, items.length)),+ );+ await Promise.all(+ workers.map(async slot => {+ for (let i = next++; i < items.length; i = next++) {+ try {+ out[i] = await scan(items[i], slot.page);+ } catch (error) {+ out[i] = onError(items[i], error);+ await recover(reason => pool.replace(slot, reason), {+ ...describe(items[i]),+ error: firstLine(error),+ });+ }+ }+ }),+ );+ return out;+}++/**+ * The two pages the serial curated pass runs on: the first worker slot's page+ * (`'main'`) and a coarse-pointer page from its own context (`'coarse'`).+ * `replace(kind, reason)` swaps one for a fresh page and records why.+ */+export function createCuratedPages({+ pool,+ coarsePage,+ openCoarsePage,+ closePage = closePageQuietly,+}) {+ let coarse = coarsePage;+ return {+ page: () => pool.first(),+ coarsePage: () => coarse,+ async replace(kind, reason) {+ if (kind === 'main') {+ await pool.replace(pool.slots[0], reason);+ return;+ }+ const discarded = coarse;+ coarse = await openCoarsePage();+ pool.recoveries.push({worker: 'coarse', ...reason});+ await closePage(discarded);+ },+ };+}++/**+ * Runs one target's steps in order, each on the page `pageFor` names+ * (`'main'` or `'coarse'`). A step that throws records its error through+ * `onError`, and the page it ran on is replaced before the next step, so+ * neither the rest of the target nor the next target inherits a broken page.+ * `describe(step)` names the step in the recovery record.+ */+export async function runSteps(+ steps,+ pages,+ {run, onError, pageFor, describe = () => ({})},+) {+ for (const step of steps) {+ const kind = pageFor(step);+ try {+ await run(step, kind === 'main' ? pages.page() : pages.coarsePage());+ } catch (error) {+ onError(step, error);+ await recover(reason => pages.replace(kind, reason), {+ ...describe(step),+ error: firstLine(error),+ });+ }+ }+}diff --git a/apps/storybook/rtl-audit/rtl-audit.mjs b/apps/storybook/rtl-audit/rtl-audit.mjsindex f3dcab26fb..99842b6af8 100644--- a/apps/storybook/rtl-audit/rtl-audit.mjs+++ b/apps/storybook/rtl-audit/rtl-audit.mjs@@ -28,8 +28,9 @@* [--verified-not-applicable <path>] [--filter <csv>] [--packages <csv>]* [--auto-only] [--curated-only]* @output JSON scorecard: D1/D5/D6 auto verdicts, curated D2/D3/D4/D7/D8/D9- * results, exact planned/completed scan counts, and a component coverage- * rollup. Mirrors the pr-a11y accessibility-audit harness.+ * results, exact planned/completed scan counts, a component coverage+ * rollup, and the worker pages replaced after a failed story+ * (`pageRecoveries`). Mirrors the pr-a11y accessibility-audit harness.* @position internal test harness; run by the soft-gated `pr-rtl` CI job and* locally via `pnpm -F @astryxdesign/storybook rtl-audit`.*@@ -61,6 +62,12 @@ import {evaluateDirectionalDecorations,filterStoryRoutesByPackages,} from './rtl-audit-coverage.mjs';+import {+ createCuratedPages,+ createPagePool,+ mapPool,+ runSteps,+} from './rtl-audit-pool.mjs';const {componentPackage,@@ -101,8 +108,10 @@ const CURATED_ONLY = hasFlag('curated-only');// Story-id prefixes the auto-discovery layer sweeps come from the same// canonical package registry used for source discovery below.const AUDITED_STORY_PREFIX = new RegExp(`^(?:${AUDITED_STORY_PREFIXES.join('|')})`);-// Worker pool size. Each worker owns its own Playwright page; stories are-// independent, and the run is dominated by page-load latency rather than CPU.+// Worker pool size. Each worker holds one Playwright page at a time; stories+// are independent, and the run is dominated by page-load latency rather than+// CPU. A worker whose story fails gets a fresh page before its next story+// (rtl-audit-pool.mjs), so one unusable page cannot fail the stories after it.// Defaults to 1 (serial) so the per-PR job's behaviour is unchanged while the// suite is still soft-gated; rtl-weekly.yml opts into 4 for the full sweep.const CONCURRENCY = Math.max(1, Number(getArg('concurrency') || process.env.RTL_CONCURRENCY || 1));@@ -953,22 +962,27 @@ async function checkD9GroupedCorners(page, port, t, card) {card.groupedCorners = results;}-async function scoreCurated(page, coarsePage, port, t) {+// `pages` is the curated page pair (rtl-audit-pool.mjs). A dim that throws is+// recorded as an ERROR, and the page it ran on is replaced before the next dim.+async function scoreCurated(pages, port, t) {const card = {component: t.component, storyId: t.storyId, dims: {}, notes: []};- for (const dim of t.dims) {- try {+ await runSteps(t.dims, pages, {+ pageFor: dim => (dim === 'D7' ? 'coarse' : 'main'),+ run: async (dim, page) => {if (dim === 'D2') await checkD2(page, port, t, card);else if (dim === 'D3') await checkD3Scroll(page, port, t, card);else if (dim === 'D4') await checkD4(page, port, t, card);- else if (dim === 'D7') await checkD7CoarseHit(coarsePage, port, t, card);+ else if (dim === 'D7') await checkD7CoarseHit(page, port, t, card);else if (dim === 'D8') await checkD8LogicalInline(page, port, t, card);else if (dim === 'D9') await checkD9GroupedCorners(page, port, t, card);// D1 is handled by auto-discovery; ignore any stray D1 in curated entries.- } catch (e) {+ },+ onError: (dim, e) => {card.dims[dim] = 'ERROR';card.notes.push(`${dim} threw: ${String(e).slice(0, 160)}`);- }- }+ },+ describe: dim => ({phase: 'curated', storyId: t.storyId, dim}),+ });const vals = Object.entries(card.dims).filter(([, v]) => v !== 'N-A');const anyFail = vals.some(([, v]) => v === 'fail' || v === 'ERROR');const allPass = vals.length > 0 && vals.every(([, v]) => v === 'pass');@@ -987,32 +1001,15 @@ function belongsToActivePackage(route) {return filterStoryRoutesByPackages([route], ACTIVE_PACKAGE_NAMES).length === 1;}-// Run `fn` over `items` with `pages.length` workers, each pinned to its own-// page. Results are written by index, so the output array is in input order-// regardless of completion order — the report stays byte-identical to a serial-// run. Progress lines still print as they land, so they interleave.-async function mapPool(items, pages, fn) {- const out = new Array(items.length);- let next = 0;- await Promise.all(- pages.slice(0, Math.max(1, Math.min(pages.length, items.length))).map(async page => {- for (let i = next++; i < items.length; i = next++) {- out[i] = await fn(items[i], page);- }- }),- );- return out;-}-const runtime = {server: null,browser: null,- pages: [],+ pool: null,coarseContext: null,};async function cleanupRuntime() {- await Promise.all(runtime.pages.map(page => page.close().catch(() => {})));+ await runtime.pool?.close();await runtime.coarseContext?.close().catch(() => {});await runtime.browser?.close().catch(() => {});if (runtime.server) {@@ -1088,14 +1085,14 @@ async function cleanupRuntime() {runtime.server = server;const browser = await chromium.launch();runtime.browser = browser;- const pages = await Promise.all(- Array.from({length: CONCURRENCY}, () =>+ const pool = await createPagePool({+ size: CONCURRENCY,+ openPage: () =>browser.newPage({viewport: {width: 1100, height: 760}, deviceScaleFactor: 1}),- ),- );- runtime.pages = pages;- const page = pages[0]; // curated dims run serially on the first page- const d8BrowserContract = await verifyD8BrowserContract(page);+ });+ runtime.pool = pool;+ // Curated dims run serially on the first slot's current page.+ const d8BrowserContract = await verifyD8BrowserContract(pool.first());const coarseContext = await browser.newContext({viewport: {width: 1100, height: 760},deviceScaleFactor: 1,@@ -1103,7 +1100,11 @@ async function cleanupRuntime() {isMobile: true,});runtime.coarseContext = coarseContext;- const coarsePage = await coarseContext.newPage();+ const curatedPages = createCuratedPages({+ pool,+ coarsePage: await coarseContext.newPage(),+ openCoarsePage: () => coarseContext.newPage(),+ });// ---- (A) auto-discovery over every audited-package story ----const autoResults = []; // D1 icon-mirror@@ -1121,49 +1122,55 @@ async function cleanupRuntime() {// positioned bug can be story-specific (only a `withStatus` variant mounts// the offending element), so we don't collapse to one-per-component.autoResults.push(- ...(await mapPool(d1Targets, pages, async ({comp, id}, workerPage) => {- try {+ ...(await mapPool(d1Targets, pool, {+ scan: async ({comp, id}, workerPage) => {const card = await autoD1(workerPage, port, id, comp);if (card.verdict !== 'N-A') {console.error(`AUTO ${card.verdict.toUpperCase().padEnd(4)} ${comp.padEnd(24)} icons=${card.icons}`);}return card;- } catch (e) {+ },+ onError: ({comp, id}, e) => {console.error(`AUTO ERROR ${comp}: ${String(e).slice(0, 120)}`);return {component: comp, storyId: id, dim: 'D1', verdict: 'ERROR', notes: [String(e).slice(0, 160)], icons: 0};- }+ },+ describe: ({id}) => ({phase: 'D1', storyId: id}),})),);// D5 positional-mirror over every audited story.const pmTargets = scopedStoryRoutes.map(({id, component}) => ({id, comp: component}));pmResults.push(- ...(await mapPool(pmTargets, pages, async ({id, comp}, workerPage) => {- try {+ ...(await mapPool(pmTargets, pool, {+ scan: async ({id, comp}, workerPage) => {const card = await autoPositionalMirror(workerPage, port, id, comp);if (card.verdict !== 'N-A') {console.error(`PM ${card.verdict.toUpperCase().padEnd(4)} ${comp.padEnd(24)} ${id.padEnd(40)} cand=${card.candidates}`);}return card;- } catch (e) {+ },+ onError: ({id, comp}, e) => {console.error(`PM ERROR ${comp} ${id}: ${String(e).slice(0, 120)}`);return {component: comp, storyId: id, dim: 'D5-positional', verdict: 'ERROR', notes: [String(e).slice(0, 160)], candidates: 0, fails: []};- }+ },+ describe: ({id}) => ({phase: 'D5', storyId: id}),})),);// D6 scans every story. A directional decoration can exist only in a// custom/variant story even when the default story is neutral.decorationResults.push(- ...(await mapPool(pmTargets, pages, async ({id, comp}, workerPage) => {- try {+ ...(await mapPool(pmTargets, pool, {+ scan: async ({id, comp}, workerPage) => {const card = await autoDirectionalDecorations(workerPage, port, id, comp);if (card.verdict !== 'N-A') {console.error(`DEC ${card.verdict.toUpperCase().padEnd(4)} ${comp.padEnd(24)} ${id.padEnd(40)} glyphs=${card.decorations}`);}return card;- } catch (e) {+ },+ onError: ({id, comp}, e) => {console.error(`DEC ERROR ${comp} ${id}: ${String(e).slice(0, 120)}`);return {component: comp, storyId: id, dim: 'D6-decoration', verdict: 'ERROR', notes: [String(e).slice(0, 160)], decorations: 0, results: []};- }+ },+ describe: ({id}) => ({phase: 'D6', storyId: id}),})),);}@@ -1189,13 +1196,11 @@ async function cleanupRuntime() {// skip if the entry only had D1 (now covered by auto-discovery)const dims = (t.dims || []).filter(d => d !== 'D1');if (dims.length === 0) continue;- try {- const card = await scoreCurated(page, coarsePage, port, {...t, component, dims});- curatedResults.push(card);- console.error(`CUR ${card.rollup.padEnd(10)} ${component.padEnd(20)} ${JSON.stringify(card.dims)}`);- } catch (e) {- curatedResults.push({component, storyId: t.storyId, rollup: 'ERROR', dims: {}, notes: [String(e).slice(0, 200)]});- }+ // scoreCurated records each dim's failure itself; what escapes it is a+ // page that could not be replaced, which ends the run.+ const card = await scoreCurated(curatedPages, port, {...t, component, dims});+ curatedResults.push(card);+ console.error(`CUR ${card.rollup.padEnd(10)} ${component.padEnd(20)} ${JSON.stringify(card.dims)}`);}}@@ -1260,6 +1265,10 @@ async function cleanupRuntime() {},dist: DIST,selfChecks: {d8LogicalInline: d8BrowserContract},+ // Worker pages replaced after a story failed on them. The failed story+ // keeps its ERROR result; the record shows the stories after it ran on a+ // fresh page.+ pageRecoveries: pool.recoveries,autoDiscovery: {total: autoResults.length,applicable: autoResults.filter(r => r.verdict !== 'N-A').length,@@ -1295,6 +1304,7 @@ async function cleanupRuntime() {console.error(`AUTO: ${report.autoDiscovery.pass} pass / ${report.autoDiscovery.fail} fail (${surprises.length} surprise) / ${report.autoDiscovery.na} N-A`);console.error(`PM : ${report.positionalMirror.pass} pass / ${report.positionalMirror.fail} fail / ${report.positionalMirror.na} N-A (tol ${PM_TOL}px)`);console.error(`DEC : ${report.directionalDecorations.pass} pass / ${report.directionalDecorations.fail} fail / ${report.directionalDecorations.na} N-A`);+ console.error(`POOL: ${pool.recoveries.length} page replacement(s) after a failed story`);console.error(`COV : ${coverage.measured} measured / ${coverage.verifiedNa} verified N-A / ${coverage.gaps} gap / ${coverage.staleVerifiedNa} stale`);// Non-zero exit only signals CI (which is soft/continue-on-error). Surface a// signal but never let it hard-block during the stability window.